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