5956004818721d57c58f287a1d6901f2582c699e
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import java.io.File;
22
23 import android.accounts.Account;
24 import android.accounts.AccountManager;
25 import android.app.AlertDialog;
26 import android.app.ProgressDialog;
27 import android.app.AlertDialog.Builder;
28 import android.app.Dialog;
29 import android.content.BroadcastReceiver;
30 import android.content.ContentResolver;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.DialogInterface.OnClickListener;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageInfo;
38 import android.content.pm.PackageManager.NameNotFoundException;
39 import android.content.res.Resources.NotFoundException;
40 import android.database.Cursor;
41 import android.net.Uri;
42 import android.os.Bundle;
43 import android.os.Handler;
44 import android.preference.PreferenceManager;
45 import android.provider.MediaStore;
46 import android.support.v4.app.FragmentTransaction;
47 import android.util.Log;
48 import android.view.View;
49 import android.view.ViewGroup;
50 import android.widget.ArrayAdapter;
51 import android.widget.EditText;
52 import android.widget.TextView;
53 import android.widget.Toast;
54
55 import com.actionbarsherlock.app.ActionBar;
56 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
57 import com.actionbarsherlock.app.SherlockFragmentActivity;
58 import com.actionbarsherlock.view.Menu;
59 import com.actionbarsherlock.view.MenuInflater;
60 import com.actionbarsherlock.view.MenuItem;
61 import com.actionbarsherlock.view.Window;
62 import com.owncloud.android.AccountUtils;
63 import com.owncloud.android.CrashHandler;
64 import com.owncloud.android.authenticator.AccountAuthenticator;
65 import com.owncloud.android.datamodel.DataStorageManager;
66 import com.owncloud.android.datamodel.FileDataStorageManager;
67 import com.owncloud.android.datamodel.OCFile;
68 import com.owncloud.android.files.services.FileDownloader;
69 import com.owncloud.android.files.services.FileUploader;
70 import com.owncloud.android.syncadapter.FileSyncService;
71 import com.owncloud.android.ui.fragment.FileDetailFragment;
72 import com.owncloud.android.ui.fragment.OCFileListFragment;
73 import com.owncloud.android.utils.OwnCloudClientUtils;
74
75 import com.owncloud.android.R;
76 import eu.alefzero.webdav.WebdavClient;
77
78 /**
79 * Displays, what files the user has available in his ownCloud.
80 *
81 * @author Bartek Przybylski
82 *
83 */
84
85 public class FileDisplayActivity extends SherlockFragmentActivity implements
86 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener {
87
88 private ArrayAdapter<String> mDirectories;
89 private OCFile mCurrentDir;
90
91 private DataStorageManager mStorageManager;
92 private SyncBroadcastReceiver mSyncBroadcastReceiver;
93 private UploadFinishReceiver mUploadFinishReceiver;
94 private DownloadFinishReceiver mDownloadFinishReceiver;
95
96 private OCFileListFragment mFileList;
97
98 private boolean mDualPane;
99
100 private static final int DIALOG_SETUP_ACCOUNT = 0;
101 private static final int DIALOG_CREATE_DIR = 1;
102 private static final int DIALOG_ABOUT_APP = 2;
103 public static final int DIALOG_SHORT_WAIT = 3;
104 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;
105
106 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
107 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
108
109 private static final String TAG = "FileDisplayActivity";
110
111
112 @Override
113 public void onCreate(Bundle savedInstanceState) {
114 Log.d(getClass().toString(), "onCreate() start");
115 super.onCreate(savedInstanceState);
116
117 Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
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
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, "org.owncloud"); // 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 "org.owncloud", 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 AccountManager mAm;
636 private Handler mHandler;
637
638 public DirectoryCreator(String targetPath, Account account, Handler handler) {
639 mTargetPath = targetPath;
640 mAccount = account;
641 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
642 mHandler = handler;
643 }
644
645 @Override
646 public void run() {
647 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
648 boolean created = wdc.createDirectory(mTargetPath);
649 if (created) {
650 mHandler.post(new Runnable() {
651 @Override
652 public void run() {
653 dismissDialog(DIALOG_SHORT_WAIT);
654
655 // Save new directory in local database
656 OCFile newDir = new OCFile(mTargetPath);
657 newDir.setMimetype("DIR");
658 newDir.setParentId(mCurrentDir.getFileId());
659 mStorageManager.saveFile(newDir);
660
661 // Display the new folder right away
662 mFileList.listDirectory(mCurrentDir);
663 }
664 });
665
666 } else {
667 mHandler.post(new Runnable() {
668 @Override
669 public void run() {
670 dismissDialog(DIALOG_SHORT_WAIT);
671 try {
672 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
673 msg.show();
674
675 } catch (NotFoundException e) {
676 Log.e(TAG, "Error while trying to show fail message " , e);
677 }
678 }
679 });
680 }
681 }
682
683 }
684
685 // Custom array adapter to override text colors
686 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
687
688 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
689 super(ctx, view);
690 }
691
692 public View getView(int position, View convertView, ViewGroup parent) {
693 View v = super.getView(position, convertView, parent);
694
695 ((TextView) v).setTextColor(getResources().getColorStateList(
696 android.R.color.white));
697 return v;
698 }
699
700 public View getDropDownView(int position, View convertView,
701 ViewGroup parent) {
702 View v = super.getDropDownView(position, convertView, parent);
703
704 ((TextView) v).setTextColor(getResources().getColorStateList(
705 android.R.color.white));
706
707 return v;
708 }
709
710 }
711
712 private class SyncBroadcastReceiver extends BroadcastReceiver {
713 /**
714 * {@link BroadcastReceiver} to enable syncing feedback in UI
715 */
716 @Override
717 public void onReceive(Context context, Intent intent) {
718 boolean inProgress = intent.getBooleanExtra(
719 FileSyncService.IN_PROGRESS, false);
720 String accountName = intent
721 .getStringExtra(FileSyncService.ACCOUNT_NAME);
722
723 Log.d("FileDisplay", "sync of account " + accountName
724 + " is in_progress: " + inProgress);
725
726 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
727
728 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
729
730 boolean fillBlankRoot = false;
731 if (mCurrentDir == null) {
732 mCurrentDir = mStorageManager.getFileByPath("/");
733 fillBlankRoot = (mCurrentDir != null);
734 }
735
736 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
737 || fillBlankRoot ) {
738 if (!fillBlankRoot)
739 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
740 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
741 .findFragmentById(R.id.fileList);
742 if (fileListFragment != null) {
743 fileListFragment.listDirectory(mCurrentDir);
744 }
745 }
746
747 setSupportProgressBarIndeterminateVisibility(inProgress);
748
749 }
750 }
751 }
752
753
754 private class UploadFinishReceiver extends BroadcastReceiver {
755 /**
756 * Once the file upload has finished -> update view
757 * @author David A. Velasco
758 * {@link BroadcastReceiver} to enable upload feedback in UI
759 */
760 @Override
761 public void onReceive(Context context, Intent intent) {
762 long parentDirId = intent.getLongExtra(FileUploader.EXTRA_PARENT_DIR_ID, -1);
763 OCFile parentDir = mStorageManager.getFileById(parentDirId);
764 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
765
766 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
767 parentDir != null &&
768 ( (mCurrentDir == null && parentDir.getFileName().equals("/")) ||
769 parentDir.equals(mCurrentDir)
770 )
771 ) {
772 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
773 if (fileListFragment != null) {
774 fileListFragment.listDirectory();
775 }
776 }
777 }
778
779 }
780
781
782 /**
783 * Once the file download has finished -> update view
784 */
785 private class DownloadFinishReceiver extends BroadcastReceiver {
786 @Override
787 public void onReceive(Context context, Intent intent) {
788 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
789 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
790
791 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
792 mCurrentDir != null && mCurrentDir.getFileId() == mStorageManager.getFileByPath(downloadedRemotePath).getParentId()) {
793 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
794 if (fileListFragment != null) {
795 fileListFragment.listDirectory();
796 }
797 }
798 }
799 }
800
801
802
803
804 /**
805 * {@inheritDoc}
806 */
807 @Override
808 public DataStorageManager getStorageManager() {
809 return mStorageManager;
810 }
811
812
813 /**
814 * {@inheritDoc}
815 */
816 @Override
817 public void onDirectoryClick(OCFile directory) {
818 pushDirname(directory);
819 ActionBar actionBar = getSupportActionBar();
820 actionBar.setDisplayHomeAsUpEnabled(true);
821
822 if (mDualPane) {
823 // Resets the FileDetailsFragment on Tablets so that it always displays
824 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
825 if (fileDetails != null && !fileDetails.isEmpty()) {
826 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
827 transaction.remove(fileDetails);
828 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null));
829 transaction.commit();
830 }
831 }
832 }
833
834
835 /**
836 * {@inheritDoc}
837 */
838 @Override
839 public void onFileClick(OCFile file) {
840
841 // If we are on a large device -> update fragment
842 if (mDualPane) {
843 // 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'
844 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
845 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
846 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
847 transaction.commit();
848
849 } else { // small or medium screen device -> new Activity
850 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
851 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
852 showDetailsIntent.putExtra(FileDownloader.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
853 startActivity(showDetailsIntent);
854 }
855 }
856
857
858 /**
859 * {@inheritDoc}
860 */
861 @Override
862 public void onFileStateChanged() {
863 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
864 if (fileListFragment != null) {
865 fileListFragment.listDirectory();
866 }
867 }
868
869 /**
870 * Launch an intent to request the PIN code to the user before letting him use the app
871 */
872 private void requestPinCode() {
873 boolean pinStart = false;
874 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
875 pinStart = appPrefs.getBoolean("set_pincode", false);
876 if (pinStart) {
877 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
878 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
879 startActivity(i);
880 }
881 }
882
883
884 }