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