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