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