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