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