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