Merge branch 'develop' into fixForCrashedSharedContents
[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 as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20 package com.owncloud.android.ui.activity;
21
22 import java.io.File;
23
24 import android.accounts.Account;
25 import android.app.AlertDialog;
26 import android.app.ProgressDialog;
27 import android.app.AlertDialog.Builder;
28 import android.app.Dialog;
29 import android.content.BroadcastReceiver;
30 import android.content.ComponentName;
31 import android.content.ContentResolver;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.DialogInterface.OnClickListener;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.ServiceConnection;
38 import android.content.SharedPreferences;
39 import android.content.SharedPreferences.Editor;
40 import android.content.pm.PackageInfo;
41 import android.content.pm.PackageManager.NameNotFoundException;
42 import android.content.res.Resources.NotFoundException;
43 import android.database.Cursor;
44 import android.graphics.Bitmap;
45 import android.graphics.drawable.BitmapDrawable;
46 import android.net.Uri;
47 import android.os.Bundle;
48 import android.os.Handler;
49 import android.os.IBinder;
50 import android.preference.PreferenceManager;
51 import android.provider.MediaStore;
52 import android.support.v4.app.Fragment;
53 import android.support.v4.app.FragmentTransaction;
54 import android.util.Log;
55 import android.view.View;
56 import android.view.ViewGroup;
57 import android.widget.ArrayAdapter;
58 import android.widget.EditText;
59 import android.widget.TextView;
60 import android.widget.Toast;
61
62 import com.actionbarsherlock.app.ActionBar;
63 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
64 import com.actionbarsherlock.app.SherlockFragmentActivity;
65 import com.actionbarsherlock.view.Menu;
66 import com.actionbarsherlock.view.MenuInflater;
67 import com.actionbarsherlock.view.MenuItem;
68 import com.actionbarsherlock.view.Window;
69 import com.owncloud.android.AccountUtils;
70 import com.owncloud.android.authenticator.AccountAuthenticator;
71 import com.owncloud.android.datamodel.DataStorageManager;
72 import com.owncloud.android.datamodel.FileDataStorageManager;
73 import com.owncloud.android.datamodel.OCFile;
74 import com.owncloud.android.files.services.FileDownloader;
75 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
76 import com.owncloud.android.files.services.FileObserverService;
77 import com.owncloud.android.files.services.FileUploader;
78 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
79 import com.owncloud.android.network.OwnCloudClientUtils;
80 import com.owncloud.android.operations.OnRemoteOperationListener;
81 import com.owncloud.android.operations.RemoteOperation;
82 import com.owncloud.android.operations.RemoteOperationResult;
83 import com.owncloud.android.operations.RemoveFileOperation;
84 import com.owncloud.android.operations.RenameFileOperation;
85 import com.owncloud.android.operations.SynchronizeFileOperation;
86 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
87 import com.owncloud.android.syncadapter.FileSyncService;
88 import com.owncloud.android.ui.dialog.ChangelogDialog;
89 import com.owncloud.android.ui.dialog.EditNameDialog;
90 import com.owncloud.android.ui.dialog.SslValidatorDialog;
91 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
92 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
93 import com.owncloud.android.ui.fragment.FileDetailFragment;
94 import com.owncloud.android.ui.fragment.FileFragment;
95 import com.owncloud.android.ui.fragment.OCFileListFragment;
96 import com.owncloud.android.ui.preview.PreviewImageActivity;
97 import com.owncloud.android.ui.preview.PreviewImageFragment;
98 import com.owncloud.android.ui.preview.PreviewMediaFragment;
99
100 import com.owncloud.android.R;
101 import eu.alefzero.webdav.WebdavClient;
102
103 /**
104 * Displays, what files the user has available in his ownCloud.
105 *
106 * @author Bartek Przybylski
107 * @author David A. Velasco
108 */
109
110 public class FileDisplayActivity extends SherlockFragmentActivity implements
111 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, OnRemoteOperationListener, EditNameDialogListener {
112
113 private ArrayAdapter<String> mDirectories;
114 private OCFile mCurrentDir = null;
115 private OCFile mCurrentFile = null;
116
117 private DataStorageManager mStorageManager;
118 private SyncBroadcastReceiver mSyncBroadcastReceiver;
119 private UploadFinishReceiver mUploadFinishReceiver;
120 private DownloadFinishReceiver mDownloadFinishReceiver;
121 private FileDownloaderBinder mDownloaderBinder = null;
122 private FileUploaderBinder mUploaderBinder = null;
123 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
124 private RemoteOperationResult mLastSslUntrustedServerResult = null;
125
126 private OCFileListFragment mFileList;
127
128 private boolean mDualPane;
129 private boolean mBackFromCreatingFirstAccount;
130
131 private static final int DIALOG_SETUP_ACCOUNT = 0;
132 private static final int DIALOG_CREATE_DIR = 1;
133 private static final int DIALOG_ABOUT_APP = 2;
134 public static final int DIALOG_SHORT_WAIT = 3;
135 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;
136 private static final int DIALOG_SSL_VALIDATOR = 5;
137 private static final int DIALOG_CERT_NOT_SAVED = 6;
138 private static final String DIALOG_CHANGELOG_TAG = "DIALOG_CHANGELOG";
139
140
141 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
142 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
143
144 private static final String TAG = "FileDisplayActivity";
145
146 private static int[] mMenuIdentifiersToPatch = {R.id.action_about_app};
147
148 private OCFile mWaitingToPreview;
149 private Handler mHandler;
150
151
152 @Override
153 public void onCreate(Bundle savedInstanceState) {
154 Log.d(getClass().toString(), "onCreate() start");
155 super.onCreate(savedInstanceState);
156
157 /// Load of parameters from received intent
158 Account account = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
159 if (account != null && AccountUtils.setCurrentOwnCloudAccount(this, account.name)) {
160 mCurrentDir = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
161 }
162
163 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
164 if(savedInstanceState != null) {
165 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
166 mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
167 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDetailActivity.KEY_WAITING_TO_PREVIEW);
168
169 } else {
170 mWaitingToPreview = null;
171 }
172
173 if (!AccountUtils.accountsAreSetup(this)) {
174 /// no account available: FORCE ACCOUNT CREATION
175 mStorageManager = null;
176 createFirstAccount();
177
178 } else { /// at least an account is available
179
180 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
181
182 }
183
184 mUploadConnection = new ListServiceConnection();
185 mDownloadConnection = new ListServiceConnection();
186 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
187 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
188
189 // PIN CODE request ; best location is to decide, let's try this first
190 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
191 requestPinCode();
192 }
193
194 // file observer
195 Intent observer_intent = new Intent(this, FileObserverService.class);
196 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
197 startService(observer_intent);
198
199
200 /// USER INTERFACE
201 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
202
203 // Drop-down navigation
204 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
205 OCFile currFile = mCurrentDir;
206 while(mStorageManager != null && currFile != null && currFile.getFileName() != OCFile.PATH_SEPARATOR) {
207 mDirectories.add(currFile.getFileName());
208 currFile = mStorageManager.getFileById(currFile.getParentId());
209 }
210 mDirectories.add(OCFile.PATH_SEPARATOR);
211
212 // Inflate and set the layout view
213 setContentView(R.layout.files);
214 mFileList = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
215 mDualPane = (findViewById(R.id.file_details_container) != null);
216 if (mDualPane) {
217 if (savedInstanceState == null) initFileDetailsInDualPane();
218 } else {
219 // quick patchES to fix problem in turn from landscape to portrait, when a file is selected in the right pane
220 // TODO serious refactorization in activities and fragments providing file browsing and handling
221 if (mCurrentFile != null) {
222 onFileClick(mCurrentFile);
223 mCurrentFile = null;
224 }
225 Fragment rightPanel = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
226 if (rightPanel != null) {
227 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
228 transaction.remove(rightPanel);
229 transaction.commit();
230 }
231 }
232
233 // Action bar setup
234 ActionBar actionBar = getSupportActionBar();
235 actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
236 actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getParentId() != 0);
237 actionBar.setDisplayShowTitleEnabled(false);
238 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
239 actionBar.setListNavigationCallbacks(mDirectories, this);
240 setSupportProgressBarIndeterminateVisibility(false); // always AFTER setContentView(...) ; to workaround bug in its implementation
241
242
243 // show changelog, if needed
244 //showChangeLog();
245 mBackFromCreatingFirstAccount = false;
246
247 Log.d(getClass().toString(), "onCreate() end");
248 }
249
250
251 /**
252 * Shows a dialog with the change log of the current version after each app update
253 *
254 * TODO make it permanent; by now, only to advice the workaround app for 4.1.x
255 */
256 private void showChangeLog() {
257 if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.JELLY_BEAN) {
258 final String KEY_VERSION = "version";
259 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
260 int currentVersionNumber = 0;
261 int savedVersionNumber = sharedPref.getInt(KEY_VERSION, 0);
262 try {
263 PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
264 currentVersionNumber = pi.versionCode;
265 } catch (Exception e) {}
266
267 if (currentVersionNumber > savedVersionNumber) {
268 ChangelogDialog.newInstance(true).show(getSupportFragmentManager(), DIALOG_CHANGELOG_TAG);
269 Editor editor = sharedPref.edit();
270 editor.putInt(KEY_VERSION, currentVersionNumber);
271 editor.commit();
272 }
273 }
274 }
275
276
277 /**
278 * Launches the account creation activity. To use when no ownCloud account is available
279 */
280 private void createFirstAccount() {
281 Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
282 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
283 startActivity(intent); // the new activity won't be created until this.onStart() and this.onResume() are finished;
284 }
285
286
287 /**
288 * Load of state dependent of the existence of an ownCloud account
289 */
290 private void initDataFromCurrentAccount() {
291 /// Storage manager initialization - access to local database
292 mStorageManager = new FileDataStorageManager(
293 AccountUtils.getCurrentOwnCloudAccount(this),
294 getContentResolver());
295
296 /// Check if mCurrentDir is a directory
297 if(mCurrentDir != null && !mCurrentDir.isDirectory()) {
298 mCurrentFile = mCurrentDir;
299 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
300 }
301
302 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
303 if (mCurrentDir != null) {
304 mCurrentDir = mStorageManager.getFileByPath(mCurrentDir.getRemotePath()); // mCurrentDir == null if it is not in the current account
305 }
306 if (mCurrentFile != null) {
307 if (mCurrentFile.fileExists()) {
308 mCurrentFile = mStorageManager.getFileByPath(mCurrentFile.getRemotePath()); // mCurrentFile == null if it is not in the current account
309 } // else : keep mCurrentFile 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
310 }
311
312 /// Default to root if mCurrentDir was not found
313 if (mCurrentDir == null) {
314 mCurrentDir = mStorageManager.getFileByPath("/"); // will be NULL if the database was never synchronized
315 }
316 }
317
318
319 private void initFileDetailsInDualPane() {
320 if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
321 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
322 if (mCurrentFile != null) {
323 if (PreviewMediaFragment.canBePreviewed(mCurrentFile)) {
324 if (mCurrentFile.isDown()) {
325 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
326 } else {
327 transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
328 mWaitingToPreview = mCurrentFile;
329 }
330 } else {
331 transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
332 }
333 mCurrentFile = null;
334
335 } else {
336 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
337 }
338 transaction.commit();
339 }
340 }
341
342
343 @Override
344 public void onDestroy() {
345 super.onDestroy();
346 if (mDownloadConnection != null)
347 unbindService(mDownloadConnection);
348 if (mUploadConnection != null)
349 unbindService(mUploadConnection);
350 }
351
352
353 @Override
354 public boolean onCreateOptionsMenu(Menu menu) {
355 MenuInflater inflater = getSherlock().getMenuInflater();
356 inflater.inflate(R.menu.main_menu, menu);
357
358 patchHiddenAccents(menu);
359
360 return true;
361 }
362
363 /**
364 * Workaround for this: <a href="http://code.google.com/p/android/issues/detail?id=3974">http://code.google.com/p/android/issues/detail?id=3974</a>
365 *
366 * @param menu Menu to patch
367 */
368 private void patchHiddenAccents(Menu menu) {
369 for (int i = 0; i < mMenuIdentifiersToPatch.length ; i++) {
370 MenuItem aboutItem = menu.findItem(mMenuIdentifiersToPatch[i]);
371 if (aboutItem != null && aboutItem.getIcon() instanceof BitmapDrawable) {
372 // Clip off the bottom three (density independent) pixels of transparent padding
373 Bitmap original = ((BitmapDrawable) aboutItem.getIcon()).getBitmap();
374 float scale = getResources().getDisplayMetrics().density;
375 int clippedHeight = (int) (original.getHeight() - (3 * scale));
376 Bitmap scaled = Bitmap.createBitmap(original, 0, 0, original.getWidth(), clippedHeight);
377 aboutItem.setIcon(new BitmapDrawable(getResources(), scaled));
378 }
379 }
380 }
381
382
383 @Override
384 public boolean onOptionsItemSelected(MenuItem item) {
385 boolean retval = true;
386 switch (item.getItemId()) {
387 case R.id.action_create_dir: {
388 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.uploader_info_dirname), "", this);
389 dialog.show(getSupportFragmentManager(), "createdirdialog");
390 break;
391 }
392 case R.id.action_sync_account: {
393 startSynchronization();
394 break;
395 }
396 case R.id.action_upload: {
397 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
398 break;
399 }
400 case R.id.action_settings: {
401 Intent settingsIntent = new Intent(this, Preferences.class);
402 startActivity(settingsIntent);
403 break;
404 }
405 case R.id.action_about_app: {
406 showDialog(DIALOG_ABOUT_APP);
407 break;
408 }
409 case android.R.id.home: {
410 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
411 onBackPressed();
412 }
413 break;
414 }
415 default:
416 retval = super.onOptionsItemSelected(item);
417 }
418 return retval;
419 }
420
421 private void startSynchronization() {
422 ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE); // cancel the current synchronizations of any ownCloud account
423 Bundle bundle = new Bundle();
424 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
425 ContentResolver.requestSync(
426 AccountUtils.getCurrentOwnCloudAccount(this),
427 AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);
428 }
429
430
431 @Override
432 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
433 int i = itemPosition;
434 while (i-- != 0) {
435 onBackPressed();
436 }
437 // the next operation triggers a new call to this method, but it's necessary to
438 // ensure that the name exposed in the action bar is the current directory when the
439 // user selected it in the navigation list
440 if (itemPosition != 0)
441 getSupportActionBar().setSelectedNavigationItem(0);
442 return true;
443 }
444
445 /**
446 * Called, when the user selected something for uploading
447 */
448 public void onActivityResult(int requestCode, int resultCode, Intent data) {
449
450 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
451 requestSimpleUpload(data, resultCode);
452
453 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
454 requestMultipleUpload(data, resultCode);
455
456 }
457 }
458
459 private void requestMultipleUpload(Intent data, int resultCode) {
460 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
461 if (filePaths != null) {
462 String[] remotePaths = new String[filePaths.length];
463 String remotePathBase = "";
464 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
465 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
466 }
467 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
468 remotePathBase += OCFile.PATH_SEPARATOR;
469 for (int j = 0; j< remotePaths.length; j++) {
470 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
471 }
472
473 Intent i = new Intent(this, FileUploader.class);
474 i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
475 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
476 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
477 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
478 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
479 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
480 startService(i);
481
482 } else {
483 Log.d("FileDisplay", "User clicked on 'Update' with no selection");
484 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
485 t.show();
486 return;
487 }
488 }
489
490
491 private void requestSimpleUpload(Intent data, int resultCode) {
492 String filepath = null;
493 try {
494 Uri selectedImageUri = data.getData();
495
496 String filemanagerstring = selectedImageUri.getPath();
497 String selectedImagePath = getPath(selectedImageUri);
498
499 if (selectedImagePath != null)
500 filepath = selectedImagePath;
501 else
502 filepath = filemanagerstring;
503
504 } catch (Exception e) {
505 Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
506 e.printStackTrace();
507
508 } finally {
509 if (filepath == null) {
510 Log.e("FileDisplay", "Couldnt resolve path to file");
511 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
512 t.show();
513 return;
514 }
515 }
516
517 Intent i = new Intent(this, FileUploader.class);
518 i.putExtra(FileUploader.KEY_ACCOUNT,
519 AccountUtils.getCurrentOwnCloudAccount(this));
520 String remotepath = new String();
521 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
522 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
523 }
524 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
525 remotepath += OCFile.PATH_SEPARATOR;
526 remotepath += new File(filepath).getName();
527
528 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
529 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
530 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
531 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
532 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
533 startService(i);
534 }
535
536
537 @Override
538 public void onBackPressed() {
539 if (mDirectories.getCount() <= 1) {
540 finish();
541 return;
542 }
543 popDirname();
544 mFileList.onNavigateUp();
545 mCurrentDir = mFileList.getCurrentFile();
546
547 if (mDualPane) {
548 // Resets the FileDetailsFragment on Tablets so that it always displays
549 Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
550 if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
551 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
552 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
553 transaction.commit();
554 }
555 }
556
557 if(mCurrentDir.getParentId() == 0){
558 ActionBar actionBar = getSupportActionBar();
559 actionBar.setDisplayHomeAsUpEnabled(false);
560 }
561 }
562
563 @Override
564 protected void onSaveInstanceState(Bundle outState) {
565 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
566 Log.d(getClass().toString(), "onSaveInstanceState() start");
567 super.onSaveInstanceState(outState);
568 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
569 if (mDualPane) {
570 FileFragment fragment = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
571 if (fragment != null) {
572 OCFile file = fragment.getFile();
573 if (file != null) {
574 outState.putParcelable(FileDetailFragment.EXTRA_FILE, file);
575 }
576 }
577 }
578 outState.putParcelable(FileDetailActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
579 Log.d(getClass().toString(), "onSaveInstanceState() end");
580 }
581
582
583 @Override
584 public void onResume() {
585 Log.d(getClass().toString(), "onResume() start");
586 super.onResume();
587
588 if (AccountUtils.accountsAreSetup(this)) {
589
590 if (mStorageManager == null) {
591 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
592 initDataFromCurrentAccount();
593 if (mDualPane) {
594 initFileDetailsInDualPane();
595 }
596 mBackFromCreatingFirstAccount = true;
597 }
598
599 // Listen for sync messages
600 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
601 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
602 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
603
604 // Listen for upload messages
605 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
606 mUploadFinishReceiver = new UploadFinishReceiver();
607 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
608
609 // Listen for download messages
610 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
611 downloadIntentFilter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
612 mDownloadFinishReceiver = new DownloadFinishReceiver();
613 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
614
615 // List current directory
616 mFileList.listDirectory(mCurrentDir); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
617
618 } else {
619
620 mStorageManager = null; // an invalid object will be there if all the ownCloud accounts are removed
621 showDialog(DIALOG_SETUP_ACCOUNT);
622
623 }
624 Log.d(getClass().toString(), "onResume() end");
625 }
626
627
628 @Override
629 public void onPause() {
630 Log.d(getClass().toString(), "onPause() start");
631 super.onPause();
632 if (mSyncBroadcastReceiver != null) {
633 unregisterReceiver(mSyncBroadcastReceiver);
634 mSyncBroadcastReceiver = null;
635 }
636 if (mUploadFinishReceiver != null) {
637 unregisterReceiver(mUploadFinishReceiver);
638 mUploadFinishReceiver = null;
639 }
640 if (mDownloadFinishReceiver != null) {
641 unregisterReceiver(mDownloadFinishReceiver);
642 mDownloadFinishReceiver = null;
643 }
644 if (!AccountUtils.accountsAreSetup(this)) {
645 dismissDialog(DIALOG_SETUP_ACCOUNT);
646 }
647
648 Log.d(getClass().toString(), "onPause() end");
649 }
650
651
652 @Override
653 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
654 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
655 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
656 }
657 }
658
659
660 @Override
661 protected Dialog onCreateDialog(int id) {
662 Dialog dialog = null;
663 AlertDialog.Builder builder;
664 switch (id) {
665 case DIALOG_SETUP_ACCOUNT: {
666 builder = new AlertDialog.Builder(this);
667 builder.setTitle(R.string.main_tit_accsetup);
668 builder.setMessage(R.string.main_wrn_accsetup);
669 builder.setCancelable(false);
670 builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
671 public void onClick(DialogInterface dialog, int which) {
672 createFirstAccount();
673 dialog.dismiss();
674 }
675 });
676 String message = String.format(getString(R.string.common_exit), getString(R.string.app_name));
677 builder.setNegativeButton(message, new OnClickListener() {
678 public void onClick(DialogInterface dialog, int which) {
679 dialog.dismiss();
680 finish();
681 }
682 });
683 //builder.setNegativeButton(android.R.string.cancel, this);
684 dialog = builder.create();
685 break;
686 }
687 case DIALOG_ABOUT_APP: {
688 builder = new AlertDialog.Builder(this);
689 builder.setTitle(getString(R.string.about_title));
690 PackageInfo pkg;
691 try {
692 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
693 builder.setMessage(String.format(getString(R.string.about_message), getString(R.string.app_name), pkg.versionName));
694 builder.setIcon(android.R.drawable.ic_menu_info_details);
695 dialog = builder.create();
696 } catch (NameNotFoundException e) {
697 builder = null;
698 dialog = null;
699 Log.e(TAG, "Error while showing about dialog", e);
700 }
701 break;
702 }
703 case DIALOG_CREATE_DIR: {
704 builder = new Builder(this);
705 final EditText dirNameInput = new EditText(getBaseContext());
706 builder.setView(dirNameInput);
707 builder.setTitle(R.string.uploader_info_dirname);
708 int typed_color = getResources().getColor(R.color.setup_text_typed);
709 dirNameInput.setTextColor(typed_color);
710 builder.setPositiveButton(android.R.string.ok,
711 new OnClickListener() {
712 public void onClick(DialogInterface dialog, int which) {
713 String directoryName = dirNameInput.getText().toString();
714 if (directoryName.trim().length() == 0) {
715 dialog.cancel();
716 return;
717 }
718
719 // Figure out the path where the dir needs to be created
720 String path;
721 if (mCurrentDir == null) {
722 // this is just a patch; we should ensure that mCurrentDir never is null
723 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
724 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
725 mStorageManager.saveFile(file);
726 }
727 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
728 }
729 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
730
731 // Create directory
732 path += directoryName + OCFile.PATH_SEPARATOR;
733 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
734 thread.start();
735
736 dialog.dismiss();
737
738 showDialog(DIALOG_SHORT_WAIT);
739 }
740 });
741 builder.setNegativeButton(R.string.common_cancel,
742 new OnClickListener() {
743 public void onClick(DialogInterface dialog, int which) {
744 dialog.cancel();
745 }
746 });
747 dialog = builder.create();
748 break;
749 }
750 case DIALOG_SHORT_WAIT: {
751 ProgressDialog working_dialog = new ProgressDialog(this);
752 working_dialog.setMessage(getResources().getString(
753 R.string.wait_a_moment));
754 working_dialog.setIndeterminate(true);
755 working_dialog.setCancelable(false);
756 dialog = working_dialog;
757 break;
758 }
759 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
760
761 String[] items = null;
762
763 String[] allTheItems = { getString(R.string.actionbar_upload_files),
764 getString(R.string.actionbar_upload_from_apps),
765 getString(R.string.actionbar_failed_instant_upload) };
766
767 String[] commonItems = { getString(R.string.actionbar_upload_files),
768 getString(R.string.actionbar_upload_from_apps) };
769
770 if (InstantUploadActivity.IS_ENABLED)
771 items = allTheItems;
772 else
773 items = commonItems;
774
775 builder = new AlertDialog.Builder(this);
776 builder.setTitle(R.string.actionbar_upload);
777 builder.setItems(items, new DialogInterface.OnClickListener() {
778 public void onClick(DialogInterface dialog, int item) {
779 if (item == 0) {
780 // if (!mDualPane) {
781 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
782 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT,
783 AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this));
784 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
785 // } else {
786 // TODO create and handle new fragment
787 // LocalFileListFragment
788 // }
789 } else if (item == 1) {
790 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
791 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
792 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
793 ACTION_SELECT_CONTENT_FROM_APPS);
794 } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
795 Account account = AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this);
796 Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
797 action.putExtra(FileUploader.KEY_ACCOUNT, account);
798 startActivity(action);
799 }
800 }
801 });
802 dialog = builder.create();
803 break;
804 }
805 case DIALOG_SSL_VALIDATOR: {
806 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
807 break;
808 }
809 case DIALOG_CERT_NOT_SAVED: {
810 builder = new AlertDialog.Builder(this);
811 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
812 builder.setCancelable(false);
813 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
814 @Override
815 public void onClick(DialogInterface dialog, int which) {
816 dialog.dismiss();
817 };
818 });
819 dialog = builder.create();
820 break;
821 }
822 default:
823 dialog = null;
824 }
825
826 return dialog;
827 }
828
829
830 /**
831 * Translates a content URI of an image to a physical path
832 * on the disk
833 * @param uri The URI to resolve
834 * @return The path to the image or null if it could not be found
835 */
836 public String getPath(Uri uri) {
837 String[] projection = { MediaStore.Images.Media.DATA };
838 Cursor cursor = managedQuery(uri, projection, null, null, null);
839 if (cursor != null) {
840 int column_index = cursor
841 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
842 cursor.moveToFirst();
843 return cursor.getString(column_index);
844 }
845 return null;
846 }
847
848 /**
849 * Pushes a directory to the drop down list
850 * @param directory to push
851 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
852 */
853 public void pushDirname(OCFile directory) {
854 if(!directory.isDirectory()){
855 throw new IllegalArgumentException("Only directories may be pushed!");
856 }
857 mDirectories.insert(directory.getFileName(), 0);
858 mCurrentDir = directory;
859 }
860
861 /**
862 * Pops a directory name from the drop down list
863 * @return True, unless the stack is empty
864 */
865 public boolean popDirname() {
866 mDirectories.remove(mDirectories.getItem(0));
867 return !mDirectories.isEmpty();
868 }
869
870 private class DirectoryCreator implements Runnable {
871 private String mTargetPath;
872 private Account mAccount;
873 private Handler mHandler;
874
875 public DirectoryCreator(String targetPath, Account account, Handler handler) {
876 mTargetPath = targetPath;
877 mAccount = account;
878 mHandler = handler;
879 }
880
881 @Override
882 public void run() {
883 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
884 boolean created = wdc.createDirectory(mTargetPath);
885 if (created) {
886 mHandler.post(new Runnable() {
887 @Override
888 public void run() {
889 dismissDialog(DIALOG_SHORT_WAIT);
890
891 // Save new directory in local database
892 OCFile newDir = new OCFile(mTargetPath);
893 newDir.setMimetype("DIR");
894 newDir.setParentId(mCurrentDir.getFileId());
895 mStorageManager.saveFile(newDir);
896
897 // Display the new folder right away
898 mFileList.listDirectory();
899 }
900 });
901
902 } else {
903 mHandler.post(new Runnable() {
904 @Override
905 public void run() {
906 dismissDialog(DIALOG_SHORT_WAIT);
907 try {
908 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
909 msg.show();
910
911 } catch (NotFoundException e) {
912 Log.e(TAG, "Error while trying to show fail message " , e);
913 }
914 }
915 });
916 }
917 }
918
919 }
920
921 // Custom array adapter to override text colors
922 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
923
924 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
925 super(ctx, view);
926 }
927
928 public View getView(int position, View convertView, ViewGroup parent) {
929 View v = super.getView(position, convertView, parent);
930
931 ((TextView) v).setTextColor(getResources().getColorStateList(
932 android.R.color.white));
933 return v;
934 }
935
936 public View getDropDownView(int position, View convertView,
937 ViewGroup parent) {
938 View v = super.getDropDownView(position, convertView, parent);
939
940 ((TextView) v).setTextColor(getResources().getColorStateList(
941 android.R.color.white));
942
943 return v;
944 }
945
946 }
947
948 private class SyncBroadcastReceiver extends BroadcastReceiver {
949
950 /**
951 * {@link BroadcastReceiver} to enable syncing feedback in UI
952 */
953 @Override
954 public void onReceive(Context context, Intent intent) {
955 boolean inProgress = intent.getBooleanExtra(
956 FileSyncService.IN_PROGRESS, false);
957 String accountName = intent
958 .getStringExtra(FileSyncService.ACCOUNT_NAME);
959
960 Log.d("FileDisplay", "sync of account " + accountName
961 + " is in_progress: " + inProgress);
962
963 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
964
965 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
966
967 boolean fillBlankRoot = false;
968 if (mCurrentDir == null) {
969 mCurrentDir = mStorageManager.getFileByPath("/");
970 fillBlankRoot = (mCurrentDir != null);
971 }
972
973 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
974 || fillBlankRoot ) {
975 if (!fillBlankRoot)
976 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
977 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
978 .findFragmentById(R.id.fileList);
979 if (fileListFragment != null) {
980 fileListFragment.listDirectory(mCurrentDir);
981 }
982 }
983
984 setSupportProgressBarIndeterminateVisibility(inProgress);
985 if (mBackFromCreatingFirstAccount) {
986 // awful patch to fix problem with visibility of progress circle with the first refresh of the first account
987 // TODO - kill this Activity when the first account has to be created instead of stack the account creation on it
988 getSupportActionBar().hide();
989 getSupportActionBar().show();
990 mBackFromCreatingFirstAccount = false;
991 }
992 removeStickyBroadcast(intent);
993
994 }
995
996 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
997 if (synchResult != null) {
998 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
999 mLastSslUntrustedServerResult = synchResult;
1000 showDialog(DIALOG_SSL_VALIDATOR);
1001 }
1002 }
1003 }
1004 }
1005
1006
1007 private class UploadFinishReceiver extends BroadcastReceiver {
1008 /**
1009 * Once the file upload has finished -> update view
1010 * @author David A. Velasco
1011 * {@link BroadcastReceiver} to enable upload feedback in UI
1012 */
1013 @Override
1014 public void onReceive(Context context, Intent intent) {
1015 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1016 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1017 boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
1018 boolean isDescendant = (mCurrentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
1019 if (sameAccount && isDescendant) {
1020 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1021 if (fileListFragment != null) {
1022 fileListFragment.listDirectory();
1023 }
1024 }
1025 }
1026
1027 }
1028
1029
1030 /**
1031 * Class waiting for broadcast events from the {@link FielDownloader} service.
1032 *
1033 * Updates the UI when a download is started or finished, provided that it is relevant for the
1034 * current folder.
1035 */
1036 private class DownloadFinishReceiver extends BroadcastReceiver {
1037 @Override
1038 public void onReceive(Context context, Intent intent) {
1039 boolean sameAccount = isSameAccount(context, intent);
1040 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1041 boolean isDescendant = isDescendant(downloadedRemotePath);
1042
1043 if (sameAccount && isDescendant) {
1044 updateLeftPanel();
1045 if (mDualPane) {
1046 updateRightPanel(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1047 }
1048 }
1049
1050 removeStickyBroadcast(intent);
1051 }
1052
1053 private boolean isDescendant(String downloadedRemotePath) {
1054 return (mCurrentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
1055 }
1056
1057 private boolean isSameAccount(Context context, Intent intent) {
1058 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1059 return (accountName != null && accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name));
1060 }
1061 }
1062
1063
1064 protected void updateLeftPanel() {
1065 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1066 if (fileListFragment != null) {
1067 fileListFragment.listDirectory();
1068 }
1069 }
1070
1071 protected void updateRightPanel(String downloadEvent, String downloadedRemotePath, boolean success) {
1072 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1073 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
1074 if (fragment != null && fragment instanceof FileDetailFragment) {
1075 FileDetailFragment detailsFragment = (FileDetailFragment) fragment;
1076 OCFile fileInFragment = detailsFragment.getFile();
1077 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
1078 // the user browsed to other file ; forget the automatic preview
1079 mWaitingToPreview = null;
1080
1081 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
1082 // grant that the right panel updates the progress bar
1083 detailsFragment.listenForTransferProgress();
1084 detailsFragment.updateFileDetails(true, false);
1085
1086 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
1087 // update the right panel
1088 if (success && waitedPreview) {
1089 mWaitingToPreview = mStorageManager.getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
1090 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1091 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mWaitingToPreview, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1092 transaction.commit();
1093 mWaitingToPreview = null;
1094
1095 } else {
1096 detailsFragment.updateFileDetails(false, (success));
1097 }
1098 }
1099 }
1100 }
1101
1102
1103 /**
1104 * {@inheritDoc}
1105 */
1106 @Override
1107 public DataStorageManager getStorageManager() {
1108 return mStorageManager;
1109 }
1110
1111
1112 /**
1113 * {@inheritDoc}
1114 */
1115 @Override
1116 public void onDirectoryClick(OCFile directory) {
1117 pushDirname(directory);
1118 ActionBar actionBar = getSupportActionBar();
1119 actionBar.setDisplayHomeAsUpEnabled(true);
1120
1121 if (mDualPane) {
1122 // Resets the FileDetailsFragment on Tablets so that it always displays
1123 Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1124 if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
1125 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1126 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
1127 transaction.commit();
1128 }
1129 }
1130 }
1131
1132
1133 /**
1134 * {@inheritDoc}
1135 */
1136 @Override
1137 public void onFileClick(OCFile file) {
1138 if (file != null && PreviewImageFragment.canBePreviewed(file)) {
1139 // preview image - it handles the download, if needed
1140 startPreviewImage(file);
1141
1142 } else if (file != null && PreviewMediaFragment.canBePreviewed(file)) {
1143 if (file.isDown()) {
1144 // general preview
1145 startMediaPreview(file);
1146
1147 } else {
1148 // automatic download, preview on finish
1149 startDownloadForPreview(file);
1150
1151 }
1152 } else {
1153 // details view
1154 startDetails(file);
1155 }
1156 }
1157
1158 private void startPreviewImage(OCFile file) {
1159 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1160 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1161 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1162 startActivity(showDetailsIntent);
1163 }
1164
1165 private void startMediaPreview(OCFile file) {
1166 if (mDualPane) {
1167 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1168 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1169 transaction.commit();
1170
1171 } else {
1172 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1173 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1174 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1175 startActivity(showDetailsIntent);
1176 }
1177 }
1178
1179 private void startDownloadForPreview(OCFile file) {
1180 if (mDualPane) {
1181 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1182 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1183 transaction.commit();
1184 mWaitingToPreview = file;
1185 requestForDownload();
1186
1187 } else {
1188 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1189 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1190 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1191 startActivity(showDetailsIntent);
1192 }
1193 }
1194
1195
1196 private void startDetails(OCFile file) {
1197 if (mDualPane && !file.isImage()) {
1198 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1199 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1200 transaction.commit();
1201 } else {
1202 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1203 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1204 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1205 startActivity(showDetailsIntent);
1206 }
1207 }
1208
1209
1210 /**
1211 * {@inheritDoc}
1212 */
1213 @Override
1214 public OCFile getInitialDirectory() {
1215 return mCurrentDir;
1216 }
1217
1218
1219 /**
1220 * {@inheritDoc}
1221 */
1222 @Override
1223 public void onFileStateChanged() {
1224 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1225 if (fileListFragment != null) {
1226 fileListFragment.listDirectory();
1227 }
1228 }
1229
1230
1231 /**
1232 * {@inheritDoc}
1233 */
1234 @Override
1235 public FileDownloaderBinder getFileDownloaderBinder() {
1236 return mDownloaderBinder;
1237 }
1238
1239
1240 /**
1241 * {@inheritDoc}
1242 */
1243 @Override
1244 public FileUploaderBinder getFileUploaderBinder() {
1245 return mUploaderBinder;
1246 }
1247
1248
1249 /** Defines callbacks for service binding, passed to bindService() */
1250 private class ListServiceConnection implements ServiceConnection {
1251
1252 @Override
1253 public void onServiceConnected(ComponentName component, IBinder service) {
1254 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1255 Log.d(TAG, "Download service connected");
1256 mDownloaderBinder = (FileDownloaderBinder) service;
1257 if (mWaitingToPreview != null) {
1258 requestForDownload();
1259 }
1260
1261 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1262 Log.d(TAG, "Upload service connected");
1263 mUploaderBinder = (FileUploaderBinder) service;
1264 } else {
1265 return;
1266 }
1267 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1268 if (mFileList != null)
1269 mFileList.listDirectory();
1270 if (mDualPane) {
1271 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1272 if (fragment != null && fragment instanceof FileDetailFragment) {
1273 FileDetailFragment detailFragment = (FileDetailFragment)fragment;
1274 detailFragment.listenForTransferProgress();
1275 detailFragment.updateFileDetails(false, false);
1276 }
1277 }
1278 }
1279
1280 @Override
1281 public void onServiceDisconnected(ComponentName component) {
1282 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1283 Log.d(TAG, "Download service disconnected");
1284 mDownloaderBinder = null;
1285 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1286 Log.d(TAG, "Upload service disconnected");
1287 mUploaderBinder = null;
1288 }
1289 }
1290 };
1291
1292
1293
1294 /**
1295 * Launch an intent to request the PIN code to the user before letting him use the app
1296 */
1297 private void requestPinCode() {
1298 boolean pinStart = false;
1299 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1300 pinStart = appPrefs.getBoolean("set_pincode", false);
1301 if (pinStart) {
1302 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1303 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1304 startActivity(i);
1305 }
1306 }
1307
1308
1309 @Override
1310 public void onSavedCertificate() {
1311 startSynchronization();
1312 }
1313
1314
1315 @Override
1316 public void onFailedSavingCertificate() {
1317 showDialog(DIALOG_CERT_NOT_SAVED);
1318 }
1319
1320
1321 /**
1322 * Updates the view associated to the activity after the finish of some operation over files
1323 * in the current account.
1324 *
1325 * @param operation Removal operation performed.
1326 * @param result Result of the removal.
1327 */
1328 @Override
1329 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1330 if (operation instanceof RemoveFileOperation) {
1331 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1332
1333 } else if (operation instanceof RenameFileOperation) {
1334 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1335
1336 } else if (operation instanceof SynchronizeFileOperation) {
1337 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1338 }
1339 }
1340
1341
1342 /**
1343 * Updates the view associated to the activity after the finish of an operation trying to remove a
1344 * file.
1345 *
1346 * @param operation Removal operation performed.
1347 * @param result Result of the removal.
1348 */
1349 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1350 dismissDialog(DIALOG_SHORT_WAIT);
1351 if (result.isSuccess()) {
1352 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1353 msg.show();
1354 OCFile removedFile = operation.getFile();
1355 if (mDualPane) {
1356 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1357 if (details != null && removedFile.equals(details.getFile())) {
1358 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1359 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1360 transaction.commit();
1361 }
1362 }
1363 if (mStorageManager.getFileById(removedFile.getParentId()).equals(mCurrentDir)) {
1364 mFileList.listDirectory();
1365 }
1366
1367 } else {
1368 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1369 msg.show();
1370 if (result.isSslRecoverableException()) {
1371 mLastSslUntrustedServerResult = result;
1372 showDialog(DIALOG_SSL_VALIDATOR);
1373 }
1374 }
1375 }
1376
1377 /**
1378 * Updates the view associated to the activity after the finish of an operation trying to rename a
1379 * file.
1380 *
1381 * @param operation Renaming operation performed.
1382 * @param result Result of the renaming.
1383 */
1384 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1385 dismissDialog(DIALOG_SHORT_WAIT);
1386 OCFile renamedFile = operation.getFile();
1387 if (result.isSuccess()) {
1388 if (mDualPane) {
1389 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1390 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1391 ((FileDetailFragment) details).updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
1392 }
1393 }
1394 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(mCurrentDir)) {
1395 mFileList.listDirectory();
1396 }
1397
1398 } else {
1399 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1400 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1401 msg.show();
1402 // TODO throw again the new rename dialog
1403 } else {
1404 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1405 msg.show();
1406 if (result.isSslRecoverableException()) {
1407 mLastSslUntrustedServerResult = result;
1408 showDialog(DIALOG_SSL_VALIDATOR);
1409 }
1410 }
1411 }
1412 }
1413
1414
1415 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1416 dismissDialog(DIALOG_SHORT_WAIT);
1417 OCFile syncedFile = operation.getLocalFile();
1418 if (!result.isSuccess()) {
1419 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1420 Intent i = new Intent(this, ConflictsResolveActivity.class);
1421 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1422 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1423 startActivity(i);
1424
1425 } else {
1426 Toast msg = Toast.makeText(this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1427 msg.show();
1428 }
1429
1430 } else {
1431 if (operation.transferWasRequested()) {
1432 mFileList.listDirectory();
1433 onTransferStateChanged(syncedFile, true, true);
1434
1435 } else {
1436 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1437 msg.show();
1438 }
1439 }
1440 }
1441
1442
1443 /**
1444 * {@inheritDoc}
1445 */
1446 @Override
1447 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1448 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1449 if (fileListFragment != null) {
1450 fileListFragment.listDirectory();
1451 }*/
1452 if (mDualPane) {
1453 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1454 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1455 if (downloading || uploading) {
1456 ((FileDetailFragment)details).updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
1457 } else {
1458 ((FileDetailFragment)details).updateFileDetails(false, true);
1459 }
1460 }
1461 }
1462 }
1463
1464
1465 @Override
1466 public void showFragmentWithDetails(OCFile file) {
1467 if (mDualPane) {
1468 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1469 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1470 transaction.commit();
1471
1472 } else {
1473 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1474 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1475 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1476 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
1477 startActivity(showDetailsIntent);
1478 }
1479 }
1480
1481 public void onDismiss(EditNameDialog dialog) {
1482 //dialog.dismiss();
1483 if (dialog.getResult()) {
1484 String newDirectoryName = dialog.getNewFilename().trim();
1485 Log.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1486 if (newDirectoryName.length() > 0) {
1487 String path;
1488 if (mCurrentDir == null) {
1489 // this is just a patch; we should ensure that mCurrentDir never is null
1490 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
1491 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
1492 mStorageManager.saveFile(file);
1493 }
1494 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
1495 }
1496 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
1497
1498 // Create directory
1499 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1500 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
1501 thread.start();
1502
1503 showDialog(DIALOG_SHORT_WAIT);
1504 }
1505 }
1506 }
1507
1508 private void requestForDownload() {
1509 Account account = AccountUtils.getCurrentOwnCloudAccount(this);
1510 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1511 Intent i = new Intent(this, FileDownloader.class);
1512 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1513 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1514 startService(i);
1515 }
1516 }
1517
1518
1519 }