Merge branch 'bug_hunting' into feature_previews
[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 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 @Override
583 public void onResume() {
584 Log.d(getClass().toString(), "onResume() start");
585 super.onResume();
586
587 if (AccountUtils.accountsAreSetup(this)) {
588
589 if (mStorageManager == null) {
590 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
591 initDataFromCurrentAccount();
592 if (mDualPane) {
593 initFileDetailsInDualPane();
594 }
595 mBackFromCreatingFirstAccount = true;
596 }
597
598 // Listen for sync messages
599 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
600 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
601 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
602
603 // Listen for upload messages
604 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
605 mUploadFinishReceiver = new UploadFinishReceiver();
606 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
607
608 // Listen for download messages
609 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
610 downloadIntentFilter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
611 mDownloadFinishReceiver = new DownloadFinishReceiver();
612 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
613
614 // List current directory
615 mFileList.listDirectory(mCurrentDir); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
616
617 } else {
618
619 mStorageManager = null; // an invalid object will be there if all the ownCloud accounts are removed
620 showDialog(DIALOG_SETUP_ACCOUNT);
621
622 }
623 Log.d(getClass().toString(), "onResume() end");
624 }
625
626
627 @Override
628 public void onPause() {
629 Log.d(getClass().toString(), "onPause() start");
630 super.onPause();
631 if (mSyncBroadcastReceiver != null) {
632 unregisterReceiver(mSyncBroadcastReceiver);
633 mSyncBroadcastReceiver = null;
634 }
635 if (mUploadFinishReceiver != null) {
636 unregisterReceiver(mUploadFinishReceiver);
637 mUploadFinishReceiver = null;
638 }
639 if (mDownloadFinishReceiver != null) {
640 unregisterReceiver(mDownloadFinishReceiver);
641 mDownloadFinishReceiver = null;
642 }
643 if (!AccountUtils.accountsAreSetup(this)) {
644 dismissDialog(DIALOG_SETUP_ACCOUNT);
645 }
646
647 Log.d(getClass().toString(), "onPause() end");
648 }
649
650
651 @Override
652 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
653 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
654 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
655 }
656 }
657
658
659 @Override
660 protected Dialog onCreateDialog(int id) {
661 Dialog dialog = null;
662 AlertDialog.Builder builder;
663 switch (id) {
664 case DIALOG_SETUP_ACCOUNT: {
665 builder = new AlertDialog.Builder(this);
666 builder.setTitle(R.string.main_tit_accsetup);
667 builder.setMessage(R.string.main_wrn_accsetup);
668 builder.setCancelable(false);
669 builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
670 public void onClick(DialogInterface dialog, int which) {
671 createFirstAccount();
672 dialog.dismiss();
673 }
674 });
675 String message = String.format(getString(R.string.common_exit), getString(R.string.app_name));
676 builder.setNegativeButton(message, new OnClickListener() {
677 public void onClick(DialogInterface dialog, int which) {
678 dialog.dismiss();
679 finish();
680 }
681 });
682 //builder.setNegativeButton(android.R.string.cancel, this);
683 dialog = builder.create();
684 break;
685 }
686 case DIALOG_ABOUT_APP: {
687 builder = new AlertDialog.Builder(this);
688 builder.setTitle(getString(R.string.about_title));
689 PackageInfo pkg;
690 try {
691 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
692 builder.setMessage(String.format(getString(R.string.about_message), getString(R.string.app_name), pkg.versionName));
693 builder.setIcon(android.R.drawable.ic_menu_info_details);
694 dialog = builder.create();
695 } catch (NameNotFoundException e) {
696 builder = null;
697 dialog = null;
698 Log.e(TAG, "Error while showing about dialog", e);
699 }
700 break;
701 }
702 case DIALOG_CREATE_DIR: {
703 builder = new Builder(this);
704 final EditText dirNameInput = new EditText(getBaseContext());
705 builder.setView(dirNameInput);
706 builder.setTitle(R.string.uploader_info_dirname);
707 int typed_color = getResources().getColor(R.color.setup_text_typed);
708 dirNameInput.setTextColor(typed_color);
709 builder.setPositiveButton(android.R.string.ok,
710 new OnClickListener() {
711 public void onClick(DialogInterface dialog, int which) {
712 String directoryName = dirNameInput.getText().toString();
713 if (directoryName.trim().length() == 0) {
714 dialog.cancel();
715 return;
716 }
717
718 // Figure out the path where the dir needs to be created
719 String path;
720 if (mCurrentDir == null) {
721 // this is just a patch; we should ensure that mCurrentDir never is null
722 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
723 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
724 mStorageManager.saveFile(file);
725 }
726 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
727 }
728 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
729
730 // Create directory
731 path += directoryName + OCFile.PATH_SEPARATOR;
732 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
733 thread.start();
734
735 dialog.dismiss();
736
737 showDialog(DIALOG_SHORT_WAIT);
738 }
739 });
740 builder.setNegativeButton(R.string.common_cancel,
741 new OnClickListener() {
742 public void onClick(DialogInterface dialog, int which) {
743 dialog.cancel();
744 }
745 });
746 dialog = builder.create();
747 break;
748 }
749 case DIALOG_SHORT_WAIT: {
750 ProgressDialog working_dialog = new ProgressDialog(this);
751 working_dialog.setMessage(getResources().getString(
752 R.string.wait_a_moment));
753 working_dialog.setIndeterminate(true);
754 working_dialog.setCancelable(false);
755 dialog = working_dialog;
756 break;
757 }
758 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
759
760 String[] items = null;
761
762 String[] allTheItems = { getString(R.string.actionbar_upload_files),
763 getString(R.string.actionbar_upload_from_apps),
764 getString(R.string.actionbar_failed_instant_upload) };
765
766 String[] commonItems = { getString(R.string.actionbar_upload_files),
767 getString(R.string.actionbar_upload_from_apps) };
768
769 if (InstantUploadActivity.IS_ENABLED)
770 items = allTheItems;
771 else
772 items = commonItems;
773
774 builder = new AlertDialog.Builder(this);
775 builder.setTitle(R.string.actionbar_upload);
776 builder.setItems(items, new DialogInterface.OnClickListener() {
777 public void onClick(DialogInterface dialog, int item) {
778 if (item == 0) {
779 // if (!mDualPane) {
780 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
781 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT,
782 AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this));
783 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
784 // } else {
785 // TODO create and handle new fragment
786 // LocalFileListFragment
787 // }
788 } else if (item == 1) {
789 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
790 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
791 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
792 ACTION_SELECT_CONTENT_FROM_APPS);
793 } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
794 Account account = AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this);
795 Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
796 action.putExtra(FileUploader.KEY_ACCOUNT, account);
797 startActivity(action);
798 }
799 }
800 });
801 dialog = builder.create();
802 break;
803 }
804 case DIALOG_SSL_VALIDATOR: {
805 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
806 break;
807 }
808 case DIALOG_CERT_NOT_SAVED: {
809 builder = new AlertDialog.Builder(this);
810 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
811 builder.setCancelable(false);
812 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
813 @Override
814 public void onClick(DialogInterface dialog, int which) {
815 dialog.dismiss();
816 };
817 });
818 dialog = builder.create();
819 break;
820 }
821 default:
822 dialog = null;
823 }
824
825 return dialog;
826 }
827
828
829 /**
830 * Translates a content URI of an image to a physical path
831 * on the disk
832 * @param uri The URI to resolve
833 * @return The path to the image or null if it could not be found
834 */
835 public String getPath(Uri uri) {
836 String[] projection = { MediaStore.Images.Media.DATA };
837 Cursor cursor = managedQuery(uri, projection, null, null, null);
838 if (cursor != null) {
839 int column_index = cursor
840 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
841 cursor.moveToFirst();
842 return cursor.getString(column_index);
843 }
844 return null;
845 }
846
847 /**
848 * Pushes a directory to the drop down list
849 * @param directory to push
850 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
851 */
852 public void pushDirname(OCFile directory) {
853 if(!directory.isDirectory()){
854 throw new IllegalArgumentException("Only directories may be pushed!");
855 }
856 mDirectories.insert(directory.getFileName(), 0);
857 mCurrentDir = directory;
858 }
859
860 /**
861 * Pops a directory name from the drop down list
862 * @return True, unless the stack is empty
863 */
864 public boolean popDirname() {
865 mDirectories.remove(mDirectories.getItem(0));
866 return !mDirectories.isEmpty();
867 }
868
869 private class DirectoryCreator implements Runnable {
870 private String mTargetPath;
871 private Account mAccount;
872 private Handler mHandler;
873
874 public DirectoryCreator(String targetPath, Account account, Handler handler) {
875 mTargetPath = targetPath;
876 mAccount = account;
877 mHandler = handler;
878 }
879
880 @Override
881 public void run() {
882 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
883 boolean created = wdc.createDirectory(mTargetPath);
884 if (created) {
885 mHandler.post(new Runnable() {
886 @Override
887 public void run() {
888 dismissDialog(DIALOG_SHORT_WAIT);
889
890 // Save new directory in local database
891 OCFile newDir = new OCFile(mTargetPath);
892 newDir.setMimetype("DIR");
893 newDir.setParentId(mCurrentDir.getFileId());
894 mStorageManager.saveFile(newDir);
895
896 // Display the new folder right away
897 mFileList.listDirectory();
898 }
899 });
900
901 } else {
902 mHandler.post(new Runnable() {
903 @Override
904 public void run() {
905 dismissDialog(DIALOG_SHORT_WAIT);
906 try {
907 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
908 msg.show();
909
910 } catch (NotFoundException e) {
911 Log.e(TAG, "Error while trying to show fail message " , e);
912 }
913 }
914 });
915 }
916 }
917
918 }
919
920 // Custom array adapter to override text colors
921 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
922
923 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
924 super(ctx, view);
925 }
926
927 public View getView(int position, View convertView, ViewGroup parent) {
928 View v = super.getView(position, convertView, parent);
929
930 ((TextView) v).setTextColor(getResources().getColorStateList(
931 android.R.color.white));
932 return v;
933 }
934
935 public View getDropDownView(int position, View convertView,
936 ViewGroup parent) {
937 View v = super.getDropDownView(position, convertView, parent);
938
939 ((TextView) v).setTextColor(getResources().getColorStateList(
940 android.R.color.white));
941
942 return v;
943 }
944
945 }
946
947 private class SyncBroadcastReceiver extends BroadcastReceiver {
948
949 /**
950 * {@link BroadcastReceiver} to enable syncing feedback in UI
951 */
952 @Override
953 public void onReceive(Context context, Intent intent) {
954 boolean inProgress = intent.getBooleanExtra(
955 FileSyncService.IN_PROGRESS, false);
956 String accountName = intent
957 .getStringExtra(FileSyncService.ACCOUNT_NAME);
958
959 Log.d("FileDisplay", "sync of account " + accountName
960 + " is in_progress: " + inProgress);
961
962 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
963
964 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
965
966 boolean fillBlankRoot = false;
967 if (mCurrentDir == null) {
968 mCurrentDir = mStorageManager.getFileByPath("/");
969 fillBlankRoot = (mCurrentDir != null);
970 }
971
972 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
973 || fillBlankRoot ) {
974 if (!fillBlankRoot)
975 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
976 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
977 .findFragmentById(R.id.fileList);
978 if (fileListFragment != null) {
979 fileListFragment.listDirectory(mCurrentDir);
980 }
981 }
982
983 setSupportProgressBarIndeterminateVisibility(inProgress);
984 if (mBackFromCreatingFirstAccount) {
985 // awful patch to fix problem with visibility of progress circle with the first refresh of the first account
986 // TODO - kill this Activity when the first account has to be created instead of stack the account creation on it
987 getSupportActionBar().hide();
988 getSupportActionBar().show();
989 mBackFromCreatingFirstAccount = false;
990 }
991 removeStickyBroadcast(intent);
992
993 }
994
995 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
996 if (synchResult != null) {
997 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
998 mLastSslUntrustedServerResult = synchResult;
999 showDialog(DIALOG_SSL_VALIDATOR);
1000 }
1001 }
1002 }
1003 }
1004
1005
1006 private class UploadFinishReceiver extends BroadcastReceiver {
1007 /**
1008 * Once the file upload has finished -> update view
1009 * @author David A. Velasco
1010 * {@link BroadcastReceiver} to enable upload feedback in UI
1011 */
1012 @Override
1013 public void onReceive(Context context, Intent intent) {
1014 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1015 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1016 boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
1017 boolean isDescendant = (mCurrentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
1018 if (sameAccount && isDescendant) {
1019 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1020 if (fileListFragment != null) {
1021 fileListFragment.listDirectory();
1022 }
1023 }
1024 }
1025
1026 }
1027
1028
1029 /**
1030 * Class waiting for broadcast events from the {@link FielDownloader} service.
1031 *
1032 * Updates the UI when a download is started or finished, provided that it is relevant for the
1033 * current folder.
1034 */
1035 private class DownloadFinishReceiver extends BroadcastReceiver {
1036 @Override
1037 public void onReceive(Context context, Intent intent) {
1038 boolean sameAccount = isSameAccount(context, intent);
1039 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1040 boolean isDescendant = isDescendant(downloadedRemotePath);
1041
1042 if (sameAccount && isDescendant) {
1043 updateLeftPanel();
1044 if (mDualPane) {
1045 updateRightPanel(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1046 }
1047 }
1048
1049 removeStickyBroadcast(intent);
1050 }
1051
1052 private boolean isDescendant(String downloadedRemotePath) {
1053 return (mCurrentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
1054 }
1055
1056 private boolean isSameAccount(Context context, Intent intent) {
1057 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1058 return (accountName != null && accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name));
1059 }
1060 }
1061
1062
1063 protected void updateLeftPanel() {
1064 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1065 if (fileListFragment != null) {
1066 fileListFragment.listDirectory();
1067 }
1068 }
1069
1070 protected void updateRightPanel(String downloadEvent, String downloadedRemotePath, boolean success) {
1071 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1072 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
1073 if (fragment != null && fragment instanceof FileDetailFragment) {
1074 FileDetailFragment detailsFragment = (FileDetailFragment) fragment;
1075 OCFile fileInFragment = detailsFragment.getFile();
1076 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
1077 // the user browsed to other file ; forget the automatic preview
1078 mWaitingToPreview = null;
1079
1080 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
1081 // grant that the right panel updates the progress bar
1082 detailsFragment.listenForTransferProgress();
1083 detailsFragment.updateFileDetails(true, false);
1084
1085 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
1086 // update the right panel
1087 if (success && waitedPreview) {
1088 mWaitingToPreview = mStorageManager.getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
1089 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1090 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mWaitingToPreview, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1091 transaction.commit();
1092 mWaitingToPreview = null;
1093
1094 } else {
1095 detailsFragment.updateFileDetails(false, (success));
1096 }
1097 }
1098 }
1099 }
1100
1101
1102 /**
1103 * {@inheritDoc}
1104 */
1105 @Override
1106 public DataStorageManager getStorageManager() {
1107 return mStorageManager;
1108 }
1109
1110
1111 /**
1112 * {@inheritDoc}
1113 */
1114 @Override
1115 public void onDirectoryClick(OCFile directory) {
1116 pushDirname(directory);
1117 ActionBar actionBar = getSupportActionBar();
1118 actionBar.setDisplayHomeAsUpEnabled(true);
1119
1120 if (mDualPane) {
1121 // Resets the FileDetailsFragment on Tablets so that it always displays
1122 Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1123 if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
1124 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1125 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
1126 transaction.commit();
1127 }
1128 }
1129 }
1130
1131
1132 /**
1133 * {@inheritDoc}
1134 */
1135 @Override
1136 public void onFileClick(OCFile file) {
1137 if (file != null && PreviewImageFragment.canBePreviewed(file)) {
1138 // preview image - it handles the download, if needed
1139 startPreviewImage(file);
1140
1141 } else if (file != null && PreviewMediaFragment.canBePreviewed(file)) {
1142 if (file.isDown()) {
1143 // general preview
1144 startMediaPreview(file);
1145
1146 } else {
1147 // automatic download, preview on finish
1148 startDownloadForPreview(file);
1149
1150 }
1151 } else {
1152 // details view
1153 startDetails(file);
1154 }
1155 }
1156
1157 private void startPreviewImage(OCFile file) {
1158 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1159 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1160 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1161 startActivity(showDetailsIntent);
1162 }
1163
1164 private void startMediaPreview(OCFile file) {
1165 if (mDualPane) {
1166 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1167 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1168 transaction.commit();
1169
1170 } else {
1171 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1172 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1173 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1174 startActivity(showDetailsIntent);
1175 }
1176 }
1177
1178 private void startDownloadForPreview(OCFile file) {
1179 if (mDualPane) {
1180 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1181 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1182 transaction.commit();
1183 mWaitingToPreview = file;
1184 requestForDownload();
1185
1186 } else {
1187 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1188 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1189 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1190 startActivity(showDetailsIntent);
1191 }
1192 }
1193
1194
1195 private void startDetails(OCFile file) {
1196 if (mDualPane && !file.isImage()) {
1197 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1198 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1199 transaction.commit();
1200 } else {
1201 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1202 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1203 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1204 startActivity(showDetailsIntent);
1205 }
1206 }
1207
1208
1209 /**
1210 * {@inheritDoc}
1211 */
1212 @Override
1213 public OCFile getInitialDirectory() {
1214 return mCurrentDir;
1215 }
1216
1217
1218 /**
1219 * {@inheritDoc}
1220 */
1221 @Override
1222 public void onFileStateChanged() {
1223 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1224 if (fileListFragment != null) {
1225 fileListFragment.listDirectory();
1226 }
1227 }
1228
1229
1230 /**
1231 * {@inheritDoc}
1232 */
1233 @Override
1234 public FileDownloaderBinder getFileDownloaderBinder() {
1235 return mDownloaderBinder;
1236 }
1237
1238
1239 /**
1240 * {@inheritDoc}
1241 */
1242 @Override
1243 public FileUploaderBinder getFileUploaderBinder() {
1244 return mUploaderBinder;
1245 }
1246
1247
1248 /** Defines callbacks for service binding, passed to bindService() */
1249 private class ListServiceConnection implements ServiceConnection {
1250
1251 @Override
1252 public void onServiceConnected(ComponentName component, IBinder service) {
1253 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1254 Log.d(TAG, "Download service connected");
1255 mDownloaderBinder = (FileDownloaderBinder) service;
1256 if (mWaitingToPreview != null) {
1257 requestForDownload();
1258 }
1259
1260 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1261 Log.d(TAG, "Upload service connected");
1262 mUploaderBinder = (FileUploaderBinder) service;
1263 } else {
1264 return;
1265 }
1266 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1267 if (mFileList != null)
1268 mFileList.listDirectory();
1269 if (mDualPane) {
1270 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1271 if (fragment != null && fragment instanceof FileDetailFragment) {
1272 FileDetailFragment detailFragment = (FileDetailFragment)fragment;
1273 detailFragment.listenForTransferProgress();
1274 detailFragment.updateFileDetails(false, false);
1275 }
1276 }
1277 }
1278
1279 @Override
1280 public void onServiceDisconnected(ComponentName component) {
1281 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1282 Log.d(TAG, "Download service disconnected");
1283 mDownloaderBinder = null;
1284 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1285 Log.d(TAG, "Upload service disconnected");
1286 mUploaderBinder = null;
1287 }
1288 }
1289 };
1290
1291
1292
1293 /**
1294 * Launch an intent to request the PIN code to the user before letting him use the app
1295 */
1296 private void requestPinCode() {
1297 boolean pinStart = false;
1298 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1299 pinStart = appPrefs.getBoolean("set_pincode", false);
1300 if (pinStart) {
1301 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1302 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1303 startActivity(i);
1304 }
1305 }
1306
1307
1308 @Override
1309 public void onSavedCertificate() {
1310 startSynchronization();
1311 }
1312
1313
1314 @Override
1315 public void onFailedSavingCertificate() {
1316 showDialog(DIALOG_CERT_NOT_SAVED);
1317 }
1318
1319
1320 /**
1321 * Updates the view associated to the activity after the finish of some operation over files
1322 * in the current account.
1323 *
1324 * @param operation Removal operation performed.
1325 * @param result Result of the removal.
1326 */
1327 @Override
1328 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1329 if (operation instanceof RemoveFileOperation) {
1330 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1331
1332 } else if (operation instanceof RenameFileOperation) {
1333 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1334
1335 } else if (operation instanceof SynchronizeFileOperation) {
1336 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1337 }
1338 }
1339
1340
1341 /**
1342 * Updates the view associated to the activity after the finish of an operation trying to remove a
1343 * file.
1344 *
1345 * @param operation Removal operation performed.
1346 * @param result Result of the removal.
1347 */
1348 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1349 dismissDialog(DIALOG_SHORT_WAIT);
1350 if (result.isSuccess()) {
1351 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1352 msg.show();
1353 OCFile removedFile = operation.getFile();
1354 if (mDualPane) {
1355 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1356 if (details != null && removedFile.equals(details.getFile())) {
1357 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1358 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1359 transaction.commit();
1360 }
1361 }
1362 if (mStorageManager.getFileById(removedFile.getParentId()).equals(mCurrentDir)) {
1363 mFileList.listDirectory();
1364 }
1365
1366 } else {
1367 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1368 msg.show();
1369 if (result.isSslRecoverableException()) {
1370 mLastSslUntrustedServerResult = result;
1371 showDialog(DIALOG_SSL_VALIDATOR);
1372 }
1373 }
1374 }
1375
1376 /**
1377 * Updates the view associated to the activity after the finish of an operation trying to rename a
1378 * file.
1379 *
1380 * @param operation Renaming operation performed.
1381 * @param result Result of the renaming.
1382 */
1383 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1384 dismissDialog(DIALOG_SHORT_WAIT);
1385 OCFile renamedFile = operation.getFile();
1386 if (result.isSuccess()) {
1387 if (mDualPane) {
1388 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1389 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1390 ((FileDetailFragment) details).updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
1391 }
1392 }
1393 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(mCurrentDir)) {
1394 mFileList.listDirectory();
1395 }
1396
1397 } else {
1398 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1399 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1400 msg.show();
1401 // TODO throw again the new rename dialog
1402 } else {
1403 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1404 msg.show();
1405 if (result.isSslRecoverableException()) {
1406 mLastSslUntrustedServerResult = result;
1407 showDialog(DIALOG_SSL_VALIDATOR);
1408 }
1409 }
1410 }
1411 }
1412
1413
1414 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1415 dismissDialog(DIALOG_SHORT_WAIT);
1416 OCFile syncedFile = operation.getLocalFile();
1417 if (!result.isSuccess()) {
1418 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1419 Intent i = new Intent(this, ConflictsResolveActivity.class);
1420 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1421 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1422 startActivity(i);
1423
1424 } else {
1425 Toast msg = Toast.makeText(this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1426 msg.show();
1427 }
1428
1429 } else {
1430 if (operation.transferWasRequested()) {
1431 mFileList.listDirectory();
1432 onTransferStateChanged(syncedFile, true, true);
1433
1434 } else {
1435 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1436 msg.show();
1437 }
1438 }
1439 }
1440
1441
1442 /**
1443 * {@inheritDoc}
1444 */
1445 @Override
1446 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1447 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1448 if (fileListFragment != null) {
1449 fileListFragment.listDirectory();
1450 }*/
1451 if (mDualPane) {
1452 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1453 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1454 if (downloading || uploading) {
1455 ((FileDetailFragment)details).updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
1456 } else {
1457 ((FileDetailFragment)details).updateFileDetails(false, true);
1458 }
1459 }
1460 }
1461 }
1462
1463
1464 @Override
1465 public void showFragmentWithDetails(OCFile file) {
1466 if (mDualPane) {
1467 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1468 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1469 transaction.commit();
1470
1471 } else {
1472 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1473 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1474 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1475 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
1476 startActivity(showDetailsIntent);
1477 }
1478 }
1479
1480 public void onDismiss(EditNameDialog dialog) {
1481 //dialog.dismiss();
1482 if (dialog.getResult()) {
1483 String newDirectoryName = dialog.getNewFilename().trim();
1484 Log.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1485 if (newDirectoryName.length() > 0) {
1486 String path;
1487 if (mCurrentDir == null) {
1488 // this is just a patch; we should ensure that mCurrentDir never is null
1489 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
1490 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
1491 mStorageManager.saveFile(file);
1492 }
1493 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
1494 }
1495 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
1496
1497 // Create directory
1498 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1499 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
1500 thread.start();
1501
1502 showDialog(DIALOG_SHORT_WAIT);
1503 }
1504 }
1505 }
1506
1507 private void requestForDownload() {
1508 Account account = AccountUtils.getCurrentOwnCloudAccount(this);
1509 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1510 Intent i = new Intent(this, FileDownloader.class);
1511 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1512 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1513 startService(i);
1514 }
1515 }
1516
1517
1518 }
1519