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