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