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