Fixed update of progress bar for file transfers in landscape mode
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import java.io.File;
22
23 import android.accounts.Account;
24 import android.app.Activity;
25 import android.app.AlertDialog;
26 import android.app.ProgressDialog;
27 import android.app.AlertDialog.Builder;
28 import android.app.Dialog;
29 import android.content.BroadcastReceiver;
30 import android.content.ComponentName;
31 import android.content.ContentResolver;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.DialogInterface.OnClickListener;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.ServiceConnection;
38 import android.content.SharedPreferences;
39 import android.content.SharedPreferences.Editor;
40 import android.content.pm.PackageInfo;
41 import android.content.pm.PackageManager.NameNotFoundException;
42 import android.content.res.Resources.NotFoundException;
43 import android.database.Cursor;
44 import android.graphics.Bitmap;
45 import android.graphics.drawable.BitmapDrawable;
46 import android.net.Uri;
47 import android.os.Bundle;
48 import android.os.Handler;
49 import android.os.IBinder;
50 import android.preference.PreferenceManager;
51 import android.provider.MediaStore;
52 import android.support.v4.app.Fragment;
53 import android.support.v4.app.FragmentTransaction;
54 import android.util.Log;
55 import android.view.View;
56 import android.view.ViewGroup;
57 import android.widget.ArrayAdapter;
58 import android.widget.EditText;
59 import android.widget.TextView;
60 import android.widget.Toast;
61
62 import com.actionbarsherlock.app.ActionBar;
63 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
64 import com.actionbarsherlock.app.SherlockFragmentActivity;
65 import com.actionbarsherlock.view.Menu;
66 import com.actionbarsherlock.view.MenuInflater;
67 import com.actionbarsherlock.view.MenuItem;
68 import com.actionbarsherlock.view.Window;
69 import com.owncloud.android.AccountUtils;
70 import com.owncloud.android.authenticator.AccountAuthenticator;
71 import com.owncloud.android.datamodel.DataStorageManager;
72 import com.owncloud.android.datamodel.FileDataStorageManager;
73 import com.owncloud.android.datamodel.OCFile;
74 import com.owncloud.android.files.services.FileDownloader;
75 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
76 import com.owncloud.android.files.services.FileObserverService;
77 import com.owncloud.android.files.services.FileUploader;
78 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
79 import com.owncloud.android.network.OwnCloudClientUtils;
80 import com.owncloud.android.operations.OnRemoteOperationListener;
81 import com.owncloud.android.operations.RemoteOperation;
82 import com.owncloud.android.operations.RemoteOperationResult;
83 import com.owncloud.android.operations.RemoveFileOperation;
84 import com.owncloud.android.operations.RenameFileOperation;
85 import com.owncloud.android.operations.SynchronizeFileOperation;
86 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
87 import com.owncloud.android.syncadapter.FileSyncService;
88 import com.owncloud.android.ui.dialog.ChangelogDialog;
89 import com.owncloud.android.ui.dialog.SslValidatorDialog;
90 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
91 import com.owncloud.android.ui.fragment.FileDetailFragment;
92 import com.owncloud.android.ui.fragment.FileFragment;
93 import com.owncloud.android.ui.fragment.FilePreviewFragment;
94 import com.owncloud.android.ui.fragment.OCFileListFragment;
95
96 import com.owncloud.android.R;
97 import eu.alefzero.webdav.WebdavClient;
98
99 /**
100 * Displays, what files the user has available in his ownCloud.
101 *
102 * @author Bartek Przybylski
103 *
104 */
105
106 public class FileDisplayActivity extends SherlockFragmentActivity implements
107 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, OnRemoteOperationListener {
108
109 private ArrayAdapter<String> mDirectories;
110 private OCFile mCurrentDir = null;
111 private OCFile mCurrentFile = null;
112
113 private DataStorageManager mStorageManager;
114 private SyncBroadcastReceiver mSyncBroadcastReceiver;
115 private UploadFinishReceiver mUploadFinishReceiver;
116 private DownloadFinishReceiver mDownloadFinishReceiver;
117 private FileDownloaderBinder mDownloaderBinder = null;
118 private FileUploaderBinder mUploaderBinder = null;
119 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
120 private RemoteOperationResult mLastSslUntrustedServerResult = null;
121
122 private OCFileListFragment mFileList;
123
124 private boolean mDualPane;
125
126 private static final int DIALOG_SETUP_ACCOUNT = 0;
127 private static final int DIALOG_CREATE_DIR = 1;
128 private static final int DIALOG_ABOUT_APP = 2;
129 public static final int DIALOG_SHORT_WAIT = 3;
130 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;
131 private static final int DIALOG_SSL_VALIDATOR = 5;
132 private static final int DIALOG_CERT_NOT_SAVED = 6;
133 private static final String DIALOG_CHANGELOG_TAG = "DIALOG_CHANGELOG";
134
135
136 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
137 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
138
139 private static final String TAG = "FileDisplayActivity";
140
141 private static int[] mMenuIdentifiersToPatch = {R.id.action_about_app};
142
143 @Override
144 public void onCreate(Bundle savedInstanceState) {
145 Log.d(getClass().toString(), "onCreate() start");
146 super.onCreate(savedInstanceState);
147
148 /// Load of parameters from received intent
149 mCurrentDir = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE); // no check necessary, mCurrenDir == null if the parameter is not in the intent
150 Account account = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
151 if (account != null)
152 AccountUtils.setCurrentOwnCloudAccount(this, account.name);
153
154 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
155 if(savedInstanceState != null) {
156 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
157 mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
158 }
159
160 if (!AccountUtils.accountsAreSetup(this)) {
161 /// no account available: FORCE ACCOUNT CREATION
162 mStorageManager = null;
163 createFirstAccount();
164
165 } else { /// at least an account is available
166
167 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
168
169 }
170
171 mUploadConnection = new ListServiceConnection();
172 mDownloadConnection = new ListServiceConnection();
173 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
174 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
175
176 // PIN CODE request ; best location is to decide, let's try this first
177 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
178 requestPinCode();
179 }
180
181 // file observer
182 Intent observer_intent = new Intent(this, FileObserverService.class);
183 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
184 startService(observer_intent);
185
186
187 /// USER INTERFACE
188 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
189
190 // Drop-down navigation
191 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
192 OCFile currFile = mCurrentDir;
193 while(currFile != null && currFile.getFileName() != OCFile.PATH_SEPARATOR) {
194 mDirectories.add(currFile.getFileName());
195 currFile = mStorageManager.getFileById(currFile.getParentId());
196 }
197 mDirectories.add(OCFile.PATH_SEPARATOR);
198
199 // Inflate and set the layout view
200 setContentView(R.layout.files);
201 mFileList = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
202 mDualPane = (findViewById(R.id.file_details_container) != null);
203 if (mDualPane) {
204 initFileDetailsInDualPane();
205 }
206
207 // Action bar setup
208 ActionBar actionBar = getSupportActionBar();
209 actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
210 actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getParentId() != 0);
211 actionBar.setDisplayShowTitleEnabled(false);
212 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
213 actionBar.setListNavigationCallbacks(mDirectories, this);
214 setSupportProgressBarIndeterminateVisibility(false); // always AFTER setContentView(...) ; to workaround bug in its implementation
215
216
217 // show changelog, if needed
218 showChangeLog();
219
220 Log.d(getClass().toString(), "onCreate() end");
221 }
222
223
224 /**
225 * Shows a dialog with the change log of the current version after each app update
226 *
227 * TODO make it permanent; by now, only to advice the workaround app for 4.1.x
228 */
229 private void showChangeLog() {
230 if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.JELLY_BEAN) {
231 final String KEY_VERSION = "version";
232 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
233 int currentVersionNumber = 0;
234 int savedVersionNumber = sharedPref.getInt(KEY_VERSION, 0);
235 try {
236 PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
237 currentVersionNumber = pi.versionCode;
238 } catch (Exception e) {}
239
240 if (currentVersionNumber > savedVersionNumber) {
241 ChangelogDialog.newInstance(true).show(getSupportFragmentManager(), DIALOG_CHANGELOG_TAG);
242 Editor editor = sharedPref.edit();
243 editor.putInt(KEY_VERSION, currentVersionNumber);
244 editor.commit();
245 }
246 }
247 }
248
249
250 /**
251 * Launches the account creation activity. To use when no ownCloud account is available
252 */
253 private void createFirstAccount() {
254 Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
255 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
256 startActivity(intent); // the new activity won't be created until this.onStart() and this.onResume() are finished;
257 }
258
259
260 /**
261 * Load of state dependent of the existence of an ownCloud account
262 */
263 private void initDataFromCurrentAccount() {
264 /// Storage manager initialization - access to local database
265 mStorageManager = new FileDataStorageManager(
266 AccountUtils.getCurrentOwnCloudAccount(this),
267 getContentResolver());
268
269 /// Check if mCurrentDir is a directory
270 if(mCurrentDir != null && !mCurrentDir.isDirectory()) {
271 mCurrentFile = mCurrentDir;
272 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
273 }
274
275 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
276 if (mCurrentDir != null) {
277 mCurrentDir = mStorageManager.getFileByPath(mCurrentDir.getRemotePath()); // mCurrentDir == null if it is not in the current account
278 }
279 if (mCurrentFile != null) {
280 if (mCurrentFile.fileExists()) {
281 mCurrentFile = mStorageManager.getFileByPath(mCurrentFile.getRemotePath()); // mCurrentFile == null if it is not in the current account
282 } // else : keep mCurrentFile with the received value; this is currently the case of an upload in progress, when the user presses the status notification in a landscape tablet
283 }
284
285 /// Default to root if mCurrentDir was not found
286 if (mCurrentDir == null) {
287 mCurrentDir = mStorageManager.getFileByPath("/"); // will be NULL if the database was never synchronized
288 }
289 }
290
291
292 private void initFileDetailsInDualPane() {
293 if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
294 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
295 if (mCurrentFile != null) {
296 if (mCurrentFile.isDown() && FilePreviewFragment.canBePreviewed(mCurrentFile)) {
297 transaction.replace(R.id.file_details_container, new FilePreviewFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
298 } else {
299 transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
300 }
301 mCurrentFile = null;
302
303 } else {
304 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
305 }
306 transaction.commit();
307 }
308 }
309
310
311 @Override
312 public void onDestroy() {
313 super.onDestroy();
314 if (mDownloadConnection != null)
315 unbindService(mDownloadConnection);
316 if (mUploadConnection != null)
317 unbindService(mUploadConnection);
318 }
319
320
321 @Override
322 public boolean onCreateOptionsMenu(Menu menu) {
323 MenuInflater inflater = getSherlock().getMenuInflater();
324 inflater.inflate(R.menu.main_menu, menu);
325
326 patchHiddenAccents(menu);
327
328 return true;
329 }
330
331 /**
332 * Workaround for this: <a href="http://code.google.com/p/android/issues/detail?id=3974">http://code.google.com/p/android/issues/detail?id=3974</a>
333 *
334 * @param menu Menu to patch
335 */
336 private void patchHiddenAccents(Menu menu) {
337 for (int i = 0; i < mMenuIdentifiersToPatch.length ; i++) {
338 MenuItem aboutItem = menu.findItem(mMenuIdentifiersToPatch[i]);
339 if (aboutItem != null && aboutItem.getIcon() instanceof BitmapDrawable) {
340 // Clip off the bottom three (density independent) pixels of transparent padding
341 Bitmap original = ((BitmapDrawable) aboutItem.getIcon()).getBitmap();
342 float scale = getResources().getDisplayMetrics().density;
343 int clippedHeight = (int) (original.getHeight() - (3 * scale));
344 Bitmap scaled = Bitmap.createBitmap(original, 0, 0, original.getWidth(), clippedHeight);
345 aboutItem.setIcon(new BitmapDrawable(getResources(), scaled));
346 }
347 }
348 }
349
350
351 @Override
352 public boolean onOptionsItemSelected(MenuItem item) {
353 boolean retval = true;
354 switch (item.getItemId()) {
355 case R.id.action_create_dir: {
356 showDialog(DIALOG_CREATE_DIR);
357 break;
358 }
359 case R.id.action_sync_account: {
360 startSynchronization();
361 break;
362 }
363 case R.id.action_upload: {
364 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
365 break;
366 }
367 case R.id.action_settings: {
368 Intent settingsIntent = new Intent(this, Preferences.class);
369 startActivity(settingsIntent);
370 break;
371 }
372 case R.id.action_about_app: {
373 showDialog(DIALOG_ABOUT_APP);
374 break;
375 }
376 case android.R.id.home: {
377 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
378 onBackPressed();
379 }
380 break;
381 }
382 default:
383 retval = super.onOptionsItemSelected(item);
384 }
385 return retval;
386 }
387
388 private void startSynchronization() {
389 ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE); // cancel the current synchronizations of any ownCloud account
390 Bundle bundle = new Bundle();
391 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
392 ContentResolver.requestSync(
393 AccountUtils.getCurrentOwnCloudAccount(this),
394 AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);
395 }
396
397
398 @Override
399 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
400 int i = itemPosition;
401 while (i-- != 0) {
402 onBackPressed();
403 }
404 // the next operation triggers a new call to this method, but it's necessary to
405 // ensure that the name exposed in the action bar is the current directory when the
406 // user selected it in the navigation list
407 if (itemPosition != 0)
408 getSupportActionBar().setSelectedNavigationItem(0);
409 return true;
410 }
411
412 /**
413 * Called, when the user selected something for uploading
414 */
415 public void onActivityResult(int requestCode, int resultCode, Intent data) {
416
417 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
418 requestSimpleUpload(data, resultCode);
419
420 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
421 requestMultipleUpload(data, resultCode);
422
423 }
424 }
425
426 private void requestMultipleUpload(Intent data, int resultCode) {
427 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
428 if (filePaths != null) {
429 String[] remotePaths = new String[filePaths.length];
430 String remotePathBase = "";
431 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
432 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
433 }
434 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
435 remotePathBase += OCFile.PATH_SEPARATOR;
436 for (int j = 0; j< remotePaths.length; j++) {
437 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
438 }
439
440 Intent i = new Intent(this, FileUploader.class);
441 i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
442 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
443 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
444 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
445 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
446 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
447 startService(i);
448
449 } else {
450 Log.d("FileDisplay", "User clicked on 'Update' with no selection");
451 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
452 t.show();
453 return;
454 }
455 }
456
457
458 private void requestSimpleUpload(Intent data, int resultCode) {
459 String filepath = null;
460 try {
461 Uri selectedImageUri = data.getData();
462
463 String filemanagerstring = selectedImageUri.getPath();
464 String selectedImagePath = getPath(selectedImageUri);
465
466 if (selectedImagePath != null)
467 filepath = selectedImagePath;
468 else
469 filepath = filemanagerstring;
470
471 } catch (Exception e) {
472 Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
473 e.printStackTrace();
474
475 } finally {
476 if (filepath == null) {
477 Log.e("FileDisplay", "Couldnt resolve path to file");
478 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
479 t.show();
480 return;
481 }
482 }
483
484 Intent i = new Intent(this, FileUploader.class);
485 i.putExtra(FileUploader.KEY_ACCOUNT,
486 AccountUtils.getCurrentOwnCloudAccount(this));
487 String remotepath = new String();
488 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
489 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
490 }
491 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
492 remotepath += OCFile.PATH_SEPARATOR;
493 remotepath += new File(filepath).getName();
494
495 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
496 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
497 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
498 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
499 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
500 startService(i);
501 }
502
503
504 @Override
505 public void onBackPressed() {
506 if (mDirectories.getCount() <= 1) {
507 finish();
508 return;
509 }
510 popDirname();
511 mFileList.onNavigateUp();
512 mCurrentDir = mFileList.getCurrentFile();
513
514 if (mDualPane) {
515 // Resets the FileDetailsFragment on Tablets so that it always displays
516 Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
517 if (fileFragment != null && (fileFragment instanceof FilePreviewFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
518 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
519 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
520 transaction.commit();
521 }
522 }
523
524 if(mCurrentDir.getParentId() == 0){
525 ActionBar actionBar = getSupportActionBar();
526 actionBar.setDisplayHomeAsUpEnabled(false);
527 }
528 }
529
530 @Override
531 protected void onSaveInstanceState(Bundle outState) {
532 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
533 Log.d(getClass().toString(), "onSaveInstanceState() start");
534 super.onSaveInstanceState(outState);
535 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
536 if (mDualPane) {
537 FileFragment fragment = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
538 if (fragment != null) {
539 OCFile file = fragment.getFile();
540 if (file != null) {
541 outState.putParcelable(FileDetailFragment.EXTRA_FILE, file);
542 }
543 }
544 }
545 Log.d(getClass().toString(), "onSaveInstanceState() end");
546 }
547
548 @Override
549 protected void onResume() {
550 Log.d(getClass().toString(), "onResume() start");
551 super.onResume();
552
553 if (AccountUtils.accountsAreSetup(this)) {
554
555 if (mStorageManager == null) {
556 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
557 initDataFromCurrentAccount();
558 if (mDualPane) {
559 initFileDetailsInDualPane();
560 }
561 }
562
563 // Listen for sync messages
564 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
565 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
566 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
567
568 // Listen for upload messages
569 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
570 mUploadFinishReceiver = new UploadFinishReceiver();
571 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
572
573 // Listen for download messages
574 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
575 mDownloadFinishReceiver = new DownloadFinishReceiver();
576 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
577
578 // List current directory
579 mFileList.listDirectory(mCurrentDir); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
580
581 } else {
582
583 mStorageManager = null; // an invalid object will be there if all the ownCloud accounts are removed
584 showDialog(DIALOG_SETUP_ACCOUNT);
585
586 }
587 Log.d(getClass().toString(), "onResume() end");
588 }
589
590
591 @Override
592 protected void onPause() {
593 Log.d(getClass().toString(), "onPause() start");
594 super.onPause();
595 if (mSyncBroadcastReceiver != null) {
596 unregisterReceiver(mSyncBroadcastReceiver);
597 mSyncBroadcastReceiver = null;
598 }
599 if (mUploadFinishReceiver != null) {
600 unregisterReceiver(mUploadFinishReceiver);
601 mUploadFinishReceiver = null;
602 }
603 if (mDownloadFinishReceiver != null) {
604 unregisterReceiver(mDownloadFinishReceiver);
605 mDownloadFinishReceiver = null;
606 }
607 if (!AccountUtils.accountsAreSetup(this)) {
608 dismissDialog(DIALOG_SETUP_ACCOUNT);
609 }
610
611 Log.d(getClass().toString(), "onPause() end");
612 }
613
614
615 @Override
616 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
617 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
618 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
619 }
620 }
621
622
623 @Override
624 protected Dialog onCreateDialog(int id) {
625 Dialog dialog = null;
626 AlertDialog.Builder builder;
627 switch (id) {
628 case DIALOG_SETUP_ACCOUNT: {
629 builder = new AlertDialog.Builder(this);
630 builder.setTitle(R.string.main_tit_accsetup);
631 builder.setMessage(R.string.main_wrn_accsetup);
632 builder.setCancelable(false);
633 builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
634 public void onClick(DialogInterface dialog, int which) {
635 createFirstAccount();
636 dialog.dismiss();
637 }
638 });
639 String message = String.format(getString(R.string.common_exit), getString(R.string.app_name));
640 builder.setNegativeButton(message, new OnClickListener() {
641 public void onClick(DialogInterface dialog, int which) {
642 dialog.dismiss();
643 finish();
644 }
645 });
646 //builder.setNegativeButton(android.R.string.cancel, this);
647 dialog = builder.create();
648 break;
649 }
650 case DIALOG_ABOUT_APP: {
651 builder = new AlertDialog.Builder(this);
652 builder.setTitle(getString(R.string.about_title));
653 PackageInfo pkg;
654 try {
655 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
656 builder.setMessage(String.format(getString(R.string.about_message), getString(R.string.app_name), pkg.versionName));
657 builder.setIcon(android.R.drawable.ic_menu_info_details);
658 dialog = builder.create();
659 } catch (NameNotFoundException e) {
660 builder = null;
661 dialog = null;
662 Log.e(TAG, "Error while showing about dialog", e);
663 }
664 break;
665 }
666 case DIALOG_CREATE_DIR: {
667 builder = new Builder(this);
668 final EditText dirNameInput = new EditText(getBaseContext());
669 builder.setView(dirNameInput);
670 builder.setTitle(R.string.uploader_info_dirname);
671 int typed_color = getResources().getColor(R.color.setup_text_typed);
672 dirNameInput.setTextColor(typed_color);
673 builder.setPositiveButton(android.R.string.ok,
674 new OnClickListener() {
675 public void onClick(DialogInterface dialog, int which) {
676 String directoryName = dirNameInput.getText().toString();
677 if (directoryName.trim().length() == 0) {
678 dialog.cancel();
679 return;
680 }
681
682 // Figure out the path where the dir needs to be created
683 String path;
684 if (mCurrentDir == null) {
685 // this is just a patch; we should ensure that mCurrentDir never is null
686 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
687 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
688 mStorageManager.saveFile(file);
689 }
690 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
691 }
692 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
693
694 // Create directory
695 path += directoryName + OCFile.PATH_SEPARATOR;
696 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
697 thread.start();
698
699 dialog.dismiss();
700
701 showDialog(DIALOG_SHORT_WAIT);
702 }
703 });
704 builder.setNegativeButton(R.string.common_cancel,
705 new OnClickListener() {
706 public void onClick(DialogInterface dialog, int which) {
707 dialog.cancel();
708 }
709 });
710 dialog = builder.create();
711 break;
712 }
713 case DIALOG_SHORT_WAIT: {
714 ProgressDialog working_dialog = new ProgressDialog(this);
715 working_dialog.setMessage(getResources().getString(
716 R.string.wait_a_moment));
717 working_dialog.setIndeterminate(true);
718 working_dialog.setCancelable(false);
719 dialog = working_dialog;
720 break;
721 }
722 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
723 final String [] items = { getString(R.string.actionbar_upload_files),
724 getString(R.string.actionbar_upload_from_apps) };
725 builder = new AlertDialog.Builder(this);
726 builder.setTitle(R.string.actionbar_upload);
727 builder.setItems(items, new DialogInterface.OnClickListener() {
728 public void onClick(DialogInterface dialog, int item) {
729 if (item == 0) {
730 //if (!mDualPane) {
731 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
732 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this));
733 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
734 //} else {
735 // TODO create and handle new fragment LocalFileListFragment
736 //}
737 } else if (item == 1) {
738 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
739 action = action.setType("*/*")
740 .addCategory(Intent.CATEGORY_OPENABLE);
741 startActivityForResult(
742 Intent.createChooser(action, getString(R.string.upload_chooser_title)),
743 ACTION_SELECT_CONTENT_FROM_APPS);
744 }
745 }
746 });
747 dialog = builder.create();
748 break;
749 }
750 case DIALOG_SSL_VALIDATOR: {
751 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
752 break;
753 }
754 case DIALOG_CERT_NOT_SAVED: {
755 builder = new AlertDialog.Builder(this);
756 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
757 builder.setCancelable(false);
758 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
759 @Override
760 public void onClick(DialogInterface dialog, int which) {
761 dialog.dismiss();
762 };
763 });
764 dialog = builder.create();
765 break;
766 }
767 default:
768 dialog = null;
769 }
770
771 return dialog;
772 }
773
774
775 /**
776 * Translates a content URI of an image to a physical path
777 * on the disk
778 * @param uri The URI to resolve
779 * @return The path to the image or null if it could not be found
780 */
781 public String getPath(Uri uri) {
782 String[] projection = { MediaStore.Images.Media.DATA };
783 Cursor cursor = managedQuery(uri, projection, null, null, null);
784 if (cursor != null) {
785 int column_index = cursor
786 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
787 cursor.moveToFirst();
788 return cursor.getString(column_index);
789 }
790 return null;
791 }
792
793 /**
794 * Pushes a directory to the drop down list
795 * @param directory to push
796 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
797 */
798 public void pushDirname(OCFile directory) {
799 if(!directory.isDirectory()){
800 throw new IllegalArgumentException("Only directories may be pushed!");
801 }
802 mDirectories.insert(directory.getFileName(), 0);
803 mCurrentDir = directory;
804 }
805
806 /**
807 * Pops a directory name from the drop down list
808 * @return True, unless the stack is empty
809 */
810 public boolean popDirname() {
811 mDirectories.remove(mDirectories.getItem(0));
812 return !mDirectories.isEmpty();
813 }
814
815 private class DirectoryCreator implements Runnable {
816 private String mTargetPath;
817 private Account mAccount;
818 private Handler mHandler;
819
820 public DirectoryCreator(String targetPath, Account account, Handler handler) {
821 mTargetPath = targetPath;
822 mAccount = account;
823 mHandler = handler;
824 }
825
826 @Override
827 public void run() {
828 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
829 boolean created = wdc.createDirectory(mTargetPath);
830 if (created) {
831 mHandler.post(new Runnable() {
832 @Override
833 public void run() {
834 dismissDialog(DIALOG_SHORT_WAIT);
835
836 // Save new directory in local database
837 OCFile newDir = new OCFile(mTargetPath);
838 newDir.setMimetype("DIR");
839 newDir.setParentId(mCurrentDir.getFileId());
840 mStorageManager.saveFile(newDir);
841
842 // Display the new folder right away
843 mFileList.listDirectory();
844 }
845 });
846
847 } else {
848 mHandler.post(new Runnable() {
849 @Override
850 public void run() {
851 dismissDialog(DIALOG_SHORT_WAIT);
852 try {
853 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
854 msg.show();
855
856 } catch (NotFoundException e) {
857 Log.e(TAG, "Error while trying to show fail message " , e);
858 }
859 }
860 });
861 }
862 }
863
864 }
865
866 // Custom array adapter to override text colors
867 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
868
869 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
870 super(ctx, view);
871 }
872
873 public View getView(int position, View convertView, ViewGroup parent) {
874 View v = super.getView(position, convertView, parent);
875
876 ((TextView) v).setTextColor(getResources().getColorStateList(
877 android.R.color.white));
878 return v;
879 }
880
881 public View getDropDownView(int position, View convertView,
882 ViewGroup parent) {
883 View v = super.getDropDownView(position, convertView, parent);
884
885 ((TextView) v).setTextColor(getResources().getColorStateList(
886 android.R.color.white));
887
888 return v;
889 }
890
891 }
892
893 private class SyncBroadcastReceiver extends BroadcastReceiver {
894
895 /**
896 * {@link BroadcastReceiver} to enable syncing feedback in UI
897 */
898 @Override
899 public void onReceive(Context context, Intent intent) {
900 boolean inProgress = intent.getBooleanExtra(
901 FileSyncService.IN_PROGRESS, false);
902 String accountName = intent
903 .getStringExtra(FileSyncService.ACCOUNT_NAME);
904
905 Log.d("FileDisplay", "sync of account " + accountName
906 + " is in_progress: " + inProgress);
907
908 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
909
910 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
911
912 boolean fillBlankRoot = false;
913 if (mCurrentDir == null) {
914 mCurrentDir = mStorageManager.getFileByPath("/");
915 fillBlankRoot = (mCurrentDir != null);
916 }
917
918 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
919 || fillBlankRoot ) {
920 if (!fillBlankRoot)
921 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
922 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
923 .findFragmentById(R.id.fileList);
924 if (fileListFragment != null) {
925 fileListFragment.listDirectory(mCurrentDir);
926 }
927 }
928
929 setSupportProgressBarIndeterminateVisibility(inProgress);
930 removeStickyBroadcast(intent);
931
932 }
933
934 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
935 if (synchResult != null) {
936 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
937 mLastSslUntrustedServerResult = synchResult;
938 showDialog(DIALOG_SSL_VALIDATOR);
939 }
940 }
941 }
942 }
943
944
945 private class UploadFinishReceiver extends BroadcastReceiver {
946 /**
947 * Once the file upload has finished -> update view
948 * @author David A. Velasco
949 * {@link BroadcastReceiver} to enable upload feedback in UI
950 */
951 @Override
952 public void onReceive(Context context, Intent intent) {
953 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
954 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
955 boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
956 boolean isDescendant = (mCurrentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
957 if (sameAccount && isDescendant) {
958 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
959 if (fileListFragment != null) {
960 fileListFragment.listDirectory();
961 }
962 }
963 }
964
965 }
966
967
968 /**
969 * Once the file download has finished -> update view
970 */
971 private class DownloadFinishReceiver extends BroadcastReceiver {
972 @Override
973 public void onReceive(Context context, Intent intent) {
974 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
975 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
976 boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
977 boolean isDescendant = (mCurrentDir != null) && (downloadedRemotePath != null) && (downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
978 if (sameAccount && isDescendant) {
979 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
980 if (fileListFragment != null) {
981 fileListFragment.listDirectory();
982 }
983 }
984 }
985 }
986
987
988
989
990 /**
991 * {@inheritDoc}
992 */
993 @Override
994 public DataStorageManager getStorageManager() {
995 return mStorageManager;
996 }
997
998
999 /**
1000 * {@inheritDoc}
1001 */
1002 @Override
1003 public void onDirectoryClick(OCFile directory) {
1004 pushDirname(directory);
1005 ActionBar actionBar = getSupportActionBar();
1006 actionBar.setDisplayHomeAsUpEnabled(true);
1007
1008 if (mDualPane) {
1009 // Resets the FileDetailsFragment on Tablets so that it always displays
1010 Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1011 if (fileFragment != null && (fileFragment instanceof FilePreviewFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
1012 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1013 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
1014 transaction.commit();
1015 }
1016 }
1017 }
1018
1019
1020 /**
1021 * {@inheritDoc}
1022 */
1023 @Override
1024 public void onFileClick(OCFile file) {
1025
1026 // If we are on a large device -> update fragment
1027 if (mDualPane) {
1028 // buttons in the details view are problematic when trying to reuse an existing fragment; create always a new one solves some of them, BUT no all; downloads are 'dangerous'
1029 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1030 if (file != null && file.isDown() && FilePreviewFragment.canBePreviewed(file)) {
1031 transaction.replace(R.id.file_details_container, new FilePreviewFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1032 } else {
1033 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1034 }
1035 //transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
1036 transaction.commit();
1037
1038 } else { // small or medium screen device -> new Activity
1039 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1040 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1041 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1042 startActivity(showDetailsIntent);
1043 }
1044 }
1045
1046
1047 /**
1048 * {@inheritDoc}
1049 */
1050 @Override
1051 public OCFile getInitialDirectory() {
1052 return mCurrentDir;
1053 }
1054
1055
1056 /**
1057 * {@inheritDoc}
1058 */
1059 @Override
1060 public void onFileStateChanged() {
1061 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1062 if (fileListFragment != null) {
1063 fileListFragment.listDirectory();
1064 }
1065 }
1066
1067
1068 /**
1069 * {@inheritDoc}
1070 */
1071 @Override
1072 public FileDownloaderBinder getFileDownloaderBinder() {
1073 return mDownloaderBinder;
1074 }
1075
1076
1077 /**
1078 * {@inheritDoc}
1079 */
1080 @Override
1081 public FileUploaderBinder getFileUploaderBinder() {
1082 return mUploaderBinder;
1083 }
1084
1085
1086 /** Defines callbacks for service binding, passed to bindService() */
1087 private class ListServiceConnection implements ServiceConnection {
1088
1089 @Override
1090 public void onServiceConnected(ComponentName component, IBinder service) {
1091 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1092 Log.d(TAG, "Download service connected");
1093 mDownloaderBinder = (FileDownloaderBinder) service;
1094 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1095 Log.d(TAG, "Upload service connected");
1096 mUploaderBinder = (FileUploaderBinder) service;
1097 } else {
1098 return;
1099 }
1100 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1101 if (mFileList != null)
1102 mFileList.listDirectory();
1103 if (mDualPane) {
1104 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1105 if (fragment != null && fragment instanceof FileDetailFragment) {
1106 FileDetailFragment detailFragment = (FileDetailFragment)fragment;
1107 detailFragment.listenForTransferProgress();
1108 detailFragment.updateFileDetails(false);
1109 }
1110 }
1111 }
1112
1113 @Override
1114 public void onServiceDisconnected(ComponentName component) {
1115 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1116 Log.d(TAG, "Download service disconnected");
1117 mDownloaderBinder = null;
1118 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1119 Log.d(TAG, "Upload service disconnected");
1120 mUploaderBinder = null;
1121 }
1122 }
1123 };
1124
1125
1126
1127 /**
1128 * Launch an intent to request the PIN code to the user before letting him use the app
1129 */
1130 private void requestPinCode() {
1131 boolean pinStart = false;
1132 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1133 pinStart = appPrefs.getBoolean("set_pincode", false);
1134 if (pinStart) {
1135 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1136 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1137 startActivity(i);
1138 }
1139 }
1140
1141
1142 @Override
1143 public void onSavedCertificate() {
1144 startSynchronization();
1145 }
1146
1147
1148 @Override
1149 public void onFailedSavingCertificate() {
1150 showDialog(DIALOG_CERT_NOT_SAVED);
1151 }
1152
1153
1154 /**
1155 * Updates the view associated to the activity after the finish of some operation over files
1156 * in the current account.
1157 *
1158 * @param operation Removal operation performed.
1159 * @param result Result of the removal.
1160 */
1161 @Override
1162 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1163 if (operation instanceof RemoveFileOperation) {
1164 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1165
1166 } else if (operation instanceof RenameFileOperation) {
1167 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1168
1169 } else if (operation instanceof SynchronizeFileOperation) {
1170 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1171 }
1172 }
1173
1174
1175 /**
1176 * Updates the view associated to the activity after the finish of an operation trying to remove a
1177 * file.
1178 *
1179 * @param operation Removal operation performed.
1180 * @param result Result of the removal.
1181 */
1182 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1183 dismissDialog(DIALOG_SHORT_WAIT);
1184 if (result.isSuccess()) {
1185 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1186 msg.show();
1187 OCFile removedFile = operation.getFile();
1188 if (mDualPane) {
1189 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1190 if (details != null && removedFile.equals(details.getFile())) {
1191 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1192 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1193 transaction.commit();
1194 }
1195 }
1196 if (mStorageManager.getFileById(removedFile.getParentId()).equals(mCurrentDir)) {
1197 mFileList.listDirectory();
1198 }
1199
1200 } else {
1201 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1202 msg.show();
1203 if (result.isSslRecoverableException()) {
1204 mLastSslUntrustedServerResult = result;
1205 showDialog(DIALOG_SSL_VALIDATOR);
1206 }
1207 }
1208 }
1209
1210 /**
1211 * Updates the view associated to the activity after the finish of an operation trying to rename a
1212 * file.
1213 *
1214 * @param operation Renaming operation performed.
1215 * @param result Result of the renaming.
1216 */
1217 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1218 dismissDialog(DIALOG_SHORT_WAIT);
1219 OCFile renamedFile = operation.getFile();
1220 if (result.isSuccess()) {
1221 if (mDualPane) {
1222 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1223 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1224 ((FileDetailFragment) details).updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
1225 }
1226 }
1227 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(mCurrentDir)) {
1228 mFileList.listDirectory();
1229 }
1230
1231 } else {
1232 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1233 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1234 msg.show();
1235 // TODO throw again the new rename dialog
1236 } else {
1237 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1238 msg.show();
1239 if (result.isSslRecoverableException()) {
1240 mLastSslUntrustedServerResult = result;
1241 showDialog(DIALOG_SSL_VALIDATOR);
1242 }
1243 }
1244 }
1245 }
1246
1247
1248 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1249 dismissDialog(DIALOG_SHORT_WAIT);
1250 OCFile syncedFile = operation.getLocalFile();
1251 if (!result.isSuccess()) {
1252 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1253 Intent i = new Intent(this, ConflictsResolveActivity.class);
1254 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1255 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1256 startActivity(i);
1257
1258 } else {
1259 Toast msg = Toast.makeText(this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1260 msg.show();
1261 }
1262
1263 } else {
1264 if (operation.transferWasRequested()) {
1265 mFileList.listDirectory();
1266 onTransferStateChanged(syncedFile, true, true);
1267
1268 } else {
1269 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1270 msg.show();
1271 }
1272 }
1273 }
1274
1275
1276 /**
1277 * {@inheritDoc}
1278 */
1279 @Override
1280 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1281 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1282 if (fileListFragment != null) {
1283 fileListFragment.listDirectory();
1284 }*/
1285 if (mDualPane) {
1286 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1287 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1288 if (downloading || uploading) {
1289 ((FileDetailFragment)details).updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
1290 } else {
1291 ((FileDetailFragment)details).updateFileDetails(downloading || uploading);
1292 }
1293 }
1294 }
1295 }
1296
1297
1298 @Override
1299 public void showFragmentWithDetails(OCFile file) {
1300 if (mDualPane) {
1301 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1302 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1303 transaction.commit();
1304
1305 } else {
1306 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1307 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1308 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1309 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
1310 startActivity(showDetailsIntent);
1311 }
1312 }
1313
1314
1315 }