Patch to fix the lack of progress circle at the first sycnhronization of the first...
[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 }
744 }
745 });
746 dialog = builder.create();
747 break;
748 }
749 case DIALOG_SSL_VALIDATOR: {
750 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
751 break;
752 }
753 case DIALOG_CERT_NOT_SAVED: {
754 builder = new AlertDialog.Builder(this);
755 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
756 builder.setCancelable(false);
757 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
758 @Override
759 public void onClick(DialogInterface dialog, int which) {
760 dialog.dismiss();
761 };
762 });
763 dialog = builder.create();
764 break;
765 }
766 default:
767 dialog = null;
768 }
769
770 return dialog;
771 }
772
773
774 /**
775 * Translates a content URI of an image to a physical path
776 * on the disk
777 * @param uri The URI to resolve
778 * @return The path to the image or null if it could not be found
779 */
780 public String getPath(Uri uri) {
781 String[] projection = { MediaStore.Images.Media.DATA };
782 Cursor cursor = managedQuery(uri, projection, null, null, null);
783 if (cursor != null) {
784 int column_index = cursor
785 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
786 cursor.moveToFirst();
787 return cursor.getString(column_index);
788 }
789 return null;
790 }
791
792 /**
793 * Pushes a directory to the drop down list
794 * @param directory to push
795 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
796 */
797 public void pushDirname(OCFile directory) {
798 if(!directory.isDirectory()){
799 throw new IllegalArgumentException("Only directories may be pushed!");
800 }
801 mDirectories.insert(directory.getFileName(), 0);
802 mCurrentDir = directory;
803 }
804
805 /**
806 * Pops a directory name from the drop down list
807 * @return True, unless the stack is empty
808 */
809 public boolean popDirname() {
810 mDirectories.remove(mDirectories.getItem(0));
811 return !mDirectories.isEmpty();
812 }
813
814 private class DirectoryCreator implements Runnable {
815 private String mTargetPath;
816 private Account mAccount;
817 private Handler mHandler;
818
819 public DirectoryCreator(String targetPath, Account account, Handler handler) {
820 mTargetPath = targetPath;
821 mAccount = account;
822 mHandler = handler;
823 }
824
825 @Override
826 public void run() {
827 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
828 boolean created = wdc.createDirectory(mTargetPath);
829 if (created) {
830 mHandler.post(new Runnable() {
831 @Override
832 public void run() {
833 dismissDialog(DIALOG_SHORT_WAIT);
834
835 // Save new directory in local database
836 OCFile newDir = new OCFile(mTargetPath);
837 newDir.setMimetype("DIR");
838 newDir.setParentId(mCurrentDir.getFileId());
839 mStorageManager.saveFile(newDir);
840
841 // Display the new folder right away
842 mFileList.listDirectory();
843 }
844 });
845
846 } else {
847 mHandler.post(new Runnable() {
848 @Override
849 public void run() {
850 dismissDialog(DIALOG_SHORT_WAIT);
851 try {
852 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
853 msg.show();
854
855 } catch (NotFoundException e) {
856 Log.e(TAG, "Error while trying to show fail message " , e);
857 }
858 }
859 });
860 }
861 }
862
863 }
864
865 // Custom array adapter to override text colors
866 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
867
868 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
869 super(ctx, view);
870 }
871
872 public View getView(int position, View convertView, ViewGroup parent) {
873 View v = super.getView(position, convertView, parent);
874
875 ((TextView) v).setTextColor(getResources().getColorStateList(
876 android.R.color.white));
877 return v;
878 }
879
880 public View getDropDownView(int position, View convertView,
881 ViewGroup parent) {
882 View v = super.getDropDownView(position, convertView, parent);
883
884 ((TextView) v).setTextColor(getResources().getColorStateList(
885 android.R.color.white));
886
887 return v;
888 }
889
890 }
891
892 private class SyncBroadcastReceiver extends BroadcastReceiver {
893
894 /**
895 * {@link BroadcastReceiver} to enable syncing feedback in UI
896 */
897 @Override
898 public void onReceive(Context context, Intent intent) {
899 boolean inProgress = intent.getBooleanExtra(
900 FileSyncService.IN_PROGRESS, false);
901 String accountName = intent
902 .getStringExtra(FileSyncService.ACCOUNT_NAME);
903
904 Log.d("FileDisplay", "sync of account " + accountName
905 + " is in_progress: " + inProgress);
906
907 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
908
909 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
910
911 boolean fillBlankRoot = false;
912 if (mCurrentDir == null) {
913 mCurrentDir = mStorageManager.getFileByPath("/");
914 fillBlankRoot = (mCurrentDir != null);
915 }
916
917 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
918 || fillBlankRoot ) {
919 if (!fillBlankRoot)
920 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
921 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
922 .findFragmentById(R.id.fileList);
923 if (fileListFragment != null) {
924 fileListFragment.listDirectory(mCurrentDir);
925 }
926 }
927
928 setSupportProgressBarIndeterminateVisibility(inProgress);
929 if (mBackFromCreatingFirstAccount) {
930 // awful patch to fix problem with visibility of progress circle with the first refresh of the first account
931 // TODO - kill this Activity when the first account has to be created instead of stack the account creation on it
932 getSupportActionBar().hide();
933 getSupportActionBar().show();
934 mBackFromCreatingFirstAccount = false;
935 }
936 removeStickyBroadcast(intent);
937
938 }
939
940 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
941 if (synchResult != null) {
942 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
943 mLastSslUntrustedServerResult = synchResult;
944 showDialog(DIALOG_SSL_VALIDATOR);
945 }
946 }
947 }
948 }
949
950
951 private class UploadFinishReceiver extends BroadcastReceiver {
952 /**
953 * Once the file upload has finished -> update view
954 * @author David A. Velasco
955 * {@link BroadcastReceiver} to enable upload feedback in UI
956 */
957 @Override
958 public void onReceive(Context context, Intent intent) {
959 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
960 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
961 boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
962 boolean isDescendant = (mCurrentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
963 if (sameAccount && isDescendant) {
964 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
965 if (fileListFragment != null) {
966 fileListFragment.listDirectory();
967 }
968 }
969 }
970
971 }
972
973
974 /**
975 * Once the file download has finished -> update view
976 */
977 private class DownloadFinishReceiver extends BroadcastReceiver {
978 @Override
979 public void onReceive(Context context, Intent intent) {
980 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
981 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
982 boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
983 boolean isDescendant = (mCurrentDir != null) && (downloadedRemotePath != null) && (downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
984 if (sameAccount && isDescendant) {
985 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
986 if (fileListFragment != null) {
987 fileListFragment.listDirectory();
988 }
989 }
990 }
991 }
992
993
994
995
996 /**
997 * {@inheritDoc}
998 */
999 @Override
1000 public DataStorageManager getStorageManager() {
1001 return mStorageManager;
1002 }
1003
1004
1005 /**
1006 * {@inheritDoc}
1007 */
1008 @Override
1009 public void onDirectoryClick(OCFile directory) {
1010 pushDirname(directory);
1011 ActionBar actionBar = getSupportActionBar();
1012 actionBar.setDisplayHomeAsUpEnabled(true);
1013
1014 if (mDualPane) {
1015 // Resets the FileDetailsFragment on Tablets so that it always displays
1016 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1017 if (fileDetails != null && !fileDetails.isEmpty()) {
1018 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1019 transaction.remove(fileDetails);
1020 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
1021 transaction.commit();
1022 }
1023 }
1024 }
1025
1026
1027 /**
1028 * {@inheritDoc}
1029 */
1030 @Override
1031 public void onFileClick(OCFile file) {
1032
1033 // If we are on a large device -> update fragment
1034 if (mDualPane) {
1035 // 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'
1036 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1037 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1038 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
1039 transaction.commit();
1040
1041 } else { // small or medium screen device -> new Activity
1042 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1043 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1044 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1045 startActivity(showDetailsIntent);
1046 }
1047 }
1048
1049
1050 /**
1051 * {@inheritDoc}
1052 */
1053 @Override
1054 public OCFile getInitialDirectory() {
1055 return mCurrentDir;
1056 }
1057
1058
1059 /**
1060 * {@inheritDoc}
1061 */
1062 @Override
1063 public void onFileStateChanged() {
1064 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1065 if (fileListFragment != null) {
1066 fileListFragment.listDirectory();
1067 }
1068 }
1069
1070
1071 /**
1072 * {@inheritDoc}
1073 */
1074 @Override
1075 public FileDownloaderBinder getFileDownloaderBinder() {
1076 return mDownloaderBinder;
1077 }
1078
1079
1080 /**
1081 * {@inheritDoc}
1082 */
1083 @Override
1084 public FileUploaderBinder getFileUploaderBinder() {
1085 return mUploaderBinder;
1086 }
1087
1088
1089 /** Defines callbacks for service binding, passed to bindService() */
1090 private class ListServiceConnection implements ServiceConnection {
1091
1092 @Override
1093 public void onServiceConnected(ComponentName component, IBinder service) {
1094 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1095 Log.d(TAG, "Download service connected");
1096 mDownloaderBinder = (FileDownloaderBinder) service;
1097 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1098 Log.d(TAG, "Upload service connected");
1099 mUploaderBinder = (FileUploaderBinder) service;
1100 } else {
1101 return;
1102 }
1103 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1104 if (mFileList != null)
1105 mFileList.listDirectory();
1106 if (mDualPane) {
1107 FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1108 if (fragment != null)
1109 fragment.updateFileDetails(false);
1110 }
1111 }
1112
1113 @Override
1114 public void onServiceDisconnected(ComponentName component) {
1115 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1116 Log.d(TAG, "Download service disconnected");
1117 mDownloaderBinder = null;
1118 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1119 Log.d(TAG, "Upload service disconnected");
1120 mUploaderBinder = null;
1121 }
1122 }
1123 };
1124
1125
1126
1127 /**
1128 * Launch an intent to request the PIN code to the user before letting him use the app
1129 */
1130 private void requestPinCode() {
1131 boolean pinStart = false;
1132 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1133 pinStart = appPrefs.getBoolean("set_pincode", false);
1134 if (pinStart) {
1135 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1136 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1137 startActivity(i);
1138 }
1139 }
1140
1141
1142 @Override
1143 public void onSavedCertificate() {
1144 startSynchronization();
1145 }
1146
1147
1148 @Override
1149 public void onFailedSavingCertificate() {
1150 showDialog(DIALOG_CERT_NOT_SAVED);
1151 }
1152
1153
1154 /**
1155 * Updates the view associated to the activity after the finish of some operation over files
1156 * in the current account.
1157 *
1158 * @param operation Removal operation performed.
1159 * @param result Result of the removal.
1160 */
1161 @Override
1162 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1163 if (operation instanceof RemoveFileOperation) {
1164 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1165
1166 } else if (operation instanceof RenameFileOperation) {
1167 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1168
1169 } else if (operation instanceof SynchronizeFileOperation) {
1170 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1171 }
1172 }
1173
1174
1175 /**
1176 * Updates the view associated to the activity after the finish of an operation trying to remove a
1177 * file.
1178 *
1179 * @param operation Removal operation performed.
1180 * @param result Result of the removal.
1181 */
1182 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1183 dismissDialog(DIALOG_SHORT_WAIT);
1184 if (result.isSuccess()) {
1185 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1186 msg.show();
1187 OCFile removedFile = operation.getFile();
1188 if (mDualPane) {
1189 FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1190 if (details != null && removedFile.equals(details.getDisplayedFile()) ) {
1191 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1192 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1193 transaction.commit();
1194 }
1195 }
1196 if (mStorageManager.getFileById(removedFile.getParentId()).equals(mCurrentDir)) {
1197 mFileList.listDirectory();
1198 }
1199
1200 } else {
1201 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1202 msg.show();
1203 if (result.isSslRecoverableException()) {
1204 mLastSslUntrustedServerResult = result;
1205 showDialog(DIALOG_SSL_VALIDATOR);
1206 }
1207 }
1208 }
1209
1210 /**
1211 * Updates the view associated to the activity after the finish of an operation trying to rename a
1212 * file.
1213 *
1214 * @param operation Renaming operation performed.
1215 * @param result Result of the renaming.
1216 */
1217 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1218 dismissDialog(DIALOG_SHORT_WAIT);
1219 OCFile renamedFile = operation.getFile();
1220 if (result.isSuccess()) {
1221 if (mDualPane) {
1222 FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1223 if (details != null && renamedFile.equals(details.getDisplayedFile()) ) {
1224 details.updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
1225 }
1226 }
1227 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(mCurrentDir)) {
1228 mFileList.listDirectory();
1229 }
1230
1231 } else {
1232 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1233 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1234 msg.show();
1235 // TODO throw again the new rename dialog
1236 } else {
1237 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1238 msg.show();
1239 if (result.isSslRecoverableException()) {
1240 mLastSslUntrustedServerResult = result;
1241 showDialog(DIALOG_SSL_VALIDATOR);
1242 }
1243 }
1244 }
1245 }
1246
1247
1248 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1249 dismissDialog(DIALOG_SHORT_WAIT);
1250 OCFile syncedFile = operation.getLocalFile();
1251 if (!result.isSuccess()) {
1252 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1253 Intent i = new Intent(this, ConflictsResolveActivity.class);
1254 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1255 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1256 startActivity(i);
1257
1258 } else {
1259 Toast msg = Toast.makeText(this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1260 msg.show();
1261 }
1262
1263 } else {
1264 if (operation.transferWasRequested()) {
1265 mFileList.listDirectory();
1266 onTransferStateChanged(syncedFile, true, true);
1267
1268 } else {
1269 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1270 msg.show();
1271 }
1272 }
1273 }
1274
1275
1276 /**
1277 * {@inheritDoc}
1278 */
1279 @Override
1280 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1281 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1282 if (fileListFragment != null) {
1283 fileListFragment.listDirectory();
1284 }*/
1285 if (mDualPane) {
1286 FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1287 if (details != null && file.equals(details.getDisplayedFile()) ) {
1288 if (downloading || uploading) {
1289 details.updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
1290 } else {
1291 details.updateFileDetails(downloading || uploading);
1292 }
1293 }
1294 }
1295 }
1296
1297
1298 @Override
1299 public void onDismiss(EditNameDialog dialog) {
1300 //dialog.dismiss();
1301 if (dialog.getResult()) {
1302 String newDirectoryName = dialog.getNewFilename().trim();
1303 Log.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1304 if (newDirectoryName.length() > 0) {
1305 String path;
1306 if (mCurrentDir == null) {
1307 // this is just a patch; we should ensure that mCurrentDir never is null
1308 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
1309 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
1310 mStorageManager.saveFile(file);
1311 }
1312 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
1313 }
1314 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
1315
1316 // Create directory
1317 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1318 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
1319 thread.start();
1320
1321 showDialog(DIALOG_SHORT_WAIT);
1322 }
1323 }
1324 }
1325
1326 }