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