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