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