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