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