From 7cb6e6b72375fa384c509651657aeba3f67110be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Verschelde?= Date: Sun, 10 Dec 2017 01:16:07 +0100 Subject: Style: Apply clang-format to Java files Only those from org/godotengine/godot though, not the thirdparty ones. --- .clang-format | 5 +- misc/hooks/pre-commit-clang-format | 2 +- misc/travis/clang-format.sh | 2 +- .../java/src/org/godotengine/godot/Dictionary.java | 7 +- .../java/src/org/godotengine/godot/Godot.java | 812 ++++++++++----------- .../godot/GodotDownloaderAlarmReceiver.java | 18 +- .../godotengine/godot/GodotDownloaderService.java | 55 +- .../java/src/org/godotengine/godot/GodotIO.java | 273 +++---- .../java/src/org/godotengine/godot/GodotLib.java | 56 +- .../src/org/godotengine/godot/GodotPaymentV3.java | 25 +- .../java/src/org/godotengine/godot/GodotView.java | 261 +++---- .../org/godotengine/godot/input/GodotEditText.java | 61 +- .../godot/input/GodotTextInputWrapper.java | 3 +- .../godot/input/InputManagerCompat.java | 204 +++--- .../godotengine/godot/input/InputManagerV16.java | 144 ++-- .../godotengine/godot/input/InputManagerV9.java | 352 +++++---- .../godotengine/godot/payments/ConsumeTask.java | 38 +- .../godot/payments/GenericConsumeTask.java | 20 +- .../godot/payments/HandlePurchaseTask.java | 30 +- .../godotengine/godot/payments/PaymentsCache.java | 45 +- .../godot/payments/PaymentsManager.java | 87 ++- .../godotengine/godot/payments/PurchaseTask.java | 38 +- .../godot/payments/ReleaseAllConsumablesTask.java | 46 +- .../godotengine/godot/payments/ValidateTask.java | 36 +- .../src/org/godotengine/godot/utils/Crypt.java | 46 +- .../godot/utils/CustomSSLSocketFactory.java | 31 +- .../org/godotengine/godot/utils/HttpRequester.java | 207 +++--- .../org/godotengine/godot/utils/RequestParams.java | 34 +- 28 files changed, 1425 insertions(+), 1513 deletions(-) diff --git a/.clang-format b/.clang-format index bc69a6a3a6..212bc25109 100644 --- a/.clang-format +++ b/.clang-format @@ -44,7 +44,6 @@ AllowShortIfStatementsOnASingleLine: true BreakBeforeTernaryOperators: false # BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: AfterColon -# BreakAfterJavaFieldAnnotations: false # BreakStringLiterals: true ColumnLimit: 0 # CommentPragmas: '^ IWYU pragma:' @@ -113,4 +112,8 @@ Language: ObjC ObjCBlockIndentWidth: 4 # ObjCSpaceAfterProperty: false # ObjCSpaceBeforeProtocolList: true +--- +### Java specific config ### +Language: Java +# BreakAfterJavaFieldAnnotations: false ... diff --git a/misc/hooks/pre-commit-clang-format b/misc/hooks/pre-commit-clang-format index d2d65a7428..8ef4e27748 100755 --- a/misc/hooks/pre-commit-clang-format +++ b/misc/hooks/pre-commit-clang-format @@ -31,7 +31,7 @@ PARSE_EXTS=true # File types to parse. Only effective when PARSE_EXTS is true. # 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. # Install it with `pip install pygments` (Linux) or `easy_install Pygments` (Mac) diff --git a/misc/travis/clang-format.sh b/misc/travis/clang-format.sh index 2b30cf5ada..d1e37cc10e 100755 --- a/misc/travis/clang-format.sh +++ b/misc/travis/clang-format.sh @@ -11,7 +11,7 @@ else RANGE=HEAD 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" # create a random filename to store our generated patch diff --git a/platform/android/java/src/org/godotengine/godot/Dictionary.java b/platform/android/java/src/org/godotengine/godot/Dictionary.java index ed91fedd85..2bc9c083aa 100644 --- a/platform/android/java/src/org/godotengine/godot/Dictionary.java +++ b/platform/android/java/src/org/godotengine/godot/Dictionary.java @@ -32,7 +32,6 @@ package org.godotengine.godot; import java.util.HashMap; import java.util.Set; - public class Dictionary extends HashMap { protected String[] keys_cache; @@ -40,7 +39,7 @@ public class Dictionary extends HashMap { public String[] get_keys() { String[] ret = new String[size()]; - int i=0; + int i = 0; Set keys = keySet(); for (String key : keys) { @@ -54,7 +53,7 @@ public class Dictionary extends HashMap { public Object[] get_values() { Object[] ret = new Object[size()]; - int i=0; + int i = 0; Set keys = keySet(); for (String key : keys) { @@ -71,7 +70,7 @@ public class Dictionary extends HashMap { public void set_values(Object[] vals) { - int i=0; + int i = 0; for (String key : keys_cache) { put(key, vals[i]); i++; diff --git a/platform/android/java/src/org/godotengine/godot/Godot.java b/platform/android/java/src/org/godotengine/godot/Godot.java index 4daf06142d..3939ceb2e7 100644 --- a/platform/android/java/src/org/godotengine/godot/Godot.java +++ b/platform/android/java/src/org/godotengine/godot/Godot.java @@ -90,35 +90,34 @@ import android.os.Bundle; import android.os.Messenger; import android.os.SystemClock; - -public class Godot extends Activity implements SensorEventListener, IDownloaderClient -{ +public class Godot extends Activity implements SensorEventListener, IDownloaderClient { static final int MAX_SINGLETONS = 64; private IStub mDownloaderClientStub; - private IDownloaderService mRemoteService; - private TextView mStatusText; - private TextView mProgressFraction; - private TextView mProgressPercent; - private TextView mAverageSpeed; - private TextView mTimeRemaining; - private ProgressBar mPB; - - private View mDashboard; - private View mCellMessage; - - private Button mPauseButton; - private Button mWiFiSettingsButton; - - private boolean use_32_bits=false; - private boolean use_immersive=false; - private boolean mStatePaused; - private int mState; - private boolean keep_screen_on=true; + private IDownloaderService mRemoteService; + private TextView mStatusText; + private TextView mProgressFraction; + private TextView mProgressPercent; + private TextView mAverageSpeed; + private TextView mTimeRemaining; + private ProgressBar mPB; + + private View mDashboard; + private View mCellMessage; + + private Button mPauseButton; + private Button mWiFiSettingsButton; + + private boolean use_32_bits = false; + private boolean use_immersive = false; + private boolean mStatePaused; + private int mState; + private boolean keep_screen_on = true; static private Intent mCurrentIntent; - @Override public void onNewIntent(Intent intent) { + @Override + public void onNewIntent(Intent intent) { mCurrentIntent = intent; } @@ -127,43 +126,43 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC } private void setState(int newState) { - if (mState != newState) { - mState = newState; - mStatusText.setText(Helpers.getDownloaderStringResourceIDFromState(newState)); - } - } - - private void setButtonPausedState(boolean paused) { - mStatePaused = paused; - int stringResourceID = paused ? com.godot.game.R.string.text_button_resume : - com.godot.game.R.string.text_button_pause; - mPauseButton.setText(stringResourceID); - } + if (mState != newState) { + mState = newState; + mStatusText.setText(Helpers.getDownloaderStringResourceIDFromState(newState)); + } + } + + private void setButtonPausedState(boolean paused) { + mStatePaused = paused; + int stringResourceID = paused ? com.godot.game.R.string.text_button_resume : + com.godot.game.R.string.text_button_pause; + mPauseButton.setText(stringResourceID); + } static public class SingletonBase { protected void registerClass(String p_name, String[] p_methods) { - GodotLib.singleton(p_name,this); + GodotLib.singleton(p_name, this); Class clazz = getClass(); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { - boolean found=false; - Log.d("XXX","METHOD: %s\n" + method.getName()); + boolean found = false; + Log.d("XXX", "METHOD: %s\n" + method.getName()); for (String s : p_methods) { - Log.d("XXX", "METHOD CMP WITH: %s\n" + s); + Log.d("XXX", "METHOD CMP WITH: %s\n" + s); if (s.equals(method.getName())) { - found=true; - Log.d("XXX","METHOD CMP VALID"); + found = true; + Log.d("XXX", "METHOD CMP VALID"); break; } } if (!found) continue; - Log.d("XXX","METHOD FOUND: %s\n" + method.getName()); + Log.d("XXX", "METHOD FOUND: %s\n" + method.getName()); List ptr = new ArrayList(); @@ -175,17 +174,13 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC String[] pt = new String[ptr.size()]; ptr.toArray(pt); - GodotLib.method(p_name,method.getName(),method.getReturnType().getName(),pt); - - + GodotLib.method(p_name, method.getName(), method.getReturnType().getName(), pt); } - Godot.singletons[Godot.singleton_count++]=this; + Godot.singletons[Godot.singleton_count++] = this; } protected void onMainActivityResult(int requestCode, int resultCode, Intent data) { - - } protected void onMainPause() {} @@ -200,22 +195,20 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC public void registerMethods() {} } -/* + /* protected List singletons = new ArrayList(); protected void instanceSingleton(SingletonBase s) { s.registerMethods(); singletons.add(s); } - -*/ + */ private String[] command_line; private boolean use_apk_expansion; public GodotView mView; - private boolean godot_initialized=false; - + private boolean godot_initialized = false; private SensorManager mSensorManager; private Sensor mAccelerometer; @@ -226,36 +219,34 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC public FrameLayout layout; public RelativeLayout adLayout; - static public GodotIO io; public static void setWindowTitle(String title) { //setTitle(title); } - static SingletonBase singletons[] = new SingletonBase[MAX_SINGLETONS]; - static int singleton_count=0; - + static int singleton_count = 0; public interface ResultCallback { public void callback(int requestCode, int resultCode, Intent data); - }; + } public ResultCallback result_callback; private PaymentsManager mPaymentsManager = null; - @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { - if(requestCode == PaymentsManager.REQUEST_CODE_FOR_PURCHASE){ + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode == PaymentsManager.REQUEST_CODE_FOR_PURCHASE) { mPaymentsManager.processPurchaseResponse(resultCode, data); - }else if (result_callback != null) { + } else if (result_callback != null) { result_callback.callback(requestCode, resultCode, data); result_callback = null; }; - for(int i=0;i65535) { - Log.d("GODOT", "**ERROR** Wrong command len\n"); - return new String[0]; - } - byte[] arg = new byte[strlen]; - r = is.read(arg); - if (r==strlen) { - cmdline[i]=new String(arg,"UTF-8"); - } + InputStream is; + try { + is = getAssets().open("_cl_"); + byte[] len = new byte[4]; + int r = is.read(len); + if (r < 4) { + Log.d("XXX", "**ERROR** Wrong cmdline length.\n"); + Log.d("GODOT", "**ERROR** Wrong cmdline length.\n"); + return new String[0]; + } + int argc = ((int)(len[3] & 0xFF) << 24) | ((int)(len[2] & 0xFF) << 16) | ((int)(len[1] & 0xFF) << 8) | ((int)(len[0] & 0xFF)); + String[] cmdline = new String[argc]; + + for (int i = 0; i < argc; i++) { + r = is.read(len); + if (r < 4) { + + Log.d("GODOT", "**ERROR** Wrong cmdline param length.\n"); + return new String[0]; + } + int strlen = ((int)(len[3] & 0xFF) << 24) | ((int)(len[2] & 0xFF) << 16) | ((int)(len[1] & 0xFF) << 8) | ((int)(len[0] & 0xFF)); + if (strlen > 65535) { + Log.d("GODOT", "**ERROR** Wrong command len\n"); + return new String[0]; + } + byte[] arg = new byte[strlen]; + r = is.read(arg); + if (r == strlen) { + cmdline[i] = new String(arg, "UTF-8"); + } } return cmdline; } catch (Exception e) { - e.printStackTrace(); - Log.d("GODOT", "**ERROR** Exception " + e.getClass().getName() + ":" + e.getMessage()); + e.printStackTrace(); + Log.d("GODOT", "**ERROR** Exception " + e.getClass().getName() + ":" + e.getMessage()); return new String[0]; } - - } - String expansion_pack_path; - private void initializeGodot() { - if (expansion_pack_path!=null) { + if (expansion_pack_path != null) { String[] new_cmdline; - int cll=0; - if (command_line!=null) { - Log.d("GODOT", "initializeGodot: command_line: is not null" ); - new_cmdline = new String[ command_line.length + 2 ]; - cll=command_line.length; - for(int i=0;i new_args = new LinkedList(); + for (int i = 0; i < command_line.length; i++) { - for(int i=0;i= 19.0){ // check if the application runs on an android 4.4+ + use_immersive = true; + if (Build.VERSION.SDK_INT >= 19.0) { // check if the application runs on an android 4.4+ window.getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar - | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); + View.SYSTEM_UI_FLAG_LAYOUT_STABLE | + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | // hide nav bar + View.SYSTEM_UI_FLAG_FULLSCREEN | // hide status bar + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); UiChangeListener(); } } else if (command_line[i].equals("--use_apk_expansion")) { - use_apk_expansion=true; + use_apk_expansion = true; } else if (has_extra && command_line[i].equals("--apk_expansion_md5")) { - main_pack_md5=command_line[i+1]; + main_pack_md5 = command_line[i + 1]; i++; } else if (has_extra && command_line[i].equals("--apk_expansion_key")) { - main_pack_key=command_line[i+1]; + main_pack_key = command_line[i + 1]; SharedPreferences prefs = getSharedPreferences("app_data_keys", MODE_PRIVATE); Editor editor = prefs.edit(); editor.putString("store_public_key", main_pack_key); editor.commit(); i++; - } else if (command_line[i].trim().length()!=0){ + } else if (command_line[i].trim().length() != 0) { new_args.add(command_line[i]); } } - if (new_args.isEmpty()){ - command_line=null; - }else{ + if (new_args.isEmpty()) { + command_line = null; + } else { command_line = new_args.toArray(new String[new_args.size()]); - } - if (use_apk_expansion && main_pack_md5!=null && main_pack_key!=null) { + } + if (use_apk_expansion && main_pack_md5 != null && main_pack_key != null) { //check that environment is ok! - if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED )) { + if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Log.d("GODOT", "**ERROR! No media mounted!"); //show popup and die } @@ -534,7 +515,7 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC // Build the full path to the app's expansion files try { expansion_pack_path = Helpers.getSaveFilePath(getApplicationContext()); - expansion_pack_path+="/"+"main."+getPackageManager().getPackageInfo(getPackageName(), 0).versionCode+"."+this.getPackageName()+".obb"; + expansion_pack_path += "/main." + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + "." + this.getPackageName() + ".obb"; } catch (Exception e) { e.printStackTrace(); } @@ -542,20 +523,20 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC File f = new File(expansion_pack_path); boolean pack_valid = true; - Log.d("GODOT","**PACK** - Path "+expansion_pack_path); + Log.d("GODOT", "**PACK** - Path " + expansion_pack_path); if (!f.exists()) { - pack_valid=false; - Log.d("GODOT","**PACK** - File does not exist"); + pack_valid = false; + Log.d("GODOT", "**PACK** - File does not exist"); - } else if( obbIsCorrupted(expansion_pack_path, main_pack_md5)){ + } else if (obbIsCorrupted(expansion_pack_path, main_pack_md5)) { Log.d("GODOT", "**PACK** - Expansion pack (obb) is corrupted"); pack_valid = false; - try{ - f.delete(); - }catch(Exception e){ - Log.d("GODOT", "**PACK** - Error deleting corrupted expansion pack (obb)"); + try { + f.delete(); + } catch (Exception e) { + Log.d("GODOT", "**PACK** - Error deleting corrupted expansion pack (obb)"); } } @@ -564,12 +545,12 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC Intent notifierIntent = new Intent(this, this.getClass()); notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | - Intent.FLAG_ACTIVITY_CLEAR_TOP); + Intent.FLAG_ACTIVITY_CLEAR_TOP); - PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, - notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, + notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT); - int startResult; + int startResult; try { Log.d("GODOT", "INITIALIZING DOWNLOAD"); startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired( @@ -578,36 +559,34 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC GodotDownloaderService.class); Log.d("GODOT", "DOWNLOAD SERVICE FINISHED:" + startResult); - if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) { - Log.d("GODOT", "DOWNLOAD REQUIRED"); - // This is where you do set up to display the download - // progress (next step) - mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, - GodotDownloaderService.class); - - setContentView(com.godot.game.R.layout.downloading_expansion); - mPB = (ProgressBar) findViewById(com.godot.game.R.id.progressBar); - mStatusText = (TextView) findViewById(com.godot.game.R.id.statusText); - mProgressFraction = (TextView) findViewById(com.godot.game.R.id.progressAsFraction); - mProgressPercent = (TextView) findViewById(com.godot.game.R.id.progressAsPercentage); - mAverageSpeed = (TextView) findViewById(com.godot.game.R.id.progressAverageSpeed); - mTimeRemaining = (TextView) findViewById(com.godot.game.R.id.progressTimeRemaining); - mDashboard = findViewById(com.godot.game.R.id.downloaderDashboard); - mCellMessage = findViewById(com.godot.game.R.id.approveCellular); - mPauseButton = (Button) findViewById(com.godot.game.R.id.pauseButton); - mWiFiSettingsButton = (Button) findViewById(com.godot.game.R.id.wifiSettingsButton); - - return; - } else{ - Log.d("GODOT", "NO DOWNLOAD REQUIRED"); - } + if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) { + Log.d("GODOT", "DOWNLOAD REQUIRED"); + // This is where you do set up to display the download + // progress (next step) + mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, + GodotDownloaderService.class); + + setContentView(com.godot.game.R.layout.downloading_expansion); + mPB = (ProgressBar)findViewById(com.godot.game.R.id.progressBar); + mStatusText = (TextView)findViewById(com.godot.game.R.id.statusText); + mProgressFraction = (TextView)findViewById(com.godot.game.R.id.progressAsFraction); + mProgressPercent = (TextView)findViewById(com.godot.game.R.id.progressAsPercentage); + mAverageSpeed = (TextView)findViewById(com.godot.game.R.id.progressAverageSpeed); + mTimeRemaining = (TextView)findViewById(com.godot.game.R.id.progressTimeRemaining); + mDashboard = findViewById(com.godot.game.R.id.downloaderDashboard); + mCellMessage = findViewById(com.godot.game.R.id.approveCellular); + mPauseButton = (Button)findViewById(com.godot.game.R.id.pauseButton); + mWiFiSettingsButton = (Button)findViewById(com.godot.game.R.id.wifiSettingsButton); + + return; + } else { + Log.d("GODOT", "NO DOWNLOAD REQUIRED"); + } } catch (NameNotFoundException e) { // TODO Auto-generated catch block Log.d("GODOT", "Error downloading expansion package:" + e.getMessage()); } - } - } } @@ -615,28 +594,26 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC initializeGodot(); - //instanceSingleton( new GodotFacebook(this) ); - - } + @Override + protected void onDestroy() { - @Override protected void onDestroy(){ - - if(mPaymentsManager != null ) mPaymentsManager.destroy(); - for(int i=0;i= 19.0){ // check if the application runs on an android 4.4+ + if (use_immersive && Build.VERSION.SDK_INT >= 19.0) { // check if the application runs on an android 4.4+ Window window = getWindow(); window.getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar - | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); + View.SYSTEM_UI_FLAG_LAYOUT_STABLE | + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | // hide nav bar + View.SYSTEM_UI_FLAG_FULLSCREEN | // hide status bar + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } - for(int i=0;i 0) { - complete.update(buffer, 0, numRead); - } - } while (numRead != -1); + // Create MD5 Hash + byte[] buffer = new byte[16384]; + MessageDigest complete = MessageDigest.getInstance("MD5"); + int numRead; + do { + numRead = fis.read(buffer); + if (numRead > 0) { + complete.update(buffer, 0, numRead); + } + } while (numRead != -1); - fis.close(); - byte[] messageDigest = complete.digest(); + fis.close(); + byte[] messageDigest = complete.digest(); - // Create Hex String - StringBuffer hexString = new StringBuffer(); - for (int i=0; i= 0; cnt += cc[i] != 0 ? 1 : 0); + for (int i = cc.length; --i >= 0; cnt += cc[i] != 0 ? 1 : 0) + ; if (cnt == 0) return super.onKeyMultiple(inKeyCode, repeatCount, event); final Activity me = this; queueEvent(new Runnable() { @@ -939,7 +917,6 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC private void queueEvent(Runnable runnable) { // TODO Auto-generated method stub - } public PaymentsManager getPaymentsManager() { @@ -952,7 +929,6 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC } */ - // Audio /** @@ -960,110 +936,106 @@ public class Godot extends Activity implements SensorEventListener, IDownloaderC * to show the state as being indeterminate at times. This sample can be * considered a guideline. */ - @Override - public void onDownloadStateChanged(int newState) { - Log.d("GODOT", "onDownloadStateChanged:" + newState); - setState(newState); - boolean showDashboard = true; - boolean showCellMessage = false; - boolean paused; - boolean indeterminate; - switch (newState) { - case IDownloaderClient.STATE_IDLE: - Log.d("GODOT", "DOWNLOAD STATE IDLE"); - // STATE_IDLE means the service is listening, so it's - // safe to start making calls via mRemoteService. - paused = false; - indeterminate = true; - break; - case IDownloaderClient.STATE_CONNECTING: - case IDownloaderClient.STATE_FETCHING_URL: - Log.d("GODOT", "DOWNLOAD STATE CONNECTION / FETCHING URL"); - showDashboard = true; - paused = false; - indeterminate = true; - break; - case IDownloaderClient.STATE_DOWNLOADING: - Log.d("GODOT", "DOWNLOAD STATE DOWNLOADING"); - paused = false; - showDashboard = true; - indeterminate = false; - break; - - case IDownloaderClient.STATE_FAILED_CANCELED: - case IDownloaderClient.STATE_FAILED: - case IDownloaderClient.STATE_FAILED_FETCHING_URL: - case IDownloaderClient.STATE_FAILED_UNLICENSED: - Log.d("GODOT", "DOWNLOAD STATE: FAILED, CANCELLED, UNLICENSED OR FAILED TO FETCH URL"); - paused = true; - showDashboard = false; - indeterminate = false; - break; - case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION: - case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION: - Log.d("GODOT", "DOWNLOAD STATE: PAUSED BY MISSING CELLULAR PERMISSION"); - showDashboard = false; - paused = true; - indeterminate = false; - showCellMessage = true; - break; - - case IDownloaderClient.STATE_PAUSED_BY_REQUEST: - Log.d("GODOT", "DOWNLOAD STATE: PAUSED BY USER"); - paused = true; - indeterminate = false; - break; - case IDownloaderClient.STATE_PAUSED_ROAMING: - case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE: - Log.d("GODOT", "DOWNLOAD STATE: PAUSED BY ROAMING OR SDCARD UNAVAILABLE"); - paused = true; - indeterminate = false; - break; - case IDownloaderClient.STATE_COMPLETED: - Log.d("GODOT", "DOWNLOAD STATE: COMPLETED"); - showDashboard = false; - paused = false; - indeterminate = false; -// validateXAPKZipFiles(); - initializeGodot(); - return; - default: - Log.d("GODOT", "DOWNLOAD STATE: DEFAULT"); - paused = true; - indeterminate = true; - showDashboard = true; - } - int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE; - if (mDashboard.getVisibility() != newDashboardVisibility) { - mDashboard.setVisibility(newDashboardVisibility); - } - int cellMessageVisibility = showCellMessage ? View.VISIBLE : View.GONE; - if (mCellMessage.getVisibility() != cellMessageVisibility) { - mCellMessage.setVisibility(cellMessageVisibility); - } - - mPB.setIndeterminate(indeterminate); - setButtonPausedState(paused); - } + @Override + public void onDownloadStateChanged(int newState) { + Log.d("GODOT", "onDownloadStateChanged:" + newState); + setState(newState); + boolean showDashboard = true; + boolean showCellMessage = false; + boolean paused; + boolean indeterminate; + switch (newState) { + case IDownloaderClient.STATE_IDLE: + Log.d("GODOT", "DOWNLOAD STATE IDLE"); + // STATE_IDLE means the service is listening, so it's + // safe to start making calls via mRemoteService. + paused = false; + indeterminate = true; + break; + case IDownloaderClient.STATE_CONNECTING: + case IDownloaderClient.STATE_FETCHING_URL: + Log.d("GODOT", "DOWNLOAD STATE CONNECTION / FETCHING URL"); + showDashboard = true; + paused = false; + indeterminate = true; + break; + case IDownloaderClient.STATE_DOWNLOADING: + Log.d("GODOT", "DOWNLOAD STATE DOWNLOADING"); + paused = false; + showDashboard = true; + indeterminate = false; + break; + + case IDownloaderClient.STATE_FAILED_CANCELED: + case IDownloaderClient.STATE_FAILED: + case IDownloaderClient.STATE_FAILED_FETCHING_URL: + case IDownloaderClient.STATE_FAILED_UNLICENSED: + Log.d("GODOT", "DOWNLOAD STATE: FAILED, CANCELLED, UNLICENSED OR FAILED TO FETCH URL"); + paused = true; + showDashboard = false; + indeterminate = false; + break; + case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION: + case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION: + Log.d("GODOT", "DOWNLOAD STATE: PAUSED BY MISSING CELLULAR PERMISSION"); + showDashboard = false; + paused = true; + indeterminate = false; + showCellMessage = true; + break; + + case IDownloaderClient.STATE_PAUSED_BY_REQUEST: + Log.d("GODOT", "DOWNLOAD STATE: PAUSED BY USER"); + paused = true; + indeterminate = false; + break; + case IDownloaderClient.STATE_PAUSED_ROAMING: + case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE: + Log.d("GODOT", "DOWNLOAD STATE: PAUSED BY ROAMING OR SDCARD UNAVAILABLE"); + paused = true; + indeterminate = false; + break; + case IDownloaderClient.STATE_COMPLETED: + Log.d("GODOT", "DOWNLOAD STATE: COMPLETED"); + showDashboard = false; + paused = false; + indeterminate = false; + // validateXAPKZipFiles(); + initializeGodot(); + return; + default: + Log.d("GODOT", "DOWNLOAD STATE: DEFAULT"); + paused = true; + indeterminate = true; + showDashboard = true; + } + int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE; + if (mDashboard.getVisibility() != newDashboardVisibility) { + mDashboard.setVisibility(newDashboardVisibility); + } + int cellMessageVisibility = showCellMessage ? View.VISIBLE : View.GONE; + if (mCellMessage.getVisibility() != cellMessageVisibility) { + mCellMessage.setVisibility(cellMessageVisibility); + } + mPB.setIndeterminate(indeterminate); + setButtonPausedState(paused); + } @Override public void onDownloadProgress(DownloadProgressInfo progress) { mAverageSpeed.setText(getString(com.godot.game.R.string.kilobytes_per_second, - Helpers.getSpeedString(progress.mCurrentSpeed))); - mTimeRemaining.setText(getString(com.godot.game.R.string.time_remaining, - Helpers.getTimeRemaining(progress.mTimeRemaining))); - - progress.mOverallTotal = progress.mOverallTotal; - mPB.setMax((int) (progress.mOverallTotal >> 8)); - mPB.setProgress((int) (progress.mOverallProgress >> 8)); - mProgressPercent.setText(Long.toString(progress.mOverallProgress - * 100 / - progress.mOverallTotal) + "%"); - mProgressFraction.setText(Helpers.getDownloadProgressString - (progress.mOverallProgress, - progress.mOverallTotal)); - + Helpers.getSpeedString(progress.mCurrentSpeed))); + mTimeRemaining.setText(getString(com.godot.game.R.string.time_remaining, + Helpers.getTimeRemaining(progress.mTimeRemaining))); + + progress.mOverallTotal = progress.mOverallTotal; + mPB.setMax((int)(progress.mOverallTotal >> 8)); + mPB.setProgress((int)(progress.mOverallProgress >> 8)); + mProgressPercent.setText(Long.toString(progress.mOverallProgress * 100 / + progress.mOverallTotal) + + "%"); + mProgressFraction.setText(Helpers.getDownloadProgressString(progress.mOverallProgress, + progress.mOverallTotal)); } - } diff --git a/platform/android/java/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java b/platform/android/java/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java index 2c668dd586..568c7a4140 100644 --- a/platform/android/java/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java +++ b/platform/android/java/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java @@ -46,14 +46,14 @@ import android.util.Log; */ public class GodotDownloaderAlarmReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - Log.d("GODOT", "Alarma recivida"); - try { - DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent, GodotDownloaderService.class); - } catch (NameNotFoundException e) { - e.printStackTrace(); - Log.d("GODOT", "Exception: " + e.getClass().getName() + ":" + e.getMessage()); + @Override + public void onReceive(Context context, Intent intent) { + Log.d("GODOT", "Alarma recivida"); + try { + DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent, GodotDownloaderService.class); + } catch (NameNotFoundException e) { + e.printStackTrace(); + Log.d("GODOT", "Exception: " + e.getClass().getName() + ":" + e.getMessage()); + } } - } } diff --git a/platform/android/java/src/org/godotengine/godot/GodotDownloaderService.java b/platform/android/java/src/org/godotengine/godot/GodotDownloaderService.java index 97ba7826fb..b8b3b925c5 100644 --- a/platform/android/java/src/org/godotengine/godot/GodotDownloaderService.java +++ b/platform/android/java/src/org/godotengine/godot/GodotDownloaderService.java @@ -40,46 +40,45 @@ import com.google.android.vending.expansion.downloader.impl.DownloaderService; * DownloaderService from the Downloader library. */ public class GodotDownloaderService extends DownloaderService { - // stuff for LVL -- MODIFY FOR YOUR APPLICATION! - private static final String BASE64_PUBLIC_KEY = "REPLACE THIS WITH YOUR PUBLIC KEY"; - // used by the preference obfuscater - private static final byte[] SALT = new byte[] { - 1, 43, -12, -1, 54, 98, - -100, -12, 43, 2, -8, -4, 9, 5, -106, -108, -33, 45, -1, 84 - }; + // stuff for LVL -- MODIFY FOR YOUR APPLICATION! + private static final String BASE64_PUBLIC_KEY = "REPLACE THIS WITH YOUR PUBLIC KEY"; + // used by the preference obfuscater + private static final byte[] SALT = new byte[] { + 1, 43, -12, -1, 54, 98, + -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 * used by the LVL to validate responses from Market on your behalf. */ - @Override - public String getPublicKey() { - SharedPreferences prefs = getApplicationContext().getSharedPreferences("app_data_keys", Context.MODE_PRIVATE); - Log.d("GODOT", "getting public key:" + prefs.getString("store_public_key", null)); - return prefs.getString("store_public_key", null); - - //return BASE64_PUBLIC_KEY; - } + @Override + public String getPublicKey() { + SharedPreferences prefs = getApplicationContext().getSharedPreferences("app_data_keys", Context.MODE_PRIVATE); + Log.d("GODOT", "getting public key:" + prefs.getString("store_public_key", null)); + return prefs.getString("store_public_key", null); - /** + //return BASE64_PUBLIC_KEY; + } + + /** * This is used by the preference obfuscater to make sure that your * obfuscated preferences are different than the ones used by other * applications. */ - @Override - public byte[] getSALT() { - return SALT; - } + @Override + public byte[] getSALT() { + return SALT; + } - /** + /** * 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 * to make sure that your receiver is in your unique package) */ - @Override - public String getAlarmReceiverClassName() { - Log.d("GODOT", "getAlarmReceiverClassName()"); - return GodotDownloaderAlarmReceiver.class.getName(); - } - + @Override + public String getAlarmReceiverClassName() { + Log.d("GODOT", "getAlarmReceiverClassName()"); + return GodotDownloaderAlarmReceiver.class.getName(); + } } diff --git a/platform/android/java/src/org/godotengine/godot/GodotIO.java b/platform/android/java/src/org/godotengine/godot/GodotIO.java index 989fd2b609..12a2467a29 100644 --- a/platform/android/java/src/org/godotengine/godot/GodotIO.java +++ b/platform/android/java/src/org/godotengine/godot/GodotIO.java @@ -56,7 +56,6 @@ import org.godotengine.godot.input.*; public class GodotIO { - AssetManager am; Godot activity; GodotEditText edit; @@ -64,35 +63,32 @@ public class GodotIO { Context applicationContext; MediaPlayer mediaPlayer; - final int SCREEN_LANDSCAPE=0; - final int SCREEN_PORTRAIT=1; - final int SCREEN_REVERSE_LANDSCAPE=2; - final int SCREEN_REVERSE_PORTRAIT=3; - final int SCREEN_SENSOR_LANDSCAPE=4; - final int SCREEN_SENSOR_PORTRAIT=5; - final int SCREEN_SENSOR=6; + final int SCREEN_LANDSCAPE = 0; + final int SCREEN_PORTRAIT = 1; + final int SCREEN_REVERSE_LANDSCAPE = 2; + final int SCREEN_REVERSE_PORTRAIT = 3; + final int SCREEN_SENSOR_LANDSCAPE = 4; + final int SCREEN_SENSOR_PORTRAIT = 5; + final int SCREEN_SENSOR = 6; ///////////////////////// /// FILES ///////////////////////// - public int last_file_id=1; + public int last_file_id = 1; class AssetData { - - public boolean eof=false; + public boolean eof = false; public String path; public InputStream is; public int len; public int pos; } + HashMap streams; - HashMap 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); @@ -100,7 +96,6 @@ public class GodotIO { if (write) return -1; - AssetData ad = new AssetData(); try { @@ -113,76 +108,73 @@ public class GodotIO { } try { - ad.len=ad.is.available(); + ad.len = ad.is.available(); } 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; } - ad.path=path; - ad.pos=0; + ad.path = path; + ad.pos = 0; ++last_file_id; - streams.put(last_file_id,ad); + streams.put(last_file_id, ad); return last_file_id; } public int file_get_size(int 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 streams.get(id).len; - } - public void file_seek(int id,int bytes) { + public void file_seek(int id, int bytes) { 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; } //seek sucks AssetData ad = streams.get(id); - if (bytes>ad.len) - bytes=ad.len; - if (bytes<0) - bytes=0; + if (bytes > ad.len) + bytes = ad.len; + if (bytes < 0) + bytes = 0; try { - if (bytes > (int)ad.pos) { - int todo=bytes-(int)ad.pos; - while(todo>0) { - todo-=ad.is.skip(todo); - } - ad.pos=bytes; - } else if (bytes<(int)ad.pos) { + if (bytes > (int)ad.pos) { + int todo = bytes - (int)ad.pos; + while (todo > 0) { + todo -= ad.is.skip(todo); + } + ad.pos = bytes; + } else if (bytes < (int)ad.pos) { - ad.is=am.open(ad.path); + ad.is = am.open(ad.path); - ad.pos=bytes; - int todo=bytes; - while(todo>0) { - todo-=ad.is.skip(todo); + ad.pos = bytes; + int todo = bytes; + while (todo > 0) { + todo -= ad.is.skip(todo); + } } - } - ad.eof=false; + ad.eof = false; } catch (IOException e) { - System.out.printf("Exception on file_seek: %s\n",e); + System.out.printf("Exception on file_seek: %s\n", e); return; } - - } public int file_tell(int 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; } @@ -192,7 +184,7 @@ public class GodotIO { public boolean file_eof(int 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; } @@ -203,73 +195,65 @@ public class GodotIO { public byte[] file_read(int id, int bytes) { 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]; } - AssetData ad = streams.get(id); if (ad.pos + bytes > ad.len) { - bytes=ad.len-ad.pos; - ad.eof=true; + bytes = ad.len - ad.pos; + ad.eof = true; } - - if (bytes==0) { + if (bytes == 0) { return new byte[0]; } - - - byte[] buf1=new byte[bytes]; - int r=0; + byte[] buf1 = new byte[bytes]; + int r = 0; try { r = ad.is.read(buf1); } 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]; } - if (r==0) { + if (r == 0) { return new byte[0]; } - ad.pos+=r; + ad.pos += r; - if (r dirs; + HashMap dirs; public int dir_open(String path) { AssetDir ad = new AssetDir(); - ad.current=0; - ad.path=path; + ad.current = 0; + ad.path = path; try { ad.files = am.list(path); // no way to find path is directory or file exactly. // 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; } } 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; } //System.out.printf("Opened dir: %s\n",path); ++last_dir_id; - dirs.put(last_dir_id,ad); + dirs.put(last_dir_id, ad); return last_dir_id; - } public boolean dir_is_dir(int 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; } AssetDir ad = dirs.get(id); //System.out.printf("go next: %d,%d\n",ad.current,ad.files.length); int idx = ad.current; - if (idx>0) + if (idx > 0) idx--; - if (idx>=ad.files.length) + if (idx >= ad.files.length) return false; String fname = ad.files[idx]; @@ -327,7 +310,7 @@ public class GodotIO { if (ad.path.equals("")) am.open(fname); else - am.open(ad.path+"/"+fname); + am.open(ad.path + "/" + fname); return false; } catch (Exception e) { return true; @@ -337,46 +320,41 @@ public class GodotIO { public String dir_next(int 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 ""; } AssetDir ad = dirs.get(id); //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++; return ""; } String r = ad.files[ad.current]; ad.current++; return r; - } public void dir_close(int 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; } dirs.remove(id); } - - GodotIO(Godot p_activity) { - am=p_activity.getAssets(); - activity=p_activity; - streams=new HashMap(); - dirs=new HashMap(); + am = p_activity.getAssets(); + activity = p_activity; + streams = new HashMap(); + dirs = new HashMap(); applicationContext = activity.getApplicationContext(); - } - ///////////////////////// // AUDIO ///////////////////////// @@ -400,7 +378,7 @@ public class GodotIO { desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize); mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, - channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM); + channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM); audioStartThread(); @@ -412,10 +390,10 @@ public class GodotIO { public void audioStartThread() { mAudioThread = new Thread(new Runnable() { - public void run() { - mAudioTrack.play(); - GodotLib.audio(); - } + public void run() { + mAudioTrack.play(); + GodotLib.audio(); + } }); // I'd take REALTIME if I could get it! @@ -424,15 +402,15 @@ public class GodotIO { } 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); if (result > 0) { i += result; } else if (result == 0) { try { - Thread.sleep(1); - } catch(InterruptedException e) { - // Nom nom + Thread.sleep(1); + } catch (InterruptedException e) { + // Nom nom } } else { Log.w("Godot", "Godot audio: error return from write(short)"); @@ -441,18 +419,16 @@ public class GodotIO { } } - - public void audioQuit() { if (mAudioThread != null) { try { mAudioThread.join(); - } catch(Exception e) { + } catch (Exception e) { Log.v("Godot", "Problem stopping audio thread: " + e); } mAudioThread = null; - //Log.v("Godot", "Finished waiting for audio thread"); + //Log.v("Godot", "Finished waiting for audio thread"); } if (mAudioTrack != null) { @@ -473,20 +449,18 @@ public class GodotIO { // MISCELLANEOUS OS IO ///////////////////////// - - public int openURI(String p_uri) { try { Log.v("MyApp", "TRYING TO OPEN URI: " + p_uri); String path = p_uri; - String type=""; + String type = ""; if (path.startsWith("/")) { //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")) { - type="image/*"; + type = "image/*"; } } @@ -531,7 +505,7 @@ public class GodotIO { } public void showKeyboard(String p_existing_text) { - if(edit != null) + if (edit != null) edit.showKeyboard(p_existing_text); //InputMethodManager inputMgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); @@ -539,21 +513,21 @@ public class GodotIO { }; public void hideKeyboard() { - if(edit != null) + if (edit != null) edit.hideKeyboard(); - InputMethodManager inputMgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); - View v = activity.getCurrentFocus(); - if (v != null) { - inputMgr.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); - } else { - inputMgr.hideSoftInputFromWindow(new View(activity).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); - } + InputMethodManager inputMgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); + View v = activity.getCurrentFocus(); + if (v != null) { + inputMgr.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); + } else { + inputMgr.hideSoftInputFromWindow(new View(activity).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); + } }; public void setScreenOrientation(int p_orientation) { - switch(p_orientation) { + switch (p_orientation) { case SCREEN_LANDSCAPE: { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); @@ -576,16 +550,14 @@ public class GodotIO { case SCREEN_SENSOR: { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); } break; - } }; - + public void setEdit(GodotEditText _edit) { edit = _edit; } - public void playVideo(String p_path) - { + public void playVideo(String p_path) { Uri filePath = Uri.parse(p_path); mediaPlayer = new MediaPlayer(); @@ -594,11 +566,9 @@ public class GodotIO { mediaPlayer.setDataSource(applicationContext, filePath); mediaPlayer.prepare(); 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() { @@ -621,49 +591,47 @@ public class GodotIO { } } - - public static final int SYSTEM_DIR_DESKTOP=0; - public static final int SYSTEM_DIR_DCIM=1; - public static final int SYSTEM_DIR_DOCUMENTS=2; - public static final int SYSTEM_DIR_DOWNLOADS=3; - public static final int SYSTEM_DIR_MOVIES=4; - public static final int SYSTEM_DIR_MUSIC=5; - public static final int SYSTEM_DIR_PICTURES=6; - public static final int SYSTEM_DIR_RINGTONES=7; - + public static final int SYSTEM_DIR_DESKTOP = 0; + public static final int SYSTEM_DIR_DCIM = 1; + public static final int SYSTEM_DIR_DOCUMENTS = 2; + public static final int SYSTEM_DIR_DOWNLOADS = 3; + public static final int SYSTEM_DIR_MOVIES = 4; + public static final int SYSTEM_DIR_MUSIC = 5; + public static final int SYSTEM_DIR_PICTURES = 6; + public static final int SYSTEM_DIR_RINGTONES = 7; public String getSystemDir(int idx) { - String what=""; - switch(idx) { + String what = ""; + switch (idx) { case SYSTEM_DIR_DESKTOP: { //what=Environment.DIRECTORY_DOCUMENTS; - what=Environment.DIRECTORY_DOWNLOADS; + what = Environment.DIRECTORY_DOWNLOADS; } break; case SYSTEM_DIR_DCIM: { - what=Environment.DIRECTORY_DCIM; + what = Environment.DIRECTORY_DCIM; } break; case SYSTEM_DIR_DOCUMENTS: { - what=Environment.DIRECTORY_DOWNLOADS; + what = Environment.DIRECTORY_DOWNLOADS; //what=Environment.DIRECTORY_DOCUMENTS; } break; case SYSTEM_DIR_DOWNLOADS: { - what=Environment.DIRECTORY_DOWNLOADS; + what = Environment.DIRECTORY_DOWNLOADS; } break; case SYSTEM_DIR_MOVIES: { - what=Environment.DIRECTORY_MOVIES; + what = Environment.DIRECTORY_MOVIES; } break; case SYSTEM_DIR_MUSIC: { - what=Environment.DIRECTORY_MUSIC; + what = Environment.DIRECTORY_MUSIC; } break; case SYSTEM_DIR_PICTURES: { - what=Environment.DIRECTORY_PICTURES; + what = Environment.DIRECTORY_PICTURES; } break; case SYSTEM_DIR_RINGTONES: { - what=Environment.DIRECTORY_RINGTONES; + what = Environment.DIRECTORY_RINGTONES; } break; } @@ -676,10 +644,9 @@ public class GodotIO { protected static final String PREFS_FILE = "device_id.xml"; protected static final String PREFS_DEVICE_ID = "device_id"; - public static String unique_id=""; + public static String unique_id = ""; public String getUniqueID() { - return unique_id; + return unique_id; } - } diff --git a/platform/android/java/src/org/godotengine/godot/GodotLib.java b/platform/android/java/src/org/godotengine/godot/GodotLib.java index 6b84ad6555..873d30eb34 100644 --- a/platform/android/java/src/org/godotengine/godot/GodotLib.java +++ b/platform/android/java/src/org/godotengine/godot/GodotLib.java @@ -33,43 +33,41 @@ package org.godotengine.godot; 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 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 setup(String[] p_cmdline); - public static native void resize(int width, int height,boolean reload); - public static native void newcontext(boolean p_32_bits); - public static native void back(); - public static native void step(); - 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 gravity(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 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 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 joyconnectionchanged(int p_device, boolean p_connected, String p_name); - public static native void focusin(); - public static native void focusout(); - public static native void audio(); - 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 String getGlobal(String p_key); + 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 resize(int width, int height, boolean reload); + public static native void newcontext(boolean p_32_bits); + public static native void back(); + public static native void step(); + 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 gravity(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 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 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 joyconnectionchanged(int p_device, boolean p_connected, String p_name); + public static native void focusin(); + public static native void focusout(); + public static native void audio(); + 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 String getGlobal(String p_key); 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 setVirtualKeyboardHeight(int p_height); - } diff --git a/platform/android/java/src/org/godotengine/godot/GodotPaymentV3.java b/platform/android/java/src/org/godotengine/godot/GodotPaymentV3.java index 8fe79fdfc7..61d10ed9e4 100644 --- a/platform/android/java/src/org/godotengine/godot/GodotPaymentV3.java +++ b/platform/android/java/src/org/godotengine/godot/GodotPaymentV3.java @@ -40,7 +40,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - public class GodotPaymentV3 extends Godot.SingletonBase { private Godot activity; @@ -67,8 +66,8 @@ public class GodotPaymentV3 extends Godot.SingletonBase { public GodotPaymentV3(Activity p_activity) { - registerClass("GodotPayments", new String[]{"purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix", "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased", "setAutoConsume", "consume", "querySkuDetails"}); - activity = (Godot) p_activity; + registerClass("GodotPayments", new String[] { "purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix", "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased", "setAutoConsume", "consume", "querySkuDetails" }); + activity = (Godot)p_activity; mPaymentManager = activity.getPaymentsManager(); mPaymentManager.setBaseSingleton(this); } @@ -89,32 +88,32 @@ public class GodotPaymentV3 extends Godot.SingletonBase { } 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) { 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() { - GodotLib.calldeferred(purchaseCallbackId, "consume_not_required", new Object[]{}); + GodotLib.calldeferred(purchaseCallbackId, "consume_not_required", new Object[] {}); } public void callbackFailConsume() { - GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[]{}); + GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[] {}); } public void callbackFail() { - GodotLib.calldeferred(purchaseCallbackId, "purchase_fail", new Object[]{}); + GodotLib.calldeferred(purchaseCallbackId, "purchase_fail", new Object[] {}); } public void callbackCancel() { - GodotLib.calldeferred(purchaseCallbackId, "purchase_cancel", new Object[]{}); + GodotLib.calldeferred(purchaseCallbackId, "purchase_cancel", new Object[] {}); } public void callbackAlreadyOwned(String sku) { - GodotLib.calldeferred(purchaseCallbackId, "purchase_owned", new Object[]{sku}); + GodotLib.calldeferred(purchaseCallbackId, "purchase_owned", new Object[] { sku }); } public int getPurchaseCallbackId() { @@ -161,7 +160,7 @@ public class GodotPaymentV3 extends Godot.SingletonBase { // callback for requestPurchased() 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. @@ -210,10 +209,10 @@ public class GodotPaymentV3 extends Godot.SingletonBase { } 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) { - GodotLib.calldeferred(purchaseCallbackId, "sku_details_error", new Object[]{errorMessage}); + GodotLib.calldeferred(purchaseCallbackId, "sku_details_error", new Object[] { errorMessage }); } } diff --git a/platform/android/java/src/org/godotengine/godot/GodotView.java b/platform/android/java/src/org/godotengine/godot/GodotView.java index b807b952d4..b762aa021a 100644 --- a/platform/android/java/src/org/godotengine/godot/GodotView.java +++ b/platform/android/java/src/org/godotengine/godot/GodotView.java @@ -77,20 +77,19 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { private static Context ctx; private static GodotIO io; - private static boolean firsttime=true; - private static boolean use_gl3=false; - private static boolean use_32=false; + private static boolean firsttime = true; + private static boolean use_gl3 = false; + private static boolean use_32 = false; private Godot activity; - 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); - ctx=context; - io=p_io; - use_gl3=p_use_gl3; - use_32=p_use_32_bits; + ctx = context; + io = p_io; + use_gl3 = p_use_gl3; + use_32 = p_use_32_bits; activity = p_activity; @@ -101,14 +100,15 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { mInputManager = InputManagerCompat.Factory.getInputManager(this.getContext()); mInputManager.registerInputDeviceListener(this, null); 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); init(translucent, depth, stencil); - } + } - @Override public boolean onTouchEvent (MotionEvent event) { + @Override + public boolean onTouchEvent(MotionEvent event) { return activity.gotTouchEvent(event); }; @@ -196,16 +196,17 @@ public class GodotView extends GLSurfaceView implements InputDeviceListener { ArrayList joy_devices = new ArrayList(); private int find_joy_device(int device_id) { - for (int i=0; i= Build.VERSION_CODES.JELLY_BEAN) { - return new InputManagerV16(context); - } else { - return new InputManagerV9(); - } - } - } + /** + * Constructs and returns a compatible InputManger + * + * @param context the Context that will be used to get the system + * service from + * @return a compatible implementation of InputManager + */ + public static InputManagerCompat getInputManager(Context context) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + return new InputManagerV16(context); + } else { + return new InputManagerV9(); + } + } + } } diff --git a/platform/android/java/src/org/godotengine/godot/input/InputManagerV16.java b/platform/android/java/src/org/godotengine/godot/input/InputManagerV16.java index f05701f455..3b88609cc9 100644 --- a/platform/android/java/src/org/godotengine/godot/input/InputManagerV16.java +++ b/platform/android/java/src/org/godotengine/godot/input/InputManagerV16.java @@ -30,78 +30,74 @@ import java.util.Map; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class InputManagerV16 implements InputManagerCompat { - private final InputManager mInputManager; - private final Map mListeners; - - public InputManagerV16(Context context) { - mInputManager = (InputManager) context.getSystemService(Context.INPUT_SERVICE); - mListeners = new HashMap(); - } - - @Override - public InputDevice getInputDevice(int id) { - return mInputManager.getInputDevice(id); - } - - @Override - public int[] getInputDeviceIds() { - return mInputManager.getInputDeviceIds(); - } - - static class V16InputDeviceListener implements InputManager.InputDeviceListener { - final InputManagerCompat.InputDeviceListener mIDL; - - public V16InputDeviceListener(InputDeviceListener idl) { - mIDL = idl; - } - - @Override - public void onInputDeviceAdded(int deviceId) { - mIDL.onInputDeviceAdded(deviceId); - } - - @Override - public void onInputDeviceChanged(int deviceId) { - mIDL.onInputDeviceChanged(deviceId); - } - - @Override - public void onInputDeviceRemoved(int 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 - public void unregisterInputDeviceListener(InputDeviceListener listener) { - V16InputDeviceListener curListener = mListeners.remove(listener); - if (null != curListener) - { - mInputManager.unregisterInputDeviceListener(curListener); - } - - } - - @Override - public void onGenericMotionEvent(MotionEvent event) { - // unused in V16 - } - - @Override - public void onPause() { - // unused in V16 - } - - @Override - public void onResume() { - // unused in V16 - } - + private final InputManager mInputManager; + private final Map mListeners; + + public InputManagerV16(Context context) { + mInputManager = (InputManager)context.getSystemService(Context.INPUT_SERVICE); + mListeners = new HashMap(); + } + + @Override + public InputDevice getInputDevice(int id) { + return mInputManager.getInputDevice(id); + } + + @Override + public int[] getInputDeviceIds() { + return mInputManager.getInputDeviceIds(); + } + + static class V16InputDeviceListener implements InputManager.InputDeviceListener { + final InputManagerCompat.InputDeviceListener mIDL; + + public V16InputDeviceListener(InputDeviceListener idl) { + mIDL = idl; + } + + @Override + public void onInputDeviceAdded(int deviceId) { + mIDL.onInputDeviceAdded(deviceId); + } + + @Override + public void onInputDeviceChanged(int deviceId) { + mIDL.onInputDeviceChanged(deviceId); + } + + @Override + public void onInputDeviceRemoved(int 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 + public void unregisterInputDeviceListener(InputDeviceListener listener) { + V16InputDeviceListener curListener = mListeners.remove(listener); + if (null != curListener) { + mInputManager.unregisterInputDeviceListener(curListener); + } + } + + @Override + public void onGenericMotionEvent(MotionEvent event) { + // unused in V16 + } + + @Override + public void onPause() { + // unused in V16 + } + + @Override + public void onResume() { + // unused in V16 + } } diff --git a/platform/android/java/src/org/godotengine/godot/input/InputManagerV9.java b/platform/android/java/src/org/godotengine/godot/input/InputManagerV9.java index 0334c00997..a1418c5899 100644 --- a/platform/android/java/src/org/godotengine/godot/input/InputManagerV9.java +++ b/platform/android/java/src/org/godotengine/godot/input/InputManagerV9.java @@ -31,181 +31,179 @@ import java.util.Map; import java.util.Queue; public class InputManagerV9 implements InputManagerCompat { - private static final String LOG_TAG = "InputManagerV9"; - private static final int MESSAGE_TEST_FOR_DISCONNECT = 101; - private static final long CHECK_ELAPSED_TIME = 3000L; - - private static final int ON_DEVICE_ADDED = 0; - private static final int ON_DEVICE_CHANGED = 1; - private static final int ON_DEVICE_REMOVED = 2; - - private final SparseArray mDevices; - private final Map mListeners; - private final Handler mDefaultHandler; - - private static class PollingMessageHandler extends Handler { - private final WeakReference mInputManager; - - PollingMessageHandler(InputManagerV9 im) { - mInputManager = new WeakReference(im); - } - - @Override - public void handleMessage(Message msg) { - super.handleMessage(msg); - switch (msg.what) { - case MESSAGE_TEST_FOR_DISCONNECT: - InputManagerV9 imv = mInputManager.get(); - if (null != imv) { - long time = SystemClock.elapsedRealtime(); - int size = imv.mDevices.size(); - for (int i = 0; i < size; i++) { - long[] lastContact = imv.mDevices.valueAt(i); - if (null != lastContact) { - if (time - lastContact[0] > CHECK_ELAPSED_TIME) { - // check to see if the device has been - // disconnected - int id = imv.mDevices.keyAt(i); - if (null == InputDevice.getDevice(id)) { - // disconnected! - imv.notifyListeners(ON_DEVICE_REMOVED, id); - imv.mDevices.remove(id); - } else { - lastContact[0] = time; - } - } - } - } - sendEmptyMessageDelayed(MESSAGE_TEST_FOR_DISCONNECT, - CHECK_ELAPSED_TIME); - } - break; - } - } - - } - - public InputManagerV9() { - mDevices = new SparseArray(); - mListeners = new HashMap(); - mDefaultHandler = new PollingMessageHandler(this); - // as a side-effect, populates our collection of watched - // input devices - getInputDeviceIds(); - } - - @Override - public InputDevice getInputDevice(int id) { - return InputDevice.getDevice(id); - } - - @Override - public int[] getInputDeviceIds() { - // 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 - public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) { - mListeners.remove(listener); - if (handler == null) { - handler = mDefaultHandler; - } - mListeners.put(listener, handler); - } - - @Override - public void unregisterInputDeviceListener(InputDeviceListener listener) { - mListeners.remove(listener); - } - - private void notifyListeners(int why, int deviceId) { - // the state of some device has changed - 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 static class DeviceEvent implements Runnable { - private int mMessageType; - private int mId; - private InputDeviceListener mListener; - private static Queue sEventQueue = new ArrayDeque(); - - 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; - } - - @Override - public void run() { - switch (mMessageType) { - case ON_DEVICE_ADDED: - mListener.onInputDeviceAdded(mId); - break; - case ON_DEVICE_CHANGED: - mListener.onInputDeviceChanged(mId); - break; - 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 - public void onGenericMotionEvent(MotionEvent event) { - // detect new devices - 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); - } - + private static final String LOG_TAG = "InputManagerV9"; + private static final int MESSAGE_TEST_FOR_DISCONNECT = 101; + private static final long CHECK_ELAPSED_TIME = 3000L; + + private static final int ON_DEVICE_ADDED = 0; + private static final int ON_DEVICE_CHANGED = 1; + private static final int ON_DEVICE_REMOVED = 2; + + private final SparseArray mDevices; + private final Map mListeners; + private final Handler mDefaultHandler; + + private static class PollingMessageHandler extends Handler { + private final WeakReference mInputManager; + + PollingMessageHandler(InputManagerV9 im) { + mInputManager = new WeakReference(im); + } + + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case MESSAGE_TEST_FOR_DISCONNECT: + InputManagerV9 imv = mInputManager.get(); + if (null != imv) { + long time = SystemClock.elapsedRealtime(); + int size = imv.mDevices.size(); + for (int i = 0; i < size; i++) { + long[] lastContact = imv.mDevices.valueAt(i); + if (null != lastContact) { + if (time - lastContact[0] > CHECK_ELAPSED_TIME) { + // check to see if the device has been + // disconnected + int id = imv.mDevices.keyAt(i); + if (null == InputDevice.getDevice(id)) { + // disconnected! + imv.notifyListeners(ON_DEVICE_REMOVED, id); + imv.mDevices.remove(id); + } else { + lastContact[0] = time; + } + } + } + } + sendEmptyMessageDelayed(MESSAGE_TEST_FOR_DISCONNECT, + CHECK_ELAPSED_TIME); + } + break; + } + } + } + + public InputManagerV9() { + mDevices = new SparseArray(); + mListeners = new HashMap(); + mDefaultHandler = new PollingMessageHandler(this); + // as a side-effect, populates our collection of watched + // input devices + getInputDeviceIds(); + } + + @Override + public InputDevice getInputDevice(int id) { + return InputDevice.getDevice(id); + } + + @Override + public int[] getInputDeviceIds() { + // 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 + public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) { + mListeners.remove(listener); + if (handler == null) { + handler = mDefaultHandler; + } + mListeners.put(listener, handler); + } + + @Override + public void unregisterInputDeviceListener(InputDeviceListener listener) { + mListeners.remove(listener); + } + + private void notifyListeners(int why, int deviceId) { + // the state of some device has changed + 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 static class DeviceEvent implements Runnable { + private int mMessageType; + private int mId; + private InputDeviceListener mListener; + private static Queue sEventQueue = new ArrayDeque(); + + 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; + } + + @Override + public void run() { + switch (mMessageType) { + case ON_DEVICE_ADDED: + mListener.onInputDeviceAdded(mId); + break; + case ON_DEVICE_CHANGED: + mListener.onInputDeviceChanged(mId); + break; + 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 + public void onGenericMotionEvent(MotionEvent event) { + // detect new devices + 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); + } } diff --git a/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java b/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java index 8622f4ccff..d6f26e19b2 100644 --- a/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java +++ b/platform/android/java/src/org/godotengine/godot/payments/ConsumeTask.java @@ -39,33 +39,32 @@ import android.util.Log; abstract public class ConsumeTask { private Context context; - + private IInAppBillingService mService; - public ConsumeTask(IInAppBillingService mService, Context context ){ + public ConsumeTask(IInAppBillingService mService, Context context) { this.context = context; this.mService = mService; } - - public void consume(final String sku){ + public void consume(final String sku) { //Log.d("XXX", "Consuming product " + sku); PaymentsCache pc = new PaymentsCache(context); Boolean isBlocked = pc.getConsumableFlag("block", sku); String _token = pc.getConsumableValue("token", sku); - //Log.d("XXX", "token " + _token); - if(!isBlocked && _token == null){ + //Log.d("XXX", "token " + _token); + if (!isBlocked && _token == null) { //_token = "inapp:"+context.getPackageName()+":android.test.purchased"; //Log.d("XXX", "Consuming product " + sku + " with token " + _token); - }else if(!isBlocked){ + } else if (!isBlocked) { //Log.d("XXX", "It is not blocked ¿?"); return; - }else if(_token == null){ + } else if (_token == null) { //Log.d("XXX", "No token available"); this.error("No token for sku:" + sku); return; } final String token = _token; - new AsyncTask(){ + new AsyncTask() { @Override protected String doInBackground(String... params) { @@ -73,28 +72,27 @@ abstract public class ConsumeTask { //Log.d("XXX", "Requesting to release item."); int response = mService.consumePurchase(3, context.getPackageName(), token); //Log.d("XXX", "release response code: " + response); - if(response == 0 || response == 8){ + if (response == 0 || response == 8) { return null; } } catch (RemoteException e) { return e.getMessage(); - } return "Some error"; } - - protected void onPostExecute(String param){ - if(param == null){ - success( new PaymentsCache(context).getConsumableValue("ticket", sku) ); - }else{ + + protected void onPostExecute(String param) { + if (param == null) { + success(new PaymentsCache(context).getConsumableValue("ticket", sku)); + } else { error(param); } } - - }.execute(); + + } + .execute(); } - + abstract protected void success(String ticket); abstract protected void error(String message); - } diff --git a/platform/android/java/src/org/godotengine/godot/payments/GenericConsumeTask.java b/platform/android/java/src/org/godotengine/godot/payments/GenericConsumeTask.java index 0afe35510c..31f6396738 100644 --- a/platform/android/java/src/org/godotengine/godot/payments/GenericConsumeTask.java +++ b/platform/android/java/src/org/godotengine/godot/payments/GenericConsumeTask.java @@ -36,15 +36,12 @@ import android.os.AsyncTask; import android.os.RemoteException; import android.util.Log; -abstract public class GenericConsumeTask extends AsyncTask{ +abstract public class GenericConsumeTask extends AsyncTask { private Context context; 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.mService = mService; this.sku = sku; @@ -52,19 +49,19 @@ abstract public class GenericConsumeTask extends AsyncTask= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index]; - else return String.valueOf(code) + ":Unknown IAB Helper Error"; + if (index >= 0 && index < iabhelper_msgs.length) + return iabhelper_msgs[index]; + else + return String.valueOf(code) + ":Unknown IAB Helper Error"; } else if (code < 0 || code >= iab_msgs.length) return String.valueOf(code) + ":Unknown"; else @@ -375,7 +394,7 @@ public class PaymentsManager { ArrayList responseList = skuDetails.getStringArrayList("DETAILS_LIST"); for (String thisResponse : responseList) { - Log.d("godot", "response = "+thisResponse); + Log.d("godot", "response = " + thisResponse); godotPaymentV3.addSkuDetail(thisResponse); } } catch (RemoteException e) { @@ -385,7 +404,8 @@ public class PaymentsManager { } godotPaymentV3.completeSkuDetail(); } - })).start(); + })) + .start(); } private GodotPaymentV3 godotPaymentV3; @@ -393,5 +413,4 @@ public class PaymentsManager { public void setBaseSingleton(GodotPaymentV3 godotPaymentV3) { this.godotPaymentV3 = godotPaymentV3; } - } diff --git a/platform/android/java/src/org/godotengine/godot/payments/PurchaseTask.java b/platform/android/java/src/org/godotengine/godot/payments/PurchaseTask.java index 6ecea0106c..e2f08345ad 100644 --- a/platform/android/java/src/org/godotengine/godot/payments/PurchaseTask.java +++ b/platform/android/java/src/org/godotengine/godot/payments/PurchaseTask.java @@ -50,17 +50,16 @@ import android.util.Log; abstract public class PurchaseTask { private Activity context; - + private IInAppBillingService mService; - public PurchaseTask(IInAppBillingService mService, Activity context ){ + public PurchaseTask(IInAppBillingService mService, Activity context) { this.context = context; this.mService = mService; } - 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); PaymentsCache pc = new PaymentsCache(context); Boolean isBlocked = pc.getConsumableFlag("block", sku); @@ -75,7 +74,7 @@ abstract public class PurchaseTask { Bundle buyIntentBundle; try { - buyIntentBundle = mService.getBuyIntent(3, context.getApplicationContext().getPackageName(), sku, "inapp", hash ); + buyIntentBundle = mService.getBuyIntent(3, context.getApplicationContext().getPackageName(), sku, "inapp", hash); } catch (RemoteException e) { //Log.d("XXX", "Error: " + e.getMessage()); error(e.getMessage()); @@ -83,50 +82,45 @@ abstract public class PurchaseTask { } Object rc = buyIntentBundle.get("RESPONSE_CODE"); int responseCode = 0; - if(rc == null){ + if (rc == null) { responseCode = PaymentsManager.BILLING_RESPONSE_RESULT_OK; - }else if( rc instanceof Integer){ + } else if (rc instanceof Integer) { responseCode = ((Integer)rc).intValue(); - }else if( rc instanceof Long){ + } else if (rc instanceof Long) { responseCode = (int)((Long)rc).longValue(); } //Log.d("XXX", "Buy intent response code: " + responseCode); - if(responseCode == 1 || responseCode == 3 || responseCode == 4){ + if (responseCode == 1 || responseCode == 3 || responseCode == 4) { canceled(); return; } - if(responseCode == 7){ + if (responseCode == 7) { alreadyOwned(); return; } - - + PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); pc.setConsumableValue("validation_hash", sku, hash); try { - if(context == null){ + if (context == null) { //Log.d("XXX", "No context!"); } - if(pendingIntent == null){ + if (pendingIntent == null) { //Log.d("XXX", "No pending intent"); } //Log.d("XXX", "Starting activity for purchase!"); context.startIntentSenderForResult( pendingIntent.getIntentSender(), - PaymentsManager.REQUEST_CODE_FOR_PURCHASE, - new Intent(), + PaymentsManager.REQUEST_CODE_FOR_PURCHASE, + new Intent(), Integer.valueOf(0), Integer.valueOf(0), - Integer.valueOf(0)); + Integer.valueOf(0)); } catch (SendIntentException e) { error(e.getMessage()); } - - - } abstract protected void error(String message); abstract protected void canceled(); abstract protected void alreadyOwned(); - } diff --git a/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java b/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java index d831e45694..765906d0bb 100644 --- a/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java +++ b/platform/android/java/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java @@ -48,69 +48,63 @@ abstract public class ReleaseAllConsumablesTask { private Context context; private IInAppBillingService mService; - - public ReleaseAllConsumablesTask(IInAppBillingService mService, Context context ){ + + public ReleaseAllConsumablesTask(IInAppBillingService mService, Context context) { this.context = context; this.mService = mService; } - - public void consumeItAll(){ - try{ + public void consumeItAll() { + try { //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()) { Object value = bundle.get(key); //Log.d("godot", String.format("%s %s (%s)", key, //value.toString(), value.getClass().getName())); } - - - if (bundle.getInt("RESPONSE_CODE") == 0){ + + if (bundle.getInt("RESPONSE_CODE") == 0) { final ArrayList myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST"); final ArrayList mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST"); - - if (myPurchases == null || myPurchases.size() == 0){ + if (myPurchases == null || myPurchases.size() == 0) { //Log.d("godot", "No purchases!"); notRequired(); return; } - - + //Log.d("godot", "# products to be consumed:" + myPurchases.size()); - for (int i=0;i(){ - + public void validatePurchase(final String sku) { + new AsyncTask() { + private ProgressDialog dialog; @Override - protected void onPreExecute(){ + protected void onPreExecute() { dialog = ProgressDialog.show(context, null, "Please wait..."); } - + @Override protected String doInBackground(String... params) { PaymentsCache pc = new PaymentsCache(context); @@ -90,37 +89,34 @@ abstract public class ValidateTask { //Log.d("XXX", "Validation response:\n"+jsonResponse); return jsonResponse; } - + @Override - protected void onPostExecute(String response){ - if(dialog != null){ + protected void onPostExecute(String response) { + if (dialog != null) { dialog.dismiss(); } JSONObject j; try { j = new JSONObject(response); - if(j.getString("status").equals("OK")){ + if (j.getString("status").equals("OK")) { success(); return; - }else if(j.getString("status") != null){ + } else if (j.getString("status") != null) { error(j.getString("message")); - }else{ + } else { error("Connection error"); } } catch (JSONException e) { error(e.getMessage()); - }catch (Exception e){ + } catch (Exception e) { error(e.getMessage()); } - - } - - }.execute(); + + } + .execute(); } abstract protected void success(); abstract protected void error(String message); abstract protected void canceled(); - - } diff --git a/platform/android/java/src/org/godotengine/godot/utils/Crypt.java b/platform/android/java/src/org/godotengine/godot/utils/Crypt.java index 2fd66553f6..35e4e430a4 100644 --- a/platform/android/java/src/org/godotengine/godot/utils/Crypt.java +++ b/platform/android/java/src/org/godotengine/godot/utils/Crypt.java @@ -34,34 +34,34 @@ import java.util.Random; public class Crypt { - public static String md5(String input){ - try { - // Create MD5 Hash - MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); - digest.update(input.getBytes()); - byte messageDigest[] = digest.digest(); - - // Create Hex String - StringBuffer hexString = new StringBuffer(); - for (int i=0; i */ public class CustomSSLSocketFactory extends SSLSocketFactory { - SSLContext sslContext = SSLContext.getInstance("TLS"); + SSLContext sslContext = SSLContext.getInstance("TLS"); - public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { - super(truststore); + public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { + super(truststore); - TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); - tmf.init(truststore); + TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); + tmf.init(truststore); - sslContext.init(null, tmf.getTrustManagers(), null); - } + sslContext.init(null, tmf.getTrustManagers(), null); + } - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { - return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); - } + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } - @Override - public Socket createSocket() throws IOException { - return sslContext.getSocketFactory().createSocket(); - } + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } } diff --git a/platform/android/java/src/org/godotengine/godot/utils/HttpRequester.java b/platform/android/java/src/org/godotengine/godot/utils/HttpRequester.java index 0711f30b8b..81a642af9f 100644 --- a/platform/android/java/src/org/godotengine/godot/utils/HttpRequester.java +++ b/platform/android/java/src/org/godotengine/godot/utils/HttpRequester.java @@ -63,7 +63,6 @@ import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; - import android.content.Context; import android.content.SharedPreferences; import android.util.Log; @@ -73,155 +72,154 @@ import android.util.Log; * @author Luis Linietsky */ public class HttpRequester { - + private Context context; - private static final int TTL = 600000; // 10 minutos - private long cttl=0; - - public HttpRequester(){ + private static final int TTL = 600000; // 10 minutos + private long cttl = 0; + + public HttpRequester() { //Log.d("XXX", "Creando http request sin contexto"); } - - public HttpRequester(Context context){ - this.context=context; + + public HttpRequester(Context context) { + this.context = context; //Log.d("XXX", "Creando http request con contexto"); } - - public String post(RequestParams params){ - HttpPost httppost = new HttpPost(params.getUrl()); - try { + + public String post(RequestParams params) { + HttpPost httppost = new HttpPost(params.getUrl()); + try { httppost.setEntity(new UrlEncodedFormEntity(params.toPairsList())); return request(httppost); } catch (UnsupportedEncodingException e) { return null; } } - - public String get(RequestParams params){ + + public String get(RequestParams params) { String response = getResponseFromCache(params.getUrl()); - if(response == null){ + if (response == null) { //Log.d("XXX", "Cache miss!"); - HttpGet httpget = new HttpGet(params.getUrl()); - long timeInit = new Date().getTime(); - response = request(httpget); - 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"); - if(response == null || response.length() == 0){ - response = ""; - }else{ - saveResponseIntoCache(params.getUrl(), response); - } + HttpGet httpget = new HttpGet(params.getUrl()); + long timeInit = new Date().getTime(); + response = request(httpget); + 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"); + if (response == null || response.length() == 0) { + response = ""; + } else { + saveResponseIntoCache(params.getUrl(), response); + } } Log.d("XXX", "Req: " + params.getUrl()); 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("PPP", "Haciendo request a: " + request.getURI() ); + Log.d("PPP", "Haciendo request a: " + request.getURI()); long init = new Date().getTime(); HttpClient httpclient = getNewHttpClient(); HttpParams httpParameters = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 0); HttpConnectionParams.setSoTimeout(httpParameters, 0); HttpConnectionParams.setTcpNoDelay(httpParameters, true); - try { - HttpResponse response = httpclient.execute(request); - Log.d("PPP", "Fin de request (" + (new Date().getTime() - init) + ") a: " + request.getURI() ); + try { + HttpResponse response = httpclient.execute(request); + Log.d("PPP", "Fin de request (" + (new Date().getTime() - init) + ") a: " + request.getURI()); //Log.d("XXX1", "Status:" + response.getStatusLine().toString()); - if(response.getStatusLine().getStatusCode() == 200){ - String strResponse = EntityUtils.toString(response.getEntity()); + if (response.getStatusLine().getStatusCode() == 200) { + String strResponse = EntityUtils.toString(response.getEntity()); //Log.d("XXX2", strResponse); - return strResponse; - }else{ - Log.d("XXX3", "Response status code:" + response.getStatusLine().getStatusCode() + "\n" + EntityUtils.toString(response.getEntity())); - return null; - } - - } catch (ClientProtocolException e) { - Log.d("XXX3", e.getMessage()); - } catch (IOException e) { - Log.d("XXX4", e.getMessage()); - } + return strResponse; + } else { + Log.d("XXX3", "Response status code:" + response.getStatusLine().getStatusCode() + "\n" + EntityUtils.toString(response.getEntity())); + return null; + } + + } catch (ClientProtocolException e) { + Log.d("XXX3", e.getMessage()); + } catch (IOException e) { + Log.d("XXX4", e.getMessage()); + } return null; } - + private HttpClient getNewHttpClient() { - try { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); - SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore); - sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore); + sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - HttpParams params = new BasicHttpParams(); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - registry.register(new Scheme("https", sf, 443)); + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme("https", sf, 443)); - ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); - return new DefaultHttpClient(ccm, params); - } catch (Exception e) { - return new DefaultHttpClient(); - } + return new DefaultHttpClient(ccm, params); + } catch (Exception e) { + return new DefaultHttpClient(); + } } - + private static String convertStreamToString(InputStream is) { - BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - StringBuilder sb = new StringBuilder(); - String line = null; - try { - while ((line = reader.readLine()) != null) { - sb.append((line + "\n")); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return sb.toString(); + BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + StringBuilder sb = new StringBuilder(); + String line = null; + try { + while ((line = reader.readLine()) != null) { + sb.append((line + "\n")); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return sb.toString(); } - public void saveResponseIntoCache(String request, String response){ - if(context == null){ + public void saveResponseIntoCache(String request, String response) { + if (context == null) { //Log.d("XXX", "No context, cache failed!"); return; } - SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE); - SharedPreferences.Editor editor = sharedPref.edit(); - editor.putString("request_" + Crypt.md5(request), response); - editor.putLong("request_" + Crypt.md5(request) + "_ttl", new Date().getTime() + getTtl()); - editor.commit(); + SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedPref.edit(); + editor.putString("request_" + Crypt.md5(request), response); + editor.putLong("request_" + Crypt.md5(request) + "_ttl", new Date().getTime() + getTtl()); + editor.commit(); } - - - public String getResponseFromCache(String request){ - if(context == null){ + + public String getResponseFromCache(String request) { + if (context == null) { Log.d("XXX", "No context, cache miss"); return null; } - SharedPreferences sharedPref = context.getSharedPreferences( "http_get_cache", Context.MODE_PRIVATE); - long ttl = getResponseTtl(request); - if(ttl == 0l || (new Date().getTime() - ttl) > 0l){ - Log.d("XXX", "Cache invalid ttl:" + ttl + " vs now:" + new Date().getTime()); - return null; - } - return sharedPref.getString("request_" + Crypt.md5(request), null); + SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE); + long ttl = getResponseTtl(request); + if (ttl == 0l || (new Date().getTime() - ttl) > 0l) { + Log.d("XXX", "Cache invalid ttl:" + ttl + " vs now:" + new Date().getTime()); + return null; + } + return sharedPref.getString("request_" + Crypt.md5(request), null); } - public long getResponseTtl(String request){ - SharedPreferences sharedPref = context.getSharedPreferences( - "http_get_cache", Context.MODE_PRIVATE); - return sharedPref.getLong("request_" + Crypt.md5(request) + "_ttl", 0l); + public long getResponseTtl(String request) { + SharedPreferences sharedPref = context.getSharedPreferences( + "http_get_cache", Context.MODE_PRIVATE); + return sharedPref.getLong("request_" + Crypt.md5(request) + "_ttl", 0l); } public long getTtl() { @@ -229,7 +227,6 @@ public class HttpRequester { } public void setTtl(long ttl) { - this.cttl = (ttl*1000) + new Date().getTime(); + this.cttl = (ttl * 1000) + new Date().getTime(); } - } diff --git a/platform/android/java/src/org/godotengine/godot/utils/RequestParams.java b/platform/android/java/src/org/godotengine/godot/utils/RequestParams.java index ded11550bb..051fed5500 100644 --- a/platform/android/java/src/org/godotengine/godot/utils/RequestParams.java +++ b/platform/android/java/src/org/godotengine/godot/utils/RequestParams.java @@ -43,33 +43,33 @@ import org.apache.http.message.BasicNameValuePair; */ public class RequestParams { - private HashMap params; + private HashMap params; private String url; - - public RequestParams(){ - params = new HashMap(); + + public RequestParams() { + params = new HashMap(); } - - public void put(String key, String value){ + + public void put(String key, String value) { params.put(key, value); } - - public String get(String key){ + + public String get(String key) { return params.get(key); } - - public void remove(Object key){ + + public void remove(Object key) { params.remove(key); } - - public boolean has(String key){ + + public boolean has(String key) { return params.containsKey(key); } - - public List toPairsList(){ - List fields = new ArrayList(); - for(String key : params.keySet()){ + public List toPairsList() { + List fields = new ArrayList(); + + for (String key : params.keySet()) { fields.add(new BasicNameValuePair(key, this.get(key))); } return fields; @@ -82,6 +82,4 @@ public class RequestParams { public void setUrl(String url) { this.url = url; } - - } -- cgit v1.2.3