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