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