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