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