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