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