hide menu in non account vie
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / 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 eu.alefzero.owncloud.ui.activity;
20
21 import java.io.File;
22 import java.net.URLEncoder;
23 import java.util.ArrayList;
24
25 import android.accounts.Account;
26 import android.accounts.AccountManager;
27 import android.app.AlertDialog;
28 import android.app.AlertDialog.Builder;
29 import android.app.Dialog;
30 import android.content.BroadcastReceiver;
31 import android.content.ContentResolver;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.DialogInterface.OnClickListener;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.database.Cursor;
38 import android.net.Uri;
39 import android.os.Bundle;
40 import android.provider.MediaStore;
41 import android.util.Log;
42 import android.view.View;
43 import android.view.ViewGroup;
44 import android.widget.ArrayAdapter;
45 import android.widget.CheckedTextView;
46 import android.widget.EditText;
47 import android.widget.TextView;
48
49 import com.actionbarsherlock.app.ActionBar;
50 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
51 import com.actionbarsherlock.app.SherlockFragmentActivity;
52 import com.actionbarsherlock.view.Menu;
53 import com.actionbarsherlock.view.MenuInflater;
54 import com.actionbarsherlock.view.MenuItem;
55 import com.actionbarsherlock.view.Window;
56
57 import eu.alefzero.owncloud.AccountUtils;
58 import eu.alefzero.owncloud.R;
59 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
60 import eu.alefzero.owncloud.datamodel.DataStorageManager;
61 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
62 import eu.alefzero.owncloud.datamodel.OCFile;
63 import eu.alefzero.owncloud.files.services.FileUploader;
64 import eu.alefzero.owncloud.syncadapter.FileSyncService;
65 import eu.alefzero.owncloud.ui.fragment.FileDetailFragment;
66 import eu.alefzero.owncloud.ui.fragment.FileListFragment;
67 import eu.alefzero.webdav.WebdavClient;
68
69 /**
70 * Displays, what files the user has available in his ownCloud.
71 *
72 * @author Bartek Przybylski
73 *
74 */
75
76 public class FileDisplayActivity extends SherlockFragmentActivity implements
77 OnNavigationListener, OnClickListener, android.view.View.OnClickListener {
78 private ArrayAdapter<String> mDirectories;
79 private DataStorageManager mStorageManager;
80 private FileListFragment mFileList;
81 private OCFile mCurrentDir;
82 private String[] mDirs = null;
83
84 private SyncBroadcastReceiver syncBroadcastRevceiver;
85
86 private static final String KEY_DIR_ARRAY = "DIR_ARRAY";
87 private static final String KEY_CURRENT_DIR = "DIR";
88
89 private static final int DIALOG_SETUP_ACCOUNT = 0;
90 private static final int DIALOG_CREATE_DIR = 1;
91 private static final int ACTION_SELECT_FILE = 1;
92
93 @Override
94 public void onCreate(Bundle savedInstanceState) {
95 super.onCreate(savedInstanceState);
96
97 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
98 setProgressBarIndeterminateVisibility(false);
99
100 if(savedInstanceState != null){
101 mCurrentDir = (OCFile) savedInstanceState.getParcelable(KEY_CURRENT_DIR);
102 }
103 }
104
105 @Override
106 public boolean onCreateOptionsMenu(Menu menu) {
107 if (accountsAreSetup()) {
108 MenuInflater inflater = getSherlock().getMenuInflater();
109 inflater.inflate(R.menu.menu, menu);
110 return true;
111 }
112 return false;
113 }
114
115 @Override
116 public boolean onOptionsItemSelected(MenuItem item) {
117 boolean retval = true;
118 switch (item.getItemId()) {
119 case R.id.createDirectoryItem: {
120 showDialog(DIALOG_CREATE_DIR);
121 break;
122 }
123 case R.id.startSync: {
124 Bundle bundle = new Bundle();
125 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
126 ContentResolver.requestSync(
127 AccountUtils.getCurrentOwnCloudAccount(this),
128 "org.owncloud", bundle);
129 break;
130 }
131 case R.id.action_upload: {
132 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
133 action = action.setType("*/*")
134 .addCategory(Intent.CATEGORY_OPENABLE);
135 startActivityForResult(
136 Intent.createChooser(action, "Upload file from..."),
137 ACTION_SELECT_FILE);
138 break;
139 }
140 case R.id.action_accounts: {
141 Intent accountIntent = new Intent(this, AccountSelectActivity.class);
142 startActivity(accountIntent);
143 }
144 case android.R.id.home: {
145 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
146 onBackPressed();
147 }
148 break;
149 }
150 default:
151 retval = false;
152 }
153 return retval;
154 }
155
156 @Override
157 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
158 int i = itemPosition;
159 while (i-- != 0) {
160 onBackPressed();
161 }
162 return true;
163 }
164
165 /**
166 * Called, when the user selected something for uploading
167 */
168 public void onActivityResult(int requestCode, int resultCode, Intent data) {
169 if (resultCode == RESULT_OK) {
170 if (requestCode == ACTION_SELECT_FILE) {
171 Uri selectedImageUri = data.getData();
172
173 String filemanagerstring = selectedImageUri.getPath();
174 String selectedImagePath = getPath(selectedImageUri);
175 String filepath;
176
177 if (selectedImagePath != null)
178 filepath = selectedImagePath;
179 else
180 filepath = filemanagerstring;
181
182 if (filepath == null) {
183 Log.e("FileDisplay", "Couldnt resolve path to file");
184 return;
185 }
186
187 Intent i = new Intent(this, FileUploader.class);
188 i.putExtra(FileUploader.KEY_ACCOUNT,
189 AccountUtils.getCurrentOwnCloudAccount(this));
190 String remotepath = new String();
191 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
192 remotepath += "/" + URLEncoder.encode(mDirectories.getItem(j));
193 }
194 if (!remotepath.endsWith("/"))
195 remotepath += "/";
196 remotepath += URLEncoder.encode(new File(filepath).getName());
197 Log.e("ASD", remotepath + "");
198
199 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
200 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
201 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
202 startService(i);
203 }
204 }
205 }
206
207 @Override
208 public void onBackPressed() {
209 if (mDirectories == null || mDirectories.getCount() == 1) {
210 finish();
211 return;
212 }
213 popDirname();
214 mFileList.onNavigateUp();
215 mCurrentDir = mFileList.getCurrentFile();
216
217 if(mCurrentDir.getParentId() == 0){
218 ActionBar actionBar = getSupportActionBar();
219 actionBar.setDisplayHomeAsUpEnabled(false);
220 }
221 }
222
223 @Override
224 protected void onRestoreInstanceState(Bundle savedInstanceState) {
225 super.onRestoreInstanceState(savedInstanceState);
226 mDirs = savedInstanceState.getStringArray(KEY_DIR_ARRAY);
227 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
228 mDirectories.add("/");
229 if (mDirs != null)
230 for (String s : mDirs)
231 mDirectories.insert(s, 0);
232 }
233
234 @Override
235 protected void onSaveInstanceState(Bundle outState) {
236 super.onSaveInstanceState(outState);
237 if(mDirectories != null && mDirectories.getCount() != 0){
238 mDirs = new String[mDirectories.getCount()-1];
239 for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {
240 mDirs[i] = mDirectories.getItem(j);
241 }
242 }
243 outState.putStringArray(KEY_DIR_ARRAY, mDirs);
244 outState.putParcelable(KEY_CURRENT_DIR, mCurrentDir);
245 }
246
247 @Override
248 protected void onResume() {
249 super.onResume();
250
251 //TODO: Dialog useless -> get rid of this
252 if (!accountsAreSetup()) {
253 setContentView(R.layout.no_account_available);
254 setProgressBarIndeterminateVisibility(false);
255 getSupportActionBar().setNavigationMode(ActionBar.DISPLAY_SHOW_TITLE);
256 findViewById(R.id.setup_account).setOnClickListener(this);
257 return;
258 } else if (findViewById(R.id.file_list_view) == null) {
259 setContentView(R.layout.files);
260 }
261
262 // Listen for sync messages
263 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
264 syncBroadcastRevceiver = new SyncBroadcastReceiver();
265 registerReceiver(syncBroadcastRevceiver, syncIntentFilter);
266
267 // Storage manager initialization
268 mStorageManager = new FileDataStorageManager(
269 AccountUtils.getCurrentOwnCloudAccount(this),
270 getContentResolver());
271
272 // File list
273 mFileList = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
274
275 // Figure out what directory to list.
276 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
277 if(getIntent().hasExtra(FileDetailFragment.EXTRA_FILE)){
278 mCurrentDir = (OCFile) getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
279 if(!mCurrentDir.isDirectory()){
280 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
281 }
282
283 // Clear intent extra, so rotating the screen will not return us to this directory
284 getIntent().removeExtra(FileDetailFragment.EXTRA_FILE);
285 }
286
287 // Drop-Down navigation and file list restore
288 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
289
290
291 // Given the case we have a file to display:
292 if(mCurrentDir != null){
293 ArrayList<OCFile> files = new ArrayList<OCFile>();
294 OCFile currFile = mCurrentDir;
295 while(currFile != null){
296 files.add(currFile);
297 currFile = mStorageManager.getFileById(currFile.getParentId());
298 }
299
300 // Insert in mDirs
301 mDirs = new String[files.size()];
302 for(int i = files.size() - 1; i >= 0; i--){
303 mDirs[i] = files.get(i).getFileName();
304 }
305 }
306
307 if (mDirs != null) {
308 for (String s : mDirs)
309 mDirectories.add(s);
310 } else {
311 mDirectories.add("/");
312 }
313
314 // Actionbar setup
315 ActionBar action_bar = getSupportActionBar();
316 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
317 action_bar.setDisplayShowTitleEnabled(false);
318 action_bar.setListNavigationCallbacks(mDirectories, this);
319 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
320 action_bar.setDisplayHomeAsUpEnabled(true);
321 } else {
322 action_bar.setDisplayHomeAsUpEnabled(false);
323 }
324
325 // List dir here
326 mFileList.listDirectory(mCurrentDir);
327 }
328
329 @Override
330 protected void onPause() {
331 super.onPause();
332 if (syncBroadcastRevceiver != null) {
333 unregisterReceiver(syncBroadcastRevceiver);
334 syncBroadcastRevceiver = null;
335 }
336
337 }
338
339 @Override
340 protected Dialog onCreateDialog(int id) {
341 Dialog dialog;
342 AlertDialog.Builder builder;
343 switch (id) {
344 case DIALOG_SETUP_ACCOUNT:
345 builder = new AlertDialog.Builder(this);
346 builder.setTitle(R.string.main_tit_accsetup);
347 builder.setMessage(R.string.main_wrn_accsetup);
348 builder.setCancelable(false);
349 builder.setPositiveButton(android.R.string.ok, this);
350 builder.setNegativeButton(android.R.string.cancel, this);
351 dialog = builder.create();
352 break;
353 case DIALOG_CREATE_DIR: {
354 builder = new Builder(this);
355 final EditText dirNameInput = new EditText(getBaseContext());
356 final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
357 builder.setView(dirNameInput);
358 builder.setTitle(R.string.uploader_info_dirname);
359 int typed_color = getResources().getColor(R.color.setup_text_typed);
360 dirNameInput.setTextColor(typed_color);
361
362 builder.setPositiveButton(android.R.string.ok,
363 new OnClickListener() {
364 public void onClick(DialogInterface dialog, int which) {
365 String directoryName = dirNameInput.getText().toString();
366 if (directoryName.trim().length() == 0) {
367 dialog.cancel();
368 return;
369 }
370
371 // Figure out the path where the dir needs to be created
372 String path = mCurrentDir.getRemotePath();
373
374 // Create directory
375 path += directoryName + "/";
376 Thread thread = new Thread(new DirectoryCreator(
377 path, a));
378 thread.start();
379
380 // Save new directory in local database
381 OCFile newDir = new OCFile(path);
382 newDir.setMimetype("DIR");
383 newDir.setParentId(mCurrentDir.getFileId());
384 mStorageManager.saveFile(newDir);
385
386 // Display the new folder right away
387 dialog.dismiss();
388 mFileList.listDirectory(mCurrentDir);
389 }
390 });
391 builder.setNegativeButton(R.string.common_cancel,
392 new OnClickListener() {
393 public void onClick(DialogInterface dialog, int which) {
394 dialog.cancel();
395 }
396 });
397 dialog = builder.create();
398 break;
399 }
400 default:
401 dialog = null;
402 }
403
404 return dialog;
405 }
406
407
408 /**
409 * Responds to the "There are no ownCloud Accounts setup" dialog
410 * TODO: Dialog is 100% useless -> Remove
411 */
412 @Override
413 public void onClick(DialogInterface dialog, int which) {
414 // In any case - we won't need it anymore
415 dialog.dismiss();
416 switch (which) {
417 case DialogInterface.BUTTON_POSITIVE:
418 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
419 intent.putExtra("authorities",
420 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
421 startActivity(intent);
422 break;
423 case DialogInterface.BUTTON_NEGATIVE:
424 finish();
425 }
426
427 }
428
429 /**
430 * Translates a content URI of an image to a physical path
431 * on the disk
432 * @param uri The URI to resolve
433 * @return The path to the image or null if it could not be found
434 */
435 public String getPath(Uri uri) {
436 String[] projection = { MediaStore.Images.Media.DATA };
437 Cursor cursor = managedQuery(uri, projection, null, null, null);
438 if (cursor != null) {
439 int column_index = cursor
440 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
441 cursor.moveToFirst();
442 return cursor.getString(column_index);
443 }
444 return null;
445 }
446
447 /**
448 * Pushes a directory to the drop down list
449 * @param directory to push
450 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
451 */
452 public void pushDirname(OCFile directory) {
453 if(!directory.isDirectory()){
454 throw new IllegalArgumentException("Only directories may be pushed!");
455 }
456 mDirectories.insert(directory.getFileName(), 0);
457 mCurrentDir = directory;
458 }
459
460 /**
461 * Pops a directory name from the drop down list
462 * @return True, unless the stack is empty
463 */
464 public boolean popDirname() {
465 mDirectories.remove(mDirectories.getItem(0));
466 return !mDirectories.isEmpty();
467 }
468
469 /**
470 * Checks, whether or not there are any ownCloud accounts setup.
471 *
472 * @return true, if there is at least one account.
473 */
474 private boolean accountsAreSetup() {
475 AccountManager accMan = AccountManager.get(this);
476 Account[] accounts = accMan
477 .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
478 return accounts.length > 0;
479 }
480
481 private class DirectoryCreator implements Runnable {
482 private String mTargetPath;
483 private Account mAccount;
484 private AccountManager mAm;
485
486 public DirectoryCreator(String targetPath, Account account) {
487 mTargetPath = targetPath;
488 mAccount = account;
489 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
490 }
491
492 @Override
493 public void run() {
494 WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
495 mAccount, AccountAuthenticator.KEY_OC_URL)));
496
497 String username = mAccount.name.substring(0,
498 mAccount.name.lastIndexOf('@'));
499 String password = mAm.getPassword(mAccount);
500
501 wdc.setCredentials(username, password);
502 wdc.allowUnsignedCertificates();
503 wdc.createDirectory(mTargetPath);
504 }
505
506 }
507
508 // Custom array adapter to override text colors
509 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
510
511 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
512 super(ctx, view);
513 }
514
515 public View getView(int position, View convertView, ViewGroup parent) {
516 View v = super.getView(position, convertView, parent);
517
518 ((TextView) v).setTextColor(getResources().getColorStateList(
519 android.R.color.white));
520 return v;
521 }
522
523 public View getDropDownView(int position, View convertView,
524 ViewGroup parent) {
525 View v = super.getDropDownView(position, convertView, parent);
526
527 ((TextView) v).setTextColor(getResources().getColorStateList(
528 android.R.color.white));
529
530 return v;
531 }
532
533 }
534
535 private class SyncBroadcastReceiver extends BroadcastReceiver {
536 /**
537 * {@link BroadcastReceiver} to enable syncing feedback in UI
538 */
539 @Override
540 public void onReceive(Context context, Intent intent) {
541 boolean inProgress = intent.getBooleanExtra(
542 FileSyncService.IN_PROGRESS, false);
543 String account_name = intent
544 .getStringExtra(FileSyncService.ACCOUNT_NAME);
545 Log.d("FileDisplay", "sync of account " + account_name
546 + " is in_progress: " + inProgress);
547 setProgressBarIndeterminateVisibility(inProgress);
548 if (!inProgress) {
549 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
550 .findFragmentById(R.id.fileList);
551 if (fileListFramgent != null)
552 fileListFramgent.listDirectory();
553 }
554 }
555
556 }
557
558 @Override
559 public void onClick(View v) {
560 if (v.getId() == R.id.setup_account) {
561 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
562 intent.putExtra("authorities", new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
563 startActivity(intent);
564 }
565 }
566
567 }