along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<manifest package="com.owncloud.android"
- android:versionCode="10500800"
- android:versionName="1.5.8" xmlns:android="http://schemas.android.com/apk/res/android">
+ android:versionCode="10600000"
+ android:versionName="1.6.0" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.owncloud.android.workaround.accounts"
- android:versionCode="0100017"
- android:versionName="1.0.17" >
+ android:versionCode="0100018"
+ android:versionName="1.0.18" >
<uses-sdk
android:minSdkVersion="16"
-Subproject commit c29631b8bfea22e5f0b448aab8ffff959ae4de66
+Subproject commit 5bd0d7387712ce3f53869294761ac4d8537841cd
along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/fileDownloadLL"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_centerInParent="true"
/>
- <com.ortiz.touch.TouchImageView
+ <com.owncloud.android.utils.TouchImageViewCustom
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
<string name="prefs_category_accounts">Accounts</string>
<string name="prefs_add_account">Add account</string>
- <string name="auth_redirect_non_secure_connection_title">Secure connection is redirected through an unsecured route.</string>
+ <string name="auth_redirect_non_secure_connection_title">Secure connection is redirected to an unsecured route.</string>
<string name="actionbar_logger">Logs</string>
<string name="log_send_history_button">Send History</string>
import android.app.Application;
import android.content.Context;
+import com.owncloud.android.datamodel.ThumbnailsCacheManager;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory.Policy;
import com.owncloud.android.lib.common.utils.Log_OC;
OwnCloudClientManagerFactory.setDefaultPolicy(Policy.ALWAYS_NEW_CLIENT);
}
+ // initialise thumbnails cache on background thread
+ new ThumbnailsCacheManager.InitDiskCacheTask().execute();
+
if (BuildConfig.DEBUG) {
String dataFolder = getDataFolder();
if (mAccount != null) {\r
boolean oAuthRequired = \r
(mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2) != null);\r
- boolean samlWebSsoRequired = \r
- (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null);\r
+ boolean samlWebSsoRequired = ( \r
+ mAccountMgr.getUserData(\r
+ mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO\r
+ ) != null\r
+ );\r
mAuthTokenType = chooseAuthTokenType(oAuthRequired, samlWebSsoRequired);\r
\r
} else {\r
boolean oAuthSupported = AUTH_ON.equals(getString(R.string.auth_method_oauth2));\r
- boolean samlWebSsoSupported = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));\r
+ boolean samlWebSsoSupported = \r
+ AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));\r
mAuthTokenType = chooseAuthTokenType(oAuthSupported, samlWebSsoSupported);\r
}\r
}\r
if (savedInstanceState == null) {\r
if (mAccount != null) {\r
mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);\r
- mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://"); // TODO do this in a setter for mBaseUrl\r
+ // TODO do next in a setter for mBaseUrl\r
+ mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://"); \r
String ocVersion = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);\r
if (ocVersion != null) {\r
mServerInfo.mVersion = new OwnCloudVersion(ocVersion);\r
@Override\r
public boolean onTouch(View view, MotionEvent event) {\r
if (event.getAction() == MotionEvent.ACTION_DOWN) {\r
- if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&\r
- mHostUrlInput.hasFocus()) {\r
+ if (\r
+ AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(\r
+ MainApp.getAccountType()\r
+ ).equals(mAuthTokenType) &&\r
+ mHostUrlInput.hasFocus()\r
+ ) {\r
checkOcServer();\r
}\r
}\r
/**\r
* Saves relevant state before {@link #onPause()}\r
* \r
- * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the \r
- * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()} \r
+ * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, \r
+ * intended to defer the processing of the redirection caught in \r
+ * {@link #onNewIntent(Intent)} until {@link #onResume()} \r
* \r
* See {@link #loadSavedInstanceState(Bundle)}\r
*/\r
\r
\r
/**\r
- * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request\r
- * is caught here.\r
+ * The redirection triggered by the OAuth authentication server as response to the \r
+ * GET AUTHORIZATION request is caught here.\r
* \r
- * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the\r
- * AndroidManifest.xml file.\r
+ * To make this possible, this activity needs to be qualified with android:launchMode = \r
+ * "singleTask" in the AndroidManifest.xml file.\r
*/\r
@Override\r
protected void onNewIntent (Intent intent) {\r
\r
\r
/**\r
- * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and \r
- * deferred in {@link #onNewIntent(Intent)}, is processed here.\r
+ * The redirection triggered by the OAuth authentication server as response to the \r
+ * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.\r
*/\r
@Override\r
protected void onResume() {\r
\r
Intent getServerInfoIntent = new Intent();\r
getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);\r
- getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL, uri);\r
+ getServerInfoIntent.putExtra(\r
+ OperationsService.EXTRA_SERVER_URL, \r
+ normalizeUrlSuffix(uri)\r
+ );\r
if (mOperationsServiceBinder != null) {\r
mWaitingForOpId = mOperationsServiceBinder.newOperation(getServerInfoIntent);\r
} else {\r
}\r
\r
private boolean isPasswordVisible() {\r
- return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);\r
+ return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == \r
+ InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);\r
}\r
\r
private void hidePasswordButton() {\r
}\r
\r
private void showPassword() {\r
- mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);\r
+ mPasswordInput.setInputType(\r
+ InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD\r
+ );\r
showViewPasswordButton();\r
}\r
\r
private void hidePassword() {\r
- mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\r
+ mPasswordInput.setInputType(\r
+ InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD\r
+ );\r
showViewPasswordButton();\r
}\r
\r
return;\r
}\r
\r
- if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
+ if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).\r
+ equals(mAuthTokenType)) {\r
+ \r
startOauthorization();\r
- } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) { \r
+ } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
+ equals(mAuthTokenType)) {\r
+ \r
startSamlBasedFederatedSingleSignOnAuthorization();\r
} else {\r
checkBasicAuthorization();\r
// GET AUTHORIZATION request\r
Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());\r
Uri.Builder uriBuilder = uri.buildUpon();\r
- uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type));\r
- uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri)); \r
- uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));\r
- uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));\r
+ uriBuilder.appendQueryParameter(\r
+ OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type)\r
+ );\r
+ uriBuilder.appendQueryParameter(\r
+ OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri)\r
+ ); \r
+ uriBuilder.appendQueryParameter(\r
+ OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id)\r
+ );\r
+ uriBuilder.appendQueryParameter(\r
+ OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope)\r
+ );\r
uri = uriBuilder.build();\r
Log_OC.d(TAG, "Starting browser to view " + uri.toString());\r
Intent i = new Intent(Intent.ACTION_VIEW, uri);\r
\r
} else if (operation instanceof ExistenceCheckRemoteOperation) {\r
//Log_OC.wtf(TAG, "received detection response through callback" );\r
- if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
+ if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
+ equals(mAuthTokenType)) {\r
onSamlBasedFederatedSingleSignOnAuthorizationStart(result);\r
\r
} else {\r
url = "http://" + url;\r
}\r
}\r
- \r
- url = trimUrlWebdav(url);\r
-\r
- if (url.endsWith("/")) {\r
- url = url.substring(0, url.length() - 1);\r
- }\r
-\r
+ \r
+ url = normalizeUrlSuffix(url);\r
}\r
return (url != null ? url : "");\r
}\r
+ \r
+ \r
+ private String normalizeUrlSuffix(String url) {\r
+ if (url.endsWith("/")) {\r
+ url = url.substring(0, url.length() - 1);\r
+ }\r
+ url = trimUrlWebdav(url);\r
+ return url;\r
+ }\r
\r
\r
// TODO remove, if possible\r
@SuppressWarnings("unchecked")\r
Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));\r
mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
- //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);\r
\r
accessRootFolderRemoteOperation("", "");\r
showRefreshButton(true);\r
mOkButton.setEnabled(false);\r
\r
- // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)\r
+ // very special case (TODO: move to a common place for all the remote operations)\r
if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {\r
showUntrustedCertDialog(result);\r
}\r
\r
\r
/**\r
- * Sets the proper response to get that the Account Authenticator that started this activity saves \r
- * a new authorization token for mAccount.\r
+ * Sets the proper response to get that the Account Authenticator that started this activity \r
+ * saves a new authorization token for mAccount.\r
*/\r
private void updateToken() {\r
Bundle response = new Bundle();\r
response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);\r
response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);\r
\r
- if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) { \r
+ if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).\r
+ equals(mAuthTokenType)) { \r
response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);\r
- // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention\r
+ // the next line is necessary, notifications are calling directly to the \r
+ // AuthenticatorActivity to update, without AccountManager intervention\r
mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
\r
- } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
+ } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
+ equals(mAuthTokenType)) {\r
\r
response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);\r
- // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention\r
+ // the next line is necessary; by now, notifications are calling directly to the \r
+ // AuthenticatorActivity to update, without AccountManager intervention\r
mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
\r
} else {\r
*/\r
private boolean createAccount() {\r
/// create and save new ownCloud account\r
- boolean isOAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);\r
- boolean isSaml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);\r
+ boolean isOAuth = AccountTypeUtils.\r
+ getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);\r
+ boolean isSaml = AccountTypeUtils.\r
+ getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);\r
\r
Uri uri = Uri.parse(mServerInfo.mBaseUrl);\r
String username = mUsernameInput.getText().toString().trim();\r
mAccount = newAccount;\r
\r
if (isOAuth || isSaml) {\r
- mAccountMgr.addAccountExplicitly(mAccount, "", null); // with external authorizations, the password is never input in the app\r
+ // with external authorizations, the password is never input in the app\r
+ mAccountMgr.addAccountExplicitly(mAccount, "", null); \r
} else {\r
- mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);\r
+ mAccountMgr.addAccountExplicitly(\r
+ mAccount, mPasswordInput.getText().toString(), null\r
+ );\r
}\r
\r
/// add the new account as default in preferences, if there is none already\r
}\r
\r
/// prepare result to return to the Authenticator\r
- // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done\r
+ // TODO check again what the Authenticator makes with it; probably has the same \r
+ // effect as addAccountExplicitly, but it's not well done\r
final Intent intent = new Intent(); \r
intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());\r
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);\r
if (isOAuth || isSaml) {\r
mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
}\r
- /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
- mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());\r
- mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);\r
+ /// add user data to the new account; TODO probably can be done in the last parameter \r
+ // addAccountExplicitly, or in KEY_USERDATA
+ mAccountMgr.setUserData(\r
+ mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion()\r
+ );\r
+ mAccountMgr.setUserData(\r
+ mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl\r
+ );\r
if (isSaml) {\r
mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE"); \r
* @param view 'Account register' button\r
*/\r
public void onRegisterClick(View view) {\r
- Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url)));\r
+ Intent register = new Intent(\r
+ Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url))\r
+ );\r
setResult(RESULT_CANCELED);\r
startActivity(register);\r
}\r
/**\r
* Called when the 'action' button in an IME is pressed ('enter' in software keyboard).\r
* \r
- * Used to trigger the authentication check when the user presses 'enter' after writing the password, \r
- * or to throw the server test when the only field on screen is the URL input field.\r
+ * Used to trigger the authentication check when the user presses 'enter' after writing the \r
+ * password, or to throw the server test when the only field on screen is the URL input field.\r
*/\r
@Override\r
public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {\r
- if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && inputField.equals(mPasswordInput)) {\r
+ if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && \r
+ inputField.equals(mPasswordInput)) {\r
if (mOkButton.isEnabled()) {\r
mOkButton.performClick();\r
}\r
\r
- } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && inputField.equals(mHostUrlInput)) {\r
- if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
+ } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && \r
+ inputField.equals(mHostUrlInput)) {\r
+ if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
+ equals(mAuthTokenType)) {\r
checkOcServer();\r
}\r
}\r
final int x = (int) event.getX();\r
final int y = (int) event.getY();\r
final Rect bounds = rightDrawable.getBounds();\r
- if (x >= (view.getRight() - bounds.width() - fuzz) && x <= (view.getRight() - view.getPaddingRight() + fuzz)\r
- && y >= (view.getPaddingTop() - fuzz) && y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {\r
+ if ( x >= (view.getRight() - bounds.width() - fuzz) && \r
+ x <= (view.getRight() - view.getPaddingRight() + fuzz) && \r
+ y >= (view.getPaddingTop() - fuzz) &&\r
+ y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {\r
\r
return onDrawableTouch(event);\r
}\r
\r
@Override\r
public boolean onTouchEvent(MotionEvent event) {\r
- if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&\r
+ if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
+ equals(mAuthTokenType) &&\r
mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {\r
checkOcServer();\r
}\r
/**\r
* Show untrusted cert dialog \r
*/\r
- public void showUntrustedCertDialog(X509Certificate x509Certificate, SslError error, SslErrorHandler handler) {\r
+ public void showUntrustedCertDialog(\r
+ X509Certificate x509Certificate, SslError error, SslErrorHandler handler\r
+ ) {\r
// Show a dialog with the certificate info\r
SslUntrustedCertDialog dialog = null;\r
if (x509Certificate == null) {\r
dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);\r
} else {\r
- dialog = SslUntrustedCertDialog.newInstanceForFullSslError(x509Certificate, error, handler);\r
+ dialog = SslUntrustedCertDialog.\r
+ newInstanceForFullSslError(x509Certificate, error, handler);\r
}\r
FragmentManager fm = getSupportFragmentManager();\r
FragmentTransaction ft = fm.beginTransaction();\r
*/\r
private void showUntrustedCertDialog(RemoteOperationResult result) {\r
// Show a dialog with the certificate info\r
- SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());\r
+ SslUntrustedCertDialog dialog = SslUntrustedCertDialog.\r
+ newInstanceForFullSslError((CertificateCombinedException)result.getException());\r
FragmentManager fm = getSupportFragmentManager();\r
FragmentTransaction ft = fm.beginTransaction();\r
ft.addToBackStack(null);\r
public void onSavedCertificate() {\r
Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);\r
if (fd == null) {\r
- // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check\r
+ // if SAML dialog is not shown, \r
+ // the SslDialog was shown due to an SSL error in the server check\r
checkOcServer();\r
}\r
}\r
\r
@Override\r
public void onServiceConnected(ComponentName component, IBinder service) {\r
- if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {\r
+ if (component.equals(\r
+ new ComponentName(AuthenticatorActivity.this, OperationsService.class)\r
+ )) {\r
//Log_OC.wtf(TAG, "Operations service connected");\r
mOperationsServiceBinder = (OperationsServiceBinder) service;\r
\r
\r
@Override\r
public void onServiceDisconnected(ComponentName component) {\r
- if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {\r
+ if (component.equals(\r
+ new ComponentName(AuthenticatorActivity.this, OperationsService.class)\r
+ )) {\r
Log_OC.e(TAG, "Operations service crashed");\r
mOperationsServiceBinder = null;\r
}\r
public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {\r
\r
// Show a dialog with the certificate info\r
- CredentialsDialogFragment dialog = CredentialsDialogFragment.newInstanceForCredentials(webView, handler);\r
+ CredentialsDialogFragment dialog = \r
+ CredentialsDialogFragment.newInstanceForCredentials(webView, handler);\r
FragmentManager fm = getSupportFragmentManager();\r
FragmentTransaction ft = fm.beginTransaction();\r
ft.addToBackStack(null);\r
dialog.show(ft, CREDENTIALS_DIALOG_TAG);\r
\r
if (!mIsFirstAuthAttempt) {\r
- Toast.makeText(getApplicationContext(), getText(R.string.saml_authentication_wrong_pass), Toast.LENGTH_LONG).show();\r
+ Toast.makeText(\r
+ getApplicationContext(), \r
+ getText(R.string.saml_authentication_wrong_pass), \r
+ Toast.LENGTH_LONG\r
+ ).show();\r
} else {\r
mIsFirstAuthAttempt = false;\r
}\r
public Vector<OCFile> getFolderImages(OCFile folder) {
Vector<OCFile> ret = new Vector<OCFile>();
if (folder != null) {
- // TODO better implementation, filtering in the access to database (if possible) instead of here
+ // TODO better implementation, filtering in the access to database instead of here
Vector<OCFile> tmp = getFolderContent(folder);
OCFile current = null;
for (int i=0; i<tmp.size(); i++) {
boolean overriden = false;
ContentValues cv = new ContentValues();
cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
- cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData());
+ cv.put(
+ ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
+ file.getModificationTimestampAtLastSyncForData()
+ );
cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
boolean sameRemotePath = fileExists(file.getRemotePath());
if (sameRemotePath ||
- fileExists(file.getFileId()) ) { // for renamed files; no more delete and create
+ fileExists(file.getFileId()) ) { // for renamed files
OCFile oldFile = null;
if (sameRemotePath) {
* @param files
* @param removeNotUpdated
*/
- public void saveFolder(OCFile folder, Collection<OCFile> updatedFiles, Collection<OCFile> filesToRemove) {
+ public void saveFolder(
+ OCFile folder, Collection<OCFile> updatedFiles, Collection<OCFile> filesToRemove
+ ) {
- Log_OC.d(TAG, "Saving folder " + folder.getRemotePath() + " with " + updatedFiles.size() + " children and " + filesToRemove.size() + " files to remove");
+ Log_OC.d(TAG, "Saving folder " + folder.getRemotePath() + " with " + updatedFiles.size()
+ + " children and " + filesToRemove.size() + " files to remove");
- ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(updatedFiles.size());
+ ArrayList<ContentProviderOperation> operations =
+ new ArrayList<ContentProviderOperation>(updatedFiles.size());
// prepare operations to insert or update files to save in the given folder
for (OCFile file : updatedFiles) {
ContentValues cv = new ContentValues();
cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
- cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData());
+ cv.put(
+ ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
+ file.getModificationTimestampAtLastSyncForData()
+ );
cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
} else {
// adding a new file
- operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
+ operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
+ withValues(cv).build());
}
}
// prepare operations to remove files in the given folder
- String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
+ String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
+ ProviderTableMeta.FILE_PATH + "=?";
String [] whereArgs = null;
for (OCFile file : filesToRemove) {
if (file.getParentId() == folder.getFileId()) {
whereArgs = new String[]{mAccount.name, file.getRemotePath()};
//Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, "" + file.getFileId());
if (file.isFolder()) {
- operations.add(ContentProviderOperation
- .newDelete(ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, file.getFileId())).withSelection(where, whereArgs)
- .build());
- // TODO remove local folder
+ operations.add(ContentProviderOperation.newDelete(
+ ContentUris.withAppendedId(
+ ProviderTableMeta.CONTENT_URI_DIR, file.getFileId()
+ )
+ ).withSelection(where, whereArgs).build());
+
+ File localFolder =
+ new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
+ if (localFolder.exists()) {
+ removeLocalFolder(localFolder);
+ }
} else {
- operations.add(ContentProviderOperation
- .newDelete(ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, file.getFileId())).withSelection(where, whereArgs)
- .build());
+ operations.add(ContentProviderOperation.newDelete(
+ ContentUris.withAppendedId(
+ ProviderTableMeta.CONTENT_URI_FILE, file.getFileId()
+ )
+ ).withSelection(where, whereArgs).build());
+
if (file.isDown()) {
new File(file.getStoragePath()).delete();
- // TODO move the deletion of local contents after success of deletions
}
}
}
// update metadata of folder
ContentValues cv = new ContentValues();
cv.put(ProviderTableMeta.FILE_MODIFIED, folder.getModificationTimestamp());
- cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, folder.getModificationTimestampAtLastSyncForData());
+ cv.put(
+ ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
+ folder.getModificationTimestampAtLastSyncForData()
+ );
cv.put(ProviderTableMeta.FILE_CREATION, folder.getCreationTimestamp());
- cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, 0); // FileContentProvider calculates the right size
+ cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, 0);
cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, folder.getMimetype());
cv.put(ProviderTableMeta.FILE_NAME, folder.getFileName());
cv.put(ProviderTableMeta.FILE_PARENT, folder.getParentId());
// Log_OC.d(TAG, "Updating size of " + id);
// if (getContentResolver() != null) {
// getContentResolver().update(ProviderTableMeta.CONTENT_URI_DIR,
-// new ContentValues(), // won't be used, but cannot be null; crashes in KLP
+// new ContentValues(),
+ // won't be used, but cannot be null; crashes in KLP
// ProviderTableMeta._ID + "=?",
// new String[] { String.valueOf(id) });
// } else {
// try {
// getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_DIR,
-// new ContentValues(), // won't be used, but cannot be null; crashes in KLP
+// new ContentValues(),
+ // won't be used, but cannot be null; crashes in KLP
// ProviderTableMeta._ID + "=?",
// new String[] { String.valueOf(id) });
//
// } catch (RemoteException e) {
-// Log_OC.e(TAG, "Exception in update of folder size through compatibility patch " + e.getMessage());
+// Log_OC.e(
+// TAG, "Exception in update of folder size through compatibility patch " + e.getMessage());
// }
// }
// } else {
} else {
if (removeDBData) {
- //Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, ""+file.getFileId());
- Uri file_uri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, file.getFileId());
- String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
+ Uri file_uri = ContentUris.withAppendedId(
+ ProviderTableMeta.CONTENT_URI_FILE,
+ file.getFileId()
+ );
+ String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
+ ProviderTableMeta.FILE_PATH + "=?";
String [] whereArgs = new String[]{mAccount.name, file.getRemotePath()};
int deleted = 0;
if (getContentProviderClient() != null) {
}
private boolean removeFolderInDb(OCFile folder) {
- Uri folder_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, ""+ folder.getFileId()); // URI for recursive deletion
- String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
+ Uri folder_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, "" +
+ folder.getFileId()); // URI for recursive deletion
+ String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " +
+ ProviderTableMeta.FILE_PATH + "=?";
String [] whereArgs = new String[]{mAccount.name, folder.getRemotePath()};
int deleted = 0;
if (getContentProviderClient() != null) {
public void moveFolder(OCFile folder, String newPath) {
// TODO check newPath
- if (folder != null && folder.isFolder() && folder.fileExists() && !OCFile.ROOT_PATH.equals(folder.getFileName())) {
+ if ( folder != null && folder.isFolder() &&
+ folder.fileExists() && !OCFile.ROOT_PATH.equals(folder.getFileName())
+ ) {
/// 1. get all the descendants of 'dir' in a single QUERY (including 'dir')
Cursor c = null;
if (getContentProviderClient() != null) {
try {
- c = getContentProviderClient().query(ProviderTableMeta.CONTENT_URI,
- null,
- ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ",
- new String[] { mAccount.name, folder.getRemotePath() + "%" }, ProviderTableMeta.FILE_PATH + " ASC ");
+ c = getContentProviderClient().query (
+ ProviderTableMeta.CONTENT_URI,
+ null,
+ ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
+ ProviderTableMeta.FILE_PATH + " LIKE ? ",
+ new String[] { mAccount.name, folder.getRemotePath() + "%" },
+ ProviderTableMeta.FILE_PATH + " ASC "
+ );
} catch (RemoteException e) {
Log_OC.e(TAG, e.getMessage());
}
} else {
- c = getContentResolver().query(ProviderTableMeta.CONTENT_URI,
- null,
- ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ",
- new String[] { mAccount.name, folder.getRemotePath() + "%" }, ProviderTableMeta.FILE_PATH + " ASC ");
+ c = getContentResolver().query (
+ ProviderTableMeta.CONTENT_URI,
+ null,
+ ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
+ ProviderTableMeta.FILE_PATH + " LIKE ? ",
+ new String[] { mAccount.name, folder.getRemotePath() + "%" },
+ ProviderTableMeta.FILE_PATH + " ASC "
+ );
}
/// 2. prepare a batch of update operations to change all the descendants
- ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(c.getCount());
+ ArrayList<ContentProviderOperation> operations =
+ new ArrayList<ContentProviderOperation>(c.getCount());
int lengthOfOldPath = folder.getRemotePath().length();
String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name);
int lengthOfOldStoragePath = defaultSavePath.length() + lengthOfOldPath;
if (c.moveToFirst()) {
do {
- ContentValues cv = new ContentValues(); // don't take the constructor out of the loop and clear the object
+ ContentValues cv = new ContentValues(); // keep the constructor in the loop
OCFile child = createFileInstance(c);
- cv.put(ProviderTableMeta.FILE_PATH, newPath + child.getRemotePath().substring(lengthOfOldPath));
- if (child.getStoragePath() != null && child.getStoragePath().startsWith(defaultSavePath)) {
- cv.put(ProviderTableMeta.FILE_STORAGE_PATH, defaultSavePath + newPath + child.getStoragePath().substring(lengthOfOldStoragePath));
+ cv.put(
+ ProviderTableMeta.FILE_PATH,
+ newPath + child.getRemotePath().substring(lengthOfOldPath)
+ );
+ if ( child.getStoragePath() != null &&
+ child.getStoragePath().startsWith(defaultSavePath) ) {
+ cv.put(
+ ProviderTableMeta.FILE_STORAGE_PATH,
+ defaultSavePath + newPath +
+ child.getStoragePath().substring(lengthOfOldStoragePath)
+ );
}
- operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
+ operations.add(
+ ContentProviderOperation.
+ newUpdate(ProviderTableMeta.CONTENT_URI).
withValues(cv).
- withSelection( ProviderTableMeta._ID + "=?",
- new String[] { String.valueOf(child.getFileId()) })
- .build());
+ withSelection(
+ ProviderTableMeta._ID + "=?",
+ new String[] { String.valueOf(child.getFileId()) }
+ ).
+ build()
+ );
} while (c.moveToNext());
}
c.close();
}
} catch (OperationApplicationException e) {
- Log_OC.e(TAG, "Fail to update descendants of " + folder.getFileId() + " in database", e);
+ Log_OC.e(TAG, "Fail to update descendants of " +
+ folder.getFileId() + " in database", e);
} catch (RemoteException e) {
- Log_OC.e(TAG, "Fail to update desendants of " + folder.getFileId() + " in database", e);
+ Log_OC.e(TAG, "Fail to update desendants of " +
+ folder.getFileId() + " in database", e);
}
}
file.setStoragePath(c.getString(c
.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
if (file.getStoragePath() == null) {
- // try to find existing file and bind it with current account; - with the current update of SynchronizeFolderOperation, this won't be necessary anymore after a full synchronization of the account
+ // try to find existing file and bind it with current account;
+ // with the current update of SynchronizeFolderOperation, this won't be
+ // necessary anymore after a full synchronization of the account
File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
if (f.exists()) {
file.setStoragePath(f.getAbsolutePath());
cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
- cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME, share.getSharedWithDisplayName());
+ cv.put(
+ ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
+ share.getSharedWithDisplayName()
+ );
cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
cv.put(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER, mAccount.name);
- if (shareExists(share.getIdRemoteShared())) { // for renamed files; no more delete and create
+ if (shareExists(share.getIdRemoteShared())) { // for renamed files
overriden = true;
if (getContentResolver() != null) {
share.setIsFolder(c.getInt(
c.getColumnIndex(ProviderTableMeta.OCSHARES_IS_DIRECTORY)) == 1 ? true : false);
share.setUserId(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_USER_ID)));
- share.setIdRemoteShared(c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED)));
+ share.setIdRemoteShared(
+ c.getLong(c.getColumnIndex(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED))
+ );
}
return share;
} else {
try {
- getContentProviderClient().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
+ getContentProviderClient().update(
+ ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
+ );
} catch (RemoteException e) {
Log_OC.e(TAG, "Exception in cleanSharedFiles" + e.getMessage());
ContentValues cv = new ContentValues();
cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, false);
cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, "");
- String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PARENT + "=?";
+ String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +
+ ProviderTableMeta.FILE_PARENT + "=?";
String [] whereArgs = new String[] { mAccount.name , String.valueOf(folder.getFileId()) };
if (getContentResolver() != null) {
} else {
try {
- getContentProviderClient().update(ProviderTableMeta.CONTENT_URI, cv, where, whereArgs);
+ getContentProviderClient().update(
+ ProviderTableMeta.CONTENT_URI, cv, where, whereArgs
+ );
} catch (RemoteException e) {
Log_OC.e(TAG, "Exception in cleanSharedFilesInFolder " + e.getMessage());
} else {
try {
- getContentProviderClient().delete(ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs);
+ getContentProviderClient().delete(
+ ProviderTableMeta.CONTENT_URI_SHARE, where, whereArgs
+ );
} catch (RemoteException e) {
Log_OC.e(TAG, "Exception in cleanShares" + e.getMessage());
public void saveShares(Collection<OCShare> shares) {
cleanShares();
if (shares != null) {
- ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(shares.size());
+ ArrayList<ContentProviderOperation> operations =
+ new ArrayList<ContentProviderOperation>(shares.size());
// prepare operations to insert or update files to save in the given folder
for (OCShare share : shares) {
cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
- cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME, share.getSharedWithDisplayName());
+ cv.put(
+ ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
+ share.getSharedWithDisplayName()
+ );
cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
if (shareExists(share.getIdRemoteShared())) {
// updating an existing file
- operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
+ operations.add(
+ ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
withValues(cv).
- withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
- new String[] { String.valueOf(share.getIdRemoteShared()) })
- .build());
+ withSelection(
+ ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
+ new String[] { String.valueOf(share.getIdRemoteShared()) }
+ ).
+ build()
+ );
} else {
// adding a new file
- operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).withValues(cv).build());
+ operations.add(
+ ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
+ withValues(cv).
+ build()
+ );
}
}
if (operations.size() > 0) {
@SuppressWarnings("unused")
ContentProviderResult[] results = null;
- Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
+ Log_OC.d(TAG, "Sending " + operations.size() +
+ " operations to FileContentProvider");
try {
if (getContentResolver() != null) {
- results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
+ results = getContentResolver().applyBatch(
+ MainApp.getAuthority(), operations
+ );
} else {
results = getContentProviderClient().applyBatch(operations);
cleanSharedFiles();
if (sharedFiles != null) {
- ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(sharedFiles.size());
+ ArrayList<ContentProviderOperation> operations =
+ new ArrayList<ContentProviderOperation>(sharedFiles.size());
// prepare operations to insert or update files to save in the given folder
for (OCFile file : sharedFiles) {
ContentValues cv = new ContentValues();
cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
- cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData());
+ cv.put(
+ ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA,
+ file.getModificationTimestampAtLastSyncForData()
+ );
cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
}
cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
- cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
+ cv.put(
+ ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA,
+ file.getLastSyncDateForData()
+ );
cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, file.keepInSync() ? 1 : 0);
cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
cv.put(ProviderTableMeta.FILE_SHARE_BY_LINK, file.isShareByLink() ? 1 : 0);
cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
- cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail() ? 1 : 0);
+ cv.put(
+ ProviderTableMeta.FILE_UPDATE_THUMBNAIL,
+ file.needsUpdateThumbnail() ? 1 : 0
+ );
boolean existsByPath = fileExists(file.getRemotePath());
if (existsByPath || fileExists(file.getFileId())) {
// updating an existing file
- operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
+ operations.add(
+ ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).
withValues(cv).
- withSelection( ProviderTableMeta._ID + "=?",
- new String[] { String.valueOf(file.getFileId()) })
- .build());
+ withSelection(
+ ProviderTableMeta._ID + "=?",
+ new String[] { String.valueOf(file.getFileId()) }
+ ).build()
+ );
} else {
// adding a new file
- operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
+ operations.add(
+ ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).
+ withValues(cv).
+ build()
+ );
}
}
if (operations.size() > 0) {
@SuppressWarnings("unused")
ContentProviderResult[] results = null;
- Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
+ Log_OC.d(TAG, "Sending " + operations.size() +
+ " operations to FileContentProvider");
try {
if (getContentResolver() != null) {
- results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
+ results = getContentResolver().applyBatch(
+ MainApp.getAuthority(), operations
+ );
} else {
results = getContentProviderClient().applyBatch(operations);
public void removeShare(OCShare share){
Uri share_uri = ProviderTableMeta.CONTENT_URI_SHARE;
- String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
+ String where = ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?" + " AND " +
+ ProviderTableMeta.FILE_PATH + "=?";
String [] whereArgs = new String[]{mAccount.name, share.getPath()};
if (getContentProviderClient() != null) {
try {
cv.put(ProviderTableMeta.OCSHARES_SHARED_DATE, share.getSharedDate());
cv.put(ProviderTableMeta.OCSHARES_EXPIRATION_DATE, share.getExpirationDate());
cv.put(ProviderTableMeta.OCSHARES_TOKEN, share.getToken());
- cv.put(ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME, share.getSharedWithDisplayName());
+ cv.put(
+ ProviderTableMeta.OCSHARES_SHARE_WITH_DISPLAY_NAME,
+ share.getSharedWithDisplayName()
+ );
cv.put(ProviderTableMeta.OCSHARES_IS_DIRECTORY, share.isFolder() ? 1 : 0);
cv.put(ProviderTableMeta.OCSHARES_USER_ID, share.getUserId());
cv.put(ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED, share.getIdRemoteShared());
/*
if (shareExists(share.getIdRemoteShared())) {
// updating an existing share resource
- operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
+ operations.add(
+ ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI_SHARE).
withValues(cv).
withSelection( ProviderTableMeta.OCSHARES_ID_REMOTE_SHARED + "=?",
new String[] { String.valueOf(share.getIdRemoteShared()) })
} else {
*/
// adding a new share resource
- operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).withValues(cv).build());
+ operations.add(
+ ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI_SHARE).
+ withValues(cv).
+ build()
+ );
//}
}
}
}
- private ArrayList<ContentProviderOperation> prepareRemoveSharesInFolder(OCFile folder, ArrayList<ContentProviderOperation> preparedOperations) {
+ private ArrayList<ContentProviderOperation> prepareRemoveSharesInFolder(
+ OCFile folder, ArrayList<ContentProviderOperation> preparedOperations
+ ) {
if (folder != null) {
- String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND " + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
+ String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
+ + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
String [] whereArgs = new String[]{ "", mAccount.name };
Vector<OCFile> files = getFolderContent(folder);
for (OCFile file : files) {
whereArgs[0] = file.getRemotePath();
- preparedOperations.add(ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE)
- .withSelection(where, whereArgs)
- .build());
+ preparedOperations.add(
+ ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).
+ withSelection(where, whereArgs).
+ build()
+ );
}
}
return preparedOperations;
--- /dev/null
+/* ownCloud Android client application
+ * Copyright (C) 2012-2014 ownCloud Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.datamodel;
+
+import java.io.File;
+import java.lang.ref.WeakReference;
+
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Bitmap.CompressFormat;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.media.ThumbnailUtils;
+import android.os.AsyncTask;
+import android.util.TypedValue;
+import android.widget.ImageView;
+
+import com.owncloud.android.MainApp;
+import com.owncloud.android.lib.common.utils.Log_OC;
+import com.owncloud.android.ui.adapter.DiskLruImageCache;
+import com.owncloud.android.utils.BitmapUtils;
+import com.owncloud.android.utils.DisplayUtils;
+
+/**
+ * Manager for concurrent access to thumbnails cache.
+ *
+ * @author Tobias Kaminsky
+ * @author David A. Velasco
+ */
+public class ThumbnailsCacheManager {
+
+ private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
+
+ private static final String CACHE_FOLDER = "thumbnailCache";
+
+ private static final Object mThumbnailsDiskCacheLock = new Object();
+ private static DiskLruImageCache mThumbnailCache = null;
+ private static boolean mThumbnailCacheStarting = true;
+
+ private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
+ private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
+ private static final int mCompressQuality = 70;
+
+ public static Bitmap mDefaultImg =
+ BitmapFactory.decodeResource(
+ MainApp.getAppContext().getResources(),
+ DisplayUtils.getResourceId("image/png", "default.png")
+ );
+
+
+ public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
+ @Override
+ protected Void doInBackground(File... params) {
+ synchronized (mThumbnailsDiskCacheLock) {
+ mThumbnailCacheStarting = true;
+ if (mThumbnailCache == null) {
+ try {
+ // Check if media is mounted or storage is built-in, if so,
+ // try and use external cache dir; otherwise use internal cache dir
+ final String cachePath =
+ MainApp.getAppContext().getExternalCacheDir().getPath() +
+ File.separator + CACHE_FOLDER;
+ Log_OC.d(TAG, "create dir: " + cachePath);
+ final File diskCacheDir = new File(cachePath);
+ mThumbnailCache = new DiskLruImageCache(
+ diskCacheDir,
+ DISK_CACHE_SIZE,
+ mCompressFormat,
+ mCompressQuality
+ );
+ } catch (Exception e) {
+ Log_OC.d(TAG, "Thumbnail cache could not be opened ", e);
+ mThumbnailCache = null;
+ }
+ }
+ mThumbnailCacheStarting = false; // Finished initialization
+ mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
+ }
+ return null;
+ }
+ }
+
+
+ public static void addBitmapToCache(String key, Bitmap bitmap) {
+ synchronized (mThumbnailsDiskCacheLock) {
+ if (mThumbnailCache != null) {
+ mThumbnailCache.put(key, bitmap);
+ }
+ }
+ }
+
+
+ public static Bitmap getBitmapFromDiskCache(String key) {
+ synchronized (mThumbnailsDiskCacheLock) {
+ // Wait while disk cache is started from background thread
+ while (mThumbnailCacheStarting) {
+ try {
+ mThumbnailsDiskCacheLock.wait();
+ } catch (InterruptedException e) {}
+ }
+ if (mThumbnailCache != null) {
+ return (Bitmap) mThumbnailCache.getBitmap(key);
+ }
+ }
+ return null;
+ }
+
+
+ public static boolean cancelPotentialWork(OCFile file, ImageView imageView) {
+ final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
+
+ if (bitmapWorkerTask != null) {
+ final OCFile bitmapData = bitmapWorkerTask.mFile;
+ // If bitmapData is not yet set or it differs from the new data
+ if (bitmapData == null || bitmapData != file) {
+ // Cancel previous task
+ bitmapWorkerTask.cancel(true);
+ } else {
+ // The same work is already in progress
+ return false;
+ }
+ }
+ // No task associated with the ImageView, or an existing task was cancelled
+ return true;
+ }
+
+ public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
+ if (imageView != null) {
+ final Drawable drawable = imageView.getDrawable();
+ if (drawable instanceof AsyncDrawable) {
+ final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
+ return asyncDrawable.getBitmapWorkerTask();
+ }
+ }
+ return null;
+ }
+
+ public static class ThumbnailGenerationTask extends AsyncTask<OCFile, Void, Bitmap> {
+ private final WeakReference<ImageView> mImageViewReference;
+ private OCFile mFile;
+ private FileDataStorageManager mStorageManager;
+
+ public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager) {
+ // Use a WeakReference to ensure the ImageView can be garbage collected
+ mImageViewReference = new WeakReference<ImageView>(imageView);
+ if (storageManager == null)
+ throw new IllegalArgumentException("storageManager must not be NULL");
+ mStorageManager = storageManager;
+ }
+
+ // Decode image in background.
+ @Override
+ protected Bitmap doInBackground(OCFile... params) {
+ Bitmap thumbnail = null;
+
+ try {
+ mFile = params[0];
+ final String imageKey = String.valueOf(mFile.getRemoteId());
+
+ // Check disk cache in background thread
+ thumbnail = getBitmapFromDiskCache(imageKey);
+
+ // Not found in disk cache
+ if (thumbnail == null || mFile.needsUpdateThumbnail()) {
+ // Converts dp to pixel
+ Resources r = MainApp.getAppContext().getResources();
+ int px = (int) Math.round(TypedValue.applyDimension(
+ TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics()
+ ));
+
+ if (mFile.isDown()){
+ Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
+ mFile.getStoragePath(), px, px);
+
+ if (bitmap != null) {
+ thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
+
+ // Add thumbnail to cache
+ addBitmapToCache(imageKey, thumbnail);
+
+ mFile.setNeedsUpdateThumbnail(false);
+ mStorageManager.saveFile(mFile);
+ }
+
+ }
+ }
+
+ } catch (Throwable t) {
+ // the app should never break due to a problem with thumbnails
+ Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
+ if (t instanceof OutOfMemoryError) {
+ System.gc();
+ }
+ }
+
+ return thumbnail;
+ }
+
+ protected void onPostExecute(Bitmap bitmap){
+ if (isCancelled()) {
+ bitmap = null;
+ }
+
+ if (mImageViewReference != null && bitmap != null) {
+ final ImageView imageView = mImageViewReference.get();
+ final ThumbnailGenerationTask bitmapWorkerTask =
+ getBitmapWorkerTask(imageView);
+ if (this == bitmapWorkerTask && imageView != null) {
+ if (imageView.getTag().equals(mFile.getFileId())) {
+ imageView.setImageBitmap(bitmap);
+ }
+ }
+ }
+ }
+ }
+
+
+ public static class AsyncDrawable extends BitmapDrawable {
+ private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
+
+ public AsyncDrawable(
+ Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
+ ) {
+
+ super(res, bitmap);
+ bitmapWorkerTaskReference =
+ new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
+ }
+
+ public ThumbnailGenerationTask getBitmapWorkerTask() {
+ return bitmapWorkerTaskReference.get();
+ }
+ }
+
+
+ /**
+ * Remove from cache the remoteId passed
+ * @param fileRemoteId: remote id of mFile passed
+ */
+ public static void removeFileFromCache(String fileRemoteId){
+ synchronized (mThumbnailsDiskCacheLock) {
+ if (mThumbnailCache != null) {
+ mThumbnailCache.removeKey(fileRemoteId);
+ }
+ mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
+ }
+ }
+
+}
file.setMimetype(mCurrentDownload.getMimeType());
file.setStoragePath(mCurrentDownload.getSavePath());
file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
+ file.setRemoteId(mCurrentDownload.getFile().getRemoteId());
mStorageManager.saveFile(file);
}
// coincidence; nothing else is needed, the storagePath is right
// in the instance returned by mCurrentUpload.getFile()
}
-
+ file.setNeedsUpdateThumbnail(true);
mStorageManager.saveFile(file);
}
file.setModificationTimestamp(remoteFile.getModifiedTimestamp());
file.setModificationTimestampAtLastSyncForData(remoteFile.getModifiedTimestamp());
// file.setEtag(remoteFile.getEtag()); // TODO Etag, where available
+ file.setRemoteId(remoteFile.getRemoteId());
}
private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType,
result = new RemoteOperationResult(ResultCode.OK);
} else if (serverChanged) {
+ mLocalFile.setRemoteId(mServerFile.getRemoteId());
+
if (mSyncFileContents) {
requestForDownload(mLocalFile); // local, not server; we won't to keep the value of keepInSync!
// the update of local data will be done later by the FileUploader service when the upload finishes
private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
- public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED = SynchronizeFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
- public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED = SynchronizeFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
+ public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED =
+ SynchronizeFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
+ public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED =
+ SynchronizeFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
/** Time stamp for the synchronization process in progress */
private long mCurrentSyncTime;
/** Counter of failed operations in synchronization of kept-in-sync files */
private int mFailsInFavouritesFound;
- /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */
+ /**
+ * Map of remote and local paths to files that where locally stored in a location
+ * out of the ownCloud folder and couldn't be copied automatically into it
+ **/
private Map<String, String> mForgottenLocalFiles;
/** 'True' means that this operation is part of a full account synchronization */
private boolean mSyncFullAccount;
- /** 'True' means that Share resources bound to the files into the folder should be refreshed also */
+ /** 'True' means that Share resources bound to the files into should be refreshed also */
private boolean mIsShareSupported;
- /** 'True' means that the remote folder changed from last synchronization and should be fetched */
+ /** 'True' means that the remote folder changed and should be fetched */
private boolean mRemoteFolderChanged;
/** 'True' means that Etag will be ignored */
*
* @param remoteFolderPath Remote folder to synchronize.
* @param currentSyncTime Time stamp for the synchronization process in progress.
- * @param localFolderId Identifier in the local database of the folder to synchronize.
- * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
- * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
+ * @param localFolderId Identifier in the local database of the folder
+ * to synchronize.
+ * @param updateFolderProperties 'True' means that the properties of the folder should
+ * be updated also, not just its content.
+ * @param syncFullAccount 'True' means that this operation is part of a full account
+ * synchronization.
* @param dataStorageManager Interface with the local database.
* @param account ownCloud account where the folder is located.
* @param context Application context.
}
/**
- * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
+ * Returns the list of files and folders contained in the synchronized folder,
+ * if called after synchronization is complete.
*
* @return List of files and folders contained in the synchronized folder.
*/
}
if (!mSyncFullAccount) {
- sendLocalBroadcast(EVENT_SINGLE_FOLDER_CONTENTS_SYNCED, mLocalFolder.getRemotePath(), result);
+ sendLocalBroadcast(
+ EVENT_SINGLE_FOLDER_CONTENTS_SYNCED, mLocalFolder.getRemotePath(), result
+ );
}
if (result.isSuccess() && mIsShareSupported && !mSyncFullAccount) {
}
if (!mSyncFullAccount) {
- sendLocalBroadcast(EVENT_SINGLE_FOLDER_SHARES_SYNCED, mLocalFolder.getRemotePath(), result);
+ sendLocalBroadcast(
+ EVENT_SINGLE_FOLDER_SHARES_SYNCED, mLocalFolder.getRemotePath(), result
+ );
}
return result;
if (!mIgnoreETag) {
// check if remote and local folder are different
- mRemoteFolderChanged = !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
+ mRemoteFolderChanged =
+ !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
}
result = new RemoteOperationResult(ResultCode.OK);
- Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " + (mRemoteFolderChanged ? "changed" : "not changed"));
+ Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " +
+ (mRemoteFolderChanged ? "changed" : "not changed"));
} else {
// check failed
removeLocalFolder();
}
if (result.isException()) {
- Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " + result.getLogMessage(), result.getException());
+ Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
+ result.getLogMessage(), result.getException());
} else {
- Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " + result.getLogMessage());
+ Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
+ result.getLogMessage());
}
}
if (result.isSuccess()) {
synchronizeData(result.getData(), client);
if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
- result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
+ result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
+ // should be a different result code, but will do the job
}
} else {
if (result.getCode() == ResultCode.FILE_NOT_FOUND)
private void removeLocalFolder() {
if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
- mStorageManager.removeFolder(mLocalFolder, true, (mLocalFolder.isDown() && mLocalFolder.getStoragePath().startsWith(currentSavePath)));
+ mStorageManager.removeFolder(
+ mLocalFolder,
+ true,
+ ( mLocalFolder.isDown() &&
+ mLocalFolder.getStoragePath().startsWith(currentSavePath)
+ )
+ );
}
}
*
* @param client Client instance to the remote server where the data were
* retrieved.
- * @return 'True' when any change was made in the local data, 'false' otherwise.
+ * @return 'True' when any change was made in the local data, 'false' otherwise
*/
private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client) {
// get 'fresh data' from the database
remoteFolder.setParentId(mLocalFolder.getParentId());
remoteFolder.setFileId(mLocalFolder.getFileId());
- Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath() + " changed - starting update of local data ");
+ Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
+ + " changed - starting update of local data ");
List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
remoteFile.setParentId(mLocalFolder.getFileId());
/// retrieve local data for the read file
- //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
+ // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
localFile = localFilesMap.remove(remoteFile.getRemotePath());
- /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
+ /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
if (localFile != null) {
// some properties of local state are kept unmodified
remoteFile.setFileId(localFile.getFileId());
remoteFile.setKeepInSync(localFile.keepInSync());
remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
- remoteFile.setModificationTimestampAtLastSyncForData(localFile.getModificationTimestampAtLastSyncForData());
+ remoteFile.setModificationTimestampAtLastSyncForData(
+ localFile.getModificationTimestampAtLastSyncForData()
+ );
remoteFile.setStoragePath(localFile.getStoragePath());
- remoteFile.setEtag(localFile.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
+ // eTag will not be updated unless contents are synchronized
+ // (Synchronize[File|Folder]Operation with remoteFile as parameter)
+ remoteFile.setEtag(localFile.getEtag());
if (remoteFile.isFolder()) {
- remoteFile.setFileLength(localFile.getFileLength()); // TODO move operations about size of folders to FileContentProvider
+ remoteFile.setFileLength(localFile.getFileLength());
+ // TODO move operations about size of folders to FileContentProvider
}
remoteFile.setPublicLink(localFile.getPublicLink());
remoteFile.setShareByLink(localFile.isShareByLink());
} else {
- remoteFile.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
+ // remote eTag will not be updated unless contents are synchronized
+ // (Synchronize[File|Folder]Operation with remoteFile as parameter)
+ remoteFile.setEtag("");
}
/// check and fix, if needed, local storage path
- checkAndFixForeignStoragePath(remoteFile); // fixing old policy - now local files must be copied into the ownCloud local folder
+ checkAndFixForeignStoragePath(remoteFile); // policy - local files are COPIED
+ // into the ownCloud local folder;
searchForLocalFileInDefaultPath(remoteFile); // legacy
/// prepare content synchronization for kept-in-sync files
updatedFiles.add(remoteFile);
}
- // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
+ // save updated contents in local database
mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
// request for the synchronization of file contents AFTER saving current remote properties
}
/**
- * Performs a list of synchronization operations, determining if a download or upload is needed or
- * if exists conflict due to changes both in local and remote contents of the each file.
+ * Performs a list of synchronization operations, determining if a download or upload is needed
+ * or if exists conflict due to changes both in local and remote contents of the each file.
*
- * If download or upload is needed, request the operation to the corresponding service and goes on.
+ * If download or upload is needed, request the operation to the corresponding service and goes
+ * on.
*
* @param filesToSyncContents Synchronization operations to execute.
* @param client Interface to the remote ownCloud server.
*/
- private void startContentSynchronizations(List<SynchronizeFileOperation> filesToSyncContents, OwnCloudClient client) {
+ private void startContentSynchronizations(
+ List<SynchronizeFileOperation> filesToSyncContents, OwnCloudClient client
+ ) {
RemoteOperationResult contentsResult = null;
for (SynchronizeFileOperation op: filesToSyncContents) {
- contentsResult = op.execute(mStorageManager, mContext); // returns without waiting for upload or download finishes
+ contentsResult = op.execute(mStorageManager, mContext); // async
if (!contentsResult.isSuccess()) {
if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
mConflictsFound++;
} else {
mFailsInFavouritesFound++;
if (contentsResult.getException() != null) {
- Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
+ Log_OC.e(TAG, "Error while synchronizing favourites : "
+ + contentsResult.getLogMessage(), contentsResult.getException());
} else {
- Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
+ Log_OC.e(TAG, "Error while synchronizing favourites : "
+ + contentsResult.getLogMessage());
}
}
} // won't let these fails break the synchronization process
/**
- * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
- * tries to copy the file inside it.
+ * Checks the storage path of the OCFile received as parameter.
+ * If it's out of the local ownCloud folder, tries to copy the file inside it.
*
- * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
- * {@link #mForgottenLocalFiles}
+ * If the copy fails, the link to the local file is nullified. The account of forgotten
+ * files is kept in {@link #mForgottenLocalFiles}
*)
* @param file File to check and fix.
*/
File expectedParent = expectedFile.getParentFile();
expectedParent.mkdirs();
if (!expectedParent.isDirectory()) {
- throw new IOException("Unexpected error: parent directory could not be created");
+ throw new IOException(
+ "Unexpected error: parent directory could not be created"
+ );
}
expectedFile.createNewFile();
if (!expectedFile.isFile()) {
try {
if (in != null) in.close();
} catch (Exception e) {
- Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
+ Log_OC.d(TAG, "Weird exception while closing input stream for "
+ + storagePath + " (ignoring)", e);
}
try {
if (out != null) out.close();
} catch (Exception e) {
- Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
+ Log_OC.d(TAG, "Weird exception while closing output stream for "
+ + expectedPath + " (ignoring)", e);
}
}
}
RemoteOperationResult result = null;
// remote request
- GetRemoteSharesForFileOperation operation = new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), false, true);
+ GetRemoteSharesForFileOperation operation =
+ new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), false, true);
result = operation.execute(client);
if (result.isSuccess()) {
/**
- * Sends a message to any application component interested in the progress of the synchronization.
+ * Sends a message to any application component interested in the progress
+ * of the synchronization.
*
* @param event
- * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
+ * @param dirRemotePath Remote path of a folder that was just synchronized
+ * (with or without success)
* @param result
*/
- private void sendLocalBroadcast(String event, String dirRemotePath, RemoteOperationResult result) {
+ private void sendLocalBroadcast(
+ String event, String dirRemotePath, RemoteOperationResult result
+ ) {
Log_OC.d(TAG, "Send broadcast " + event);
Intent intent = new Intent(event);
intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, mAccount.name);
import java.util.HashMap;
import com.owncloud.android.R;
+import com.owncloud.android.datamodel.ThumbnailsCacheManager;
import com.owncloud.android.db.ProviderMeta;
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.shares.ShareType;
-
-
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
int count = 0;
switch (mUriMatcher.match(uri)) {
case SINGLE_FILE:
- /*Cursor c = query(db, uri, null, where, whereArgs, null);
- String remotePath = "(unexisting)";
+ Cursor c = query(db, uri, null, where, whereArgs, null);
+ String remoteId = "";
if (c != null && c.moveToFirst()) {
- remotePath = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH));
+ remoteId = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_REMOTE_ID));
+ //ThumbnailsCacheManager.removeFileFromCache(remoteId);
}
- Log_OC.d(TAG, "Removing FILE " + remotePath);
- */
+ Log_OC.d(TAG, "Removing FILE " + remoteId);
+
count = db.delete(ProviderTableMeta.FILE_TABLE_NAME,
ProviderTableMeta._ID
+ "="
Cursor children = query(uri, null, null, null, null);
if (children != null && children.moveToFirst()) {
long childId;
- boolean isDir;
+ boolean isDir;
//String remotePath;
while (!children.isAfterLast()) {
childId = children.getLong(children.getColumnIndex(ProviderTableMeta._ID));
- isDir = "DIR".equals(children.getString(children.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
+ isDir = "DIR".equals(children.getString(
+ children.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)
+ ));
//remotePath = children.getString(children.getColumnIndex(ProviderTableMeta.FILE_PATH));
if (isDir) {
- count += delete(db, ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId), null, null);
+ count += delete(
+ db,
+ ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, childId),
+ null,
+ null
+ );
} else {
- count += delete(db, ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId), null, null);
+ count += delete(
+ db,
+ ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, childId),
+ null,
+ null
+ );
}
children.moveToNext();
}
}
return count;
}
-
@Override
public String getType(Uri uri) {
@Override
public Uri insert(Uri uri, ContentValues values) {
- //Log_OC.d(TAG, "Inserting " + values.getAsString(ProviderTableMeta.FILE_PATH) + " at provider " + this);
Uri newUri = null;
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.beginTransaction();
case SINGLE_FILE:
String remotePath = values.getAsString(ProviderTableMeta.FILE_PATH);
String accountName = values.getAsString(ProviderTableMeta.FILE_ACCOUNT_OWNER);
- String[] projection = new String[] {ProviderTableMeta._ID, ProviderTableMeta.FILE_PATH, ProviderTableMeta.FILE_ACCOUNT_OWNER };
- String where = ProviderTableMeta.FILE_PATH + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
+ String[] projection = new String[] {
+ ProviderTableMeta._ID, ProviderTableMeta.FILE_PATH,
+ ProviderTableMeta.FILE_ACCOUNT_OWNER
+ };
+ String where = ProviderTableMeta.FILE_PATH + "=? AND " +
+ ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
String[] whereArgs = new String[] {remotePath, accountName};
Cursor doubleCheck = query(db, uri, projection, where, whereArgs, null);
- if (doubleCheck == null || !doubleCheck.moveToFirst()) { // ugly patch; serious refactorization is needed to reduce work in FileDataStorageManager and bring it to FileContentProvider
+ // ugly patch; serious refactorization is needed to reduce work in
+ // FileDataStorageManager and bring it to FileContentProvider
+ if (doubleCheck == null || !doubleCheck.moveToFirst()) {
long rowId = db.insert(ProviderTableMeta.FILE_TABLE_NAME, null, values);
if (rowId > 0) {
- Uri insertedFileUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, rowId);
- //Log_OC.d(TAG, "Inserted " + values.getAsString(ProviderTableMeta.FILE_PATH) + " at provider " + this);
+ Uri insertedFileUri =
+ ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, rowId);
return insertedFileUri;
} else {
- //Log_OC.d(TAG, "Error while inserting " + values.getAsString(ProviderTableMeta.FILE_PATH) + " at provider " + this);
throw new SQLException("ERROR " + uri);
}
} else {
// file is already inserted; race condition, let's avoid a duplicated entry
- Uri insertedFileUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, doubleCheck.getLong(doubleCheck.getColumnIndex(ProviderTableMeta._ID)));
+ Uri insertedFileUri = ContentUris.withAppendedId(
+ ProviderTableMeta.CONTENT_URI_FILE,
+ doubleCheck.getLong(doubleCheck.getColumnIndex(ProviderTableMeta._ID))
+ );
doubleCheck.close();
return insertedFileUri;
case SHARES:
String path = values.getAsString(ProviderTableMeta.OCSHARES_PATH);
String accountNameShare= values.getAsString(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER);
- String[] projectionShare = new String[] {ProviderTableMeta._ID, ProviderTableMeta.OCSHARES_PATH, ProviderTableMeta.OCSHARES_ACCOUNT_OWNER };
- String whereShare = ProviderTableMeta.OCSHARES_PATH + "=? AND " + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
+ String[] projectionShare = new String[] {
+ ProviderTableMeta._ID, ProviderTableMeta.OCSHARES_PATH,
+ ProviderTableMeta.OCSHARES_ACCOUNT_OWNER
+ };
+ String whereShare = ProviderTableMeta.OCSHARES_PATH + "=? AND " +
+ ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
String[] whereArgsShare = new String[] {path, accountNameShare};
Uri insertedShareUri = null;
- Cursor doubleCheckShare = query(db, uri, projectionShare, whereShare, whereArgsShare, null);
- if (doubleCheckShare == null || !doubleCheckShare.moveToFirst()) { // ugly patch; serious refactorization is needed to reduce work in FileDataStorageManager and bring it to FileContentProvider
+ Cursor doubleCheckShare =
+ query(db, uri, projectionShare, whereShare, whereArgsShare, null);
+ // ugly patch; serious refactorization is needed to reduce work in
+ // FileDataStorageManager and bring it to FileContentProvider
+ if (doubleCheckShare == null || !doubleCheckShare.moveToFirst()) {
long rowId = db.insert(ProviderTableMeta.OCSHARES_TABLE_NAME, null, values);
if (rowId >0) {
- insertedShareUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_SHARE, rowId);
+ insertedShareUri =
+ ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_SHARE, rowId);
} else {
throw new SQLException("ERROR " + uri);
}
} else {
// file is already inserted; race condition, let's avoid a duplicated entry
- insertedShareUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_SHARE, doubleCheckShare.getLong(doubleCheckShare.getColumnIndex(ProviderTableMeta._ID)));
+ insertedShareUri = ContentUris.withAppendedId(
+ ProviderTableMeta.CONTENT_URI_SHARE,
+ doubleCheckShare.getLong(
+ doubleCheckShare.getColumnIndex(ProviderTableMeta._ID)
+ )
+ );
doubleCheckShare.close();
}
updateFilesTableAccordingToShareInsertion(db, uri, values);
}
- private void updateFilesTableAccordingToShareInsertion(SQLiteDatabase db, Uri uri, ContentValues shareValues) {
+ private void updateFilesTableAccordingToShareInsertion(
+ SQLiteDatabase db, Uri uri, ContentValues shareValues
+ ) {
ContentValues fileValues = new ContentValues();
- fileValues.put(ProviderTableMeta.FILE_SHARE_BY_LINK,
- ShareType.PUBLIC_LINK.getValue() == shareValues.getAsInteger(ProviderTableMeta.OCSHARES_SHARE_TYPE)? 1 : 0);
- String whereShare = ProviderTableMeta.FILE_PATH + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
+ fileValues.put(
+ ProviderTableMeta.FILE_SHARE_BY_LINK,
+ ShareType.PUBLIC_LINK.getValue() ==
+ shareValues.getAsInteger(ProviderTableMeta.OCSHARES_SHARE_TYPE)? 1 : 0
+ );
+ String whereShare = ProviderTableMeta.FILE_PATH + "=? AND " +
+ ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
String[] whereArgsShare = new String[] {
shareValues.getAsString(ProviderTableMeta.OCSHARES_PATH),
shareValues.getAsString(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER)
@Override
- public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
+ public Cursor query(
+ Uri uri,
+ String[] projection,
+ String selection,
+ String[] selectionArgs,
+ String sortOrder
+ ) {
+
Cursor result = null;
SQLiteDatabase db = mDbHelper.getReadableDatabase();
db.beginTransaction();
return result;
}
- private Cursor query(SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
+ private Cursor query(
+ SQLiteDatabase db,
+ Uri uri,
+ String[] projection,
+ String selection,
+ String[] selectionArgs,
+ String sortOrder
+ ) {
+
SQLiteQueryBuilder sqlQuery = new SQLiteQueryBuilder();
sqlQuery.setTables(ProviderTableMeta.FILE_TABLE_NAME);
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
- //Log_OC.d(TAG, "Updating " + values.getAsString(ProviderTableMeta.FILE_PATH) + " at provider " + this);
int count = 0;
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.beginTransaction();
- private int update(SQLiteDatabase db, Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+ private int update(
+ SQLiteDatabase db,
+ Uri uri,
+ ContentValues values,
+ String selection,
+ String[] selectionArgs
+ ) {
switch (mUriMatcher.match(uri)) {
case DIRECTORY:
return 0; //updateFolderSize(db, selectionArgs[0]);
case SHARES:
- return db.update(ProviderTableMeta.OCSHARES_TABLE_NAME, values, selection, selectionArgs);
+ return db.update(
+ ProviderTableMeta.OCSHARES_TABLE_NAME, values, selection, selectionArgs
+ );
default:
- return db.update(ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs);
+ return db.update(
+ ProviderTableMeta.FILE_TABLE_NAME, values, selection, selectionArgs
+ );
}
}
*/
@Override
- public ContentProviderResult[] applyBatch (ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
- Log_OC.d("FileContentProvider", "applying batch in provider " + this + " (temporary: " + isTemporary() + ")" );
+ public ContentProviderResult[] applyBatch (ArrayList<ContentProviderOperation> operations)
+ throws OperationApplicationException {
+ Log_OC.d("FileContentProvider", "applying batch in provider " + this +
+ " (temporary: " + isTemporary() + ")" );
ContentProviderResult[] results = new ContentProviderResult[operations.size()];
int i=0;
db.beginTransaction();
try {
db.execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
- " ADD COLUMN " + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + " INTEGER " +
- " DEFAULT 0");
+ " ADD COLUMN " + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA +
+ " INTEGER " + " DEFAULT 0");
// assume there are not local changes pending to upload
db.execSQL("UPDATE " + ProviderTableMeta.FILE_TABLE_NAME +
- " SET " + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + " = " + System.currentTimeMillis() +
+ " SET " + ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA + " = "
+ + System.currentTimeMillis() +
" WHERE " + ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL");
upgraded = true;
db.beginTransaction();
try {
db .execSQL("ALTER TABLE " + ProviderTableMeta.FILE_TABLE_NAME +
- " ADD COLUMN " + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " INTEGER " +
- " DEFAULT 0");
+ " ADD COLUMN " + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA +
+ " INTEGER " + " DEFAULT 0");
db.execSQL("UPDATE " + ProviderTableMeta.FILE_TABLE_NAME +
- " SET " + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " = " + ProviderTableMeta.FILE_MODIFIED +
+ " SET " + ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA + " = " +
+ ProviderTableMeta.FILE_MODIFIED +
" WHERE " + ProviderTableMeta.FILE_STORAGE_PATH + " IS NOT NULL");
upgraded = true;
}
}
if (!upgraded)
- Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + ", newVersion == " + newVersion);
+ Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
+ ", newVersion == " + newVersion);
if (oldVersion < 5 && newVersion >= 5) {
Log_OC.i("SQL", "Entering in the #4 ADD in onUpgrade");
}
}
if (!upgraded)
- Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + ", newVersion == " + newVersion);
+ Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
+ ", newVersion == " + newVersion);
if (oldVersion < 6 && newVersion >= 6) {
Log_OC.i("SQL", "Entering in the #5 ADD in onUpgrade");
}
}
if (!upgraded)
- Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + ", newVersion == " + newVersion);
+ Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
+ ", newVersion == " + newVersion);
if (oldVersion < 7 && newVersion >= 7) {
Log_OC.i("SQL", "Entering in the #7 ADD in onUpgrade");
}
}
if (!upgraded)
- Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + ", newVersion == " + newVersion);
+ Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
+ ", newVersion == " + newVersion);
if (oldVersion < 8 && newVersion >= 8) {
Log_OC.i("SQL", "Entering in the #8 ADD in onUpgrade");
}
}
if (!upgraded)
- Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion + ", newVersion == " + newVersion);
+ Log_OC.i("SQL", "OUT of the ADD in onUpgrade; oldVersion == " + oldVersion +
+ ", newVersion == " + newVersion);
}
}
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
-import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import com.owncloud.android.lib.common.utils.Log_OC;
public class MoveActivity extends HookActivity implements FileFragment.ContainerActivity,
- OnClickListener, SwipeRefreshLayout.OnRefreshListener {
+ OnClickListener, OnEnforceableRefreshListener {
public static final String EXTRA_CURRENT_FOLDER = UploadFilesActivity.class.getCanonicalName() + ".EXTRA_CURRENT_FOLDER";
public static final String EXTRA_TARGET_FILE = UploadFilesActivity.class.getCanonicalName() + "EXTRA_TARGET_FILE";
}
-
@Override
public void onRefresh() {
+ refreshList(true);
+ }
+
+ @Override
+ public void onRefresh(boolean enforced) {
+ refreshList(enforced);
+ }
+
+ private void refreshList(boolean ignoreETag) {
OCFileListFragment listOfFiles = getListOfFilesFragment();
if (listOfFiles != null) {
OCFile folder = listOfFiles.getCurrentFile();
if (folder != null) {
- startSyncFolderOperation(folder, true);
+ startSyncFolderOperation(folder, ignoreETag);
}
}
}
-
}
+/* ownCloud Android client application
+ * Copyright (C) 2012-2014 ownCloud Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
package com.owncloud.android.ui.adapter;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
-import android.util.Log;
import com.jakewharton.disklrucache.DiskLruCache;
import com.owncloud.android.BuildConfig;
private static final int CACHE_VERSION = 1;
private static final int VALUE_COUNT = 1;
private static final int IO_BUFFER_SIZE = 8 * 1024;
- private static final Pattern CAPITAL_LETTERS = Pattern.compile("[A-Z]");
-
- private StringBuffer mValidKeyBuffer = new StringBuffer(64);
- private StringBuffer mConversionBuffer = new StringBuffer(2).append('_');
- private static final String TAG = "DiskLruImageCache";
+ private static final String TAG = DiskLruImageCache.class.getSimpleName();
+
+ //public DiskLruImageCache( Context context,String uniqueName, int diskCacheSize,
+ public DiskLruImageCache(
+ File diskCacheDir, int diskCacheSize, CompressFormat compressFormat, int quality
+ ) throws IOException {
- public DiskLruImageCache( Context context,String uniqueName, int diskCacheSize,
- CompressFormat compressFormat, int quality ) throws IOException {
- final File diskCacheDir = getDiskCacheDir(context, uniqueName );
mDiskCache = DiskLruCache.open(
diskCacheDir, CACHE_VERSION, VALUE_COUNT, diskCacheSize
);
}
}
- private File getDiskCacheDir(Context context, String uniqueName) {
-
- // Check if media is mounted or storage is built-in, if so, try and use external cache dir
- // otherwise use internal cache dir
- final String cachePath = context.getExternalCacheDir().getPath();
-
- Log_OC.d(TAG, "create dir: " + cachePath + File.separator + uniqueName);
-
- return new File(cachePath + File.separator + uniqueName);
- }
-
public void put( String key, Bitmap data ) {
DiskLruCache.Editor editor = null;
mDiskCache.flush();
editor.commit();
if ( BuildConfig.DEBUG ) {
- Log.d( "cache_test_DISK_", "image put on disk cache " + validKey );
+ Log_OC.d( "cache_test_DISK_", "image put on disk cache " + validKey );
}
} else {
editor.abort();
if ( BuildConfig.DEBUG ) {
- Log.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + validKey );
+ Log_OC.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + validKey );
}
}
} catch (IOException e) {
if ( BuildConfig.DEBUG ) {
- Log.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + validKey );
+ Log_OC.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + validKey );
}
try {
if ( editor != null ) {
}
if ( BuildConfig.DEBUG ) {
- Log.d("cache_test_DISK_", bitmap == null ? "not found" : "image read from disk " + validKey);
+ Log_OC.d("cache_test_DISK_", bitmap == null ?
+ "not found" : "image read from disk " + validKey);
}
return bitmap;
public void clearCache() {
if ( BuildConfig.DEBUG ) {
- Log.d( "cache_test_DISK_", "disk cache CLEARED");
+ Log_OC.d( "cache_test_DISK_", "disk cache CLEARED");
}
try {
mDiskCache.delete();
}
private String convertToValidKey(String key) {
- Matcher capitalLettersMatcher = CAPITAL_LETTERS.matcher(key);
- mValidKeyBuffer.delete(0, mValidKeyBuffer.length());
- mConversionBuffer.delete(1, mConversionBuffer.length());
-
- while (capitalLettersMatcher.find()) {
- mConversionBuffer.replace(1, 2, capitalLettersMatcher.group(0).toLowerCase());
- capitalLettersMatcher.appendReplacement(mValidKeyBuffer, mConversionBuffer.toString());
- }
- capitalLettersMatcher.appendTail(mValidKeyBuffer);
- return mValidKeyBuffer.toString();
+ return Integer.toString(key.hashCode());
}
+ /**
+ * Remove passed key from cache
+ * @param key
+ */
+ public void removeKey( String key ) {
+ String validKey = convertToValidKey(key);
+ try {
+ mDiskCache.remove(validKey);
+ Log_OC.d(TAG, "removeKey from cache: " + validKey);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
}
\ No newline at end of file
*/\r
package com.owncloud.android.ui.adapter;\r
\r
-import java.io.File;\r
-import java.lang.ref.WeakReference;\r
import java.util.Vector;\r
\r
import android.accounts.Account;\r
import android.content.Context;\r
-import android.content.res.Resources;\r
import android.graphics.Bitmap;\r
-import android.graphics.Bitmap.CompressFormat;\r
-import android.graphics.BitmapFactory;\r
-import android.graphics.drawable.BitmapDrawable;\r
-import android.graphics.drawable.Drawable;\r
-import android.media.ThumbnailUtils;\r
-import android.os.AsyncTask;\r
-import android.util.TypedValue;\r
import android.view.LayoutInflater;\r
import android.view.View;\r
import android.view.ViewGroup;\r
import com.owncloud.android.authentication.AccountUtils;\r
import com.owncloud.android.datamodel.FileDataStorageManager;\r
import com.owncloud.android.datamodel.OCFile;\r
+import com.owncloud.android.datamodel.ThumbnailsCacheManager;\r
+import com.owncloud.android.datamodel.ThumbnailsCacheManager.AsyncDrawable;\r
import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;\r
import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;\r
-import com.owncloud.android.lib.common.utils.Log_OC;\r
import com.owncloud.android.ui.activity.ComponentsGetter;\r
-import com.owncloud.android.utils.BitmapUtils;\r
import com.owncloud.android.utils.DisplayUtils;\r
\r
\r
public class FileListListAdapter extends BaseAdapter implements ListAdapter {\r
private final static String PERMISSION_SHARED_WITH_ME = "S";\r
\r
- private static final String TAG = FileListListAdapter.class.getSimpleName();\r
-\r
private Context mContext;\r
private OCFile mFile = null;\r
private Vector<OCFile> mFiles = null;\r
private Account mAccount;
private ComponentsGetter mTransferServiceGetter;\r
\r
- private final Object thumbnailDiskCacheLock = new Object();\r
- private DiskLruImageCache mThumbnailCache;\r
- private boolean mThumbnailCacheStarting = true;\r
- private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB\r
- private static final CompressFormat mCompressFormat = CompressFormat.JPEG;\r
- private static final int mCompressQuality = 70;\r
- private Bitmap defaultImg;\r
- \r
public FileListListAdapter(\r
boolean justFolders, \r
Context context, \r
mContext = context;\r
mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);\r
mTransferServiceGetter = transferServiceGetter;\r
- defaultImg = BitmapFactory.decodeResource(mContext.getResources(), \r
- DisplayUtils.getResourceId("image/png", "default.png"));\r
\r
- // Initialise disk cache on background thread\r
- new InitDiskCacheTask().execute();\r
- }\r
- \r
- class InitDiskCacheTask extends AsyncTask<File, Void, Void> {\r
- @Override\r
- protected Void doInBackground(File... params) {\r
- synchronized (thumbnailDiskCacheLock) {\r
- try {\r
- mThumbnailCache = new DiskLruImageCache(mContext, "thumbnailCache", \r
- DISK_CACHE_SIZE, mCompressFormat, mCompressQuality);\r
- } catch (Exception e) {\r
- Log_OC.d(TAG, "Thumbnail cache could not be opened ", e);\r
- mThumbnailCache = null;\r
- }\r
- mThumbnailCacheStarting = false; // Finished initialization\r
- thumbnailDiskCacheLock.notifyAll(); // Wake any waiting threads\r
- }\r
- return null;\r
- }\r
+ // initialise thumbnails cache on background thread\r
+ new ThumbnailsCacheManager.InitDiskCacheTask().execute();\r
}\r
\r
- static class AsyncDrawable extends BitmapDrawable {\r
- private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;\r
-\r
- public AsyncDrawable(Resources res, Bitmap bitmap,\r
- ThumbnailGenerationTask bitmapWorkerTask) {\r
- super(res, bitmap);\r
- bitmapWorkerTaskReference =\r
- new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);\r
- }\r
-\r
- public ThumbnailGenerationTask getBitmapWorkerTask() {\r
- return bitmapWorkerTaskReference.get();\r
- }\r
- }\r
-\r
- class ThumbnailGenerationTask extends AsyncTask<OCFile, Void, Bitmap> {\r
- private final WeakReference<ImageView> imageViewReference;\r
- private OCFile file;\r
-\r
- \r
- public ThumbnailGenerationTask(ImageView imageView) {\r
- // Use a WeakReference to ensure the ImageView can be garbage collected\r
- imageViewReference = new WeakReference<ImageView>(imageView);\r
- }\r
-\r
- // Decode image in background.\r
- @Override\r
- protected Bitmap doInBackground(OCFile... params) {\r
- Bitmap thumbnail = null;\r
- \r
- try {\r
- file = params[0];\r
- final String imageKey = String.valueOf(file.getRemoteId());\r
- \r
- // Check disk cache in background thread\r
- thumbnail = getBitmapFromDiskCache(imageKey);\r
- \r
- // Not found in disk cache\r
- if (thumbnail == null || file.needsUpdateThumbnail()) { \r
- // Converts dp to pixel\r
- Resources r = mContext.getResources();\r
- int px = (int) Math.round(TypedValue.applyDimension(\r
- TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics()\r
- ));\r
- \r
- if (file.isDown()){\r
- Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(\r
- file.getStoragePath(), px, px);\r
- \r
- if (bitmap != null) {\r
- thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);\r
- \r
- // Add thumbnail to cache\r
- addBitmapToCache(imageKey, thumbnail);\r
-\r
- file.setNeedsUpdateThumbnail(false);\r
- mStorageManager.saveFile(file);\r
- }\r
- \r
- }\r
- }\r
- \r
- } catch (Throwable t) {\r
- // the app should never break due to a problem with thumbnails\r
- Log_OC.e(TAG, "Generation of thumbnail for " + file + " failed", t);\r
- if (t instanceof OutOfMemoryError) {\r
- System.gc();\r
- }\r
- }\r
- \r
- return thumbnail;\r
- }\r
- \r
- protected void onPostExecute(Bitmap bitmap){\r
- if (isCancelled()) {\r
- bitmap = null;\r
- }\r
-\r
- if (imageViewReference != null && bitmap != null) {\r
- final ImageView imageView = imageViewReference.get();\r
- final ThumbnailGenerationTask bitmapWorkerTask =\r
- getBitmapWorkerTask(imageView);\r
- if (this == bitmapWorkerTask && imageView != null) {\r
- imageView.setImageBitmap(bitmap);\r
- }\r
- }\r
- }\r
- }\r
- \r
- public void addBitmapToCache(String key, Bitmap bitmap) {\r
- synchronized (thumbnailDiskCacheLock) {\r
- if (mThumbnailCache != null) {\r
- mThumbnailCache.put(key, bitmap);\r
- }\r
- }\r
- }\r
-\r
- public Bitmap getBitmapFromDiskCache(String key) {\r
- synchronized (thumbnailDiskCacheLock) {\r
- // Wait while disk cache is started from background thread\r
- while (mThumbnailCacheStarting) {\r
- try {\r
- thumbnailDiskCacheLock.wait();\r
- } catch (InterruptedException e) {}\r
- }\r
- if (mThumbnailCache != null) {\r
- return (Bitmap) mThumbnailCache.getBitmap(key);\r
- }\r
- }\r
- return null;\r
- }
-\r
@Override\r
public boolean areAllItemsEnabled() {\r
return true;\r
\r
fileName.setText(name);\r
ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);\r
+ fileIcon.setTag(file.getFileId());\r
ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);\r
ImageView sharedWithMeIconV = (ImageView) view.findViewById(R.id.sharedWithMeIcon);\r
sharedWithMeIconV.setVisibility(View.GONE);\r
} \r
\r
// get Thumbnail if file is image\r
- if (file.isImage()){\r
+ if (file.isImage() && file.getRemoteId() != null){\r
// Thumbnail in Cache?\r
- Bitmap thumbnail = getBitmapFromDiskCache(String.valueOf(file.getRemoteId()));\r
+ Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(\r
+ String.valueOf(file.getRemoteId())\r
+ );\r
if (thumbnail != null && !file.needsUpdateThumbnail()){\r
fileIcon.setImageBitmap(thumbnail);\r
} else {\r
// generate new Thumbnail\r
- if (cancelPotentialWork(file, fileIcon)) {\r
- final ThumbnailGenerationTask task = \r
- new ThumbnailGenerationTask(fileIcon);\r
- final AsyncDrawable asyncDrawable =\r
- new AsyncDrawable(mContext.getResources(), defaultImg, task);\r
+ if (ThumbnailsCacheManager.cancelPotentialWork(file, fileIcon)) {\r
+ final ThumbnailsCacheManager.ThumbnailGenerationTask task = \r
+ new ThumbnailsCacheManager.ThumbnailGenerationTask(\r
+ fileIcon, mStorageManager\r
+ );\r
+ if (thumbnail == null) {\r
+ thumbnail = ThumbnailsCacheManager.mDefaultImg;\r
+ }\r
+ final AsyncDrawable asyncDrawable = new AsyncDrawable(\r
+ mContext.getResources(), \r
+ thumbnail, \r
+ task\r
+ );\r
fileIcon.setImageDrawable(asyncDrawable);\r
task.execute(file);\r
}\r
return view;\r
}\r
\r
- public static boolean cancelPotentialWork(OCFile file, ImageView imageView) {\r
- final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);\r
-\r
- if (bitmapWorkerTask != null) {\r
- final OCFile bitmapData = bitmapWorkerTask.file;\r
- // If bitmapData is not yet set or it differs from the new data\r
- if (bitmapData == null || bitmapData != file) {\r
- // Cancel previous task\r
- bitmapWorkerTask.cancel(true);\r
- } else {\r
- // The same work is already in progress\r
- return false;\r
- }\r
- }\r
- // No task associated with the ImageView, or an existing task was cancelled\r
- return true;\r
- }\r
- \r
- private static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {\r
- if (imageView != null) {\r
- final Drawable drawable = imageView.getDrawable();\r
- if (drawable instanceof AsyncDrawable) {\r
- final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;\r
- return asyncDrawable.getBitmapWorkerTask();\r
- }\r
- }\r
- return null;\r
- }\r
-\r
@Override\r
public int getViewTypeCount() {\r
return 1;\r
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
+import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
((ImageButton)mView.findViewById(R.id.cancelBtn)).setOnClickListener(this);
+ ((LinearLayout)mView.findViewById(R.id.fileDownloadLL)).setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ ((PreviewImageActivity) getActivity()).toggleFullScreen();
+ }
+ });
+
if (mError) {
setButtonsForRemote();
} else {
--- /dev/null
+package com.owncloud.android.ui.preview;
+
+import android.annotation.SuppressLint;
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.os.Build;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.ImageView;
+
+import com.owncloud.android.lib.common.utils.Log_OC;
+
+public class ImageViewCustom extends ImageView {
+
+ private static final boolean IS_ICS_OR_HIGHER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
+
+ private Bitmap mBitmap;
+
+
+ public ImageViewCustom(Context context) {
+ super(context);
+ }
+
+ public ImageViewCustom(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public ImageViewCustom(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ }
+
+ @SuppressLint("NewApi")
+ @Override
+ protected void onDraw(Canvas canvas) {
+
+ if(IS_ICS_OR_HIGHER && checkIfMaximumBitmapExceed(canvas)) {
+ // Set layer type to software one for avoiding exceed
+ // and problems in visualization
+ setLayerType(View.LAYER_TYPE_SOFTWARE, null);
+ }
+
+ super.onDraw(canvas);
+ }
+
+ /**
+ * Checks if current bitmaps exceed the maximum OpenGL texture size limit
+ * @param bitmap
+ * @return boolean
+ */
+ @SuppressLint("NewApi")
+ private boolean checkIfMaximumBitmapExceed(Canvas canvas) {
+ Log_OC.d("OC", "Canvas maximum: " + canvas.getMaximumBitmapWidth() + " - " + canvas.getMaximumBitmapHeight());
+ if (mBitmap!= null && (mBitmap.getWidth() > canvas.getMaximumBitmapWidth()
+ || mBitmap.getHeight() > canvas.getMaximumBitmapHeight())) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Set current bitmap
+ * @param bitmap
+ */
+ public void setBitmap (Bitmap bitmap) {
+ mBitmap = bitmap;
+ }
+
+}
*/
package com.owncloud.android.ui.preview;
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.lang.ref.WeakReference;
import android.accounts.Account;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
-import com.ortiz.touch.TouchImageView;
import com.owncloud.android.R;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.files.FileMenuFilter;
import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
import com.owncloud.android.ui.fragment.FileFragment;
+import com.owncloud.android.utils.TouchImageViewCustom;
+
/**
* @author David A. Velasco
*/
public class PreviewImageFragment extends FileFragment {
+
public static final String EXTRA_FILE = "FILE";
public static final String EXTRA_ACCOUNT = "ACCOUNT";
private View mView;
private Account mAccount;
- private TouchImageView mImageView;
+ private TouchImageViewCustom mImageView;
private TextView mMessageView;
private ProgressBar mProgressWheel;
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
- mImageView = (TouchImageView) mView.findViewById(R.id.image);
+ mImageView = (TouchImageViewCustom) mView.findViewById(R.id.image);
mImageView.setVisibility(View.GONE);
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onDestroy() {
if (mBitmap != null) {
mBitmap.recycle();
+ System.gc();
}
super.onDestroy();
}
*
* Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
*/
- private final WeakReference<ImageView> mImageViewRef;
+ private final WeakReference<ImageViewCustom> mImageViewRef;
/**
* Weak reference to the target {@link TextView} where error messages will be written.
*
* @param imageView Target {@link ImageView} where the bitmap will be loaded into.
*/
- public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
- mImageViewRef = new WeakReference<ImageView>(imageView);
+ public BitmapLoader(ImageViewCustom imageView, TextView messageView, ProgressBar progressWheel) {
+ mImageViewRef = new WeakReference<ImageViewCustom>(imageView);
mMessageViewRef = new WeakReference<TextView>(messageView);
mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
}
- @SuppressWarnings("deprecation")
- @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
- @Override
+ @Override
protected Bitmap doInBackground(String... params) {
Bitmap result = null;
if (params.length != 1) return result;
String storagePath = params[0];
try {
- // set desired options that will affect the size of the bitmap
- BitmapFactory.Options options = new Options();
- options.inScaled = true;
- options.inPurgeable = true;
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
- options.inPreferQualityOverSpeed = false;
- }
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
- options.inMutable = false;
- }
- // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(storagePath, options);
-
- int width = options.outWidth;
- int height = options.outHeight;
- int scale = 1;
-
- Display display = getActivity().getWindowManager().getDefaultDisplay();
- Point size = new Point();
- int screenWidth;
- int screenHeight;
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
- display.getSize(size);
- screenWidth = size.x;
- screenHeight = size.y;
- } else {
- screenWidth = display.getWidth();
- screenHeight = display.getHeight();
- }
- if (width > screenWidth) {
- // second try to scale down the image , this time depending upon the screen size
- scale = (int) Math.floor((float)width / screenWidth);
- }
- if (height > screenHeight) {
- scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
- }
- options.inSampleSize = scale;
+ File picture = new File(storagePath);
- // really load the bitmap
- options.inJustDecodeBounds = false; // the next decodeFile call will be real
- result = BitmapFactory.decodeFile(storagePath, options);
- //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
+ if (picture != null) {
+ //Decode file into a bitmap in real size for being able to make zoom on the image
+ result = BitmapFactory.decodeStream(new FlushedInputStream
+ (new BufferedInputStream(new FileInputStream(picture))));
+ }
if (result == null) {
mErrorMessageId = R.string.preview_image_error_unknown_format;
}
} catch (OutOfMemoryError e) {
- mErrorMessageId = R.string.preview_image_error_unknown_format;
Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
+
+ // If out of memory error when loading image, try to load it scaled
+ result = loadScaledImage(storagePath);
+
+ if (result == null) {
+ mErrorMessageId = R.string.preview_image_error_unknown_format;
+ Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
+ }
} catch (NoSuchFieldError e) {
mErrorMessageId = R.string.common_error_unknown;
showErrorMessage();
}
}
-
+
+ @SuppressLint("InlinedApi")
private void showLoadedImage(Bitmap result) {
if (mImageViewRef != null) {
- final ImageView imageView = mImageViewRef.get();
+ final ImageViewCustom imageView = mImageViewRef.get();
if (imageView != null) {
+ imageView.setBitmap(result);
imageView.setImageBitmap(result);
imageView.setVisibility(View.VISIBLE);
mBitmap = result;
container.finish();
}
- public TouchImageView getImageView() {
+ public TouchImageViewCustom getImageView() {
return mImageView;
}
-
+
+ static class FlushedInputStream extends FilterInputStream {
+ public FlushedInputStream(InputStream inputStream) {
+ super(inputStream);
+ }
+
+ @Override
+ public long skip(long n) throws IOException {
+ long totalBytesSkipped = 0L;
+ while (totalBytesSkipped < n) {
+ long bytesSkipped = in.skip(n - totalBytesSkipped);
+ if (bytesSkipped == 0L) {
+ int byteValue = read();
+ if (byteValue < 0) {
+ break; // we reached EOF
+ } else {
+ bytesSkipped = 1; // we read one byte
+ }
+ }
+ totalBytesSkipped += bytesSkipped;
+ }
+ return totalBytesSkipped;
+ }
+ }
+
+ /**
+ * Load image scaled
+ * @param storagePath: path of the image
+ * @return Bitmap
+ */
+ @SuppressWarnings("deprecation")
+ private Bitmap loadScaledImage(String storagePath) {
+
+ Log_OC.d(TAG, "Loading image scaled");
+
+ // set desired options that will affect the size of the bitmap
+ BitmapFactory.Options options = new Options();
+ options.inScaled = true;
+ options.inPurgeable = true;
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
+ options.inPreferQualityOverSpeed = false;
+ }
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
+ options.inMutable = false;
+ }
+ // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
+ options.inJustDecodeBounds = true;
+ BitmapFactory.decodeFile(storagePath, options);
+
+ int width = options.outWidth;
+ int height = options.outHeight;
+ int scale = 1;
+
+ Display display = getActivity().getWindowManager().getDefaultDisplay();
+ Point size = new Point();
+ int screenWidth;
+ int screenHeight;
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
+ display.getSize(size);
+ screenWidth = size.x;
+ screenHeight = size.y;
+ } else {
+ screenWidth = display.getWidth();
+ screenHeight = display.getHeight();
+ }
+
+ if (width > screenWidth) {
+ // second try to scale down the image , this time depending upon the screen size
+ scale = (int) Math.floor((float)width / screenWidth);
+ }
+ if (height > screenHeight) {
+ scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
+ }
+ options.inSampleSize = scale;
+
+ // really load the bitmap
+ options.inJustDecodeBounds = false; // the next decodeFile call will be real
+ return BitmapFactory.decodeFile(storagePath, options);
+
+ }
}
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
+import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
mVideoPreview.setOnErrorListener(mVideoHelper);
}
+ @SuppressWarnings("static-access")
private void playVideo() {
// create and prepare control panel for the user
mMediaController.setMediaPlayer(mVideoPreview);
// load the video file in the video player ;
// when done, VideoHelper#onPrepared() will be called
- mVideoPreview.setVideoPath(getFile().getStoragePath());
+ Uri uri = Uri.parse(getFile().getStoragePath());
+ mVideoPreview.setVideoPath(uri.encode(getFile().getStoragePath()));
}
--- /dev/null
+/*
+ * TouchImageView.java
+ * By: Michael Ortiz
+ * Updated By: Patrick Lackemacher
+ * Updated By: Babay88
+ * Updated By: @ipsilondev
+ * Updated By: hank-cp
+ * Updated By: singpolyma
+ * -------------------
+ * Extends Android ImageView to include pinch zooming, panning, fling and double tap zoom.
+ */
+
+package com.owncloud.android.utils;
+
+import com.owncloud.android.ui.preview.ImageViewCustom;
+
+import android.annotation.TargetApi;
+import android.content.Context;
+import android.content.res.Configuration;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Matrix;
+import android.graphics.PointF;
+import android.graphics.RectF;
+import android.graphics.drawable.Drawable;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Build.VERSION;
+import android.os.Build.VERSION_CODES;
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.GestureDetector;
+import android.view.MotionEvent;
+import android.view.ScaleGestureDetector;
+import android.view.View;
+import android.view.animation.AccelerateDecelerateInterpolator;
+import android.widget.OverScroller;
+import android.widget.Scroller;
+
+public class TouchImageViewCustom extends ImageViewCustom {
+ private static final String DEBUG = "DEBUG";
+
+ //
+ // SuperMin and SuperMax multipliers. Determine how much the image can be
+ // zoomed below or above the zoom boundaries, before animating back to the
+ // min/max zoom boundary.
+ //
+ private static final float SUPER_MIN_MULTIPLIER = .75f;
+ private static final float SUPER_MAX_MULTIPLIER = 1.25f;
+
+ //
+ // Scale of image ranges from minScale to maxScale, where minScale == 1
+ // when the image is stretched to fit view.
+ //
+ private float normalizedScale;
+
+ //
+ // Matrix applied to image. MSCALE_X and MSCALE_Y should always be equal.
+ // MTRANS_X and MTRANS_Y are the other values used. prevMatrix is the matrix
+ // saved prior to the screen rotating.
+ //
+ private Matrix matrix, prevMatrix;
+
+ private static enum State { NONE, DRAG, ZOOM, FLING, ANIMATE_ZOOM };
+ private State state;
+
+ private float minScale;
+ private float maxScale;
+ private float superMinScale;
+ private float superMaxScale;
+ private float[] m;
+
+ private Context context;
+ private Fling fling;
+
+ private ScaleType mScaleType;
+
+ private boolean imageRenderedAtLeastOnce;
+ private boolean onDrawReady;
+
+ private ZoomVariables delayedZoomVariables;
+
+ //
+ // Size of view and previous view size (ie before rotation)
+ //
+ private int viewWidth, viewHeight, prevViewWidth, prevViewHeight;
+
+ //
+ // Size of image when it is stretched to fit view. Before and After rotation.
+ //
+ private float matchViewWidth, matchViewHeight, prevMatchViewWidth, prevMatchViewHeight;
+
+ private ScaleGestureDetector mScaleDetector;
+ private GestureDetector mGestureDetector;
+ private GestureDetector.OnDoubleTapListener doubleTapListener = null;
+ private OnTouchListener userTouchListener = null;
+ private OnTouchImageViewListener touchImageViewListener = null;
+
+ public TouchImageViewCustom(Context context) {
+ super(context);
+ sharedConstructing(context);
+ }
+
+ public TouchImageViewCustom(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ sharedConstructing(context);
+ }
+
+ public TouchImageViewCustom(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ sharedConstructing(context);
+ }
+
+ private void sharedConstructing(Context context) {
+ super.setClickable(true);
+ this.context = context;
+ mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
+ mGestureDetector = new GestureDetector(context, new GestureListener());
+ matrix = new Matrix();
+ prevMatrix = new Matrix();
+ m = new float[9];
+ normalizedScale = 1;
+ if (mScaleType == null) {
+ mScaleType = ScaleType.FIT_CENTER;
+ }
+ minScale = 1;
+ maxScale = 3;
+ superMinScale = SUPER_MIN_MULTIPLIER * minScale;
+ superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
+ setImageMatrix(matrix);
+ setScaleType(ScaleType.MATRIX);
+ setState(State.NONE);
+ onDrawReady = false;
+ super.setOnTouchListener(new PrivateOnTouchListener());
+ }
+
+ @Override
+ public void setOnTouchListener(View.OnTouchListener l) {
+ userTouchListener = l;
+ }
+
+ public void setOnTouchImageViewListener(OnTouchImageViewListener l) {
+ touchImageViewListener = l;
+ }
+
+ public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener l) {
+ doubleTapListener = l;
+ }
+
+ @Override
+ public void setImageResource(int resId) {
+ super.setImageResource(resId);
+ savePreviousImageValues();
+ fitImageToView();
+ }
+
+ @Override
+ public void setImageBitmap(Bitmap bm) {
+ super.setImageBitmap(bm);
+ savePreviousImageValues();
+ fitImageToView();
+ }
+
+ @Override
+ public void setImageDrawable(Drawable drawable) {
+ super.setImageDrawable(drawable);
+ savePreviousImageValues();
+ fitImageToView();
+ }
+
+ @Override
+ public void setImageURI(Uri uri) {
+ super.setImageURI(uri);
+ savePreviousImageValues();
+ fitImageToView();
+ }
+
+ @Override
+ public void setScaleType(ScaleType type) {
+ if (type == ScaleType.FIT_START || type == ScaleType.FIT_END) {
+ throw new UnsupportedOperationException("TouchImageView does not support FIT_START or FIT_END");
+ }
+ if (type == ScaleType.MATRIX) {
+ super.setScaleType(ScaleType.MATRIX);
+
+ } else {
+ mScaleType = type;
+ if (onDrawReady) {
+ //
+ // If the image is already rendered, scaleType has been called programmatically
+ // and the TouchImageView should be updated with the new scaleType.
+ //
+ setZoom(this);
+ }
+ }
+ }
+
+ @Override
+ public ScaleType getScaleType() {
+ return mScaleType;
+ }
+
+ /**
+ * Returns false if image is in initial, unzoomed state. False, otherwise.
+ * @return true if image is zoomed
+ */
+ public boolean isZoomed() {
+ return normalizedScale != 1;
+ }
+
+ /**
+ * Return a Rect representing the zoomed image.
+ * @return rect representing zoomed image
+ */
+ public RectF getZoomedRect() {
+ if (mScaleType == ScaleType.FIT_XY) {
+ throw new UnsupportedOperationException("getZoomedRect() not supported with FIT_XY");
+ }
+ PointF topLeft = transformCoordTouchToBitmap(0, 0, true);
+ PointF bottomRight = transformCoordTouchToBitmap(viewWidth, viewHeight, true);
+
+ float w = getDrawable().getIntrinsicWidth();
+ float h = getDrawable().getIntrinsicHeight();
+ return new RectF(topLeft.x / w, topLeft.y / h, bottomRight.x / w, bottomRight.y / h);
+ }
+
+ /**
+ * Save the current matrix and view dimensions
+ * in the prevMatrix and prevView variables.
+ */
+ private void savePreviousImageValues() {
+ if (matrix != null && viewHeight != 0 && viewWidth != 0) {
+ matrix.getValues(m);
+ prevMatrix.setValues(m);
+ prevMatchViewHeight = matchViewHeight;
+ prevMatchViewWidth = matchViewWidth;
+ prevViewHeight = viewHeight;
+ prevViewWidth = viewWidth;
+ }
+ }
+
+ @Override
+ public Parcelable onSaveInstanceState() {
+ Bundle bundle = new Bundle();
+ bundle.putParcelable("instanceState", super.onSaveInstanceState());
+ bundle.putFloat("saveScale", normalizedScale);
+ bundle.putFloat("matchViewHeight", matchViewHeight);
+ bundle.putFloat("matchViewWidth", matchViewWidth);
+ bundle.putInt("viewWidth", viewWidth);
+ bundle.putInt("viewHeight", viewHeight);
+ matrix.getValues(m);
+ bundle.putFloatArray("matrix", m);
+ bundle.putBoolean("imageRendered", imageRenderedAtLeastOnce);
+ return bundle;
+ }
+
+ @Override
+ public void onRestoreInstanceState(Parcelable state) {
+ if (state instanceof Bundle) {
+ Bundle bundle = (Bundle) state;
+ normalizedScale = bundle.getFloat("saveScale");
+ m = bundle.getFloatArray("matrix");
+ prevMatrix.setValues(m);
+ prevMatchViewHeight = bundle.getFloat("matchViewHeight");
+ prevMatchViewWidth = bundle.getFloat("matchViewWidth");
+ prevViewHeight = bundle.getInt("viewHeight");
+ prevViewWidth = bundle.getInt("viewWidth");
+ imageRenderedAtLeastOnce = bundle.getBoolean("imageRendered");
+ super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
+ return;
+ }
+
+ super.onRestoreInstanceState(state);
+ }
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+ onDrawReady = true;
+ imageRenderedAtLeastOnce = true;
+ if (delayedZoomVariables != null) {
+ setZoom(delayedZoomVariables.scale, delayedZoomVariables.focusX, delayedZoomVariables.focusY, delayedZoomVariables.scaleType);
+ delayedZoomVariables = null;
+ }
+ super.onDraw(canvas);
+ }
+
+ @Override
+ public void onConfigurationChanged(Configuration newConfig) {
+ super.onConfigurationChanged(newConfig);
+ savePreviousImageValues();
+ }
+
+ /**
+ * Get the max zoom multiplier.
+ * @return max zoom multiplier.
+ */
+ public float getMaxZoom() {
+ return maxScale;
+ }
+
+ /**
+ * Set the max zoom multiplier. Default value: 3.
+ * @param max max zoom multiplier.
+ */
+ public void setMaxZoom(float max) {
+ maxScale = max;
+ superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
+ }
+
+ /**
+ * Get the min zoom multiplier.
+ * @return min zoom multiplier.
+ */
+ public float getMinZoom() {
+ return minScale;
+ }
+
+ /**
+ * Get the current zoom. This is the zoom relative to the initial
+ * scale, not the original resource.
+ * @return current zoom multiplier.
+ */
+ public float getCurrentZoom() {
+ return normalizedScale;
+ }
+
+ /**
+ * Set the min zoom multiplier. Default value: 1.
+ * @param min min zoom multiplier.
+ */
+ public void setMinZoom(float min) {
+ minScale = min;
+ superMinScale = SUPER_MIN_MULTIPLIER * minScale;
+ }
+
+ /**
+ * Reset zoom and translation to initial state.
+ */
+ public void resetZoom() {
+ normalizedScale = 1;
+ fitImageToView();
+ }
+
+ /**
+ * Set zoom to the specified scale. Image will be centered by default.
+ * @param scale
+ */
+ public void setZoom(float scale) {
+ setZoom(scale, 0.5f, 0.5f);
+ }
+
+ /**
+ * Set zoom to the specified scale. Image will be centered around the point
+ * (focusX, focusY). These floats range from 0 to 1 and denote the focus point
+ * as a fraction from the left and top of the view. For example, the top left
+ * corner of the image would be (0, 0). And the bottom right corner would be (1, 1).
+ * @param scale
+ * @param focusX
+ * @param focusY
+ */
+ public void setZoom(float scale, float focusX, float focusY) {
+ setZoom(scale, focusX, focusY, mScaleType);
+ }
+
+ /**
+ * Set zoom to the specified scale. Image will be centered around the point
+ * (focusX, focusY). These floats range from 0 to 1 and denote the focus point
+ * as a fraction from the left and top of the view. For example, the top left
+ * corner of the image would be (0, 0). And the bottom right corner would be (1, 1).
+ * @param scale
+ * @param focusX
+ * @param focusY
+ * @param scaleType
+ */
+ public void setZoom(float scale, float focusX, float focusY, ScaleType scaleType) {
+ //
+ // setZoom can be called before the image is on the screen, but at this point,
+ // image and view sizes have not yet been calculated in onMeasure. Thus, we should
+ // delay calling setZoom until the view has been measured.
+ //
+ if (!onDrawReady) {
+ delayedZoomVariables = new ZoomVariables(scale, focusX, focusY, scaleType);
+ return;
+ }
+
+ if (scaleType != mScaleType) {
+ setScaleType(scaleType);
+ }
+ resetZoom();
+ scaleImage(scale, viewWidth / 2, viewHeight / 2, true);
+ matrix.getValues(m);
+ m[Matrix.MTRANS_X] = -((focusX * getImageWidth()) - (viewWidth * 0.5f));
+ m[Matrix.MTRANS_Y] = -((focusY * getImageHeight()) - (viewHeight * 0.5f));
+ matrix.setValues(m);
+ fixTrans();
+ setImageMatrix(matrix);
+ }
+
+ /**
+ * Set zoom parameters equal to another TouchImageView. Including scale, position,
+ * and ScaleType.
+ * @param TouchImageView
+ */
+ public void setZoom(TouchImageViewCustom img) {
+ PointF center = img.getScrollPosition();
+ setZoom(img.getCurrentZoom(), center.x, center.y, img.getScaleType());
+ }
+
+ /**
+ * Return the point at the center of the zoomed image. The PointF coordinates range
+ * in value between 0 and 1 and the focus point is denoted as a fraction from the left
+ * and top of the view. For example, the top left corner of the image would be (0, 0).
+ * And the bottom right corner would be (1, 1).
+ * @return PointF representing the scroll position of the zoomed image.
+ */
+ public PointF getScrollPosition() {
+ Drawable drawable = getDrawable();
+ if (drawable == null) {
+ return null;
+ }
+ int drawableWidth = drawable.getIntrinsicWidth();
+ int drawableHeight = drawable.getIntrinsicHeight();
+
+ PointF point = transformCoordTouchToBitmap(viewWidth / 2, viewHeight / 2, true);
+ point.x /= drawableWidth;
+ point.y /= drawableHeight;
+ return point;
+ }
+
+ /**
+ * Set the focus point of the zoomed image. The focus points are denoted as a fraction from the
+ * left and top of the view. The focus points can range in value between 0 and 1.
+ * @param focusX
+ * @param focusY
+ */
+ public void setScrollPosition(float focusX, float focusY) {
+ setZoom(normalizedScale, focusX, focusY);
+ }
+
+ /**
+ * Performs boundary checking and fixes the image matrix if it
+ * is out of bounds.
+ */
+ private void fixTrans() {
+ matrix.getValues(m);
+ float transX = m[Matrix.MTRANS_X];
+ float transY = m[Matrix.MTRANS_Y];
+
+ float fixTransX = getFixTrans(transX, viewWidth, getImageWidth());
+ float fixTransY = getFixTrans(transY, viewHeight, getImageHeight());
+
+ if (fixTransX != 0 || fixTransY != 0) {
+ matrix.postTranslate(fixTransX, fixTransY);
+ }
+ }
+
+ /**
+ * When transitioning from zooming from focus to zoom from center (or vice versa)
+ * the image can become unaligned within the view. This is apparent when zooming
+ * quickly. When the content size is less than the view size, the content will often
+ * be centered incorrectly within the view. fixScaleTrans first calls fixTrans() and
+ * then makes sure the image is centered correctly within the view.
+ */
+ private void fixScaleTrans() {
+ fixTrans();
+ matrix.getValues(m);
+ if (getImageWidth() < viewWidth) {
+ m[Matrix.MTRANS_X] = (viewWidth - getImageWidth()) / 2;
+ }
+
+ if (getImageHeight() < viewHeight) {
+ m[Matrix.MTRANS_Y] = (viewHeight - getImageHeight()) / 2;
+ }
+ matrix.setValues(m);
+ }
+
+ private float getFixTrans(float trans, float viewSize, float contentSize) {
+ float minTrans, maxTrans;
+
+ if (contentSize <= viewSize) {
+ minTrans = 0;
+ maxTrans = viewSize - contentSize;
+
+ } else {
+ minTrans = viewSize - contentSize;
+ maxTrans = 0;
+ }
+
+ if (trans < minTrans)
+ return -trans + minTrans;
+ if (trans > maxTrans)
+ return -trans + maxTrans;
+ return 0;
+ }
+
+ private float getFixDragTrans(float delta, float viewSize, float contentSize) {
+ if (contentSize <= viewSize) {
+ return 0;
+ }
+ return delta;
+ }
+
+ private float getImageWidth() {
+ return matchViewWidth * normalizedScale;
+ }
+
+ private float getImageHeight() {
+ return matchViewHeight * normalizedScale;
+ }
+
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ Drawable drawable = getDrawable();
+ if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
+ setMeasuredDimension(0, 0);
+ return;
+ }
+
+ int drawableWidth = drawable.getIntrinsicWidth();
+ int drawableHeight = drawable.getIntrinsicHeight();
+ int widthSize = MeasureSpec.getSize(widthMeasureSpec);
+ int widthMode = MeasureSpec.getMode(widthMeasureSpec);
+ int heightSize = MeasureSpec.getSize(heightMeasureSpec);
+ int heightMode = MeasureSpec.getMode(heightMeasureSpec);
+ viewWidth = setViewSize(widthMode, widthSize, drawableWidth);
+ viewHeight = setViewSize(heightMode, heightSize, drawableHeight);
+
+ //
+ // Set view dimensions
+ //
+ setMeasuredDimension(viewWidth, viewHeight);
+
+ //
+ // Fit content within view
+ //
+ fitImageToView();
+ }
+
+ /**
+ * If the normalizedScale is equal to 1, then the image is made to fit the screen. Otherwise,
+ * it is made to fit the screen according to the dimensions of the previous image matrix. This
+ * allows the image to maintain its zoom after rotation.
+ */
+ private void fitImageToView() {
+ Drawable drawable = getDrawable();
+ if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
+ return;
+ }
+ if (matrix == null || prevMatrix == null) {
+ return;
+ }
+
+ int drawableWidth = drawable.getIntrinsicWidth();
+ int drawableHeight = drawable.getIntrinsicHeight();
+
+ //
+ // Scale image for view
+ //
+ float scaleX = (float) viewWidth / drawableWidth;
+ float scaleY = (float) viewHeight / drawableHeight;
+
+ switch (mScaleType) {
+ case CENTER:
+ scaleX = scaleY = 1;
+ break;
+
+ case CENTER_CROP:
+ scaleX = scaleY = Math.max(scaleX, scaleY);
+ break;
+
+ case CENTER_INSIDE:
+ scaleX = scaleY = Math.min(1, Math.min(scaleX, scaleY));
+
+ case FIT_CENTER:
+ scaleX = scaleY = Math.min(scaleX, scaleY);
+ break;
+
+ case FIT_XY:
+ break;
+
+ default:
+ //
+ // FIT_START and FIT_END not supported
+ //
+ throw new UnsupportedOperationException("TouchImageView does not support FIT_START or FIT_END");
+
+ }
+
+ //
+ // Center the image
+ //
+ float redundantXSpace = viewWidth - (scaleX * drawableWidth);
+ float redundantYSpace = viewHeight - (scaleY * drawableHeight);
+ matchViewWidth = viewWidth - redundantXSpace;
+ matchViewHeight = viewHeight - redundantYSpace;
+ if (!isZoomed() && !imageRenderedAtLeastOnce) {
+ //
+ // Stretch and center image to fit view
+ //
+ matrix.setScale(scaleX, scaleY);
+ matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
+ normalizedScale = 1;
+
+ } else {
+ //
+ // These values should never be 0 or we will set viewWidth and viewHeight
+ // to NaN in translateMatrixAfterRotate. To avoid this, call savePreviousImageValues
+ // to set them equal to the current values.
+ //
+ if (prevMatchViewWidth == 0 || prevMatchViewHeight == 0) {
+ savePreviousImageValues();
+ }
+
+ prevMatrix.getValues(m);
+
+ //
+ // Rescale Matrix after rotation
+ //
+ m[Matrix.MSCALE_X] = matchViewWidth / drawableWidth * normalizedScale;
+ m[Matrix.MSCALE_Y] = matchViewHeight / drawableHeight * normalizedScale;
+
+ //
+ // TransX and TransY from previous matrix
+ //
+ float transX = m[Matrix.MTRANS_X];
+ float transY = m[Matrix.MTRANS_Y];
+
+ //
+ // Width
+ //
+ float prevActualWidth = prevMatchViewWidth * normalizedScale;
+ float actualWidth = getImageWidth();
+ translateMatrixAfterRotate(Matrix.MTRANS_X, transX, prevActualWidth, actualWidth, prevViewWidth, viewWidth, drawableWidth);
+
+ //
+ // Height
+ //
+ float prevActualHeight = prevMatchViewHeight * normalizedScale;
+ float actualHeight = getImageHeight();
+ translateMatrixAfterRotate(Matrix.MTRANS_Y, transY, prevActualHeight, actualHeight, prevViewHeight, viewHeight, drawableHeight);
+
+ //
+ // Set the matrix to the adjusted scale and translate values.
+ //
+ matrix.setValues(m);
+ }
+ fixTrans();
+ setImageMatrix(matrix);
+ }
+
+ /**
+ * Set view dimensions based on layout params
+ *
+ * @param mode
+ * @param size
+ * @param drawableWidth
+ * @return
+ */
+ private int setViewSize(int mode, int size, int drawableWidth) {
+ int viewSize;
+ switch (mode) {
+ case MeasureSpec.EXACTLY:
+ viewSize = size;
+ break;
+
+ case MeasureSpec.AT_MOST:
+ viewSize = Math.min(drawableWidth, size);
+ break;
+
+ case MeasureSpec.UNSPECIFIED:
+ viewSize = drawableWidth;
+ break;
+
+ default:
+ viewSize = size;
+ break;
+ }
+ return viewSize;
+ }
+
+ /**
+ * After rotating, the matrix needs to be translated. This function finds the area of image
+ * which was previously centered and adjusts translations so that is again the center, post-rotation.
+ *
+ * @param axis Matrix.MTRANS_X or Matrix.MTRANS_Y
+ * @param trans the value of trans in that axis before the rotation
+ * @param prevImageSize the width/height of the image before the rotation
+ * @param imageSize width/height of the image after rotation
+ * @param prevViewSize width/height of view before rotation
+ * @param viewSize width/height of view after rotation
+ * @param drawableSize width/height of drawable
+ */
+ private void translateMatrixAfterRotate(int axis, float trans, float prevImageSize, float imageSize, int prevViewSize, int viewSize, int drawableSize) {
+ if (imageSize < viewSize) {
+ //
+ // The width/height of image is less than the view's width/height. Center it.
+ //
+ m[axis] = (viewSize - (drawableSize * m[Matrix.MSCALE_X])) * 0.5f;
+
+ } else if (trans > 0) {
+ //
+ // The image is larger than the view, but was not before rotation. Center it.
+ //
+ m[axis] = -((imageSize - viewSize) * 0.5f);
+
+ } else {
+ //
+ // Find the area of the image which was previously centered in the view. Determine its distance
+ // from the left/top side of the view as a fraction of the entire image's width/height. Use that percentage
+ // to calculate the trans in the new view width/height.
+ //
+ float percentage = (Math.abs(trans) + (0.5f * prevViewSize)) / prevImageSize;
+ m[axis] = -((percentage * imageSize) - (viewSize * 0.5f));
+ }
+ }
+
+ private void setState(State state) {
+ this.state = state;
+ }
+
+ public boolean canScrollHorizontallyFroyo(int direction) {
+ return canScrollHorizontally(direction);
+ }
+
+ @Override
+ public boolean canScrollHorizontally(int direction) {
+ matrix.getValues(m);
+ float x = m[Matrix.MTRANS_X];
+
+ if (getImageWidth() < viewWidth) {
+ return false;
+
+ } else if (x >= -1 && direction < 0) {
+ return false;
+
+ } else if (Math.abs(x) + viewWidth + 1 >= getImageWidth() && direction > 0) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Gesture Listener detects a single click or long click and passes that on
+ * to the view's listener.
+ * @author Ortiz
+ *
+ */
+ private class GestureListener extends GestureDetector.SimpleOnGestureListener {
+
+ @Override
+ public boolean onSingleTapConfirmed(MotionEvent e)
+ {
+ if(doubleTapListener != null) {
+ return doubleTapListener.onSingleTapConfirmed(e);
+ }
+ return performClick();
+ }
+
+ @Override
+ public void onLongPress(MotionEvent e)
+ {
+ performLongClick();
+ }
+
+ @Override
+ public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
+ {
+ if (fling != null) {
+ //
+ // If a previous fling is still active, it should be cancelled so that two flings
+ // are not run simultaenously.
+ //
+ fling.cancelFling();
+ }
+ fling = new Fling((int) velocityX, (int) velocityY);
+ compatPostOnAnimation(fling);
+ return super.onFling(e1, e2, velocityX, velocityY);
+ }
+
+ @Override
+ public boolean onDoubleTap(MotionEvent e) {
+ boolean consumed = false;
+ if(doubleTapListener != null) {
+ consumed = doubleTapListener.onDoubleTap(e);
+ }
+ if (state == State.NONE) {
+ float targetZoom = (normalizedScale == minScale) ? maxScale : minScale;
+ DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, e.getX(), e.getY(), false);
+ compatPostOnAnimation(doubleTap);
+ consumed = true;
+ }
+ return consumed;
+ }
+
+ @Override
+ public boolean onDoubleTapEvent(MotionEvent e) {
+ if(doubleTapListener != null) {
+ return doubleTapListener.onDoubleTapEvent(e);
+ }
+ return false;
+ }
+ }
+
+ public interface OnTouchImageViewListener {
+ public void onMove();
+ }
+
+ /**
+ * Responsible for all touch events. Handles the heavy lifting of drag and also sends
+ * touch events to Scale Detector and Gesture Detector.
+ * @author Ortiz
+ *
+ */
+ private class PrivateOnTouchListener implements OnTouchListener {
+
+ //
+ // Remember last point position for dragging
+ //
+ private PointF last = new PointF();
+
+ @Override
+ public boolean onTouch(View v, MotionEvent event) {
+ mScaleDetector.onTouchEvent(event);
+ mGestureDetector.onTouchEvent(event);
+ PointF curr = new PointF(event.getX(), event.getY());
+
+ if (state == State.NONE || state == State.DRAG || state == State.FLING) {
+ switch (event.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ last.set(curr);
+ if (fling != null)
+ fling.cancelFling();
+ setState(State.DRAG);
+ break;
+
+ case MotionEvent.ACTION_MOVE:
+ if (state == State.DRAG) {
+ float deltaX = curr.x - last.x;
+ float deltaY = curr.y - last.y;
+ float fixTransX = getFixDragTrans(deltaX, viewWidth, getImageWidth());
+ float fixTransY = getFixDragTrans(deltaY, viewHeight, getImageHeight());
+ matrix.postTranslate(fixTransX, fixTransY);
+ fixTrans();
+ last.set(curr.x, curr.y);
+ }
+ break;
+
+ case MotionEvent.ACTION_UP:
+ case MotionEvent.ACTION_POINTER_UP:
+ setState(State.NONE);
+ break;
+ }
+ }
+
+ setImageMatrix(matrix);
+
+ //
+ // User-defined OnTouchListener
+ //
+ if(userTouchListener != null) {
+ userTouchListener.onTouch(v, event);
+ }
+
+ //
+ // OnTouchImageViewListener is set: TouchImageView dragged by user.
+ //
+ if (touchImageViewListener != null) {
+ touchImageViewListener.onMove();
+ }
+
+ //
+ // indicate event was handled
+ //
+ return true;
+ }
+ }
+
+ /**
+ * ScaleListener detects user two finger scaling and scales image.
+ * @author Ortiz
+ *
+ */
+ private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
+ @Override
+ public boolean onScaleBegin(ScaleGestureDetector detector) {
+ setState(State.ZOOM);
+ return true;
+ }
+
+ @Override
+ public boolean onScale(ScaleGestureDetector detector) {
+ scaleImage(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY(), true);
+
+ //
+ // OnTouchImageViewListener is set: TouchImageView pinch zoomed by user.
+ //
+ if (touchImageViewListener != null) {
+ touchImageViewListener.onMove();
+ }
+ return true;
+ }
+
+ @Override
+ public void onScaleEnd(ScaleGestureDetector detector) {
+ super.onScaleEnd(detector);
+ setState(State.NONE);
+ boolean animateToZoomBoundary = false;
+ float targetZoom = normalizedScale;
+ if (normalizedScale > maxScale) {
+ targetZoom = maxScale;
+ animateToZoomBoundary = true;
+
+ } else if (normalizedScale < minScale) {
+ targetZoom = minScale;
+ animateToZoomBoundary = true;
+ }
+
+ if (animateToZoomBoundary) {
+ DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, viewWidth / 2, viewHeight / 2, true);
+ compatPostOnAnimation(doubleTap);
+ }
+ }
+ }
+
+ private void scaleImage(double deltaScale, float focusX, float focusY, boolean stretchImageToSuper) {
+
+ float lowerScale, upperScale;
+ if (stretchImageToSuper) {
+ lowerScale = superMinScale;
+ upperScale = superMaxScale;
+
+ } else {
+ lowerScale = minScale;
+ upperScale = maxScale;
+ }
+
+ float origScale = normalizedScale;
+ normalizedScale *= deltaScale;
+ if (normalizedScale > upperScale) {
+ normalizedScale = upperScale;
+ deltaScale = upperScale / origScale;
+ } else if (normalizedScale < lowerScale) {
+ normalizedScale = lowerScale;
+ deltaScale = lowerScale / origScale;
+ }
+
+ matrix.postScale((float) deltaScale, (float) deltaScale, focusX, focusY);
+ fixScaleTrans();
+ }
+
+ /**
+ * DoubleTapZoom calls a series of runnables which apply
+ * an animated zoom in/out graphic to the image.
+ * @author Ortiz
+ *
+ */
+ private class DoubleTapZoom implements Runnable {
+
+ private long startTime;
+ private static final float ZOOM_TIME = 500;
+ private float startZoom, targetZoom;
+ private float bitmapX, bitmapY;
+ private boolean stretchImageToSuper;
+ private AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator();
+ private PointF startTouch;
+ private PointF endTouch;
+
+ DoubleTapZoom(float targetZoom, float focusX, float focusY, boolean stretchImageToSuper) {
+ setState(State.ANIMATE_ZOOM);
+ startTime = System.currentTimeMillis();
+ this.startZoom = normalizedScale;
+ this.targetZoom = targetZoom;
+ this.stretchImageToSuper = stretchImageToSuper;
+ PointF bitmapPoint = transformCoordTouchToBitmap(focusX, focusY, false);
+ this.bitmapX = bitmapPoint.x;
+ this.bitmapY = bitmapPoint.y;
+
+ //
+ // Used for translating image during scaling
+ //
+ startTouch = transformCoordBitmapToTouch(bitmapX, bitmapY);
+ endTouch = new PointF(viewWidth / 2, viewHeight / 2);
+ }
+
+ @Override
+ public void run() {
+ float t = interpolate();
+ double deltaScale = calculateDeltaScale(t);
+ scaleImage(deltaScale, bitmapX, bitmapY, stretchImageToSuper);
+ translateImageToCenterTouchPosition(t);
+ fixScaleTrans();
+ setImageMatrix(matrix);
+
+ //
+ // OnTouchImageViewListener is set: double tap runnable updates listener
+ // with every frame.
+ //
+ if (touchImageViewListener != null) {
+ touchImageViewListener.onMove();
+ }
+
+ if (t < 1f) {
+ //
+ // We haven't finished zooming
+ //
+ compatPostOnAnimation(this);
+
+ } else {
+ //
+ // Finished zooming
+ //
+ setState(State.NONE);
+ }
+ }
+
+ /**
+ * Interpolate between where the image should start and end in order to translate
+ * the image so that the point that is touched is what ends up centered at the end
+ * of the zoom.
+ * @param t
+ */
+ private void translateImageToCenterTouchPosition(float t) {
+ float targetX = startTouch.x + t * (endTouch.x - startTouch.x);
+ float targetY = startTouch.y + t * (endTouch.y - startTouch.y);
+ PointF curr = transformCoordBitmapToTouch(bitmapX, bitmapY);
+ matrix.postTranslate(targetX - curr.x, targetY - curr.y);
+ }
+
+ /**
+ * Use interpolator to get t
+ * @return
+ */
+ private float interpolate() {
+ long currTime = System.currentTimeMillis();
+ float elapsed = (currTime - startTime) / ZOOM_TIME;
+ elapsed = Math.min(1f, elapsed);
+ return interpolator.getInterpolation(elapsed);
+ }
+
+ /**
+ * Interpolate the current targeted zoom and get the delta
+ * from the current zoom.
+ * @param t
+ * @return
+ */
+ private double calculateDeltaScale(float t) {
+ double zoom = startZoom + t * (targetZoom - startZoom);
+ return zoom / normalizedScale;
+ }
+ }
+
+ /**
+ * This function will transform the coordinates in the touch event to the coordinate
+ * system of the drawable that the imageview contain
+ * @param x x-coordinate of touch event
+ * @param y y-coordinate of touch event
+ * @param clipToBitmap Touch event may occur within view, but outside image content. True, to clip return value
+ * to the bounds of the bitmap size.
+ * @return Coordinates of the point touched, in the coordinate system of the original drawable.
+ */
+ private PointF transformCoordTouchToBitmap(float x, float y, boolean clipToBitmap) {
+ matrix.getValues(m);
+ float origW = getDrawable().getIntrinsicWidth();
+ float origH = getDrawable().getIntrinsicHeight();
+ float transX = m[Matrix.MTRANS_X];
+ float transY = m[Matrix.MTRANS_Y];
+ float finalX = ((x - transX) * origW) / getImageWidth();
+ float finalY = ((y - transY) * origH) / getImageHeight();
+
+ if (clipToBitmap) {
+ finalX = Math.min(Math.max(finalX, 0), origW);
+ finalY = Math.min(Math.max(finalY, 0), origH);
+ }
+
+ return new PointF(finalX , finalY);
+ }
+
+ /**
+ * Inverse of transformCoordTouchToBitmap. This function will transform the coordinates in the
+ * drawable's coordinate system to the view's coordinate system.
+ * @param bx x-coordinate in original bitmap coordinate system
+ * @param by y-coordinate in original bitmap coordinate system
+ * @return Coordinates of the point in the view's coordinate system.
+ */
+ private PointF transformCoordBitmapToTouch(float bx, float by) {
+ matrix.getValues(m);
+ float origW = getDrawable().getIntrinsicWidth();
+ float origH = getDrawable().getIntrinsicHeight();
+ float px = bx / origW;
+ float py = by / origH;
+ float finalX = m[Matrix.MTRANS_X] + getImageWidth() * px;
+ float finalY = m[Matrix.MTRANS_Y] + getImageHeight() * py;
+ return new PointF(finalX , finalY);
+ }
+
+ /**
+ * Fling launches sequential runnables which apply
+ * the fling graphic to the image. The values for the translation
+ * are interpolated by the Scroller.
+ * @author Ortiz
+ *
+ */
+ private class Fling implements Runnable {
+
+ CompatScroller scroller;
+ int currX, currY;
+
+ Fling(int velocityX, int velocityY) {
+ setState(State.FLING);
+ scroller = new CompatScroller(context);
+ matrix.getValues(m);
+
+ int startX = (int) m[Matrix.MTRANS_X];
+ int startY = (int) m[Matrix.MTRANS_Y];
+ int minX, maxX, minY, maxY;
+
+ if (getImageWidth() > viewWidth) {
+ minX = viewWidth - (int) getImageWidth();
+ maxX = 0;
+
+ } else {
+ minX = maxX = startX;
+ }
+
+ if (getImageHeight() > viewHeight) {
+ minY = viewHeight - (int) getImageHeight();
+ maxY = 0;
+
+ } else {
+ minY = maxY = startY;
+ }
+
+ scroller.fling(startX, startY, (int) velocityX, (int) velocityY, minX,
+ maxX, minY, maxY);
+ currX = startX;
+ currY = startY;
+ }
+
+ public void cancelFling() {
+ if (scroller != null) {
+ setState(State.NONE);
+ scroller.forceFinished(true);
+ }
+ }
+
+ @Override
+ public void run() {
+
+ //
+ // OnTouchImageViewListener is set: TouchImageView listener has been flung by user.
+ // Listener runnable updated with each frame of fling animation.
+ //
+ if (touchImageViewListener != null) {
+ touchImageViewListener.onMove();
+ }
+
+ if (scroller.isFinished()) {
+ scroller = null;
+ return;
+ }
+
+ if (scroller.computeScrollOffset()) {
+ int newX = scroller.getCurrX();
+ int newY = scroller.getCurrY();
+ int transX = newX - currX;
+ int transY = newY - currY;
+ currX = newX;
+ currY = newY;
+ matrix.postTranslate(transX, transY);
+ fixTrans();
+ setImageMatrix(matrix);
+ compatPostOnAnimation(this);
+ }
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.GINGERBREAD)
+ private class CompatScroller {
+ Scroller scroller;
+ OverScroller overScroller;
+ boolean isPreGingerbread;
+
+ public CompatScroller(Context context) {
+ if (VERSION.SDK_INT < VERSION_CODES.GINGERBREAD) {
+ isPreGingerbread = true;
+ scroller = new Scroller(context);
+
+ } else {
+ isPreGingerbread = false;
+ overScroller = new OverScroller(context);
+ }
+ }
+
+ public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY) {
+ if (isPreGingerbread) {
+ scroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
+ } else {
+ overScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
+ }
+ }
+
+ public void forceFinished(boolean finished) {
+ if (isPreGingerbread) {
+ scroller.forceFinished(finished);
+ } else {
+ overScroller.forceFinished(finished);
+ }
+ }
+
+ public boolean isFinished() {
+ if (isPreGingerbread) {
+ return scroller.isFinished();
+ } else {
+ return overScroller.isFinished();
+ }
+ }
+
+ public boolean computeScrollOffset() {
+ if (isPreGingerbread) {
+ return scroller.computeScrollOffset();
+ } else {
+ overScroller.computeScrollOffset();
+ return overScroller.computeScrollOffset();
+ }
+ }
+
+ public int getCurrX() {
+ if (isPreGingerbread) {
+ return scroller.getCurrX();
+ } else {
+ return overScroller.getCurrX();
+ }
+ }
+
+ public int getCurrY() {
+ if (isPreGingerbread) {
+ return scroller.getCurrY();
+ } else {
+ return overScroller.getCurrY();
+ }
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
+ private void compatPostOnAnimation(Runnable runnable) {
+ if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
+ postOnAnimation(runnable);
+
+ } else {
+ postDelayed(runnable, 1000/60);
+ }
+ }
+
+ private class ZoomVariables {
+ public float scale;
+ public float focusX;
+ public float focusY;
+ public ScaleType scaleType;
+
+ public ZoomVariables(float scale, float focusX, float focusY, ScaleType scaleType) {
+ this.scale = scale;
+ this.focusX = focusX;
+ this.focusY = focusY;
+ this.scaleType = scaleType;
+ }
+ }
+
+ private void printMatrixInfo() {
+ float[] n = new float[9];
+ matrix.getValues(n);
+ Log.d(DEBUG, "Scale: " + n[Matrix.MSCALE_X] + " TransX: " + n[Matrix.MTRANS_X] + " TransY: " + n[Matrix.MTRANS_Y]);
+ }
+}
\ No newline at end of file