FIleDisplayActivity refactored to fix view never updated after installation in some...
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / OldFileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import java.io.File;
22 import java.util.ArrayList;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.app.AlertDialog;
27 import android.app.ProgressDialog;
28 import android.app.AlertDialog.Builder;
29 import android.app.Dialog;
30 import android.content.BroadcastReceiver;
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.SharedPreferences;
38 import android.content.pm.PackageInfo;
39 import android.content.pm.PackageManager.NameNotFoundException;
40 import android.content.res.Resources.NotFoundException;
41 import android.database.Cursor;
42 import android.net.Uri;
43 import android.os.Bundle;
44 import android.os.Handler;
45 import android.preference.PreferenceManager;
46 import android.provider.MediaStore;
47 import android.support.v4.app.FragmentTransaction;
48 import android.util.Log;
49 import android.view.View;
50 import android.view.ViewGroup;
51 import android.widget.ArrayAdapter;
52 import android.widget.EditText;
53 import android.widget.TextView;
54 import android.widget.Toast;
55
56 import com.actionbarsherlock.app.ActionBar;
57 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
58 import com.actionbarsherlock.app.SherlockFragmentActivity;
59 import com.actionbarsherlock.view.Menu;
60 import com.actionbarsherlock.view.MenuInflater;
61 import com.actionbarsherlock.view.MenuItem;
62 import com.actionbarsherlock.view.Window;
63 import com.owncloud.android.AccountUtils;
64 import com.owncloud.android.CrashHandler;
65 import com.owncloud.android.authenticator.AccountAuthenticator;
66 import com.owncloud.android.datamodel.DataStorageManager;
67 import com.owncloud.android.datamodel.FileDataStorageManager;
68 import com.owncloud.android.datamodel.OCFile;
69 import com.owncloud.android.files.services.FileDownloader;
70 import com.owncloud.android.files.services.FileUploader;
71 import com.owncloud.android.syncadapter.FileSyncService;
72 import com.owncloud.android.ui.fragment.FileDetailFragment;
73 import com.owncloud.android.ui.fragment.FileListFragment;
74
75 import com.owncloud.android.R;
76 import eu.alefzero.webdav.WebdavClient;
77
78 /**
79 * Displays, what files the user has available in his ownCloud.
80 *
81 * @author Bartek Przybylski
82 *
83 */
84
85 public class OldFileDisplayActivity extends SherlockFragmentActivity implements
86 FileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnClickListener, android.view.View.OnClickListener {
87
88 private ArrayAdapter<String> mDirectories;
89 private OCFile mCurrentDir;
90 private String[] mDirs = null;
91
92 private DataStorageManager mStorageManager;
93 private SyncBroadcastReceiver mSyncBroadcastReceiver;
94 private UploadFinishReceiver mUploadFinishReceiver;
95 private DownloadFinishReceiver mDownloadFinishReceiver;
96
97 private View mLayoutView = null;
98 private FileListFragment mFileList;
99
100 private boolean mDualPane;
101
102 private boolean mForcedLoginToCreateFirstAccount = false;
103
104 private static final String KEY_DIR_ARRAY = "DIR_ARRAY";
105 private static final String KEY_CURRENT_DIR = "DIR";
106
107 private static final int DIALOG_SETUP_ACCOUNT = 0;
108 private static final int DIALOG_CREATE_DIR = 1;
109 private static final int DIALOG_ABOUT_APP = 2;
110 public static final int DIALOG_SHORT_WAIT = 3;
111
112 private static final int ACTION_SELECT_FILE = 1;
113
114 private static final String TAG = "FileDisplayActivity";
115
116
117 @Override
118 public void onCreate(Bundle savedInstanceState) {
119 Log.i(getClass().toString(), "onCreate() start");
120 super.onCreate(savedInstanceState);
121
122 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
123
124 Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
125
126 if(savedInstanceState != null) {
127 mDirs = savedInstanceState.getStringArray(KEY_DIR_ARRAY);
128 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
129 mDirectories.add(OCFile.PATH_SEPARATOR);
130 if (mDirs != null)
131 for (String s : mDirs)
132 mDirectories.insert(s, 0);
133 mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
134 }
135
136 mLayoutView = getLayoutInflater().inflate(R.layout.files, null); // always inflate this at onCreate() ; just once!
137
138 if (AccountUtils.accountsAreSetup(this)) {
139
140 initDelayedTilAccountAvailabe();
141
142 // PIN CODE request ; best location is to decide, let's try this first
143 //if (savedInstanceState == null) {
144 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
145 requestPinCode();
146 }
147
148
149 } else {
150
151 setContentView(R.layout.no_account_available);
152 getSupportActionBar().setNavigationMode(ActionBar.DISPLAY_SHOW_TITLE);
153 findViewById(R.id.setup_account).setOnClickListener(this);
154
155 setSupportProgressBarIndeterminateVisibility(false);
156
157 Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
158 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
159 startActivity(intent); // although the code is here, the activity won't be created until this.onStart() and this.onResume() are finished;
160 mForcedLoginToCreateFirstAccount = true;
161 }
162
163 Log.i(getClass().toString(), "onCreate() end");
164 }
165
166 @Override
167 public boolean onCreateOptionsMenu(Menu menu) {
168 MenuInflater inflater = getSherlock().getMenuInflater();
169 inflater.inflate(R.menu.menu, menu);
170 return true;
171 }
172
173 @Override
174 public boolean onOptionsItemSelected(MenuItem item) {
175 boolean retval = true;
176 switch (item.getItemId()) {
177 case R.id.createDirectoryItem: {
178 showDialog(DIALOG_CREATE_DIR);
179 break;
180 }
181 case R.id.startSync: {
182 ContentResolver.cancelSync(null, "org.owncloud"); // cancel the current synchronizations of any ownCloud account
183 Bundle bundle = new Bundle();
184 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
185 ContentResolver.requestSync(
186 AccountUtils.getCurrentOwnCloudAccount(this),
187 "org.owncloud", bundle);
188 break;
189 }
190 case R.id.action_upload: {
191 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
192 action = action.setType("*/*")
193 .addCategory(Intent.CATEGORY_OPENABLE);
194 startActivityForResult(
195 Intent.createChooser(action, getString(R.string.upload_chooser_title)),
196 ACTION_SELECT_FILE);
197 break;
198 }
199 case R.id.action_settings: {
200 Intent settingsIntent = new Intent(this, Preferences.class);
201 startActivity(settingsIntent);
202 break;
203 }
204 case R.id.about_app : {
205 showDialog(DIALOG_ABOUT_APP);
206 break;
207 }
208 case android.R.id.home: {
209 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
210 onBackPressed();
211 }
212 break;
213 }
214 default:
215 retval = false;
216 }
217 return retval;
218 }
219
220 @Override
221 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
222 int i = itemPosition;
223 while (i-- != 0) {
224 onBackPressed();
225 }
226 return true;
227 }
228
229 /**
230 * Called, when the user selected something for uploading
231 */
232 public void onActivityResult(int requestCode, int resultCode, Intent data) {
233 if (requestCode == ACTION_SELECT_FILE) {
234 if (resultCode == RESULT_OK) {
235 String filepath = null;
236 try {
237 Uri selectedImageUri = data.getData();
238
239 String filemanagerstring = selectedImageUri.getPath();
240 String selectedImagePath = getPath(selectedImageUri);
241
242 if (selectedImagePath != null)
243 filepath = selectedImagePath;
244 else
245 filepath = filemanagerstring;
246
247 } catch (Exception e) {
248 Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
249 e.printStackTrace();
250
251 } finally {
252 if (filepath == null) {
253 Log.e("FileDisplay", "Couldnt resolve path to file");
254 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
255 t.show();
256 return;
257 }
258 }
259
260 Intent i = new Intent(this, FileUploader.class);
261 i.putExtra(FileUploader.KEY_ACCOUNT,
262 AccountUtils.getCurrentOwnCloudAccount(this));
263 String remotepath = new String();
264 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
265 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
266 }
267 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
268 remotepath += OCFile.PATH_SEPARATOR;
269 remotepath += new File(filepath).getName();
270
271 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
272 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
273 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
274 startService(i);
275 }
276
277 }/* dvelasco: WIP - not working as expected ... yet :)
278 else if (requestCode == ACTION_CREATE_FIRST_ACCOUNT) {
279 if (resultCode != RESULT_OK) {
280 finish(); // the user cancelled the AuthenticatorActivity
281 }
282 }*/
283 }
284
285 @Override
286 public void onBackPressed() {
287 if (mDirectories == null || mDirectories.getCount() <= 1) {
288 finish();
289 return;
290 }
291 popDirname();
292 mFileList.onNavigateUp();
293 mCurrentDir = mFileList.getCurrentFile();
294
295 if (mDualPane) {
296 // Resets the FileDetailsFragment on Tablets so that it always displays
297 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
298 if (fileDetails != null && !fileDetails.isEmpty()) {
299 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
300 transaction.remove(fileDetails);
301 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null));
302 transaction.commit();
303 }
304 }
305
306 if(mCurrentDir.getParentId() == 0){
307 ActionBar actionBar = getSupportActionBar();
308 actionBar.setDisplayHomeAsUpEnabled(false);
309 }
310 }
311
312 @Override
313 protected void onSaveInstanceState(Bundle outState) {
314 // responsability of restore is prefered in onCreate() before than in onRestoreInstanceState when there are Fragments involved
315 Log.i(getClass().toString(), "onSaveInstanceState() start");
316 super.onSaveInstanceState(outState);
317 if(mDirectories != null && mDirectories.getCount() != 0){
318 mDirs = new String[mDirectories.getCount()-1];
319 for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {
320 mDirs[i] = mDirectories.getItem(j);
321 }
322 }
323 outState.putStringArray(KEY_DIR_ARRAY, mDirs);
324 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
325 Log.i(getClass().toString(), "onSaveInstanceState() end");
326 }
327
328 @Override
329 protected void onResume() {
330 Log.i(getClass().toString(), "onResume() start");
331 super.onResume();
332
333 if (AccountUtils.accountsAreSetup(this)) {
334 // at least an account exist: normal operation
335
336 // set the layout only if it couldn't be set in onCreate
337 if (mForcedLoginToCreateFirstAccount) {
338 initDelayedTilAccountAvailabe();
339 mForcedLoginToCreateFirstAccount = false;
340 }
341
342 // Listen for sync messages
343 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
344 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
345 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
346
347 // Listen for upload messages
348 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
349 mUploadFinishReceiver = new UploadFinishReceiver();
350 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
351
352 // Listen for download messages
353 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
354 mDownloadFinishReceiver = new DownloadFinishReceiver();
355 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
356
357 // Storage manager initialization
358 mStorageManager = new FileDataStorageManager(
359 AccountUtils.getCurrentOwnCloudAccount(this),
360 getContentResolver());
361
362 // File list fragments
363 mFileList = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
364
365
366 // Figure out what directory to list.
367 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
368 if(getIntent().hasExtra(FileDetailFragment.EXTRA_FILE)){
369 mCurrentDir = (OCFile) getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
370 if(mCurrentDir != null && !mCurrentDir.isDirectory()){
371 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
372 }
373
374 // Clear intent extra, so rotating the screen will not return us to this directory
375 getIntent().removeExtra(FileDetailFragment.EXTRA_FILE);
376 }
377
378 if (mCurrentDir == null)
379 mCurrentDir = mStorageManager.getFileByPath("/");
380
381 // Drop-Down navigation and file list restore
382 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
383
384
385 // Given the case we have a file to display:
386 if(mCurrentDir != null){
387 ArrayList<OCFile> files = new ArrayList<OCFile>();
388 OCFile currFile = mCurrentDir;
389 while(currFile != null){
390 files.add(currFile);
391 currFile = mStorageManager.getFileById(currFile.getParentId());
392 }
393
394 // Insert in mDirs
395 mDirs = new String[files.size()];
396 for(int i = files.size() - 1; i >= 0; i--){
397 mDirs[i] = files.get(i).getFileName();
398 }
399 }
400
401 if (mDirs != null) {
402 for (String s : mDirs)
403 mDirectories.add(s);
404 } else {
405 mDirectories.add(OCFile.PATH_SEPARATOR);
406 }
407
408 // Actionbar setup
409 ActionBar action_bar = getSupportActionBar();
410 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
411 action_bar.setDisplayShowTitleEnabled(false);
412 action_bar.setListNavigationCallbacks(mDirectories, this);
413 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
414 action_bar.setDisplayHomeAsUpEnabled(true);
415 } else {
416 action_bar.setDisplayHomeAsUpEnabled(false);
417 }
418
419 // List dir here
420 mFileList.listDirectory(mCurrentDir);
421 }
422 Log.i(getClass().toString(), "onResume() end");
423 }
424
425 @Override
426 protected void onPause() {
427 Log.i(getClass().toString(), "onPause() start");
428 super.onPause();
429 if (mSyncBroadcastReceiver != null) {
430 unregisterReceiver(mSyncBroadcastReceiver);
431 mSyncBroadcastReceiver = null;
432 }
433 if (mUploadFinishReceiver != null) {
434 unregisterReceiver(mUploadFinishReceiver);
435 mUploadFinishReceiver = null;
436 }
437 if (mDownloadFinishReceiver != null) {
438 unregisterReceiver(mDownloadFinishReceiver);
439 mDownloadFinishReceiver = null;
440 }
441
442 getIntent().putExtra(FileDetailFragment.EXTRA_FILE, mCurrentDir);
443 Log.i(getClass().toString(), "onPause() end");
444 }
445
446 @Override
447 protected Dialog onCreateDialog(int id) {
448 Dialog dialog = null;
449 AlertDialog.Builder builder;
450 switch (id) {
451 case DIALOG_SETUP_ACCOUNT:
452 builder = new AlertDialog.Builder(this);
453 builder.setTitle(R.string.main_tit_accsetup);
454 builder.setMessage(R.string.main_wrn_accsetup);
455 builder.setCancelable(false);
456 builder.setPositiveButton(android.R.string.ok, this);
457 builder.setNegativeButton(android.R.string.cancel, this);
458 dialog = builder.create();
459 break;
460 case DIALOG_ABOUT_APP: {
461 builder = new AlertDialog.Builder(this);
462 builder.setTitle(getString(R.string.about_title));
463 PackageInfo pkg;
464 try {
465 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
466 builder.setMessage("ownCloud android client\n\nversion: " + pkg.versionName );
467 builder.setIcon(android.R.drawable.ic_menu_info_details);
468 dialog = builder.create();
469 } catch (NameNotFoundException e) {
470 builder = null;
471 dialog = null;
472 Log.e(TAG, "Error while showing about dialog", e);
473 }
474 break;
475 }
476 case DIALOG_CREATE_DIR: {
477 builder = new Builder(this);
478 final EditText dirNameInput = new EditText(getBaseContext());
479 final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
480 builder.setView(dirNameInput);
481 builder.setTitle(R.string.uploader_info_dirname);
482 int typed_color = getResources().getColor(R.color.setup_text_typed);
483 dirNameInput.setTextColor(typed_color);
484 builder.setPositiveButton(android.R.string.ok,
485 new OnClickListener() {
486 public void onClick(DialogInterface dialog, int which) {
487 String directoryName = dirNameInput.getText().toString();
488 if (directoryName.trim().length() == 0) {
489 dialog.cancel();
490 return;
491 }
492
493 // Figure out the path where the dir needs to be created
494 String path;
495 if (mCurrentDir == null) {
496 // this is just a patch; we should ensure that mCurrentDir never is null
497 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
498 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
499 mStorageManager.saveFile(file);
500 }
501 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
502 }
503 path = OldFileDisplayActivity.this.mCurrentDir.getRemotePath();
504
505 // Create directory
506 path += directoryName + OCFile.PATH_SEPARATOR;
507 Thread thread = new Thread(new DirectoryCreator(path, a, new Handler()));
508 thread.start();
509
510 dialog.dismiss();
511
512 showDialog(DIALOG_SHORT_WAIT);
513 }
514 });
515 builder.setNegativeButton(R.string.common_cancel,
516 new OnClickListener() {
517 public void onClick(DialogInterface dialog, int which) {
518 dialog.cancel();
519 }
520 });
521 dialog = builder.create();
522 break;
523 }
524 case DIALOG_SHORT_WAIT: {
525 ProgressDialog working_dialog = new ProgressDialog(this);
526 working_dialog.setMessage(getResources().getString(
527 R.string.wait_a_moment));
528 working_dialog.setIndeterminate(true);
529 working_dialog.setCancelable(false);
530 dialog = working_dialog;
531 break;
532 }
533 default:
534 dialog = null;
535 }
536
537 return dialog;
538 }
539
540
541 /**
542 * Responds to the "There are no ownCloud Accounts setup" dialog
543 * TODO: Dialog is 100% useless -> Remove
544 */
545 @Override
546 public void onClick(DialogInterface dialog, int which) {
547 // In any case - we won't need it anymore
548 dialog.dismiss();
549 switch (which) {
550 case DialogInterface.BUTTON_POSITIVE:
551 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
552 intent.putExtra("authorities",
553 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
554 startActivity(intent);
555 break;
556 case DialogInterface.BUTTON_NEGATIVE:
557 finish();
558 }
559
560 }
561
562 /**
563 * Translates a content URI of an image to a physical path
564 * on the disk
565 * @param uri The URI to resolve
566 * @return The path to the image or null if it could not be found
567 */
568 public String getPath(Uri uri) {
569 String[] projection = { MediaStore.Images.Media.DATA };
570 Cursor cursor = managedQuery(uri, projection, null, null, null);
571 if (cursor != null) {
572 int column_index = cursor
573 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
574 cursor.moveToFirst();
575 return cursor.getString(column_index);
576 }
577 return null;
578 }
579
580 /**
581 * Pushes a directory to the drop down list
582 * @param directory to push
583 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
584 */
585 public void pushDirname(OCFile directory) {
586 if(!directory.isDirectory()){
587 throw new IllegalArgumentException("Only directories may be pushed!");
588 }
589 mDirectories.insert(directory.getFileName(), 0);
590 mCurrentDir = directory;
591 }
592
593 /**
594 * Pops a directory name from the drop down list
595 * @return True, unless the stack is empty
596 */
597 public boolean popDirname() {
598 mDirectories.remove(mDirectories.getItem(0));
599 return !mDirectories.isEmpty();
600 }
601
602 private class DirectoryCreator implements Runnable {
603 private String mTargetPath;
604 private Account mAccount;
605 private AccountManager mAm;
606 private Handler mHandler;
607
608 public DirectoryCreator(String targetPath, Account account, Handler handler) {
609 mTargetPath = targetPath;
610 mAccount = account;
611 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
612 mHandler = handler;
613 }
614
615 @Override
616 public void run() {
617 WebdavClient wdc = new WebdavClient(mAccount, getApplicationContext());
618
619 String username = mAccount.name.substring(0,
620 mAccount.name.lastIndexOf('@'));
621 String password = mAm.getPassword(mAccount);
622
623 wdc.setCredentials(username, password);
624 wdc.allowSelfsignedCertificates();
625 boolean created = wdc.createDirectory(mTargetPath);
626 if (created) {
627 mHandler.post(new Runnable() {
628 @Override
629 public void run() {
630 dismissDialog(DIALOG_SHORT_WAIT);
631
632 // Save new directory in local database
633 OCFile newDir = new OCFile(mTargetPath);
634 newDir.setMimetype("DIR");
635 newDir.setParentId(mCurrentDir.getFileId());
636 mStorageManager.saveFile(newDir);
637
638 // Display the new folder right away
639 mFileList.listDirectory(mCurrentDir);
640 }
641 });
642
643 } else {
644 mHandler.post(new Runnable() {
645 @Override
646 public void run() {
647 dismissDialog(DIALOG_SHORT_WAIT);
648 try {
649 Toast msg = Toast.makeText(OldFileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
650 msg.show();
651
652 } catch (NotFoundException e) {
653 Log.e(TAG, "Error while trying to show fail message " , e);
654 }
655 }
656 });
657 }
658 }
659
660 }
661
662 // Custom array adapter to override text colors
663 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
664
665 public CustomArrayAdapter(OldFileDisplayActivity ctx, int view) {
666 super(ctx, view);
667 }
668
669 public View getView(int position, View convertView, ViewGroup parent) {
670 View v = super.getView(position, convertView, parent);
671
672 ((TextView) v).setTextColor(getResources().getColorStateList(
673 android.R.color.white));
674 return v;
675 }
676
677 public View getDropDownView(int position, View convertView,
678 ViewGroup parent) {
679 View v = super.getDropDownView(position, convertView, parent);
680
681 ((TextView) v).setTextColor(getResources().getColorStateList(
682 android.R.color.white));
683
684 return v;
685 }
686
687 }
688
689 private class SyncBroadcastReceiver extends BroadcastReceiver {
690 /**
691 * {@link BroadcastReceiver} to enable syncing feedback in UI
692 */
693 @Override
694 public void onReceive(Context context, Intent intent) {
695 boolean inProgress = intent.getBooleanExtra(
696 FileSyncService.IN_PROGRESS, false);
697 String accountName = intent
698 .getStringExtra(FileSyncService.ACCOUNT_NAME);
699
700 Log.d("FileDisplay", "sync of account " + accountName
701 + " is in_progress: " + inProgress);
702
703 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
704
705 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
706
707 boolean fillBlankRoot = false;
708 if (mCurrentDir == null) {
709 mCurrentDir = mStorageManager.getFileByPath("/");
710 fillBlankRoot = (mCurrentDir != null);
711 }
712
713 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
714 || fillBlankRoot ) {
715 if (!fillBlankRoot)
716 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
717 FileListFragment fileListFragment = (FileListFragment) getSupportFragmentManager()
718 .findFragmentById(R.id.fileList);
719 if (fileListFragment != null) {
720 fileListFragment.listDirectory(mCurrentDir);
721 }
722 }
723
724 setSupportProgressBarIndeterminateVisibility(inProgress);
725
726 }
727 }
728 }
729
730
731 private class UploadFinishReceiver extends BroadcastReceiver {
732 /**
733 * Once the file upload has finished -> update view
734 * @author David A. Velasco
735 * {@link BroadcastReceiver} to enable upload feedback in UI
736 */
737 @Override
738 public void onReceive(Context context, Intent intent) {
739 long parentDirId = intent.getLongExtra(FileUploader.EXTRA_PARENT_DIR_ID, -1);
740 OCFile parentDir = mStorageManager.getFileById(parentDirId);
741 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
742
743 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
744 parentDir != null &&
745 ( (mCurrentDir == null && parentDir.getFileName().equals("/")) ||
746 parentDir.equals(mCurrentDir)
747 )
748 ) {
749 FileListFragment fileListFragment = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
750 if (fileListFragment != null) {
751 fileListFragment.listDirectory();
752 }
753 }
754 }
755
756 }
757
758
759 /**
760 * Once the file download has finished -> update view
761 */
762 private class DownloadFinishReceiver extends BroadcastReceiver {
763 @Override
764 public void onReceive(Context context, Intent intent) {
765 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
766 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
767
768 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
769 mCurrentDir != null && mCurrentDir.getFileId() == mStorageManager.getFileByPath(downloadedRemotePath).getParentId()) {
770 FileListFragment fileListFragment = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
771 if (fileListFragment != null) {
772 fileListFragment.listDirectory();
773 }
774 }
775 }
776 }
777
778
779 @Override
780 public void onClick(View v) {
781 if (v.getId() == R.id.setup_account) {
782 Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
783 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
784 startActivity(intent);
785 mForcedLoginToCreateFirstAccount = true;
786 }
787 }
788
789
790
791
792
793 /**
794 * {@inheritDoc}
795 */
796 @Override
797 public DataStorageManager getStorageManager() {
798 return mStorageManager;
799 }
800
801
802 /**
803 * {@inheritDoc}
804 */
805 @Override
806 public void onDirectoryClick(OCFile directory) {
807 pushDirname(directory);
808 ActionBar actionBar = getSupportActionBar();
809 actionBar.setDisplayHomeAsUpEnabled(true);
810
811 if (mDualPane) {
812 // Resets the FileDetailsFragment on Tablets so that it always displays
813 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
814 if (fileDetails != null && !fileDetails.isEmpty()) {
815 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
816 transaction.remove(fileDetails);
817 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null));
818 transaction.commit();
819 }
820 }
821 }
822
823
824 /**
825 * {@inheritDoc}
826 */
827 @Override
828 public void onFileClick(OCFile file) {
829
830 // If we are on a large device -> update fragment
831 if (mDualPane) {
832 // 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'
833 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
834 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
835 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
836 transaction.commit();
837
838 } else { // small or medium screen device -> new Activity
839 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
840 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
841 showDetailsIntent.putExtra(FileDownloader.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
842 startActivity(showDetailsIntent);
843 }
844 }
845
846
847 /**
848 * {@inheritDoc}
849 */
850 @Override
851 public void onFileStateChanged() {
852 FileListFragment fileListFragment = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
853 if (fileListFragment != null) {
854 fileListFragment.listDirectory();
855 }
856 }
857
858
859 /**
860 * Operations in this method should be preferably performed in onCreate to have a lighter onResume method.
861 *
862 * But we need to delay them to onResume for the first start of the application, when no account exists and the login activity must be shown; and
863 * put instead the ugly view that shows the 'Setup' button to restart the login activity.
864 *
865 * In other way, if the users cancels or presses BACK in the login page that first time (users can be cruel sometimes) would show a blank view (the
866 * FragmentList view empty).
867 *
868 * This is temporal, until we found out how to get a result in this activity after launching the ADD_ACCOUNT Intent with startActivityForResult (not trivial)
869 */
870 private void initDelayedTilAccountAvailabe() {
871 setContentView(mLayoutView);
872 mDualPane = (findViewById(R.id.file_details_container) != null);
873 if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
874 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
875 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
876 transaction.commit();
877 }
878 setSupportProgressBarIndeterminateVisibility(false);
879 }
880
881
882 /**
883 * Launch an intent to request the PIN code to the user before letting him use the app
884 */
885 private void requestPinCode() {
886 boolean pinStart = false;
887 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
888 pinStart = appPrefs.getBoolean("set_pincode", false);
889 if (pinStart) {
890 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
891 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
892 startActivity(i);
893 }
894 }
895
896
897 }