Style: Apply clang-format to Java files

Only those from org/godotengine/godot though, not the thirdparty ones.
This commit is contained in:
Rémi Verschelde 2017-12-10 01:16:07 +01:00
parent ce0f894b48
commit 7cb6e6b723
28 changed files with 1380 additions and 1468 deletions

View file

@ -44,7 +44,6 @@ AllowShortIfStatementsOnASingleLine: true
BreakBeforeTernaryOperators: false BreakBeforeTernaryOperators: false
# BreakConstructorInitializersBeforeComma: false # BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: AfterColon BreakConstructorInitializers: AfterColon
# BreakAfterJavaFieldAnnotations: false
# BreakStringLiterals: true # BreakStringLiterals: true
ColumnLimit: 0 ColumnLimit: 0
# CommentPragmas: '^ IWYU pragma:' # CommentPragmas: '^ IWYU pragma:'
@ -113,4 +112,8 @@ Language: ObjC
ObjCBlockIndentWidth: 4 ObjCBlockIndentWidth: 4
# ObjCSpaceAfterProperty: false # ObjCSpaceAfterProperty: false
# ObjCSpaceBeforeProtocolList: true # ObjCSpaceBeforeProtocolList: true
---
### Java specific config ###
Language: Java
# BreakAfterJavaFieldAnnotations: false
... ...

View file

@ -31,7 +31,7 @@ PARSE_EXTS=true
# File types to parse. Only effective when PARSE_EXTS is true. # File types to parse. Only effective when PARSE_EXTS is true.
# FILE_EXTS=".c .h .cpp .hpp" # FILE_EXTS=".c .h .cpp .hpp"
FILE_EXTS=".c .h .cpp .hpp .cc .hh .cxx .m .mm .inc" FILE_EXTS=".c .h .cpp .hpp .cc .hh .cxx .m .mm .inc *.java"
# Use pygmentize instead of cat to parse diff with highlighting. # Use pygmentize instead of cat to parse diff with highlighting.
# Install it with `pip install pygments` (Linux) or `easy_install Pygments` (Mac) # Install it with `pip install pygments` (Linux) or `easy_install Pygments` (Mac)

View file

@ -11,7 +11,7 @@ else
RANGE=HEAD RANGE=HEAD
fi fi
FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc)$") FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc|java)$")
echo "Checking files:\n$FILES" echo "Checking files:\n$FILES"
# create a random filename to store our generated patch # create a random filename to store our generated patch

View file

@ -32,7 +32,6 @@ package org.godotengine.godot;
import java.util.HashMap; import java.util.HashMap;
import java.util.Set; import java.util.Set;
public class Dictionary extends HashMap<String, Object> { public class Dictionary extends HashMap<String, Object> {
protected String[] keys_cache; protected String[] keys_cache;
@ -40,7 +39,7 @@ public class Dictionary extends HashMap<String, Object> {
public String[] get_keys() { public String[] get_keys() {
String[] ret = new String[size()]; String[] ret = new String[size()];
int i=0; int i = 0;
Set<String> keys = keySet(); Set<String> keys = keySet();
for (String key : keys) { for (String key : keys) {
@ -54,7 +53,7 @@ public class Dictionary extends HashMap<String, Object> {
public Object[] get_values() { public Object[] get_values() {
Object[] ret = new Object[size()]; Object[] ret = new Object[size()];
int i=0; int i = 0;
Set<String> keys = keySet(); Set<String> keys = keySet();
for (String key : keys) { for (String key : keys) {
@ -71,7 +70,7 @@ public class Dictionary extends HashMap<String, Object> {
public void set_values(Object[] vals) { public void set_values(Object[] vals) {
int i=0; int i = 0;
for (String key : keys_cache) { for (String key : keys_cache) {
put(key, vals[i]); put(key, vals[i]);
i++; i++;

File diff suppressed because it is too large Load diff

View file

@ -46,14 +46,14 @@ import android.util.Log;
*/ */
public class GodotDownloaderAlarmReceiver extends BroadcastReceiver { public class GodotDownloaderAlarmReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
Log.d("GODOT", "Alarma recivida"); Log.d("GODOT", "Alarma recivida");
try { try {
DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent, GodotDownloaderService.class); DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent, GodotDownloaderService.class);
} catch (NameNotFoundException e) { } catch (NameNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
Log.d("GODOT", "Exception: " + e.getClass().getName() + ":" + e.getMessage()); Log.d("GODOT", "Exception: " + e.getClass().getName() + ":" + e.getMessage());
}
} }
}
} }

View file

@ -40,46 +40,45 @@ import com.google.android.vending.expansion.downloader.impl.DownloaderService;
* DownloaderService from the Downloader library. * DownloaderService from the Downloader library.
*/ */
public class GodotDownloaderService extends DownloaderService { public class GodotDownloaderService extends DownloaderService {
// stuff for LVL -- MODIFY FOR YOUR APPLICATION! // stuff for LVL -- MODIFY FOR YOUR APPLICATION!
private static final String BASE64_PUBLIC_KEY = "REPLACE THIS WITH YOUR PUBLIC KEY"; private static final String BASE64_PUBLIC_KEY = "REPLACE THIS WITH YOUR PUBLIC KEY";
// used by the preference obfuscater // used by the preference obfuscater
private static final byte[] SALT = new byte[] { private static final byte[] SALT = new byte[] {
1, 43, -12, -1, 54, 98, 1, 43, -12, -1, 54, 98,
-100, -12, 43, 2, -8, -4, 9, 5, -106, -108, -33, 45, -1, 84 -100, -12, 43, 2, -8, -4, 9, 5, -106, -108, -33, 45, -1, 84
}; };
/** /**
* This public key comes from your Android Market publisher account, and it * This public key comes from your Android Market publisher account, and it
* used by the LVL to validate responses from Market on your behalf. * used by the LVL to validate responses from Market on your behalf.
*/ */
@Override @Override
public String getPublicKey() { public String getPublicKey() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("app_data_keys", Context.MODE_PRIVATE); SharedPreferences prefs = getApplicationContext().getSharedPreferences("app_data_keys", Context.MODE_PRIVATE);
Log.d("GODOT", "getting public key:" + prefs.getString("store_public_key", null)); Log.d("GODOT", "getting public key:" + prefs.getString("store_public_key", null));
return prefs.getString("store_public_key", null); return prefs.getString("store_public_key", null);
//return BASE64_PUBLIC_KEY;
}
/** //return BASE64_PUBLIC_KEY;
}
/**
* This is used by the preference obfuscater to make sure that your * This is used by the preference obfuscater to make sure that your
* obfuscated preferences are different than the ones used by other * obfuscated preferences are different than the ones used by other
* applications. * applications.
*/ */
@Override @Override
public byte[] getSALT() { public byte[] getSALT() {
return SALT; return SALT;
} }
/** /**
* Fill this in with the class name for your alarm receiver. We do this * Fill this in with the class name for your alarm receiver. We do this
* because receivers must be unique across all of Android (it's a good idea * because receivers must be unique across all of Android (it's a good idea
* to make sure that your receiver is in your unique package) * to make sure that your receiver is in your unique package)
*/ */
@Override @Override
public String getAlarmReceiverClassName() { public String getAlarmReceiverClassName() {
Log.d("GODOT", "getAlarmReceiverClassName()"); Log.d("GODOT", "getAlarmReceiverClassName()");
return GodotDownloaderAlarmReceiver.class.getName(); return GodotDownloaderAlarmReceiver.class.getName();
} }
} }

View file

@ -56,7 +56,6 @@ import org.godotengine.godot.input.*;
public class GodotIO { public class GodotIO {
AssetManager am; AssetManager am;
Godot activity; Godot activity;
GodotEditText edit; GodotEditText edit;
@ -64,35 +63,32 @@ public class GodotIO {
Context applicationContext; Context applicationContext;
MediaPlayer mediaPlayer; MediaPlayer mediaPlayer;
final int SCREEN_LANDSCAPE=0; final int SCREEN_LANDSCAPE = 0;
final int SCREEN_PORTRAIT=1; final int SCREEN_PORTRAIT = 1;
final int SCREEN_REVERSE_LANDSCAPE=2; final int SCREEN_REVERSE_LANDSCAPE = 2;
final int SCREEN_REVERSE_PORTRAIT=3; final int SCREEN_REVERSE_PORTRAIT = 3;
final int SCREEN_SENSOR_LANDSCAPE=4; final int SCREEN_SENSOR_LANDSCAPE = 4;
final int SCREEN_SENSOR_PORTRAIT=5; final int SCREEN_SENSOR_PORTRAIT = 5;
final int SCREEN_SENSOR=6; final int SCREEN_SENSOR = 6;
///////////////////////// /////////////////////////
/// FILES /// FILES
///////////////////////// /////////////////////////
public int last_file_id=1; public int last_file_id = 1;
class AssetData { class AssetData {
public boolean eof = false;
public boolean eof=false;
public String path; public String path;
public InputStream is; public InputStream is;
public int len; public int len;
public int pos; public int pos;
} }
HashMap<Integer, AssetData> streams;
HashMap<Integer,AssetData> streams; public int file_open(String path, boolean write) {
public int file_open(String path,boolean write) {
//System.out.printf("file_open: Attempt to Open %s\n",path); //System.out.printf("file_open: Attempt to Open %s\n",path);
@ -100,7 +96,6 @@ public class GodotIO {
if (write) if (write)
return -1; return -1;
AssetData ad = new AssetData(); AssetData ad = new AssetData();
try { try {
@ -113,76 +108,73 @@ public class GodotIO {
} }
try { try {
ad.len=ad.is.available(); ad.len = ad.is.available();
} catch (Exception e) { } catch (Exception e) {
System.out.printf("Exception availabling on file_open: %s\n",path); System.out.printf("Exception availabling on file_open: %s\n", path);
return -1; return -1;
} }
ad.path=path; ad.path = path;
ad.pos=0; ad.pos = 0;
++last_file_id; ++last_file_id;
streams.put(last_file_id,ad); streams.put(last_file_id, ad);
return last_file_id; return last_file_id;
} }
public int file_get_size(int id) { public int file_get_size(int id) {
if (!streams.containsKey(id)) { if (!streams.containsKey(id)) {
System.out.printf("file_get_size: Invalid file id: %d\n",id); System.out.printf("file_get_size: Invalid file id: %d\n", id);
return -1; return -1;
} }
return streams.get(id).len; return streams.get(id).len;
} }
public void file_seek(int id,int bytes) { public void file_seek(int id, int bytes) {
if (!streams.containsKey(id)) { if (!streams.containsKey(id)) {
System.out.printf("file_get_size: Invalid file id: %d\n",id); System.out.printf("file_get_size: Invalid file id: %d\n", id);
return; return;
} }
//seek sucks //seek sucks
AssetData ad = streams.get(id); AssetData ad = streams.get(id);
if (bytes>ad.len) if (bytes > ad.len)
bytes=ad.len; bytes = ad.len;
if (bytes<0) if (bytes < 0)
bytes=0; bytes = 0;
try { try {
if (bytes > (int)ad.pos) { if (bytes > (int)ad.pos) {
int todo=bytes-(int)ad.pos; int todo = bytes - (int)ad.pos;
while(todo>0) { while (todo > 0) {
todo-=ad.is.skip(todo); todo -= ad.is.skip(todo);
}
ad.pos = bytes;
} else if (bytes < (int)ad.pos) {
ad.is = am.open(ad.path);
ad.pos = bytes;
int todo = bytes;
while (todo > 0) {
todo -= ad.is.skip(todo);
}
} }
ad.pos=bytes;
} else if (bytes<(int)ad.pos) {
ad.is=am.open(ad.path); ad.eof = false;
ad.pos=bytes;
int todo=bytes;
while(todo>0) {
todo-=ad.is.skip(todo);
}
}
ad.eof=false;
} catch (IOException e) { } catch (IOException e) {
System.out.printf("Exception on file_seek: %s\n",e); System.out.printf("Exception on file_seek: %s\n", e);
return; return;
} }
} }
public int file_tell(int id) { public int file_tell(int id) {
if (!streams.containsKey(id)) { if (!streams.containsKey(id)) {
System.out.printf("file_read: Can't tell eof for invalid file id: %d\n",id); System.out.printf("file_read: Can't tell eof for invalid file id: %d\n", id);
return 0; return 0;
} }
@ -192,7 +184,7 @@ public class GodotIO {
public boolean file_eof(int id) { public boolean file_eof(int id) {
if (!streams.containsKey(id)) { if (!streams.containsKey(id)) {
System.out.printf("file_read: Can't check eof for invalid file id: %d\n",id); System.out.printf("file_read: Can't check eof for invalid file id: %d\n", id);
return false; return false;
} }
@ -203,73 +195,65 @@ public class GodotIO {
public byte[] file_read(int id, int bytes) { public byte[] file_read(int id, int bytes) {
if (!streams.containsKey(id)) { if (!streams.containsKey(id)) {
System.out.printf("file_read: Can't read invalid file id: %d\n",id); System.out.printf("file_read: Can't read invalid file id: %d\n", id);
return new byte[0]; return new byte[0];
} }
AssetData ad = streams.get(id); AssetData ad = streams.get(id);
if (ad.pos + bytes > ad.len) { if (ad.pos + bytes > ad.len) {
bytes=ad.len-ad.pos; bytes = ad.len - ad.pos;
ad.eof=true; ad.eof = true;
} }
if (bytes == 0) {
if (bytes==0) {
return new byte[0]; return new byte[0];
} }
byte[] buf1 = new byte[bytes];
int r = 0;
byte[] buf1=new byte[bytes];
int r=0;
try { try {
r = ad.is.read(buf1); r = ad.is.read(buf1);
} catch (IOException e) { } catch (IOException e) {
System.out.printf("Exception on file_read: %s\n",e); System.out.printf("Exception on file_read: %s\n", e);
return new byte[bytes]; return new byte[bytes];
} }
if (r==0) { if (r == 0) {
return new byte[0]; return new byte[0];
} }
ad.pos+=r; ad.pos += r;
if (r<bytes) { if (r < bytes) {
byte[] buf2=new byte[r]; byte[] buf2 = new byte[r];
for(int i=0;i<r;i++) for (int i = 0; i < r; i++)
buf2[i]=buf1[i]; buf2[i] = buf1[i];
return buf2; return buf2;
} else { } else {
return buf1; return buf1;
} }
} }
public void file_close(int id) { public void file_close(int id) {
if (!streams.containsKey(id)) { if (!streams.containsKey(id)) {
System.out.printf("file_close: Can't close invalid file id: %d\n",id); System.out.printf("file_close: Can't close invalid file id: %d\n", id);
return; return;
} }
streams.remove(id); streams.remove(id);
} }
///////////////////////// /////////////////////////
/// DIRECTORIES /// DIRECTORIES
///////////////////////// /////////////////////////
class AssetDir { class AssetDir {
public String[] files; public String[] files;
@ -277,49 +261,48 @@ public class GodotIO {
public String path; public String path;
} }
public int last_dir_id=1; public int last_dir_id = 1;
HashMap<Integer,AssetDir> dirs; HashMap<Integer, AssetDir> dirs;
public int dir_open(String path) { public int dir_open(String path) {
AssetDir ad = new AssetDir(); AssetDir ad = new AssetDir();
ad.current=0; ad.current = 0;
ad.path=path; ad.path = path;
try { try {
ad.files = am.list(path); ad.files = am.list(path);
// no way to find path is directory or file exactly. // no way to find path is directory or file exactly.
// but if ad.files.length==0, then it's an empty directory or file. // but if ad.files.length==0, then it's an empty directory or file.
if (ad.files.length==0) { if (ad.files.length == 0) {
return -1; return -1;
} }
} catch (IOException e) { } catch (IOException e) {
System.out.printf("Exception on dir_open: %s\n",e); System.out.printf("Exception on dir_open: %s\n", e);
return -1; return -1;
} }
//System.out.printf("Opened dir: %s\n",path); //System.out.printf("Opened dir: %s\n",path);
++last_dir_id; ++last_dir_id;
dirs.put(last_dir_id,ad); dirs.put(last_dir_id, ad);
return last_dir_id; return last_dir_id;
} }
public boolean dir_is_dir(int id) { public boolean dir_is_dir(int id) {
if (!dirs.containsKey(id)) { if (!dirs.containsKey(id)) {
System.out.printf("dir_next: invalid dir id: %d\n",id); System.out.printf("dir_next: invalid dir id: %d\n", id);
return false; return false;
} }
AssetDir ad = dirs.get(id); AssetDir ad = dirs.get(id);
//System.out.printf("go next: %d,%d\n",ad.current,ad.files.length); //System.out.printf("go next: %d,%d\n",ad.current,ad.files.length);
int idx = ad.current; int idx = ad.current;
if (idx>0) if (idx > 0)
idx--; idx--;
if (idx>=ad.files.length) if (idx >= ad.files.length)
return false; return false;
String fname = ad.files[idx]; String fname = ad.files[idx];
@ -327,7 +310,7 @@ public class GodotIO {
if (ad.path.equals("")) if (ad.path.equals(""))
am.open(fname); am.open(fname);
else else
am.open(ad.path+"/"+fname); am.open(ad.path + "/" + fname);
return false; return false;
} catch (Exception e) { } catch (Exception e) {
return true; return true;
@ -337,46 +320,41 @@ public class GodotIO {
public String dir_next(int id) { public String dir_next(int id) {
if (!dirs.containsKey(id)) { if (!dirs.containsKey(id)) {
System.out.printf("dir_next: invalid dir id: %d\n",id); System.out.printf("dir_next: invalid dir id: %d\n", id);
return ""; return "";
} }
AssetDir ad = dirs.get(id); AssetDir ad = dirs.get(id);
//System.out.printf("go next: %d,%d\n",ad.current,ad.files.length); //System.out.printf("go next: %d,%d\n",ad.current,ad.files.length);
if (ad.current>=ad.files.length) { if (ad.current >= ad.files.length) {
ad.current++; ad.current++;
return ""; return "";
} }
String r = ad.files[ad.current]; String r = ad.files[ad.current];
ad.current++; ad.current++;
return r; return r;
} }
public void dir_close(int id) { public void dir_close(int id) {
if (!dirs.containsKey(id)) { if (!dirs.containsKey(id)) {
System.out.printf("dir_close: invalid dir id: %d\n",id); System.out.printf("dir_close: invalid dir id: %d\n", id);
return; return;
} }
dirs.remove(id); dirs.remove(id);
} }
GodotIO(Godot p_activity) { GodotIO(Godot p_activity) {
am=p_activity.getAssets(); am = p_activity.getAssets();
activity=p_activity; activity = p_activity;
streams=new HashMap<Integer,AssetData>(); streams = new HashMap<Integer, AssetData>();
dirs=new HashMap<Integer,AssetDir>(); dirs = new HashMap<Integer, AssetDir>();
applicationContext = activity.getApplicationContext(); applicationContext = activity.getApplicationContext();
} }
///////////////////////// /////////////////////////
// AUDIO // AUDIO
///////////////////////// /////////////////////////
@ -400,7 +378,7 @@ public class GodotIO {
desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize); desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM); channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
audioStartThread(); audioStartThread();
@ -412,10 +390,10 @@ public class GodotIO {
public void audioStartThread() { public void audioStartThread() {
mAudioThread = new Thread(new Runnable() { mAudioThread = new Thread(new Runnable() {
public void run() { public void run() {
mAudioTrack.play(); mAudioTrack.play();
GodotLib.audio(); GodotLib.audio();
} }
}); });
// I'd take REALTIME if I could get it! // I'd take REALTIME if I could get it!
@ -424,15 +402,15 @@ public class GodotIO {
} }
public void audioWriteShortBuffer(short[] buffer) { public void audioWriteShortBuffer(short[] buffer) {
for (int i = 0; i < buffer.length; ) { for (int i = 0; i < buffer.length;) {
int result = mAudioTrack.write(buffer, i, buffer.length - i); int result = mAudioTrack.write(buffer, i, buffer.length - i);
if (result > 0) { if (result > 0) {
i += result; i += result;
} else if (result == 0) { } else if (result == 0) {
try { try {
Thread.sleep(1); Thread.sleep(1);
} catch(InterruptedException e) { } catch (InterruptedException e) {
// Nom nom // Nom nom
} }
} else { } else {
Log.w("Godot", "Godot audio: error return from write(short)"); Log.w("Godot", "Godot audio: error return from write(short)");
@ -441,18 +419,16 @@ public class GodotIO {
} }
} }
public void audioQuit() { public void audioQuit() {
if (mAudioThread != null) { if (mAudioThread != null) {
try { try {
mAudioThread.join(); mAudioThread.join();
} catch(Exception e) { } catch (Exception e) {
Log.v("Godot", "Problem stopping audio thread: " + e); Log.v("Godot", "Problem stopping audio thread: " + e);
} }
mAudioThread = null; mAudioThread = null;
//Log.v("Godot", "Finished waiting for audio thread"); //Log.v("Godot", "Finished waiting for audio thread");
} }
if (mAudioTrack != null) { if (mAudioTrack != null) {
@ -473,20 +449,18 @@ public class GodotIO {
// MISCELLANEOUS OS IO // MISCELLANEOUS OS IO
///////////////////////// /////////////////////////
public int openURI(String p_uri) { public int openURI(String p_uri) {
try { try {
Log.v("MyApp", "TRYING TO OPEN URI: " + p_uri); Log.v("MyApp", "TRYING TO OPEN URI: " + p_uri);
String path = p_uri; String path = p_uri;
String type=""; String type = "";
if (path.startsWith("/")) { if (path.startsWith("/")) {
//absolute path to filesystem, prepend file:// //absolute path to filesystem, prepend file://
path="file://"+path; path = "file://" + path;
if (p_uri.endsWith(".png") || p_uri.endsWith(".jpg") || p_uri.endsWith(".gif") || p_uri.endsWith(".webp")) { if (p_uri.endsWith(".png") || p_uri.endsWith(".jpg") || p_uri.endsWith(".gif") || p_uri.endsWith(".webp")) {
type="image/*"; type = "image/*";
} }
} }
@ -531,7 +505,7 @@ public class GodotIO {
} }
public void showKeyboard(String p_existing_text) { public void showKeyboard(String p_existing_text) {
if(edit != null) if (edit != null)
edit.showKeyboard(p_existing_text); edit.showKeyboard(p_existing_text);
//InputMethodManager inputMgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); //InputMethodManager inputMgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
@ -539,21 +513,21 @@ public class GodotIO {
}; };
public void hideKeyboard() { public void hideKeyboard() {
if(edit != null) if (edit != null)
edit.hideKeyboard(); edit.hideKeyboard();
InputMethodManager inputMgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
View v = activity.getCurrentFocus(); View v = activity.getCurrentFocus();
if (v != null) { if (v != null) {
inputMgr.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); inputMgr.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} else { } else {
inputMgr.hideSoftInputFromWindow(new View(activity).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); inputMgr.hideSoftInputFromWindow(new View(activity).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} }
}; };
public void setScreenOrientation(int p_orientation) { public void setScreenOrientation(int p_orientation) {
switch(p_orientation) { switch (p_orientation) {
case SCREEN_LANDSCAPE: { case SCREEN_LANDSCAPE: {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
@ -576,16 +550,14 @@ public class GodotIO {
case SCREEN_SENSOR: { case SCREEN_SENSOR: {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
} break; } break;
} }
}; };
public void setEdit(GodotEditText _edit) { public void setEdit(GodotEditText _edit) {
edit = _edit; edit = _edit;
} }
public void playVideo(String p_path) public void playVideo(String p_path) {
{
Uri filePath = Uri.parse(p_path); Uri filePath = Uri.parse(p_path);
mediaPlayer = new MediaPlayer(); mediaPlayer = new MediaPlayer();
@ -594,11 +566,9 @@ public class GodotIO {
mediaPlayer.setDataSource(applicationContext, filePath); mediaPlayer.setDataSource(applicationContext, filePath);
mediaPlayer.prepare(); mediaPlayer.prepare();
mediaPlayer.start(); mediaPlayer.start();
} catch (IOException e) {
System.out.println("IOError while playing video");
} }
catch(IOException e)
{
System.out.println("IOError while playing video");
}
} }
public boolean isVideoPlaying() { public boolean isVideoPlaying() {
@ -621,49 +591,47 @@ public class GodotIO {
} }
} }
public static final int SYSTEM_DIR_DESKTOP = 0;
public static final int SYSTEM_DIR_DESKTOP=0; public static final int SYSTEM_DIR_DCIM = 1;
public static final int SYSTEM_DIR_DCIM=1; public static final int SYSTEM_DIR_DOCUMENTS = 2;
public static final int SYSTEM_DIR_DOCUMENTS=2; public static final int SYSTEM_DIR_DOWNLOADS = 3;
public static final int SYSTEM_DIR_DOWNLOADS=3; public static final int SYSTEM_DIR_MOVIES = 4;
public static final int SYSTEM_DIR_MOVIES=4; public static final int SYSTEM_DIR_MUSIC = 5;
public static final int SYSTEM_DIR_MUSIC=5; public static final int SYSTEM_DIR_PICTURES = 6;
public static final int SYSTEM_DIR_PICTURES=6; public static final int SYSTEM_DIR_RINGTONES = 7;
public static final int SYSTEM_DIR_RINGTONES=7;
public String getSystemDir(int idx) { public String getSystemDir(int idx) {
String what=""; String what = "";
switch(idx) { switch (idx) {
case SYSTEM_DIR_DESKTOP: { case SYSTEM_DIR_DESKTOP: {
//what=Environment.DIRECTORY_DOCUMENTS; //what=Environment.DIRECTORY_DOCUMENTS;
what=Environment.DIRECTORY_DOWNLOADS; what = Environment.DIRECTORY_DOWNLOADS;
} break; } break;
case SYSTEM_DIR_DCIM: { case SYSTEM_DIR_DCIM: {
what=Environment.DIRECTORY_DCIM; what = Environment.DIRECTORY_DCIM;
} break; } break;
case SYSTEM_DIR_DOCUMENTS: { case SYSTEM_DIR_DOCUMENTS: {
what=Environment.DIRECTORY_DOWNLOADS; what = Environment.DIRECTORY_DOWNLOADS;
//what=Environment.DIRECTORY_DOCUMENTS; //what=Environment.DIRECTORY_DOCUMENTS;
} break; } break;
case SYSTEM_DIR_DOWNLOADS: { case SYSTEM_DIR_DOWNLOADS: {
what=Environment.DIRECTORY_DOWNLOADS; what = Environment.DIRECTORY_DOWNLOADS;
} break; } break;
case SYSTEM_DIR_MOVIES: { case SYSTEM_DIR_MOVIES: {
what=Environment.DIRECTORY_MOVIES; what = Environment.DIRECTORY_MOVIES;
} break; } break;
case SYSTEM_DIR_MUSIC: { case SYSTEM_DIR_MUSIC: {
what=Environment.DIRECTORY_MUSIC; what = Environment.DIRECTORY_MUSIC;
} break; } break;
case SYSTEM_DIR_PICTURES: { case SYSTEM_DIR_PICTURES: {
what=Environment.DIRECTORY_PICTURES; what = Environment.DIRECTORY_PICTURES;
} break; } break;
case SYSTEM_DIR_RINGTONES: { case SYSTEM_DIR_RINGTONES: {
what=Environment.DIRECTORY_RINGTONES; what = Environment.DIRECTORY_RINGTONES;
} break; } break;
} }
@ -676,10 +644,9 @@ public class GodotIO {
protected static final String PREFS_FILE = "device_id.xml"; protected static final String PREFS_FILE = "device_id.xml";
protected static final String PREFS_DEVICE_ID = "device_id"; protected static final String PREFS_DEVICE_ID = "device_id";
public static String unique_id=""; public static String unique_id = "";
public String getUniqueID() { public String getUniqueID() {
return unique_id; return unique_id;
} }
} }

View file

@ -33,43 +33,41 @@ package org.godotengine.godot;
public class GodotLib { public class GodotLib {
public static GodotIO io;
public static GodotIO io; static {
System.loadLibrary("godot_android");
}
static { /**
System.loadLibrary("godot_android");
}
/**
* @param width the current view width * @param width the current view width
* @param height the current view height * @param height the current view height
*/ */
public static native void initialize(Godot p_instance,boolean need_reload_hook,Object p_asset_manager, boolean use_apk_expansion); public static native void initialize(Godot p_instance, boolean need_reload_hook, Object p_asset_manager, boolean use_apk_expansion);
public static native void setup(String[] p_cmdline); public static native void setup(String[] p_cmdline);
public static native void resize(int width, int height,boolean reload); public static native void resize(int width, int height, boolean reload);
public static native void newcontext(boolean p_32_bits); public static native void newcontext(boolean p_32_bits);
public static native void back(); public static native void back();
public static native void step(); public static native void step();
public static native void touch(int what,int pointer,int howmany, int[] arr); public static native void touch(int what, int pointer, int howmany, int[] arr);
public static native void accelerometer(float x, float y, float z); public static native void accelerometer(float x, float y, float z);
public static native void gravity(float x, float y, float z); public static native void gravity(float x, float y, float z);
public static native void magnetometer(float x, float y, float z); public static native void magnetometer(float x, float y, float z);
public static native void gyroscope(float x, float y, float z); public static native void gyroscope(float x, float y, float z);
public static native void key(int p_scancode, int p_unicode_char, boolean p_pressed); public static native void key(int p_scancode, int p_unicode_char, boolean p_pressed);
public static native void joybutton(int p_device, int p_but, boolean p_pressed); public static native void joybutton(int p_device, int p_but, boolean p_pressed);
public static native void joyaxis(int p_device, int p_axis, float p_value); public static native void joyaxis(int p_device, int p_axis, float p_value);
public static native void joyhat(int p_device, int p_hat_x, int p_hat_y); public static native void joyhat(int p_device, int p_hat_x, int p_hat_y);
public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name); public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name);
public static native void focusin(); public static native void focusin();
public static native void focusout(); public static native void focusout();
public static native void audio(); public static native void audio();
public static native void singleton(String p_name,Object p_object); public static native void singleton(String p_name, Object p_object);
public static native void method(String p_sname,String p_name,String p_ret,String[] p_params); public static native void method(String p_sname, String p_name, String p_ret, String[] p_params);
public static native String getGlobal(String p_key); public static native String getGlobal(String p_key);
public static native void callobject(int p_ID, String p_method, Object[] p_params); public static native void callobject(int p_ID, String p_method, Object[] p_params);
public static native void calldeferred(int p_ID, String p_method, Object[] p_params); public static native void calldeferred(int p_ID, String p_method, Object[] p_params);
public static native void setVirtualKeyboardHeight(int p_height); public static native void setVirtualKeyboardHeight(int p_height);
} }

View file

@ -40,7 +40,6 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class GodotPaymentV3 extends Godot.SingletonBase { public class GodotPaymentV3 extends Godot.SingletonBase {
private Godot activity; private Godot activity;
@ -67,8 +66,8 @@ public class GodotPaymentV3 extends Godot.SingletonBase {
public GodotPaymentV3(Activity p_activity) { public GodotPaymentV3(Activity p_activity) {
registerClass("GodotPayments", new String[]{"purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix", "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased", "setAutoConsume", "consume", "querySkuDetails"}); registerClass("GodotPayments", new String[] { "purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix", "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased", "setAutoConsume", "consume", "querySkuDetails" });
activity = (Godot) p_activity; activity = (Godot)p_activity;
mPaymentManager = activity.getPaymentsManager(); mPaymentManager = activity.getPaymentsManager();
mPaymentManager.setBaseSingleton(this); mPaymentManager.setBaseSingleton(this);
} }
@ -89,32 +88,32 @@ public class GodotPaymentV3 extends Godot.SingletonBase {
} }
public void callbackSuccess(String ticket, String signature, String sku) { public void callbackSuccess(String ticket, String signature, String sku) {
GodotLib.calldeferred(purchaseCallbackId, "purchase_success", new Object[]{ticket, signature, sku}); GodotLib.calldeferred(purchaseCallbackId, "purchase_success", new Object[] { ticket, signature, sku });
} }
public void callbackSuccessProductMassConsumed(String ticket, String signature, String sku) { public void callbackSuccessProductMassConsumed(String ticket, String signature, String sku) {
Log.d(this.getClass().getName(), "callbackSuccessProductMassConsumed > " + ticket + "," + signature + "," + sku); Log.d(this.getClass().getName(), "callbackSuccessProductMassConsumed > " + ticket + "," + signature + "," + sku);
GodotLib.calldeferred(purchaseCallbackId, "consume_success", new Object[]{ticket, signature, sku}); GodotLib.calldeferred(purchaseCallbackId, "consume_success", new Object[] { ticket, signature, sku });
} }
public void callbackSuccessNoUnconsumedPurchases() { public void callbackSuccessNoUnconsumedPurchases() {
GodotLib.calldeferred(purchaseCallbackId, "consume_not_required", new Object[]{}); GodotLib.calldeferred(purchaseCallbackId, "consume_not_required", new Object[] {});
} }
public void callbackFailConsume() { public void callbackFailConsume() {
GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[]{}); GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[] {});
} }
public void callbackFail() { public void callbackFail() {
GodotLib.calldeferred(purchaseCallbackId, "purchase_fail", new Object[]{}); GodotLib.calldeferred(purchaseCallbackId, "purchase_fail", new Object[] {});
} }
public void callbackCancel() { public void callbackCancel() {
GodotLib.calldeferred(purchaseCallbackId, "purchase_cancel", new Object[]{}); GodotLib.calldeferred(purchaseCallbackId, "purchase_cancel", new Object[] {});
} }
public void callbackAlreadyOwned(String sku) { public void callbackAlreadyOwned(String sku) {
GodotLib.calldeferred(purchaseCallbackId, "purchase_owned", new Object[]{sku}); GodotLib.calldeferred(purchaseCallbackId, "purchase_owned", new Object[] { sku });
} }
public int getPurchaseCallbackId() { public int getPurchaseCallbackId() {
@ -161,7 +160,7 @@ public class GodotPaymentV3 extends Godot.SingletonBase {
// callback for requestPurchased() // callback for requestPurchased()
public void callbackPurchased(String receipt, String signature, String sku) { public void callbackPurchased(String receipt, String signature, String sku) {
GodotLib.calldeferred(purchaseCallbackId, "has_purchased", new Object[]{receipt, signature, sku}); GodotLib.calldeferred(purchaseCallbackId, "has_purchased", new Object[] { receipt, signature, sku });
} }
// consume item automatically after purchase. default is true. // consume item automatically after purchase. default is true.
@ -210,10 +209,10 @@ public class GodotPaymentV3 extends Godot.SingletonBase {
} }
public void completeSkuDetail() { public void completeSkuDetail() {
GodotLib.calldeferred(purchaseCallbackId, "sku_details_complete", new Object[]{mSkuDetails}); GodotLib.calldeferred(purchaseCallbackId, "sku_details_complete", new Object[] { mSkuDetails });
} }
public void errorSkuDetail(String errorMessage) { public void errorSkuDetail(String errorMessage) {
GodotLib.calldeferred(purchaseCallbackId, "sku_details_error", new Object[]{errorMessage}); GodotLib.calldeferred(purchaseCallbackId, "sku_details_error", new Object[] { errorMessage });
} }
} }

View file

@ -77,20 +77,19 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
private static Context ctx; private static Context ctx;
private static GodotIO io; private static GodotIO io;
private static boolean firsttime=true; private static boolean firsttime = true;
private static boolean use_gl3=false; private static boolean use_gl3 = false;
private static boolean use_32=false; private static boolean use_32 = false;
private Godot activity; private Godot activity;
private InputManagerCompat mInputManager; private InputManagerCompat mInputManager;
public GodotView(Context context,GodotIO p_io,boolean p_use_gl3, boolean p_use_32_bits, Godot p_activity) { public GodotView(Context context, GodotIO p_io, boolean p_use_gl3, boolean p_use_32_bits, Godot p_activity) {
super(context); super(context);
ctx=context; ctx = context;
io=p_io; io = p_io;
use_gl3=p_use_gl3; use_gl3 = p_use_gl3;
use_32=p_use_32_bits; use_32 = p_use_32_bits;
activity = p_activity; activity = p_activity;
@ -101,14 +100,15 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
mInputManager = InputManagerCompat.Factory.getInputManager(this.getContext()); mInputManager = InputManagerCompat.Factory.getInputManager(this.getContext());
mInputManager.registerInputDeviceListener(this, null); mInputManager.registerInputDeviceListener(this, null);
init(false, 16, 0); init(false, 16, 0);
} }
public GodotView(Context context, boolean translucent, int depth, int stencil) { public GodotView(Context context, boolean translucent, int depth, int stencil) {
super(context); super(context);
init(translucent, depth, stencil); init(translucent, depth, stencil);
} }
@Override public boolean onTouchEvent (MotionEvent event) { @Override
public boolean onTouchEvent(MotionEvent event) {
return activity.gotTouchEvent(event); return activity.gotTouchEvent(event);
}; };
@ -196,16 +196,17 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
ArrayList<joystick> joy_devices = new ArrayList<joystick>(); ArrayList<joystick> joy_devices = new ArrayList<joystick>();
private int find_joy_device(int device_id) { private int find_joy_device(int device_id) {
for (int i=0; i<joy_devices.size(); i++) { for (int i = 0; i < joy_devices.size(); i++) {
if (joy_devices.get(i).device_id == device_id) { if (joy_devices.get(i).device_id == device_id) {
return i; return i;
} }
} }
onInputDeviceAdded(device_id); onInputDeviceAdded(device_id);
return joy_devices.size() - 1; return joy_devices.size() - 1;
} }
@Override public void onInputDeviceAdded(int deviceId) { @Override
public void onInputDeviceAdded(int deviceId) {
joystick joy = new joystick(); joystick joy = new joystick();
joy.device_id = deviceId; joy.device_id = deviceId;
final int id = joy_devices.size(); final int id = joy_devices.size();
@ -219,8 +220,7 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
for (InputDevice.MotionRange range : ranges) { for (InputDevice.MotionRange range : ranges) {
if (range.getAxis() == MotionEvent.AXIS_HAT_X || range.getAxis() == MotionEvent.AXIS_HAT_Y) { if (range.getAxis() == MotionEvent.AXIS_HAT_X || range.getAxis() == MotionEvent.AXIS_HAT_Y) {
joy.hats.add(range); joy.hats.add(range);
} } else {
else {
joy.axes.add(range); joy.axes.add(range);
} }
} }
@ -231,9 +231,10 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
GodotLib.joyconnectionchanged(id, true, name); GodotLib.joyconnectionchanged(id, true, name);
} }
}); });
} }
@Override public void onInputDeviceRemoved(int deviceId) { @Override
public void onInputDeviceRemoved(int deviceId) {
final int id = find_joy_device(deviceId); final int id = find_joy_device(deviceId);
joy_devices.remove(id); joy_devices.remove(id);
queueEvent(new Runnable() { queueEvent(new Runnable() {
@ -244,10 +245,11 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
}); });
} }
@Override public void onInputDeviceChanged(int deviceId) { @Override
public void onInputDeviceChanged(int deviceId) {
} }
@Override public boolean onKeyUp(final int keyCode, KeyEvent event) { @Override
public boolean onKeyUp(final int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) { if (keyCode == KeyEvent.KEYCODE_BACK) {
return true; return true;
@ -282,7 +284,8 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
return super.onKeyUp(keyCode, event); return super.onKeyUp(keyCode, event);
}; };
@Override public boolean onKeyDown(final int keyCode, KeyEvent event) { @Override
public boolean onKeyDown(final int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) { if (keyCode == KeyEvent.KEYCODE_BACK) {
activity.onBackPressed(); activity.onBackPressed();
@ -326,7 +329,8 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
return super.onKeyDown(keyCode, event); return super.onKeyDown(keyCode, event);
} }
@Override public boolean onGenericMotionEvent(MotionEvent event) { @Override
public boolean onGenericMotionEvent(MotionEvent event) {
if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK && event.getAction() == MotionEvent.ACTION_MOVE) { if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK && event.getAction() == MotionEvent.ACTION_MOVE) {
@ -335,7 +339,7 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
for (int i = 0; i < joy.axes.size(); i++) { for (int i = 0; i < joy.axes.size(); i++) {
InputDevice.MotionRange range = joy.axes.get(i); InputDevice.MotionRange range = joy.axes.get(i);
final float value = (event.getAxisValue(range.getAxis()) - range.getMin() ) / range.getRange() * 2.0f - 1.0f; final float value = (event.getAxisValue(range.getAxis()) - range.getMin()) / range.getRange() * 2.0f - 1.0f;
//Log.e(TAG, String.format("axis event: %d, value %f", i, value)); //Log.e(TAG, String.format("axis event: %d, value %f", i, value));
final int idx = i; final int idx = i;
queueEvent(new Runnable() { queueEvent(new Runnable() {
@ -346,9 +350,9 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
}); });
} }
for (int i = 0; i < joy.hats.size(); i+=2) { for (int i = 0; i < joy.hats.size(); i += 2) {
final int hatX = Math.round(event.getAxisValue(joy.hats.get(i).getAxis())); final int hatX = Math.round(event.getAxisValue(joy.hats.get(i).getAxis()));
final int hatY = Math.round(event.getAxisValue(joy.hats.get(i+1).getAxis())); final int hatY = Math.round(event.getAxisValue(joy.hats.get(i + 1).getAxis()));
//Log.e(TAG, String.format("HAT EVENT %d, %d", hatX, hatY)); //Log.e(TAG, String.format("HAT EVENT %d, %d", hatX, hatY));
queueEvent(new Runnable() { queueEvent(new Runnable() {
@Override @Override
@ -363,8 +367,7 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
return super.onGenericMotionEvent(event); return super.onGenericMotionEvent(event);
}; };
private void init(boolean translucent, int depth, int stencil) {
private void init(boolean translucent, int depth, int stencil) {
this.setFocusableInTouchMode(true); this.setFocusableInTouchMode(true);
/* By default, GLSurfaceView() creates a RGB_565 opaque surface. /* By default, GLSurfaceView() creates a RGB_565 opaque surface.
@ -388,14 +391,14 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
*/ */
if (use_32) { if (use_32) {
setEGLConfigChooser( translucent ? setEGLConfigChooser(translucent ?
new FallbackConfigChooser(8, 8, 8, 8, 24, stencil, new ConfigChooser(8, 8, 8, 8, 16, stencil)) : new FallbackConfigChooser(8, 8, 8, 8, 24, stencil, new ConfigChooser(8, 8, 8, 8, 16, stencil)) :
new FallbackConfigChooser(8, 8, 8, 8, 24, stencil, new ConfigChooser(5, 6, 5, 0, 16, stencil)) ); new FallbackConfigChooser(8, 8, 8, 8, 24, stencil, new ConfigChooser(5, 6, 5, 0, 16, stencil)));
} else { } else {
setEGLConfigChooser( translucent ? setEGLConfigChooser(translucent ?
new ConfigChooser(8, 8, 8, 8, 16, stencil) : new ConfigChooser(8, 8, 8, 8, 16, stencil) :
new ConfigChooser(5, 6, 5, 0, 16, stencil) ); new ConfigChooser(5, 6, 5, 0, 16, stencil));
} }
/* Set the renderer responsible for frame rendering */ /* Set the renderer responsible for frame rendering */
@ -403,33 +406,33 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
} }
private static class ContextFactory implements GLSurfaceView.EGLContextFactory { private static class ContextFactory implements GLSurfaceView.EGLContextFactory {
private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098; private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) { public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) {
if (use_gl3) if (use_gl3)
Log.w(TAG, "creating OpenGL ES 3.0 context :"); Log.w(TAG, "creating OpenGL ES 3.0 context :");
else else
Log.w(TAG, "creating OpenGL ES 2.0 context :"); Log.w(TAG, "creating OpenGL ES 2.0 context :");
checkEglError("Before eglCreateContext", egl); checkEglError("Before eglCreateContext", egl);
int[] attrib_list2 = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE }; int[] attrib_list2 = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE };
int[] attrib_list3 = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL10.EGL_NONE }; int[] attrib_list3 = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL10.EGL_NONE };
EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, use_gl3?attrib_list3:attrib_list2); EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, use_gl3 ? attrib_list3 : attrib_list2);
checkEglError("After eglCreateContext", egl); checkEglError("After eglCreateContext", egl);
return context; return context;
}
public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) {
egl.eglDestroyContext(display, context);
}
} }
public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) { private static void checkEglError(String prompt, EGL10 egl) {
egl.eglDestroyContext(display, context); int error;
while ((error = egl.eglGetError()) != EGL10.EGL_SUCCESS) {
Log.e(TAG, String.format("%s: EGL error: 0x%x", prompt, error));
}
} }
} /* Fallback if 32bit View is not supported*/
private static void checkEglError(String prompt, EGL10 egl) {
int error;
while ((error = egl.eglGetError()) != EGL10.EGL_SUCCESS) {
Log.e(TAG, String.format("%s: EGL error: 0x%x", prompt, error));
}
}
/* Fallback if 32bit View is not supported*/
private static class FallbackConfigChooser extends ConfigChooser { private static class FallbackConfigChooser extends ConfigChooser {
private ConfigChooser fallback; private ConfigChooser fallback;
@ -438,17 +441,17 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
this.fallback = fallback; this.fallback = fallback;
} }
@Override @Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) { public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) {
EGLConfig ec = super.chooseConfig(egl, display, configs); EGLConfig ec = super.chooseConfig(egl, display, configs);
if (ec == null) { if (ec == null) {
Log.w(TAG, "Trying ConfigChooser fallback"); Log.w(TAG, "Trying ConfigChooser fallback");
ec = fallback.chooseConfig(egl, display, configs); ec = fallback.chooseConfig(egl, display, configs);
use_32=false; use_32 = false;
} }
return ec; return ec;
} }
} }
private static class ConfigChooser implements GLSurfaceView.EGLConfigChooser { private static class ConfigChooser implements GLSurfaceView.EGLConfigChooser {
@ -467,46 +470,46 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
*/ */
private static int EGL_OPENGL_ES2_BIT = 4; private static int EGL_OPENGL_ES2_BIT = 4;
private static int[] s_configAttribs2 = private static int[] s_configAttribs2 =
{ {
EGL10.EGL_RED_SIZE, 4, EGL10.EGL_RED_SIZE, 4,
EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4,
EGL10.EGL_BLUE_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4,
// EGL10.EGL_DEPTH_SIZE, 16, // EGL10.EGL_DEPTH_SIZE, 16,
// EGL10.EGL_STENCIL_SIZE, EGL10.EGL_DONT_CARE, // EGL10.EGL_STENCIL_SIZE, EGL10.EGL_DONT_CARE,
EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL10.EGL_NONE EGL10.EGL_NONE
}; };
private static int[] s_configAttribs3 = private static int[] s_configAttribs3 =
{ {
EGL10.EGL_RED_SIZE, 4, EGL10.EGL_RED_SIZE, 4,
EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4,
EGL10.EGL_BLUE_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4,
// EGL10.EGL_DEPTH_SIZE, 16, // EGL10.EGL_DEPTH_SIZE, 16,
// EGL10.EGL_STENCIL_SIZE, EGL10.EGL_DONT_CARE, // EGL10.EGL_STENCIL_SIZE, EGL10.EGL_DONT_CARE,
EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, //apparently there is no EGL_OPENGL_ES3_BIT EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, //apparently there is no EGL_OPENGL_ES3_BIT
EGL10.EGL_NONE EGL10.EGL_NONE
}; };
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
/* Get the number of minimally matching EGL configurations /* Get the number of minimally matching EGL configurations
*/ */
int[] num_config = new int[1]; int[] num_config = new int[1];
egl.eglChooseConfig(display, use_gl3?s_configAttribs3:s_configAttribs2, null, 0, num_config); egl.eglChooseConfig(display, use_gl3 ? s_configAttribs3 : s_configAttribs2, null, 0, num_config);
int numConfigs = num_config[0]; int numConfigs = num_config[0];
if (numConfigs <= 0) { if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec"); throw new IllegalArgumentException("No configs match configSpec");
} }
/* Allocate then read the array of minimally matching EGL configs /* Allocate then read the array of minimally matching EGL configs
*/ */
EGLConfig[] configs = new EGLConfig[numConfigs]; EGLConfig[] configs = new EGLConfig[numConfigs];
egl.eglChooseConfig(display, use_gl3?s_configAttribs3:s_configAttribs2, configs, numConfigs, num_config); egl.eglChooseConfig(display, use_gl3 ? s_configAttribs3 : s_configAttribs2, configs, numConfigs, num_config);
if (DEBUG) { if (DEBUG) {
printConfigs(egl, display, configs); printConfigs(egl, display, configs);
} }
/* Now return the "best" one /* Now return the "best" one
*/ */
@ -514,54 +517,54 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
} }
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
EGLConfig[] configs) { EGLConfig[] configs) {
for(EGLConfig config : configs) { for (EGLConfig config : configs) {
int d = findConfigAttrib(egl, display, config, int d = findConfigAttrib(egl, display, config,
EGL10.EGL_DEPTH_SIZE, 0); EGL10.EGL_DEPTH_SIZE, 0);
int s = findConfigAttrib(egl, display, config, int s = findConfigAttrib(egl, display, config,
EGL10.EGL_STENCIL_SIZE, 0); EGL10.EGL_STENCIL_SIZE, 0);
// We need at least mDepthSize and mStencilSize bits // We need at least mDepthSize and mStencilSize bits
if (d < mDepthSize || s < mStencilSize) if (d < mDepthSize || s < mStencilSize)
continue; continue;
// We want an *exact* match for red/green/blue/alpha // We want an *exact* match for red/green/blue/alpha
int r = findConfigAttrib(egl, display, config, int r = findConfigAttrib(egl, display, config,
EGL10.EGL_RED_SIZE, 0); EGL10.EGL_RED_SIZE, 0);
int g = findConfigAttrib(egl, display, config, int g = findConfigAttrib(egl, display, config,
EGL10.EGL_GREEN_SIZE, 0); EGL10.EGL_GREEN_SIZE, 0);
int b = findConfigAttrib(egl, display, config, int b = findConfigAttrib(egl, display, config,
EGL10.EGL_BLUE_SIZE, 0); EGL10.EGL_BLUE_SIZE, 0);
int a = findConfigAttrib(egl, display, config, int a = findConfigAttrib(egl, display, config,
EGL10.EGL_ALPHA_SIZE, 0); EGL10.EGL_ALPHA_SIZE, 0);
if (r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize) if (r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize)
return config; return config;
} }
return null; return null;
} }
private int findConfigAttrib(EGL10 egl, EGLDisplay display, private int findConfigAttrib(EGL10 egl, EGLDisplay display,
EGLConfig config, int attribute, int defaultValue) { EGLConfig config, int attribute, int defaultValue) {
if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) { if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
return mValue[0]; return mValue[0];
} }
return defaultValue; return defaultValue;
} }
private void printConfigs(EGL10 egl, EGLDisplay display, private void printConfigs(EGL10 egl, EGLDisplay display,
EGLConfig[] configs) { EGLConfig[] configs) {
int numConfigs = configs.length; int numConfigs = configs.length;
Log.w(TAG, String.format("%d configurations", numConfigs)); Log.w(TAG, String.format("%d configurations", numConfigs));
for (int i = 0; i < numConfigs; i++) { for (int i = 0; i < numConfigs; i++) {
Log.w(TAG, String.format("Configuration %d:\n", i)); Log.w(TAG, String.format("Configuration %d:\n", i));
printConfig(egl, display, configs[i]); printConfig(egl, display, configs[i]);
} }
} }
private void printConfig(EGL10 egl, EGLDisplay display, private void printConfig(EGL10 egl, EGLDisplay display,
EGLConfig config) { EGLConfig config) {
int[] attributes = { int[] attributes = {
EGL10.EGL_BUFFER_SIZE, EGL10.EGL_BUFFER_SIZE,
EGL10.EGL_ALPHA_SIZE, EGL10.EGL_ALPHA_SIZE,
@ -634,14 +637,15 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
}; };
int[] value = new int[1]; int[] value = new int[1];
for (int i = 0; i < attributes.length; i++) { for (int i = 0; i < attributes.length; i++) {
int attribute = attributes[i]; int attribute = attributes[i];
String name = names[i]; String name = names[i];
if ( egl.eglGetConfigAttrib(display, config, attribute, value)) { if (egl.eglGetConfigAttrib(display, config, attribute, value)) {
Log.w(TAG, String.format(" %s: %d\n", name, value[0])); Log.w(TAG, String.format(" %s: %d\n", name, value[0]));
} else { } else {
// Log.w(TAG, String.format(" %s: failed\n", name)); // Log.w(TAG, String.format(" %s: failed\n", name));
while (egl.eglGetError() != EGL10.EGL_SUCCESS); while (egl.eglGetError() != EGL10.EGL_SUCCESS)
} ;
}
} }
} }
@ -657,19 +661,18 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener {
private static class Renderer implements GLSurfaceView.Renderer { private static class Renderer implements GLSurfaceView.Renderer {
public void onDrawFrame(GL10 gl) { public void onDrawFrame(GL10 gl) {
GodotLib.step(); GodotLib.step();
for(int i=0;i<Godot.singleton_count;i++) { for (int i = 0; i < Godot.singleton_count; i++) {
Godot.singletons[i].onGLDrawFrame(gl); Godot.singletons[i].onGLDrawFrame(gl);
} }
} }
public void onSurfaceChanged(GL10 gl, int width, int height) { public void onSurfaceChanged(GL10 gl, int width, int height) {
GodotLib.resize(width, height,!firsttime); GodotLib.resize(width, height, !firsttime);
firsttime=false; firsttime = false;
for(int i=0;i<Godot.singleton_count;i++) { for (int i = 0; i < Godot.singleton_count; i++) {
Godot.singletons[i].onGLSurfaceChanged(gl, width, height); Godot.singletons[i].onGLSurfaceChanged(gl, width, height);
} }
} }

View file

@ -70,42 +70,37 @@ public class GodotEditText extends EditText {
super(context, attrs, defStyle); super(context, attrs, defStyle);
this.initView(); this.initView();
} }
protected void initView() { protected void initView() {
this.setPadding(0, 0, 0, 0); this.setPadding(0, 0, 0, 0);
this.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); this.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
sHandler = new Handler() { sHandler = new Handler() {
@Override @Override
public void handleMessage(final Message msg) { public void handleMessage(final Message msg) {
switch (msg.what) { switch (msg.what) {
case HANDLER_OPEN_IME_KEYBOARD: case HANDLER_OPEN_IME_KEYBOARD: {
{ GodotEditText edit = (GodotEditText)msg.obj;
GodotEditText edit = (GodotEditText) msg.obj; String text = edit.mOriginText;
String text = edit.mOriginText; if (edit.requestFocus()) {
if (edit.requestFocus()) edit.removeTextChangedListener(edit.mInputWrapper);
{ edit.setText("");
edit.removeTextChangedListener(edit.mInputWrapper); edit.append(text);
edit.setText(""); edit.mInputWrapper.setOriginText(text);
edit.append(text); edit.addTextChangedListener(edit.mInputWrapper);
edit.mInputWrapper.setOriginText(text); final InputMethodManager imm = (InputMethodManager)mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
edit.addTextChangedListener(edit.mInputWrapper); imm.showSoftInput(edit, 0);
final InputMethodManager imm = (InputMethodManager) mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edit, 0);
}
} }
break; } break;
case HANDLER_CLOSE_IME_KEYBOARD: case HANDLER_CLOSE_IME_KEYBOARD: {
{ GodotEditText edit = (GodotEditText)msg.obj;
GodotEditText edit = (GodotEditText) msg.obj;
edit.removeTextChangedListener(mInputWrapper);
edit.removeTextChangedListener(mInputWrapper); final InputMethodManager imm = (InputMethodManager)mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
final InputMethodManager imm = (InputMethodManager) mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
imm.hideSoftInputFromWindow(edit.getWindowToken(), 0); edit.mView.requestFocus();
edit.mView.requestFocus(); } break;
}
break;
} }
} }
}; };
@ -116,7 +111,7 @@ public class GodotEditText extends EditText {
// =========================================================== // ===========================================================
public void setView(final GodotView view) { public void setView(final GodotView view) {
this.mView = view; this.mView = view;
if(mInputWrapper == null) if (mInputWrapper == null)
mInputWrapper = new GodotTextInputWrapper(mView, this); mInputWrapper = new GodotTextInputWrapper(mView, this);
this.setOnEditorActionListener(mInputWrapper); this.setOnEditorActionListener(mInputWrapper);
view.requestFocus(); view.requestFocus();
@ -125,7 +120,7 @@ public class GodotEditText extends EditText {
// =========================================================== // ===========================================================
// Methods for/from SuperClass/Interfaces // Methods for/from SuperClass/Interfaces
// =========================================================== // ===========================================================
@Override @Override
public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) { public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
super.onKeyDown(keyCode, keyEvent); super.onKeyDown(keyCode, keyEvent);
@ -142,7 +137,7 @@ public class GodotEditText extends EditText {
// =========================================================== // ===========================================================
public void showKeyboard(String p_existing_text) { public void showKeyboard(String p_existing_text) {
this.mOriginText = p_existing_text; this.mOriginText = p_existing_text;
final Message msg = new Message(); final Message msg = new Message();
msg.what = HANDLER_OPEN_IME_KEYBOARD; msg.what = HANDLER_OPEN_IME_KEYBOARD;
msg.obj = this; msg.obj = this;
@ -155,7 +150,7 @@ public class GodotEditText extends EditText {
msg.obj = this; msg.obj = this;
sHandler.sendMessage(msg); sHandler.sendMessage(msg);
} }
// =========================================================== // ===========================================================
// Inner and Anonymous Classes // Inner and Anonymous Classes
// =========================================================== // ===========================================================

View file

@ -67,7 +67,7 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene
private boolean isFullScreenEdit() { private boolean isFullScreenEdit() {
final TextView textField = this.mEdit; final TextView textField = this.mEdit;
final InputMethodManager imm = (InputMethodManager) textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); final InputMethodManager imm = (InputMethodManager)textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isFullscreenMode(); return imm.isFullscreenMode();
} }
@ -81,7 +81,6 @@ public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListene
@Override @Override
public void afterTextChanged(final Editable s) { public void afterTextChanged(final Editable s) {
} }
@Override @Override

View file

@ -23,118 +23,118 @@ import android.view.InputDevice;
import android.view.MotionEvent; import android.view.MotionEvent;
public interface InputManagerCompat { public interface InputManagerCompat {
/** /**
* Gets information about the input device with the specified id. * Gets information about the input device with the specified id.
* *
* @param id The device id * @param id The device id
* @return The input device or null if not found * @return The input device or null if not found
*/ */
public InputDevice getInputDevice(int id); public InputDevice getInputDevice(int id);
/** /**
* Gets the ids of all input devices in the system. * Gets the ids of all input devices in the system.
* *
* @return The input device ids. * @return The input device ids.
*/ */
public int[] getInputDeviceIds(); public int[] getInputDeviceIds();
/** /**
* Registers an input device listener to receive notifications about when * Registers an input device listener to receive notifications about when
* input devices are added, removed or changed. * input devices are added, removed or changed.
* *
* @param listener The listener to register. * @param listener The listener to register.
* @param handler The handler on which the listener should be invoked, or * @param handler The handler on which the listener should be invoked, or
* null if the listener should be invoked on the calling thread's * null if the listener should be invoked on the calling thread's
* looper. * looper.
*/ */
public void registerInputDeviceListener(InputManagerCompat.InputDeviceListener listener, public void registerInputDeviceListener(InputManagerCompat.InputDeviceListener listener,
Handler handler); Handler handler);
/** /**
* Unregisters an input device listener. * Unregisters an input device listener.
* *
* @param listener The listener to unregister. * @param listener The listener to unregister.
*/ */
public void unregisterInputDeviceListener(InputManagerCompat.InputDeviceListener listener); public void unregisterInputDeviceListener(InputManagerCompat.InputDeviceListener listener);
/* /*
* The following three calls are to simulate V16 behavior on pre-Jellybean * The following three calls are to simulate V16 behavior on pre-Jellybean
* devices. If you don't call them, your callback will never be called * devices. If you don't call them, your callback will never be called
* pre-API 16. * pre-API 16.
*/ */
/** /**
* Pass the motion events to the InputManagerCompat. This is used to * Pass the motion events to the InputManagerCompat. This is used to
* optimize for polling for controllers. If you do not pass these events in, * optimize for polling for controllers. If you do not pass these events in,
* polling will cause regular object creation. * polling will cause regular object creation.
* *
* @param event the motion event from the app * @param event the motion event from the app
*/ */
public void onGenericMotionEvent(MotionEvent event); public void onGenericMotionEvent(MotionEvent event);
/** /**
* Tell the V9 input manager that it should stop polling for disconnected * Tell the V9 input manager that it should stop polling for disconnected
* devices. You can call this during onPause in your activity, although you * devices. You can call this during onPause in your activity, although you
* might want to call it whenever your game is not active (or whenever you * might want to call it whenever your game is not active (or whenever you
* don't care about being notified of new input devices) * don't care about being notified of new input devices)
*/ */
public void onPause(); public void onPause();
/** /**
* Tell the V9 input manager that it should start polling for disconnected * Tell the V9 input manager that it should start polling for disconnected
* devices. You can call this during onResume in your activity, although you * devices. You can call this during onResume in your activity, although you
* might want to call it less often (only when the gameplay is actually * might want to call it less often (only when the gameplay is actually
* active) * active)
*/ */
public void onResume(); public void onResume();
public interface InputDeviceListener { public interface InputDeviceListener {
/** /**
* Called whenever the input manager detects that a device has been * Called whenever the input manager detects that a device has been
* added. This will only be called in the V9 version when a motion event * added. This will only be called in the V9 version when a motion event
* is detected. * is detected.
* *
* @param deviceId The id of the input device that was added. * @param deviceId The id of the input device that was added.
*/ */
void onInputDeviceAdded(int deviceId); void onInputDeviceAdded(int deviceId);
/** /**
* Called whenever the properties of an input device have changed since * Called whenever the properties of an input device have changed since
* they were last queried. This will not be called for the V9 version of * they were last queried. This will not be called for the V9 version of
* the API. * the API.
* *
* @param deviceId The id of the input device that changed. * @param deviceId The id of the input device that changed.
*/ */
void onInputDeviceChanged(int deviceId); void onInputDeviceChanged(int deviceId);
/** /**
* Called whenever the input manager detects that a device has been * Called whenever the input manager detects that a device has been
* removed. For the V9 version, this can take some time depending on the * removed. For the V9 version, this can take some time depending on the
* poll rate. * poll rate.
* *
* @param deviceId The id of the input device that was removed. * @param deviceId The id of the input device that was removed.
*/ */
void onInputDeviceRemoved(int deviceId); void onInputDeviceRemoved(int deviceId);
} }
/** /**
* Use this to construct a compatible InputManager. * Use this to construct a compatible InputManager.
*/ */
public static class Factory { public static class Factory {
/** /**
* Constructs and returns a compatible InputManger * Constructs and returns a compatible InputManger
* *
* @param context the Context that will be used to get the system * @param context the Context that will be used to get the system
* service from * service from
* @return a compatible implementation of InputManager * @return a compatible implementation of InputManager
*/ */
public static InputManagerCompat getInputManager(Context context) { public static InputManagerCompat getInputManager(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return new InputManagerV16(context); return new InputManagerV16(context);
} else { } else {
return new InputManagerV9(); return new InputManagerV9();
} }
} }
} }
} }

View file

@ -30,78 +30,74 @@ import java.util.Map;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class InputManagerV16 implements InputManagerCompat { public class InputManagerV16 implements InputManagerCompat {
private final InputManager mInputManager; private final InputManager mInputManager;
private final Map<InputManagerCompat.InputDeviceListener, V16InputDeviceListener> mListeners; private final Map<InputManagerCompat.InputDeviceListener, V16InputDeviceListener> mListeners;
public InputManagerV16(Context context) { public InputManagerV16(Context context) {
mInputManager = (InputManager) context.getSystemService(Context.INPUT_SERVICE); mInputManager = (InputManager)context.getSystemService(Context.INPUT_SERVICE);
mListeners = new HashMap<InputManagerCompat.InputDeviceListener, V16InputDeviceListener>(); mListeners = new HashMap<InputManagerCompat.InputDeviceListener, V16InputDeviceListener>();
} }
@Override @Override
public InputDevice getInputDevice(int id) { public InputDevice getInputDevice(int id) {
return mInputManager.getInputDevice(id); return mInputManager.getInputDevice(id);
} }
@Override @Override
public int[] getInputDeviceIds() { public int[] getInputDeviceIds() {
return mInputManager.getInputDeviceIds(); return mInputManager.getInputDeviceIds();
} }
static class V16InputDeviceListener implements InputManager.InputDeviceListener { static class V16InputDeviceListener implements InputManager.InputDeviceListener {
final InputManagerCompat.InputDeviceListener mIDL; final InputManagerCompat.InputDeviceListener mIDL;
public V16InputDeviceListener(InputDeviceListener idl) { public V16InputDeviceListener(InputDeviceListener idl) {
mIDL = idl; mIDL = idl;
} }
@Override @Override
public void onInputDeviceAdded(int deviceId) { public void onInputDeviceAdded(int deviceId) {
mIDL.onInputDeviceAdded(deviceId); mIDL.onInputDeviceAdded(deviceId);
} }
@Override @Override
public void onInputDeviceChanged(int deviceId) { public void onInputDeviceChanged(int deviceId) {
mIDL.onInputDeviceChanged(deviceId); mIDL.onInputDeviceChanged(deviceId);
} }
@Override @Override
public void onInputDeviceRemoved(int deviceId) { public void onInputDeviceRemoved(int deviceId) {
mIDL.onInputDeviceRemoved(deviceId); mIDL.onInputDeviceRemoved(deviceId);
} }
}
} @Override
public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) {
V16InputDeviceListener v16Listener = new V16InputDeviceListener(listener);
mInputManager.registerInputDeviceListener(v16Listener, handler);
mListeners.put(listener, v16Listener);
}
@Override @Override
public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) { public void unregisterInputDeviceListener(InputDeviceListener listener) {
V16InputDeviceListener v16Listener = new V16InputDeviceListener(listener); V16InputDeviceListener curListener = mListeners.remove(listener);
mInputManager.registerInputDeviceListener(v16Listener, handler); if (null != curListener) {
mListeners.put(listener, v16Listener); mInputManager.unregisterInputDeviceListener(curListener);
} }
}
@Override @Override
public void unregisterInputDeviceListener(InputDeviceListener listener) { public void onGenericMotionEvent(MotionEvent event) {
V16InputDeviceListener curListener = mListeners.remove(listener); // unused in V16
if (null != curListener) }
{
mInputManager.unregisterInputDeviceListener(curListener);
}
} @Override
public void onPause() {
@Override // unused in V16
public void onGenericMotionEvent(MotionEvent event) { }
// unused in V16
}
@Override
public void onPause() {
// unused in V16
}
@Override
public void onResume() {
// unused in V16
}
@Override
public void onResume() {
// unused in V16
}
} }

View file

@ -31,181 +31,179 @@ import java.util.Map;
import java.util.Queue; import java.util.Queue;
public class InputManagerV9 implements InputManagerCompat { public class InputManagerV9 implements InputManagerCompat {
private static final String LOG_TAG = "InputManagerV9"; private static final String LOG_TAG = "InputManagerV9";
private static final int MESSAGE_TEST_FOR_DISCONNECT = 101; private static final int MESSAGE_TEST_FOR_DISCONNECT = 101;
private static final long CHECK_ELAPSED_TIME = 3000L; private static final long CHECK_ELAPSED_TIME = 3000L;
private static final int ON_DEVICE_ADDED = 0; private static final int ON_DEVICE_ADDED = 0;
private static final int ON_DEVICE_CHANGED = 1; private static final int ON_DEVICE_CHANGED = 1;
private static final int ON_DEVICE_REMOVED = 2; private static final int ON_DEVICE_REMOVED = 2;
private final SparseArray<long[]> mDevices; private final SparseArray<long[]> mDevices;
private final Map<InputDeviceListener, Handler> mListeners; private final Map<InputDeviceListener, Handler> mListeners;
private final Handler mDefaultHandler; private final Handler mDefaultHandler;
private static class PollingMessageHandler extends Handler { private static class PollingMessageHandler extends Handler {
private final WeakReference<InputManagerV9> mInputManager; private final WeakReference<InputManagerV9> mInputManager;
PollingMessageHandler(InputManagerV9 im) { PollingMessageHandler(InputManagerV9 im) {
mInputManager = new WeakReference<InputManagerV9>(im); mInputManager = new WeakReference<InputManagerV9>(im);
} }
@Override @Override
public void handleMessage(Message msg) { public void handleMessage(Message msg) {
super.handleMessage(msg); super.handleMessage(msg);
switch (msg.what) { switch (msg.what) {
case MESSAGE_TEST_FOR_DISCONNECT: case MESSAGE_TEST_FOR_DISCONNECT:
InputManagerV9 imv = mInputManager.get(); InputManagerV9 imv = mInputManager.get();
if (null != imv) { if (null != imv) {
long time = SystemClock.elapsedRealtime(); long time = SystemClock.elapsedRealtime();
int size = imv.mDevices.size(); int size = imv.mDevices.size();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
long[] lastContact = imv.mDevices.valueAt(i); long[] lastContact = imv.mDevices.valueAt(i);
if (null != lastContact) { if (null != lastContact) {
if (time - lastContact[0] > CHECK_ELAPSED_TIME) { if (time - lastContact[0] > CHECK_ELAPSED_TIME) {
// check to see if the device has been // check to see if the device has been
// disconnected // disconnected
int id = imv.mDevices.keyAt(i); int id = imv.mDevices.keyAt(i);
if (null == InputDevice.getDevice(id)) { if (null == InputDevice.getDevice(id)) {
// disconnected! // disconnected!
imv.notifyListeners(ON_DEVICE_REMOVED, id); imv.notifyListeners(ON_DEVICE_REMOVED, id);
imv.mDevices.remove(id); imv.mDevices.remove(id);
} else { } else {
lastContact[0] = time; lastContact[0] = time;
} }
} }
} }
} }
sendEmptyMessageDelayed(MESSAGE_TEST_FOR_DISCONNECT, sendEmptyMessageDelayed(MESSAGE_TEST_FOR_DISCONNECT,
CHECK_ELAPSED_TIME); CHECK_ELAPSED_TIME);
} }
break; break;
} }
} }
}
} public InputManagerV9() {
mDevices = new SparseArray<long[]>();
mListeners = new HashMap<InputDeviceListener, Handler>();
mDefaultHandler = new PollingMessageHandler(this);
// as a side-effect, populates our collection of watched
// input devices
getInputDeviceIds();
}
public InputManagerV9() { @Override
mDevices = new SparseArray<long[]>(); public InputDevice getInputDevice(int id) {
mListeners = new HashMap<InputDeviceListener, Handler>(); return InputDevice.getDevice(id);
mDefaultHandler = new PollingMessageHandler(this); }
// as a side-effect, populates our collection of watched
// input devices
getInputDeviceIds();
}
@Override @Override
public InputDevice getInputDevice(int id) { public int[] getInputDeviceIds() {
return InputDevice.getDevice(id); // add any hitherto unknown devices to our
} // collection of watched input devices
int[] activeDevices = InputDevice.getDeviceIds();
long time = SystemClock.elapsedRealtime();
for (int id : activeDevices) {
long[] lastContact = mDevices.get(id);
if (null == lastContact) {
// we have a new device
mDevices.put(id, new long[] { time });
}
}
return activeDevices;
}
@Override @Override
public int[] getInputDeviceIds() { public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) {
// add any hitherto unknown devices to our mListeners.remove(listener);
// collection of watched input devices if (handler == null) {
int[] activeDevices = InputDevice.getDeviceIds(); handler = mDefaultHandler;
long time = SystemClock.elapsedRealtime(); }
for ( int id : activeDevices ) { mListeners.put(listener, handler);
long[] lastContact = mDevices.get(id); }
if ( null == lastContact ) {
// we have a new device
mDevices.put(id, new long[] { time });
}
}
return activeDevices;
}
@Override @Override
public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) { public void unregisterInputDeviceListener(InputDeviceListener listener) {
mListeners.remove(listener); mListeners.remove(listener);
if (handler == null) { }
handler = mDefaultHandler;
}
mListeners.put(listener, handler);
}
@Override private void notifyListeners(int why, int deviceId) {
public void unregisterInputDeviceListener(InputDeviceListener listener) { // the state of some device has changed
mListeners.remove(listener); if (!mListeners.isEmpty()) {
} // yes... this will cause an object to get created... hopefully
// it won't happen very often
for (InputDeviceListener listener : mListeners.keySet()) {
Handler handler = mListeners.get(listener);
DeviceEvent odc = DeviceEvent.getDeviceEvent(why, deviceId, listener);
handler.post(odc);
}
}
}
private void notifyListeners(int why, int deviceId) { private static class DeviceEvent implements Runnable {
// the state of some device has changed private int mMessageType;
if (!mListeners.isEmpty()) { private int mId;
// yes... this will cause an object to get created... hopefully private InputDeviceListener mListener;
// it won't happen very often private static Queue<DeviceEvent> sEventQueue = new ArrayDeque<DeviceEvent>();
for (InputDeviceListener listener : mListeners.keySet()) {
Handler handler = mListeners.get(listener);
DeviceEvent odc = DeviceEvent.getDeviceEvent(why, deviceId, listener);
handler.post(odc);
}
}
}
private static class DeviceEvent implements Runnable { private DeviceEvent() {
private int mMessageType; }
private int mId;
private InputDeviceListener mListener;
private static Queue<DeviceEvent> sEventQueue = new ArrayDeque<DeviceEvent>();
private DeviceEvent() { static DeviceEvent getDeviceEvent(int messageType, int id,
} InputDeviceListener listener) {
DeviceEvent curChanged = sEventQueue.poll();
if (null == curChanged) {
curChanged = new DeviceEvent();
}
curChanged.mMessageType = messageType;
curChanged.mId = id;
curChanged.mListener = listener;
return curChanged;
}
static DeviceEvent getDeviceEvent(int messageType, int id, @Override
InputDeviceListener listener) { public void run() {
DeviceEvent curChanged = sEventQueue.poll(); switch (mMessageType) {
if (null == curChanged) { case ON_DEVICE_ADDED:
curChanged = new DeviceEvent(); mListener.onInputDeviceAdded(mId);
} break;
curChanged.mMessageType = messageType; case ON_DEVICE_CHANGED:
curChanged.mId = id; mListener.onInputDeviceChanged(mId);
curChanged.mListener = listener; break;
return curChanged; case ON_DEVICE_REMOVED:
} mListener.onInputDeviceRemoved(mId);
break;
default:
Log.e(LOG_TAG, "Unknown Message Type");
break;
}
// dump this runnable back in the queue
sEventQueue.offer(this);
}
}
@Override @Override
public void run() { public void onGenericMotionEvent(MotionEvent event) {
switch (mMessageType) { // detect new devices
case ON_DEVICE_ADDED: int id = event.getDeviceId();
mListener.onInputDeviceAdded(mId); long[] timeArray = mDevices.get(id);
break; if (null == timeArray) {
case ON_DEVICE_CHANGED: notifyListeners(ON_DEVICE_ADDED, id);
mListener.onInputDeviceChanged(mId); timeArray = new long[1];
break; mDevices.put(id, timeArray);
case ON_DEVICE_REMOVED: }
mListener.onInputDeviceRemoved(mId); long time = SystemClock.elapsedRealtime();
break; timeArray[0] = time;
default: }
Log.e(LOG_TAG, "Unknown Message Type");
break;
}
// dump this runnable back in the queue
sEventQueue.offer(this);
}
}
@Override @Override
public void onGenericMotionEvent(MotionEvent event) { public void onPause() {
// detect new devices mDefaultHandler.removeMessages(MESSAGE_TEST_FOR_DISCONNECT);
int id = event.getDeviceId(); }
long[] timeArray = mDevices.get(id);
if (null == timeArray) {
notifyListeners(ON_DEVICE_ADDED, id);
timeArray = new long[1];
mDevices.put(id, timeArray);
}
long time = SystemClock.elapsedRealtime();
timeArray[0] = time;
}
@Override
public void onPause() {
mDefaultHandler.removeMessages(MESSAGE_TEST_FOR_DISCONNECT);
}
@Override
public void onResume() {
mDefaultHandler.sendEmptyMessage(MESSAGE_TEST_FOR_DISCONNECT);
}
@Override
public void onResume() {
mDefaultHandler.sendEmptyMessage(MESSAGE_TEST_FOR_DISCONNECT);
}
} }

View file

@ -39,33 +39,32 @@ import android.util.Log;
abstract public class ConsumeTask { abstract public class ConsumeTask {
private Context context; private Context context;
private IInAppBillingService mService; private IInAppBillingService mService;
public ConsumeTask(IInAppBillingService mService, Context context ){ public ConsumeTask(IInAppBillingService mService, Context context) {
this.context = context; this.context = context;
this.mService = mService; this.mService = mService;
} }
public void consume(final String sku){ public void consume(final String sku) {
//Log.d("XXX", "Consuming product " + sku); //Log.d("XXX", "Consuming product " + sku);
PaymentsCache pc = new PaymentsCache(context); PaymentsCache pc = new PaymentsCache(context);
Boolean isBlocked = pc.getConsumableFlag("block", sku); Boolean isBlocked = pc.getConsumableFlag("block", sku);
String _token = pc.getConsumableValue("token", sku); String _token = pc.getConsumableValue("token", sku);
//Log.d("XXX", "token " + _token); //Log.d("XXX", "token " + _token);
if(!isBlocked && _token == null){ if (!isBlocked && _token == null) {
//_token = "inapp:"+context.getPackageName()+":android.test.purchased"; //_token = "inapp:"+context.getPackageName()+":android.test.purchased";
//Log.d("XXX", "Consuming product " + sku + " with token " + _token); //Log.d("XXX", "Consuming product " + sku + " with token " + _token);
}else if(!isBlocked){ } else if (!isBlocked) {
//Log.d("XXX", "It is not blocked ¿?"); //Log.d("XXX", "It is not blocked ¿?");
return; return;
}else if(_token == null){ } else if (_token == null) {
//Log.d("XXX", "No token available"); //Log.d("XXX", "No token available");
this.error("No token for sku:" + sku); this.error("No token for sku:" + sku);
return; return;
} }
final String token = _token; final String token = _token;
new AsyncTask<String, String, String>(){ new AsyncTask<String, String, String>() {
@Override @Override
protected String doInBackground(String... params) { protected String doInBackground(String... params) {
@ -73,28 +72,27 @@ abstract public class ConsumeTask {
//Log.d("XXX", "Requesting to release item."); //Log.d("XXX", "Requesting to release item.");
int response = mService.consumePurchase(3, context.getPackageName(), token); int response = mService.consumePurchase(3, context.getPackageName(), token);
//Log.d("XXX", "release response code: " + response); //Log.d("XXX", "release response code: " + response);
if(response == 0 || response == 8){ if (response == 0 || response == 8) {
return null; return null;
} }
} catch (RemoteException e) { } catch (RemoteException e) {
return e.getMessage(); return e.getMessage();
} }
return "Some error"; return "Some error";
} }
protected void onPostExecute(String param){ protected void onPostExecute(String param) {
if(param == null){ if (param == null) {
success( new PaymentsCache(context).getConsumableValue("ticket", sku) ); success(new PaymentsCache(context).getConsumableValue("ticket", sku));
}else{ } else {
error(param); error(param);
} }
} }
}.execute(); }
.execute();
} }
abstract protected void success(String ticket); abstract protected void success(String ticket);
abstract protected void error(String message); abstract protected void error(String message);
} }

View file

@ -36,15 +36,12 @@ import android.os.AsyncTask;
import android.os.RemoteException; import android.os.RemoteException;
import android.util.Log; import android.util.Log;
abstract public class GenericConsumeTask extends AsyncTask<String, String, String>{ abstract public class GenericConsumeTask extends AsyncTask<String, String, String> {
private Context context; private Context context;
private IInAppBillingService mService; private IInAppBillingService mService;
public GenericConsumeTask(Context context, IInAppBillingService mService, String sku, String receipt, String signature, String token) {
public GenericConsumeTask(Context context, IInAppBillingService mService, String sku, String receipt, String signature, String token){
this.context = context; this.context = context;
this.mService = mService; this.mService = mService;
this.sku = sku; this.sku = sku;
@ -52,19 +49,19 @@ abstract public class GenericConsumeTask extends AsyncTask<String, String, Strin
this.signature = signature; this.signature = signature;
this.token = token; this.token = token;
} }
private String sku; private String sku;
private String receipt; private String receipt;
private String signature; private String signature;
private String token; private String token;
@Override @Override
protected String doInBackground(String... params) { protected String doInBackground(String... params) {
try { try {
//Log.d("godot", "Requesting to consume an item with token ." + token); //Log.d("godot", "Requesting to consume an item with token ." + token);
int response = mService.consumePurchase(3, context.getPackageName(), token); int response = mService.consumePurchase(3, context.getPackageName(), token);
//Log.d("godot", "consumePurchase response: " + response); //Log.d("godot", "consumePurchase response: " + response);
if(response == 0 || response == 8){ if (response == 0 || response == 8) {
return null; return null;
} }
} catch (Exception e) { } catch (Exception e) {
@ -72,11 +69,10 @@ abstract public class GenericConsumeTask extends AsyncTask<String, String, Strin
} }
return null; return null;
} }
protected void onPostExecute(String sarasa){ protected void onPostExecute(String sarasa) {
onSuccess(sku, receipt, signature, token); onSuccess(sku, receipt, signature, token);
} }
abstract public void onSuccess(String sku, String receipt, String signature, String token);
abstract public void onSuccess(String sku, String receipt, String signature, String token);
} }

View file

@ -50,28 +50,26 @@ import android.util.Log;
abstract public class HandlePurchaseTask { abstract public class HandlePurchaseTask {
private Activity context; private Activity context;
public HandlePurchaseTask(Activity context ){ public HandlePurchaseTask(Activity context) {
this.context = context; this.context = context;
} }
public void handlePurchaseRequest(int resultCode, Intent data) {
public void handlePurchaseRequest(int resultCode, Intent data){
//Log.d("XXX", "Handling purchase response"); //Log.d("XXX", "Handling purchase response");
//int responseCode = data.getIntExtra("RESPONSE_CODE", 0); //int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
PaymentsCache pc = new PaymentsCache(context); PaymentsCache pc = new PaymentsCache(context);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
//Log.d("XXX", "Purchase data:" + purchaseData); //Log.d("XXX", "Purchase data:" + purchaseData);
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
//Log.d("XXX", "Purchase signature:" + dataSignature); //Log.d("XXX", "Purchase signature:" + dataSignature);
if (resultCode == Activity.RESULT_OK) { if (resultCode == Activity.RESULT_OK) {
try { try {
//Log.d("SARLANGA", purchaseData); //Log.d("SARLANGA", purchaseData);
JSONObject jo = new JSONObject(purchaseData); JSONObject jo = new JSONObject(purchaseData);
//String sku = jo.getString("productId"); //String sku = jo.getString("productId");
//alert("You have bought the " + sku + ". Excellent choice, aventurer!"); //alert("You have bought the " + sku + ". Excellent choice, aventurer!");
@ -82,8 +80,8 @@ abstract public class HandlePurchaseTask {
//Integer state = jo.getInt("purchaseState"); //Integer state = jo.getInt("purchaseState");
String developerPayload = jo.getString("developerPayload"); String developerPayload = jo.getString("developerPayload");
String purchaseToken = jo.getString("purchaseToken"); String purchaseToken = jo.getString("purchaseToken");
if(! pc.getConsumableValue("validation_hash", productId).equals(developerPayload) ) { if (!pc.getConsumableValue("validation_hash", productId).equals(developerPayload)) {
error("Untrusted callback"); error("Untrusted callback");
return; return;
} }
@ -92,13 +90,13 @@ abstract public class HandlePurchaseTask {
pc.setConsumableValue("ticket", productId, purchaseData); pc.setConsumableValue("ticket", productId, purchaseData);
pc.setConsumableFlag("block", productId, true); pc.setConsumableFlag("block", productId, true);
pc.setConsumableValue("token", productId, purchaseToken); pc.setConsumableValue("token", productId, purchaseToken);
success(productId, dataSignature, purchaseData); success(productId, dataSignature, purchaseData);
return; return;
} catch (JSONException e) { } catch (JSONException e) {
error(e.getMessage()); error(e.getMessage());
} }
}else if( resultCode == Activity.RESULT_CANCELED){ } else if (resultCode == Activity.RESULT_CANCELED) {
canceled(); canceled();
} }
} }
@ -106,6 +104,4 @@ abstract public class HandlePurchaseTask {
abstract protected void success(String sku, String signature, String ticket); abstract protected void success(String sku, String signature, String ticket);
abstract protected void error(String message); abstract protected void error(String message);
abstract protected void canceled(); abstract protected void canceled();
} }

View file

@ -34,41 +34,38 @@ import android.content.SharedPreferences;
import android.util.Log; import android.util.Log;
public class PaymentsCache { public class PaymentsCache {
public Context context; public Context context;
public PaymentsCache(Context context){ public PaymentsCache(Context context) {
this.context = context; this.context = context;
} }
public void setConsumableFlag(String set, String sku, Boolean flag){
SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(sku, flag);
editor.commit();
}
public boolean getConsumableFlag(String set, String sku){ public void setConsumableFlag(String set, String sku, Boolean flag) {
SharedPreferences sharedPref = context.getSharedPreferences( SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
"consumables_" + set, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit();
return sharedPref.getBoolean(sku, false); editor.putBoolean(sku, flag);
editor.commit();
} }
public boolean getConsumableFlag(String set, String sku) {
SharedPreferences sharedPref = context.getSharedPreferences(
"consumables_" + set, Context.MODE_PRIVATE);
return sharedPref.getBoolean(sku, false);
}
public void setConsumableValue(String set, String sku, String value){ public void setConsumableValue(String set, String sku, String value) {
SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE); SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit(); SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(sku, value); editor.putString(sku, value);
//Log.d("XXX", "Setting asset: consumables_" + set + ":" + sku); //Log.d("XXX", "Setting asset: consumables_" + set + ":" + sku);
editor.commit(); editor.commit();
} }
public String getConsumableValue(String set, String sku){ public String getConsumableValue(String set, String sku) {
SharedPreferences sharedPref = context.getSharedPreferences( SharedPreferences sharedPref = context.getSharedPreferences(
"consumables_" + set, Context.MODE_PRIVATE); "consumables_" + set, Context.MODE_PRIVATE);
//Log.d("XXX", "Getting asset: consumables_" + set + ":" + sku); //Log.d("XXX", "Getting asset: consumables_" + set + ":" + sku);
return sharedPref.getString(sku, null); return sharedPref.getString(sku, null);
} }
} }

View file

@ -106,7 +106,6 @@ public class PaymentsManager {
@Override @Override
protected void error(String message) { protected void error(String message) {
godotPaymentV3.callbackFail(); godotPaymentV3.callbackFail();
} }
@Override @Override
@ -119,8 +118,8 @@ public class PaymentsManager {
godotPaymentV3.callbackAlreadyOwned(sku); godotPaymentV3.callbackAlreadyOwned(sku);
} }
}.purchase(sku, transactionId); }
.purchase(sku, transactionId);
} }
public void consumeUnconsumedPurchases() { public void consumeUnconsumedPurchases() {
@ -135,16 +134,15 @@ public class PaymentsManager {
protected void error(String message) { protected void error(String message) {
Log.d("godot", "consumeUnconsumedPurchases :" + message); Log.d("godot", "consumeUnconsumedPurchases :" + message);
godotPaymentV3.callbackFailConsume(); godotPaymentV3.callbackFailConsume();
} }
@Override @Override
protected void notRequired() { protected void notRequired() {
Log.d("godot", "callbackSuccessNoUnconsumedPurchases :"); Log.d("godot", "callbackSuccessNoUnconsumedPurchases :");
godotPaymentV3.callbackSuccessNoUnconsumedPurchases(); godotPaymentV3.callbackSuccessNoUnconsumedPurchases();
} }
}.consumeItAll(); }
.consumeItAll();
} }
public void requestPurchased() { public void requestPurchased() {
@ -210,9 +208,9 @@ public class PaymentsManager {
@Override @Override
protected void error(String message) { protected void error(String message) {
godotPaymentV3.callbackFail(); godotPaymentV3.callbackFail();
} }
}.consume(sku); }
.consume(sku);
} }
} }
@ -225,7 +223,8 @@ public class PaymentsManager {
protected void canceled() { protected void canceled() {
godotPaymentV3.callbackCancel(); godotPaymentV3.callbackCancel();
} }
}.handlePurchaseRequest(resultCode, data); }
.handlePurchaseRequest(resultCode, data);
} }
public void validatePurchase(String purchaseToken, final String sku) { public void validatePurchase(String purchaseToken, final String sku) {
@ -246,8 +245,8 @@ public class PaymentsManager {
protected void error(String message) { protected void error(String message) {
godotPaymentV3.callbackFail(); godotPaymentV3.callbackFail();
} }
}.consume(sku); }
.consume(sku);
} }
@Override @Override
@ -259,7 +258,8 @@ public class PaymentsManager {
protected void canceled() { protected void canceled() {
godotPaymentV3.callbackCancel(); godotPaymentV3.callbackCancel();
} }
}.validatePurchase(sku); }
.validatePurchase(sku);
} }
public void setAutoConsume(boolean autoConsume) { public void setAutoConsume(boolean autoConsume) {
@ -278,7 +278,8 @@ public class PaymentsManager {
protected void error(String message) { protected void error(String message) {
godotPaymentV3.callbackFailConsume(); godotPaymentV3.callbackFailConsume();
} }
}.consume(sku); }
.consume(sku);
} }
// Workaround to bug where sometimes response codes come as Long instead of Integer // Workaround to bug where sometimes response codes come as Long instead of Integer
@ -287,8 +288,10 @@ public class PaymentsManager {
if (o == null) { if (o == null) {
//logDebug("Bundle with null response code, assuming OK (known issue)"); //logDebug("Bundle with null response code, assuming OK (known issue)");
return BILLING_RESPONSE_RESULT_OK; return BILLING_RESPONSE_RESULT_OK;
} else if (o instanceof Integer) return ((Integer) o).intValue(); } else if (o instanceof Integer)
else if (o instanceof Long) return (int) ((Long) o).longValue(); return ((Integer)o).intValue();
else if (o instanceof Long)
return (int)((Long)o).longValue();
else { else {
//logError("Unexpected type for bundle response code."); //logError("Unexpected type for bundle response code.");
//logError(o.getClass().getName()); //logError(o.getClass().getName());
@ -304,25 +307,41 @@ public class PaymentsManager {
* It also includes the result code numerically. * It also includes the result code numerically.
*/ */
public static String getResponseDesc(int code) { public static String getResponseDesc(int code) {
String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" + 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/" + "3:Billing Unavailable/4:Item unavailable/"
"8:Item not owned").split("/"); +
String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" + "5:Developer Error/6:Error/7:Item Already Owned/"
"-1002:Bad response received/" + +
"-1003:Purchase signature verification failed/" + "8:Item not owned")
"-1004:Send intent failed/" + .split("/");
"-1005:User cancelled/" + String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/"
"-1006:Unknown purchase response/" + +
"-1007:Missing token/" + "-1002:Bad response received/"
"-1008:Unknown error/" + +
"-1009:Subscriptions not available/" + "-1003:Purchase signature verification failed/"
"-1010:Invalid consumption attempt").split("/"); +
"-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 <= -1000) { if (code <= -1000) {
int index = -1000 - code; int index = -1000 - code;
if (index >= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index]; if (index >= 0 && index < iabhelper_msgs.length)
else return String.valueOf(code) + ":Unknown IAB Helper Error"; return iabhelper_msgs[index];
else
return String.valueOf(code) + ":Unknown IAB Helper Error";
} else if (code < 0 || code >= iab_msgs.length) } else if (code < 0 || code >= iab_msgs.length)
return String.valueOf(code) + ":Unknown"; return String.valueOf(code) + ":Unknown";
else else
@ -375,7 +394,7 @@ public class PaymentsManager {
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST"); ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) { for (String thisResponse : responseList) {
Log.d("godot", "response = "+thisResponse); Log.d("godot", "response = " + thisResponse);
godotPaymentV3.addSkuDetail(thisResponse); godotPaymentV3.addSkuDetail(thisResponse);
} }
} catch (RemoteException e) { } catch (RemoteException e) {
@ -385,7 +404,8 @@ public class PaymentsManager {
} }
godotPaymentV3.completeSkuDetail(); godotPaymentV3.completeSkuDetail();
} }
})).start(); }))
.start();
} }
private GodotPaymentV3 godotPaymentV3; private GodotPaymentV3 godotPaymentV3;
@ -393,5 +413,4 @@ public class PaymentsManager {
public void setBaseSingleton(GodotPaymentV3 godotPaymentV3) { public void setBaseSingleton(GodotPaymentV3 godotPaymentV3) {
this.godotPaymentV3 = godotPaymentV3; this.godotPaymentV3 = godotPaymentV3;
} }
} }

View file

@ -50,17 +50,16 @@ import android.util.Log;
abstract public class PurchaseTask { abstract public class PurchaseTask {
private Activity context; private Activity context;
private IInAppBillingService mService; private IInAppBillingService mService;
public PurchaseTask(IInAppBillingService mService, Activity context ){ public PurchaseTask(IInAppBillingService mService, Activity context) {
this.context = context; this.context = context;
this.mService = mService; this.mService = mService;
} }
private boolean isLooping = false; private boolean isLooping = false;
public void purchase(final String sku, final String transactionId){ public void purchase(final String sku, final String transactionId) {
Log.d("XXX", "Starting purchase for: " + sku); Log.d("XXX", "Starting purchase for: " + sku);
PaymentsCache pc = new PaymentsCache(context); PaymentsCache pc = new PaymentsCache(context);
Boolean isBlocked = pc.getConsumableFlag("block", sku); Boolean isBlocked = pc.getConsumableFlag("block", sku);
@ -75,7 +74,7 @@ abstract public class PurchaseTask {
Bundle buyIntentBundle; Bundle buyIntentBundle;
try { try {
buyIntentBundle = mService.getBuyIntent(3, context.getApplicationContext().getPackageName(), sku, "inapp", hash ); buyIntentBundle = mService.getBuyIntent(3, context.getApplicationContext().getPackageName(), sku, "inapp", hash);
} catch (RemoteException e) { } catch (RemoteException e) {
//Log.d("XXX", "Error: " + e.getMessage()); //Log.d("XXX", "Error: " + e.getMessage());
error(e.getMessage()); error(e.getMessage());
@ -83,50 +82,45 @@ abstract public class PurchaseTask {
} }
Object rc = buyIntentBundle.get("RESPONSE_CODE"); Object rc = buyIntentBundle.get("RESPONSE_CODE");
int responseCode = 0; int responseCode = 0;
if(rc == null){ if (rc == null) {
responseCode = PaymentsManager.BILLING_RESPONSE_RESULT_OK; responseCode = PaymentsManager.BILLING_RESPONSE_RESULT_OK;
}else if( rc instanceof Integer){ } else if (rc instanceof Integer) {
responseCode = ((Integer)rc).intValue(); responseCode = ((Integer)rc).intValue();
}else if( rc instanceof Long){ } else if (rc instanceof Long) {
responseCode = (int)((Long)rc).longValue(); responseCode = (int)((Long)rc).longValue();
} }
//Log.d("XXX", "Buy intent response code: " + responseCode); //Log.d("XXX", "Buy intent response code: " + responseCode);
if(responseCode == 1 || responseCode == 3 || responseCode == 4){ if (responseCode == 1 || responseCode == 3 || responseCode == 4) {
canceled(); canceled();
return; return;
} }
if(responseCode == 7){ if (responseCode == 7) {
alreadyOwned(); alreadyOwned();
return; return;
} }
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
pc.setConsumableValue("validation_hash", sku, hash); pc.setConsumableValue("validation_hash", sku, hash);
try { try {
if(context == null){ if (context == null) {
//Log.d("XXX", "No context!"); //Log.d("XXX", "No context!");
} }
if(pendingIntent == null){ if (pendingIntent == null) {
//Log.d("XXX", "No pending intent"); //Log.d("XXX", "No pending intent");
} }
//Log.d("XXX", "Starting activity for purchase!"); //Log.d("XXX", "Starting activity for purchase!");
context.startIntentSenderForResult( context.startIntentSenderForResult(
pendingIntent.getIntentSender(), pendingIntent.getIntentSender(),
PaymentsManager.REQUEST_CODE_FOR_PURCHASE, PaymentsManager.REQUEST_CODE_FOR_PURCHASE,
new Intent(), new Intent(),
Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0),
Integer.valueOf(0)); Integer.valueOf(0));
} catch (SendIntentException e) { } catch (SendIntentException e) {
error(e.getMessage()); error(e.getMessage());
} }
} }
abstract protected void error(String message); abstract protected void error(String message);
abstract protected void canceled(); abstract protected void canceled();
abstract protected void alreadyOwned(); abstract protected void alreadyOwned();
} }

View file

@ -48,69 +48,63 @@ abstract public class ReleaseAllConsumablesTask {
private Context context; private Context context;
private IInAppBillingService mService; private IInAppBillingService mService;
public ReleaseAllConsumablesTask(IInAppBillingService mService, Context context ){ public ReleaseAllConsumablesTask(IInAppBillingService mService, Context context) {
this.context = context; this.context = context;
this.mService = mService; this.mService = mService;
} }
public void consumeItAll(){ public void consumeItAll() {
try{ try {
//Log.d("godot", "consumeItall for " + context.getPackageName()); //Log.d("godot", "consumeItall for " + context.getPackageName());
Bundle bundle = mService.getPurchases(3, context.getPackageName(), "inapp",null); Bundle bundle = mService.getPurchases(3, context.getPackageName(), "inapp", null);
for (String key : bundle.keySet()) { for (String key : bundle.keySet()) {
Object value = bundle.get(key); Object value = bundle.get(key);
//Log.d("godot", String.format("%s %s (%s)", key, //Log.d("godot", String.format("%s %s (%s)", key,
//value.toString(), value.getClass().getName())); //value.toString(), value.getClass().getName()));
} }
if (bundle.getInt("RESPONSE_CODE") == 0) {
if (bundle.getInt("RESPONSE_CODE") == 0){
final ArrayList<String> myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST"); final ArrayList<String> myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
final ArrayList<String> mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST"); final ArrayList<String> mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
if (myPurchases == null || myPurchases.size() == 0){ if (myPurchases == null || myPurchases.size() == 0) {
//Log.d("godot", "No purchases!"); //Log.d("godot", "No purchases!");
notRequired(); notRequired();
return; return;
} }
//Log.d("godot", "# products to be consumed:" + myPurchases.size()); //Log.d("godot", "# products to be consumed:" + myPurchases.size());
for (int i=0;i<myPurchases.size();i++) for (int i = 0; i < myPurchases.size(); i++) {
{
try {
try{
String receipt = myPurchases.get(i); String receipt = myPurchases.get(i);
JSONObject inappPurchaseData = new JSONObject(receipt); JSONObject inappPurchaseData = new JSONObject(receipt);
String sku = inappPurchaseData.getString("productId"); String sku = inappPurchaseData.getString("productId");
String token = inappPurchaseData.getString("purchaseToken"); String token = inappPurchaseData.getString("purchaseToken");
String signature = mySignatures.get(i); String signature = mySignatures.get(i);
//Log.d("godot", "A punto de consumir un item con token:" + token + "\n" + receipt); //Log.d("godot", "A punto de consumir un item con token:" + token + "\n" + receipt);
new GenericConsumeTask(context, mService, sku, receipt,signature, token) { new GenericConsumeTask(context, mService, sku, receipt, signature, token) {
@Override @Override
public void onSuccess(String sku, String receipt, String signature, String token) { public void onSuccess(String sku, String receipt, String signature, String token) {
ReleaseAllConsumablesTask.this.success(sku, receipt, signature, token); ReleaseAllConsumablesTask.this.success(sku, receipt, signature, token);
} }
}.execute(); }
.execute();
} catch (JSONException e) { } catch (JSONException e) {
} }
} }
} }
}catch(Exception e){ } catch (Exception e) {
Log.d("godot", "Error releasing products:" + e.getClass().getName() + ":" + e.getMessage()); Log.d("godot", "Error releasing products:" + e.getClass().getName() + ":" + e.getMessage());
} }
} }
abstract protected void success(String sku, String receipt, String signature, String token); abstract protected void success(String sku, String receipt, String signature, String token);
abstract protected void error(String message); abstract protected void error(String message);
abstract protected void notRequired(); abstract protected void notRequired();
} }

View file

@ -55,22 +55,21 @@ abstract public class ValidateTask {
private Activity context; private Activity context;
private GodotPaymentV3 godotPaymentsV3; private GodotPaymentV3 godotPaymentsV3;
public ValidateTask(Activity context, GodotPaymentV3 godotPaymentsV3){ public ValidateTask(Activity context, GodotPaymentV3 godotPaymentsV3) {
this.context = context; this.context = context;
this.godotPaymentsV3 = godotPaymentsV3; this.godotPaymentsV3 = godotPaymentsV3;
} }
public void validatePurchase(final String sku){
new AsyncTask<String, String, String>(){
public void validatePurchase(final String sku) {
new AsyncTask<String, String, String>() {
private ProgressDialog dialog; private ProgressDialog dialog;
@Override @Override
protected void onPreExecute(){ protected void onPreExecute() {
dialog = ProgressDialog.show(context, null, "Please wait..."); dialog = ProgressDialog.show(context, null, "Please wait...");
} }
@Override @Override
protected String doInBackground(String... params) { protected String doInBackground(String... params) {
PaymentsCache pc = new PaymentsCache(context); PaymentsCache pc = new PaymentsCache(context);
@ -90,37 +89,34 @@ abstract public class ValidateTask {
//Log.d("XXX", "Validation response:\n"+jsonResponse); //Log.d("XXX", "Validation response:\n"+jsonResponse);
return jsonResponse; return jsonResponse;
} }
@Override @Override
protected void onPostExecute(String response){ protected void onPostExecute(String response) {
if(dialog != null){ if (dialog != null) {
dialog.dismiss(); dialog.dismiss();
} }
JSONObject j; JSONObject j;
try { try {
j = new JSONObject(response); j = new JSONObject(response);
if(j.getString("status").equals("OK")){ if (j.getString("status").equals("OK")) {
success(); success();
return; return;
}else if(j.getString("status") != null){ } else if (j.getString("status") != null) {
error(j.getString("message")); error(j.getString("message"));
}else{ } else {
error("Connection error"); error("Connection error");
} }
} catch (JSONException e) { } catch (JSONException e) {
error(e.getMessage()); error(e.getMessage());
}catch (Exception e){ } catch (Exception e) {
error(e.getMessage()); error(e.getMessage());
} }
} }
}.execute(); }
.execute();
} }
abstract protected void success(); abstract protected void success();
abstract protected void error(String message); abstract protected void error(String message);
abstract protected void canceled(); abstract protected void canceled();
} }

View file

@ -34,34 +34,34 @@ import java.util.Random;
public class Crypt { public class Crypt {
public static String md5(String input){ public static String md5(String input) {
try { try {
// Create MD5 Hash // Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(input.getBytes()); digest.update(input.getBytes());
byte messageDigest[] = digest.digest(); byte messageDigest[] = digest.digest();
// Create Hex String // Create Hex String
StringBuffer hexString = new StringBuffer(); StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++) for (int i = 0; i < messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i])); hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString(); return hexString.toString();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return ""; return "";
} }
public static String createRandomHash(){ public static String createRandomHash() {
return md5(Long.toString(createRandomLong())); return md5(Long.toString(createRandomLong()));
} }
public static long createAbsRandomLong(){ public static long createAbsRandomLong() {
return Math.abs(createRandomLong()); return Math.abs(createRandomLong());
} }
public static long createRandomLong(){ public static long createRandomLong() {
Random r = new Random(); Random r = new Random();
return r.nextLong(); return r.nextLong();
} }

View file

@ -42,30 +42,29 @@ import javax.net.ssl.TrustManagerFactory;
import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory;
/** /**
* *
* @author Luis Linietsky <luis.linietsky@gmail.com> * @author Luis Linietsky <luis.linietsky@gmail.com>
*/ */
public class CustomSSLSocketFactory extends SSLSocketFactory { public class CustomSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS"); SSLContext sslContext = SSLContext.getInstance("TLS");
public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore); super(truststore);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(truststore); tmf.init(truststore);
sslContext.init(null, tmf.getTrustManagers(), null); sslContext.init(null, tmf.getTrustManagers(), null);
} }
@Override @Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
} }
@Override @Override
public Socket createSocket() throws IOException { public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket(); return sslContext.getSocketFactory().createSocket();
} }
} }

View file

@ -63,7 +63,6 @@ import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.util.Log; import android.util.Log;
@ -73,155 +72,154 @@ import android.util.Log;
* @author Luis Linietsky <luis.linietsky@gmail.com> * @author Luis Linietsky <luis.linietsky@gmail.com>
*/ */
public class HttpRequester { public class HttpRequester {
private Context context; private Context context;
private static final int TTL = 600000; // 10 minutos private static final int TTL = 600000; // 10 minutos
private long cttl=0; private long cttl = 0;
public HttpRequester(){ public HttpRequester() {
//Log.d("XXX", "Creando http request sin contexto"); //Log.d("XXX", "Creando http request sin contexto");
} }
public HttpRequester(Context context){ public HttpRequester(Context context) {
this.context=context; this.context = context;
//Log.d("XXX", "Creando http request con contexto"); //Log.d("XXX", "Creando http request con contexto");
} }
public String post(RequestParams params){ public String post(RequestParams params) {
HttpPost httppost = new HttpPost(params.getUrl()); HttpPost httppost = new HttpPost(params.getUrl());
try { try {
httppost.setEntity(new UrlEncodedFormEntity(params.toPairsList())); httppost.setEntity(new UrlEncodedFormEntity(params.toPairsList()));
return request(httppost); return request(httppost);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
return null; return null;
} }
} }
public String get(RequestParams params){ public String get(RequestParams params) {
String response = getResponseFromCache(params.getUrl()); String response = getResponseFromCache(params.getUrl());
if(response == null){ if (response == null) {
//Log.d("XXX", "Cache miss!"); //Log.d("XXX", "Cache miss!");
HttpGet httpget = new HttpGet(params.getUrl()); HttpGet httpget = new HttpGet(params.getUrl());
long timeInit = new Date().getTime(); long timeInit = new Date().getTime();
response = request(httpget); response = request(httpget);
long delay = new Date().getTime() - timeInit; long delay = new Date().getTime() - timeInit;
Log.d("com.app11tt.android.utils.HttpRequest::get(url)", "Url: " + params.getUrl() + " downloaded in " + String.format("%.03f", delay/1000.0f) + " seconds"); Log.d("com.app11tt.android.utils.HttpRequest::get(url)", "Url: " + params.getUrl() + " downloaded in " + String.format("%.03f", delay / 1000.0f) + " seconds");
if(response == null || response.length() == 0){ if (response == null || response.length() == 0) {
response = ""; response = "";
}else{ } else {
saveResponseIntoCache(params.getUrl(), response); saveResponseIntoCache(params.getUrl(), response);
} }
} }
Log.d("XXX", "Req: " + params.getUrl()); Log.d("XXX", "Req: " + params.getUrl());
Log.d("XXX", "Resp: " + response); Log.d("XXX", "Resp: " + response);
return response; return response;
} }
private String request(HttpUriRequest request){ private String request(HttpUriRequest request) {
//Log.d("XXX", "Haciendo request a: " + request.getURI() ); //Log.d("XXX", "Haciendo request a: " + request.getURI() );
Log.d("PPP", "Haciendo request a: " + request.getURI() ); Log.d("PPP", "Haciendo request a: " + request.getURI());
long init = new Date().getTime(); long init = new Date().getTime();
HttpClient httpclient = getNewHttpClient(); HttpClient httpclient = getNewHttpClient();
HttpParams httpParameters = httpclient.getParams(); HttpParams httpParameters = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 0); HttpConnectionParams.setConnectionTimeout(httpParameters, 0);
HttpConnectionParams.setSoTimeout(httpParameters, 0); HttpConnectionParams.setSoTimeout(httpParameters, 0);
HttpConnectionParams.setTcpNoDelay(httpParameters, true); HttpConnectionParams.setTcpNoDelay(httpParameters, true);
try { try {
HttpResponse response = httpclient.execute(request); HttpResponse response = httpclient.execute(request);
Log.d("PPP", "Fin de request (" + (new Date().getTime() - init) + ") a: " + request.getURI() ); Log.d("PPP", "Fin de request (" + (new Date().getTime() - init) + ") a: " + request.getURI());
//Log.d("XXX1", "Status:" + response.getStatusLine().toString()); //Log.d("XXX1", "Status:" + response.getStatusLine().toString());
if(response.getStatusLine().getStatusCode() == 200){ if (response.getStatusLine().getStatusCode() == 200) {
String strResponse = EntityUtils.toString(response.getEntity()); String strResponse = EntityUtils.toString(response.getEntity());
//Log.d("XXX2", strResponse); //Log.d("XXX2", strResponse);
return strResponse; return strResponse;
}else{ } else {
Log.d("XXX3", "Response status code:" + response.getStatusLine().getStatusCode() + "\n" + EntityUtils.toString(response.getEntity())); Log.d("XXX3", "Response status code:" + response.getStatusLine().getStatusCode() + "\n" + EntityUtils.toString(response.getEntity()));
return null; return null;
} }
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.d("XXX3", e.getMessage()); Log.d("XXX3", e.getMessage());
} catch (IOException e) { } catch (IOException e) {
Log.d("XXX4", e.getMessage()); Log.d("XXX4", e.getMessage());
} }
return null; return null;
} }
private HttpClient getNewHttpClient() { private HttpClient getNewHttpClient() {
try { try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null); trustStore.load(null, null);
SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore); SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams(); HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry(); SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443)); registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params); return new DefaultHttpClient(ccm, params);
} catch (Exception e) { } catch (Exception e) {
return new DefaultHttpClient(); return new DefaultHttpClient();
} }
} }
private static String convertStreamToString(InputStream is) { private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
String line = null; String line = null;
try { try {
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
sb.append((line + "\n")); sb.append((line + "\n"));
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
is.close(); is.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
return sb.toString(); return sb.toString();
} }
public void saveResponseIntoCache(String request, String response){ public void saveResponseIntoCache(String request, String response) {
if(context == null){ if (context == null) {
//Log.d("XXX", "No context, cache failed!"); //Log.d("XXX", "No context, cache failed!");
return; return;
} }
SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE); SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit(); SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("request_" + Crypt.md5(request), response); editor.putString("request_" + Crypt.md5(request), response);
editor.putLong("request_" + Crypt.md5(request) + "_ttl", new Date().getTime() + getTtl()); editor.putLong("request_" + Crypt.md5(request) + "_ttl", new Date().getTime() + getTtl());
editor.commit(); editor.commit();
} }
public String getResponseFromCache(String request) {
public String getResponseFromCache(String request){ if (context == null) {
if(context == null){
Log.d("XXX", "No context, cache miss"); Log.d("XXX", "No context, cache miss");
return null; return null;
} }
SharedPreferences sharedPref = context.getSharedPreferences( "http_get_cache", Context.MODE_PRIVATE); SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE);
long ttl = getResponseTtl(request); long ttl = getResponseTtl(request);
if(ttl == 0l || (new Date().getTime() - ttl) > 0l){ if (ttl == 0l || (new Date().getTime() - ttl) > 0l) {
Log.d("XXX", "Cache invalid ttl:" + ttl + " vs now:" + new Date().getTime()); Log.d("XXX", "Cache invalid ttl:" + ttl + " vs now:" + new Date().getTime());
return null; return null;
} }
return sharedPref.getString("request_" + Crypt.md5(request), null); return sharedPref.getString("request_" + Crypt.md5(request), null);
} }
public long getResponseTtl(String request){ public long getResponseTtl(String request) {
SharedPreferences sharedPref = context.getSharedPreferences( SharedPreferences sharedPref = context.getSharedPreferences(
"http_get_cache", Context.MODE_PRIVATE); "http_get_cache", Context.MODE_PRIVATE);
return sharedPref.getLong("request_" + Crypt.md5(request) + "_ttl", 0l); return sharedPref.getLong("request_" + Crypt.md5(request) + "_ttl", 0l);
} }
public long getTtl() { public long getTtl() {
@ -229,7 +227,6 @@ public class HttpRequester {
} }
public void setTtl(long ttl) { public void setTtl(long ttl) {
this.cttl = (ttl*1000) + new Date().getTime(); this.cttl = (ttl * 1000) + new Date().getTime();
} }
} }

View file

@ -43,33 +43,33 @@ import org.apache.http.message.BasicNameValuePair;
*/ */
public class RequestParams { public class RequestParams {
private HashMap<String,String> params; private HashMap<String, String> params;
private String url; private String url;
public RequestParams(){ public RequestParams() {
params = new HashMap<String,String>(); params = new HashMap<String, String>();
} }
public void put(String key, String value){ public void put(String key, String value) {
params.put(key, value); params.put(key, value);
} }
public String get(String key){ public String get(String key) {
return params.get(key); return params.get(key);
} }
public void remove(Object key){ public void remove(Object key) {
params.remove(key); params.remove(key);
} }
public boolean has(String key){ public boolean has(String key) {
return params.containsKey(key); return params.containsKey(key);
} }
public List<NameValuePair> toPairsList(){
List<NameValuePair> fields = new ArrayList<NameValuePair>();
for(String key : params.keySet()){ public List<NameValuePair> toPairsList() {
List<NameValuePair> fields = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
fields.add(new BasicNameValuePair(key, this.get(key))); fields.add(new BasicNameValuePair(key, this.get(key)));
} }
return fields; return fields;
@ -82,6 +82,4 @@ public class RequestParams {
public void setUrl(String url) { public void setUrl(String url) {
this.url = url; this.url = url;
} }
} }