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