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