When user goes to set the upload path, the folder list view is shown in the current...
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / Preferences.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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 package com.owncloud.android.ui.activity;
19
20 import android.accounts.Account;
21 import android.accounts.AccountManager;
22 import android.accounts.AccountManagerCallback;
23 import android.accounts.AccountManagerFuture;
24 import android.content.Intent;
25 import android.content.SharedPreferences;
26 import android.content.pm.PackageInfo;
27 import android.content.pm.PackageManager.NameNotFoundException;
28 import android.net.Uri;
29 import android.os.Bundle;
30 import android.os.Handler;
31 import android.preference.CheckBoxPreference;
32 import android.preference.Preference;
33 import android.preference.Preference.OnPreferenceChangeListener;
34 import android.preference.Preference.OnPreferenceClickListener;
35 import android.preference.PreferenceCategory;
36 import android.preference.PreferenceManager;
37 import android.view.ContextMenu;
38 import android.view.ContextMenu.ContextMenuInfo;
39 import android.view.View;
40 import android.widget.AdapterView;
41 import android.widget.AdapterView.OnItemLongClickListener;
42 import android.widget.ListAdapter;
43 import android.widget.ListView;
44
45 import com.actionbarsherlock.app.ActionBar;
46 import com.actionbarsherlock.app.SherlockPreferenceActivity;
47 import com.actionbarsherlock.view.Menu;
48 import com.actionbarsherlock.view.MenuItem;
49 import com.owncloud.android.MainApp;
50 import com.owncloud.android.R;
51 import com.owncloud.android.authentication.AccountUtils;
52 import com.owncloud.android.authentication.AuthenticatorActivity;
53 import com.owncloud.android.datamodel.OCFile;
54 import com.owncloud.android.db.DbHandler;
55 import com.owncloud.android.lib.common.utils.Log_OC;
56 import com.owncloud.android.ui.LongClickableCheckBoxPreference;
57 import com.owncloud.android.utils.DisplayUtils;
58
59
60 /**
61 * An Activity that allows the user to change the application's settings.
62 *
63 * @author Bartek Przybylski
64 * @author David A. Velasco
65 */
66 public class Preferences extends SherlockPreferenceActivity implements AccountManagerCallback<Boolean> {
67
68 private static final String TAG = "OwnCloudPreferences";
69
70 private static final int ACTION_SELECT_UPLOAD_PATH = 1;
71
72 private DbHandler mDbHandler;
73 private CheckBoxPreference pCode;
74 private Preference pAboutApp;
75
76 private PreferenceCategory mAccountsPrefCategory = null;
77 private final Handler mHandler = new Handler();
78 private String mAccountName;
79 private boolean mShowContextMenu = false;
80 private String mUploadPath;
81 private Preference mPrefInstantUploadPath;
82
83
84 @SuppressWarnings("deprecation")
85 @Override
86 public void onCreate(Bundle savedInstanceState) {
87 super.onCreate(savedInstanceState);
88 mDbHandler = new DbHandler(getBaseContext());
89 addPreferencesFromResource(R.xml.preferences);
90
91 ActionBar actionBar = getSherlock().getActionBar();
92 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
93 actionBar.setDisplayHomeAsUpEnabled(true);
94 actionBar.setTitle(R.string.actionbar_settings);
95
96 // Load the accounts category for adding the list of accounts
97 mAccountsPrefCategory = (PreferenceCategory) findPreference("accounts_category");
98
99 ListView listView = getListView();
100 listView.setOnItemLongClickListener(new OnItemLongClickListener() {
101 @Override
102 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
103 ListView listView = (ListView) parent;
104 ListAdapter listAdapter = listView.getAdapter();
105 Object obj = listAdapter.getItem(position);
106
107 if (obj != null && obj instanceof LongClickableCheckBoxPreference) {
108 mShowContextMenu = true;
109 mAccountName = ((LongClickableCheckBoxPreference) obj).getKey();
110
111 Preferences.this.openContextMenu(listView);
112
113 View.OnLongClickListener longListener = (View.OnLongClickListener) obj;
114 return longListener.onLongClick(view);
115 }
116 return false;
117 }
118 });
119
120 // Register context menu for list of preferences.
121 registerForContextMenu(getListView());
122
123 pCode = (CheckBoxPreference) findPreference("set_pincode");
124 if (pCode != null){
125 pCode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
126 @Override
127 public boolean onPreferenceChange(Preference preference, Object newValue) {
128 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
129 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "preferences");
130 i.putExtra(PinCodeActivity.EXTRA_NEW_STATE, newValue.toString());
131 startActivity(i);
132
133 return true;
134 }
135 });
136
137 }
138
139 PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference("more");
140
141 boolean helpEnabled = getResources().getBoolean(R.bool.help_enabled);
142 Preference pHelp = findPreference("help");
143 if (pHelp != null ){
144 if (helpEnabled) {
145 pHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
146 @Override
147 public boolean onPreferenceClick(Preference preference) {
148 String helpWeb =(String) getText(R.string.url_help);
149 if (helpWeb != null && helpWeb.length() > 0) {
150 Uri uriUrl = Uri.parse(helpWeb);
151 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
152 startActivity(intent);
153 }
154 return true;
155 }
156 });
157 } else {
158 preferenceCategory.removePreference(pHelp);
159 }
160
161 }
162
163
164 boolean recommendEnabled = getResources().getBoolean(R.bool.recommend_enabled);
165 Preference pRecommend = findPreference("recommend");
166 if (pRecommend != null){
167 if (recommendEnabled) {
168 pRecommend.setOnPreferenceClickListener(new OnPreferenceClickListener() {
169 @Override
170 public boolean onPreferenceClick(Preference preference) {
171
172 Intent intent = new Intent(Intent.ACTION_SENDTO);
173 intent.setType("text/plain");
174 intent.setData(Uri.parse(getString(R.string.mail_recommend)));
175 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
176
177 String appName = getString(R.string.app_name);
178 String downloadUrl = getString(R.string.url_app_download);
179 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(Preferences.this);
180 String username = currentAccount.name.substring(0, currentAccount.name.lastIndexOf('@'));
181
182 String recommendSubject = String.format(getString(R.string.recommend_subject), appName);
183 String recommendText = String.format(getString(R.string.recommend_text), appName, downloadUrl, username);
184
185 intent.putExtra(Intent.EXTRA_SUBJECT, recommendSubject);
186 intent.putExtra(Intent.EXTRA_TEXT, recommendText);
187 startActivity(intent);
188
189
190 return(true);
191
192 }
193 });
194 } else {
195 preferenceCategory.removePreference(pRecommend);
196 }
197
198 }
199
200 boolean feedbackEnabled = getResources().getBoolean(R.bool.feedback_enabled);
201 Preference pFeedback = findPreference("feedback");
202 if (pFeedback != null){
203 if (feedbackEnabled) {
204 pFeedback.setOnPreferenceClickListener(new OnPreferenceClickListener() {
205 @Override
206 public boolean onPreferenceClick(Preference preference) {
207 String feedbackMail =(String) getText(R.string.mail_feedback);
208 String feedback =(String) getText(R.string.prefs_feedback);
209 Intent intent = new Intent(Intent.ACTION_SENDTO);
210 intent.setType("text/plain");
211 intent.putExtra(Intent.EXTRA_SUBJECT, feedback);
212
213 intent.setData(Uri.parse(feedbackMail));
214 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
215 startActivity(intent);
216
217 return true;
218 }
219 });
220 } else {
221 preferenceCategory.removePreference(pFeedback);
222 }
223
224 }
225
226 boolean imprintEnabled = getResources().getBoolean(R.bool.imprint_enabled);
227 Preference pImprint = findPreference("imprint");
228 if (pImprint != null) {
229 if (imprintEnabled) {
230 pImprint.setOnPreferenceClickListener(new OnPreferenceClickListener() {
231 @Override
232 public boolean onPreferenceClick(Preference preference) {
233 String imprintWeb = (String) getText(R.string.url_imprint);
234 if (imprintWeb != null && imprintWeb.length() > 0) {
235 Uri uriUrl = Uri.parse(imprintWeb);
236 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
237 startActivity(intent);
238 }
239 //ImprintDialog.newInstance(true).show(preference.get, "IMPRINT_DIALOG");
240 return true;
241 }
242 });
243 } else {
244 preferenceCategory.removePreference(pImprint);
245 }
246 }
247
248 mPrefInstantUploadPath = findPreference("instant_upload_path");
249 if (mPrefInstantUploadPath != null){
250
251 mPrefInstantUploadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() {
252 @Override
253 public boolean onPreferenceClick(Preference preference) {
254 Intent intent = new Intent(Preferences.this, UploadPathActivity.class);
255 intent.putExtra(UploadPathActivity.KEY_INSTANT_UPLOAD_PATH, mUploadPath);
256 startActivityForResult(intent, ACTION_SELECT_UPLOAD_PATH);
257 return true;
258 }
259 });
260 }
261
262 /* About App */
263 pAboutApp = (Preference) findPreference("about_app");
264 if (pAboutApp != null) {
265 pAboutApp.setTitle(String.format(getString(R.string.about_android), getString(R.string.app_name)));
266 PackageInfo pkg;
267 try {
268 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
269 pAboutApp.setSummary(String.format(getString(R.string.about_version), pkg.versionName));
270 } catch (NameNotFoundException e) {
271 Log_OC.e(TAG, "Error while showing about dialog", e);
272 }
273 }
274
275 loadInstantUploadPath();
276
277 }
278
279 @Override
280 protected void onPause() {
281 saveInstantUploadPathOnPreferences();
282 super.onPause();
283 }
284
285 @Override
286 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
287
288 // Filter for only showing contextual menu when long press on the
289 // accounts
290 if (mShowContextMenu) {
291 getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
292 mShowContextMenu = false;
293 }
294 super.onCreateContextMenu(menu, v, menuInfo);
295 }
296
297 /**
298 * Called when the user clicked on an item into the context menu created at
299 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} for
300 * every ownCloud {@link Account} , containing 'secondary actions' for them.
301 *
302 * {@inheritDoc}
303 */
304 @Override
305 public boolean onContextItemSelected(android.view.MenuItem item) {
306 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
307 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
308 for (Account a : accounts) {
309 if (a.name.equals(mAccountName)) {
310 if (item.getItemId() == R.id.change_password) {
311
312 // Change account password
313 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
314 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, a);
315 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
316 AuthenticatorActivity.ACTION_UPDATE_TOKEN);
317 startActivity(updateAccountCredentials);
318
319 } else if (item.getItemId() == R.id.delete_account) {
320
321 // Remove account
322 am.removeAccount(a, this, mHandler);
323 }
324 }
325 }
326
327 return true;
328 }
329
330 @Override
331 public void run(AccountManagerFuture<Boolean> future) {
332 if (future.isDone()) {
333 Account a = AccountUtils.getCurrentOwnCloudAccount(this);
334 String accountName = "";
335 if (a == null) {
336 Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
337 if (accounts.length != 0)
338 accountName = accounts[0].name;
339 AccountUtils.setCurrentOwnCloudAccount(this, accountName);
340 }
341 addAccountsCheckboxPreferences();
342 }
343 }
344
345 @Override
346 protected void onResume() {
347 super.onResume();
348 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
349 boolean state = appPrefs.getBoolean("set_pincode", false);
350 pCode.setChecked(state);
351
352 // Populate the accounts category with the list of accounts
353 addAccountsCheckboxPreferences();
354 }
355
356 @Override
357 public boolean onCreateOptionsMenu(Menu menu) {
358 super.onCreateOptionsMenu(menu);
359 return true;
360 }
361
362 @Override
363 public boolean onMenuItemSelected(int featureId, MenuItem item) {
364 super.onMenuItemSelected(featureId, item);
365 Intent intent;
366
367 switch (item.getItemId()) {
368 case android.R.id.home:
369 intent = new Intent(getBaseContext(), FileDisplayActivity.class);
370 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
371 startActivity(intent);
372 break;
373 default:
374 Log_OC.w(TAG, "Unknown menu item triggered");
375 return false;
376 }
377 return true;
378 }
379
380 @Override
381 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
382 super.onActivityResult(requestCode, resultCode, data);
383
384 if (requestCode == ACTION_SELECT_UPLOAD_PATH && (resultCode == RESULT_OK ||
385 resultCode == UploadPathActivity.RESULT_OK_SET_UPLOAD_PATH)){
386
387 OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(UploadPathActivity.EXTRA_CURRENT_FOLDER);
388
389 mUploadPath = folderToMoveAt.getRemotePath();
390
391 saveInstantUploadPathOnPreferences();
392 }
393 }
394
395 @Override
396 protected void onDestroy() {
397 mDbHandler.close();
398 super.onDestroy();
399 }
400
401 /**
402 * Create the list of accounts that has been added into the app
403 */
404 @SuppressWarnings("deprecation")
405 private void addAccountsCheckboxPreferences() {
406
407 // Remove accounts in case list is refreshing for avoiding to have
408 // duplicate items
409 if (mAccountsPrefCategory.getPreferenceCount() > 0) {
410 mAccountsPrefCategory.removeAll();
411 }
412
413 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
414 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
415 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
416
417 if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
418 // Show create account screen if there isn't any account
419 am.addAccount(MainApp.getAccountType(), null, null, null, this,
420 null,
421 null);
422 }
423 else {
424
425 for (Account a : accounts) {
426 LongClickableCheckBoxPreference accountPreference = new LongClickableCheckBoxPreference(this);
427 accountPreference.setKey(a.name);
428 // Handle internationalized domain names
429 accountPreference.setTitle(DisplayUtils.convertIdn(a.name, false));
430 mAccountsPrefCategory.addPreference(accountPreference);
431
432 // Check the current account that is being used
433 if (a.name.equals(currentAccount.name)) {
434 accountPreference.setChecked(true);
435 } else {
436 accountPreference.setChecked(false);
437 }
438
439 accountPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
440 @Override
441 public boolean onPreferenceChange(Preference preference, Object newValue) {
442 String key = preference.getKey();
443 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
444 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
445 for (Account a : accounts) {
446 CheckBoxPreference p = (CheckBoxPreference) findPreference(a.name);
447 if (key.equals(a.name)) {
448 boolean accountChanged = !p.isChecked();
449 p.setChecked(true);
450 AccountUtils.setCurrentOwnCloudAccount(
451 getApplicationContext(),
452 a.name
453 );
454 if (accountChanged) {
455 // restart the main activity
456 Intent i = new Intent(
457 Preferences.this,
458 FileDisplayActivity.class
459 );
460 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
461 startActivity(i);
462 } else {
463 finish();
464 }
465 } else {
466 p.setChecked(false);
467 }
468 }
469 return (Boolean) newValue;
470 }
471 });
472
473 }
474
475 // Add Create Account preference at the end of account list if
476 // Multiaccount is enabled
477 if (getResources().getBoolean(R.bool.multiaccount_support)) {
478 createAddAccountPreference();
479 }
480
481 }
482 }
483
484 /**
485 * Create the preference for allow adding new accounts
486 */
487 private void createAddAccountPreference() {
488 Preference addAccountPref = new Preference(this);
489 addAccountPref.setKey("add_account");
490 addAccountPref.setTitle(getString(R.string.prefs_add_account));
491 mAccountsPrefCategory.addPreference(addAccountPref);
492
493 addAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
494 @Override
495 public boolean onPreferenceClick(Preference preference) {
496 AccountManager am = AccountManager.get(getApplicationContext());
497 am.addAccount(MainApp.getAccountType(), null, null, null, Preferences.this, null, null);
498 return true;
499 }
500 });
501
502 }
503
504 /**
505 * Load upload path set on preferences
506 */
507 private void loadInstantUploadPath() {
508 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
509 mUploadPath = appPrefs.getString("instant_upload_path", getString(R.string.instant_upload_path));
510 mPrefInstantUploadPath.setSummary(mUploadPath);
511 }
512
513 /**
514 * Save the "Instant Upload Path" on preferences
515 */
516 private void saveInstantUploadPathOnPreferences() {
517 mPrefInstantUploadPath.setSummary(mUploadPath);
518 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
519 SharedPreferences.Editor editor = appPrefs.edit();
520 editor.putString("instant_upload_path", mUploadPath);
521 editor.commit();
522 }
523 }