Added help text in background of empty files list
[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.setMessage(String.format(getString(R.string.aboout_message), pkg.versionName));
557 builder.setIcon(android.R.drawable.ic_menu_info_details);
558 dialog = builder.create();
559 } catch (NameNotFoundException e) {
560 builder = null;
561 dialog = null;
562 Log.e(TAG, "Error while showing about dialog", e);
563 }
564 break;
565 }
566 case DIALOG_CREATE_DIR: {
567 builder = new Builder(this);
568 final EditText dirNameInput = new EditText(getBaseContext());
569 builder.setView(dirNameInput);
570 builder.setTitle(R.string.uploader_info_dirname);
571 int typed_color = getResources().getColor(R.color.setup_text_typed);
572 dirNameInput.setTextColor(typed_color);
573 builder.setPositiveButton(android.R.string.ok,
574 new OnClickListener() {
575 public void onClick(DialogInterface dialog, int which) {
576 String directoryName = dirNameInput.getText().toString();
577 if (directoryName.trim().length() == 0) {
578 dialog.cancel();
579 return;
580 }
581
582 // Figure out the path where the dir needs to be created
583 String path;
584 if (mCurrentDir == null) {
585 // this is just a patch; we should ensure that mCurrentDir never is null
586 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
587 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
588 mStorageManager.saveFile(file);
589 }
590 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
591 }
592 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
593
594 // Create directory
595 path += directoryName + OCFile.PATH_SEPARATOR;
596 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
597 thread.start();
598
599 dialog.dismiss();
600
601 showDialog(DIALOG_SHORT_WAIT);
602 }
603 });
604 builder.setNegativeButton(R.string.common_cancel,
605 new OnClickListener() {
606 public void onClick(DialogInterface dialog, int which) {
607 dialog.cancel();
608 }
609 });
610 dialog = builder.create();
611 break;
612 }
613 case DIALOG_SHORT_WAIT: {
614 ProgressDialog working_dialog = new ProgressDialog(this);
615 working_dialog.setMessage(getResources().getString(
616 R.string.wait_a_moment));
617 working_dialog.setIndeterminate(true);
618 working_dialog.setCancelable(false);
619 dialog = working_dialog;
620 break;
621 }
622 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
623 final String [] items = { getString(R.string.actionbar_upload_files),
624 getString(R.string.actionbar_upload_from_apps) };
625 builder = new AlertDialog.Builder(this);
626 builder.setTitle(R.string.actionbar_upload);
627 builder.setItems(items, new DialogInterface.OnClickListener() {
628 public void onClick(DialogInterface dialog, int item) {
629 if (item == 0) {
630 //if (!mDualPane) {
631 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
632 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
633 //} else {
634 // TODO create and handle new fragment LocalFileListFragment
635 //}
636 } else if (item == 1) {
637 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
638 action = action.setType("*/*")
639 .addCategory(Intent.CATEGORY_OPENABLE);
640 startActivityForResult(
641 Intent.createChooser(action, getString(R.string.upload_chooser_title)),
642 ACTION_SELECT_CONTENT_FROM_APPS);
643 }
644 }
645 });
646 dialog = builder.create();
647 break;
648 }
649 default:
650 dialog = null;
651 }
652
653 return dialog;
654 }
655
656
657 /**
658 * Translates a content URI of an image to a physical path
659 * on the disk
660 * @param uri The URI to resolve
661 * @return The path to the image or null if it could not be found
662 */
663 public String getPath(Uri uri) {
664 String[] projection = { MediaStore.Images.Media.DATA };
665 Cursor cursor = managedQuery(uri, projection, null, null, null);
666 if (cursor != null) {
667 int column_index = cursor
668 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
669 cursor.moveToFirst();
670 return cursor.getString(column_index);
671 }
672 return null;
673 }
674
675 /**
676 * Pushes a directory to the drop down list
677 * @param directory to push
678 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
679 */
680 public void pushDirname(OCFile directory) {
681 if(!directory.isDirectory()){
682 throw new IllegalArgumentException("Only directories may be pushed!");
683 }
684 mDirectories.insert(directory.getFileName(), 0);
685 mCurrentDir = directory;
686 }
687
688 /**
689 * Pops a directory name from the drop down list
690 * @return True, unless the stack is empty
691 */
692 public boolean popDirname() {
693 mDirectories.remove(mDirectories.getItem(0));
694 return !mDirectories.isEmpty();
695 }
696
697 private class DirectoryCreator implements Runnable {
698 private String mTargetPath;
699 private Account mAccount;
700 private Handler mHandler;
701
702 public DirectoryCreator(String targetPath, Account account, Handler handler) {
703 mTargetPath = targetPath;
704 mAccount = account;
705 mHandler = handler;
706 }
707
708 @Override
709 public void run() {
710 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
711 boolean created = wdc.createDirectory(mTargetPath);
712 if (created) {
713 mHandler.post(new Runnable() {
714 @Override
715 public void run() {
716 dismissDialog(DIALOG_SHORT_WAIT);
717
718 // Save new directory in local database
719 OCFile newDir = new OCFile(mTargetPath);
720 newDir.setMimetype("DIR");
721 newDir.setParentId(mCurrentDir.getFileId());
722 mStorageManager.saveFile(newDir);
723
724 // Display the new folder right away
725 mFileList.listDirectory();
726 }
727 });
728
729 } else {
730 mHandler.post(new Runnable() {
731 @Override
732 public void run() {
733 dismissDialog(DIALOG_SHORT_WAIT);
734 try {
735 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
736 msg.show();
737
738 } catch (NotFoundException e) {
739 Log.e(TAG, "Error while trying to show fail message " , e);
740 }
741 }
742 });
743 }
744 }
745
746 }
747
748 // Custom array adapter to override text colors
749 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
750
751 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
752 super(ctx, view);
753 }
754
755 public View getView(int position, View convertView, ViewGroup parent) {
756 View v = super.getView(position, convertView, parent);
757
758 ((TextView) v).setTextColor(getResources().getColorStateList(
759 android.R.color.white));
760 return v;
761 }
762
763 public View getDropDownView(int position, View convertView,
764 ViewGroup parent) {
765 View v = super.getDropDownView(position, convertView, parent);
766
767 ((TextView) v).setTextColor(getResources().getColorStateList(
768 android.R.color.white));
769
770 return v;
771 }
772
773 }
774
775 private class SyncBroadcastReceiver extends BroadcastReceiver {
776 /**
777 * {@link BroadcastReceiver} to enable syncing feedback in UI
778 */
779 @Override
780 public void onReceive(Context context, Intent intent) {
781 boolean inProgress = intent.getBooleanExtra(
782 FileSyncService.IN_PROGRESS, false);
783 String accountName = intent
784 .getStringExtra(FileSyncService.ACCOUNT_NAME);
785
786 Log.d("FileDisplay", "sync of account " + accountName
787 + " is in_progress: " + inProgress);
788
789 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
790
791 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
792
793 boolean fillBlankRoot = false;
794 if (mCurrentDir == null) {
795 mCurrentDir = mStorageManager.getFileByPath("/");
796 fillBlankRoot = (mCurrentDir != null);
797 }
798
799 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
800 || fillBlankRoot ) {
801 if (!fillBlankRoot)
802 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
803 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
804 .findFragmentById(R.id.fileList);
805 if (fileListFragment != null) {
806 fileListFragment.listDirectory(mCurrentDir);
807 }
808 }
809
810 setSupportProgressBarIndeterminateVisibility(inProgress);
811
812 }
813 }
814 }
815
816
817 private class UploadFinishReceiver extends BroadcastReceiver {
818 /**
819 * Once the file upload has finished -> update view
820 * @author David A. Velasco
821 * {@link BroadcastReceiver} to enable upload feedback in UI
822 */
823 @Override
824 public void onReceive(Context context, Intent intent) {
825 long parentDirId = intent.getLongExtra(FileUploader.EXTRA_PARENT_DIR_ID, -1);
826 OCFile parentDir = mStorageManager.getFileById(parentDirId);
827 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
828
829 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
830 parentDir != null &&
831 ( (mCurrentDir == null && parentDir.getFileName().equals("/")) ||
832 parentDir.equals(mCurrentDir)
833 )
834 ) {
835 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
836 if (fileListFragment != null) {
837 fileListFragment.listDirectory();
838 }
839 }
840 }
841
842 }
843
844
845 /**
846 * Once the file download has finished -> update view
847 */
848 private class DownloadFinishReceiver extends BroadcastReceiver {
849 @Override
850 public void onReceive(Context context, Intent intent) {
851 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
852 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
853
854 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
855 mCurrentDir != null && mCurrentDir.getFileId() == mStorageManager.getFileByPath(downloadedRemotePath).getParentId()) {
856 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
857 if (fileListFragment != null) {
858 fileListFragment.listDirectory();
859 }
860 }
861 }
862 }
863
864
865
866
867 /**
868 * {@inheritDoc}
869 */
870 @Override
871 public DataStorageManager getStorageManager() {
872 return mStorageManager;
873 }
874
875
876 /**
877 * {@inheritDoc}
878 */
879 @Override
880 public void onDirectoryClick(OCFile directory) {
881 pushDirname(directory);
882 ActionBar actionBar = getSupportActionBar();
883 actionBar.setDisplayHomeAsUpEnabled(true);
884
885 if (mDualPane) {
886 // Resets the FileDetailsFragment on Tablets so that it always displays
887 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
888 if (fileDetails != null && !fileDetails.isEmpty()) {
889 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
890 transaction.remove(fileDetails);
891 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
892 transaction.commit();
893 }
894 }
895 }
896
897
898 /**
899 * {@inheritDoc}
900 */
901 @Override
902 public void onFileClick(OCFile file) {
903
904 // If we are on a large device -> update fragment
905 if (mDualPane) {
906 // 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'
907 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
908 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
909 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
910 transaction.commit();
911
912 } else { // small or medium screen device -> new Activity
913 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
914 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
915 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
916 startActivity(showDetailsIntent);
917 }
918 }
919
920
921 /**
922 * {@inheritDoc}
923 */
924 @Override
925 public OCFile getInitialDirectory() {
926 return mCurrentDir;
927 }
928
929
930 /**
931 * {@inheritDoc}
932 */
933 @Override
934 public void onFileStateChanged() {
935 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
936 if (fileListFragment != null) {
937 fileListFragment.listDirectory();
938 }
939 }
940
941
942 /**
943 * {@inheritDoc}
944 */
945 @Override
946 public FileDownloaderBinder getFileDownloaderBinder() {
947 return mDownloaderBinder;
948 }
949
950
951 /**
952 * {@inheritDoc}
953 */
954 @Override
955 public FileUploaderBinder getFileUploaderBinder() {
956 return mUploaderBinder;
957 }
958
959
960 /** Defines callbacks for service binding, passed to bindService() */
961 private class ListServiceConnection implements ServiceConnection {
962
963 @Override
964 public void onServiceConnected(ComponentName component, IBinder service) {
965 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
966 Log.d(TAG, "Download service connected");
967 mDownloaderBinder = (FileDownloaderBinder) service;
968 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
969 Log.d(TAG, "Upload service connected");
970 mUploaderBinder = (FileUploaderBinder) service;
971 } else {
972 return;
973 }
974 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
975 if (mFileList != null)
976 mFileList.listDirectory();
977 if (mDualPane) {
978 FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
979 if (fragment != null)
980 fragment.updateFileDetails();
981 }
982 }
983
984 @Override
985 public void onServiceDisconnected(ComponentName component) {
986 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
987 Log.d(TAG, "Download service disconnected");
988 mDownloaderBinder = null;
989 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
990 Log.d(TAG, "Upload service disconnected");
991 mUploaderBinder = null;
992 }
993 }
994 };
995
996
997
998 /**
999 * Launch an intent to request the PIN code to the user before letting him use the app
1000 */
1001 private void requestPinCode() {
1002 boolean pinStart = false;
1003 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1004 pinStart = appPrefs.getBoolean("set_pincode", false);
1005 if (pinStart) {
1006 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1007 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1008 startActivity(i);
1009 }
1010 }
1011
1012
1013 }