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