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