Merge with develop
[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.db.DbHandler;
54 import com.owncloud.android.ui.CheckBoxPreferenceWithLongTitle;
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 DbHandler mDbHandler;
71 private CheckBoxPreference pCode;
72 private CheckBoxPreference pSaveLocation;
73 private Preference pAboutApp;
74
75 private PreferenceCategory mAccountsPrefCategory = null;
76 private final Handler mHandler = new Handler();
77 private String mAccountName;
78 private boolean mShowContextMenu = false;
79 private String mUploadPath;
80
81
82 @SuppressWarnings("deprecation")
83 @Override
84 public void onCreate(Bundle savedInstanceState) {
85 super.onCreate(savedInstanceState);
86 mDbHandler = new DbHandler(getBaseContext());
87 addPreferencesFromResource(R.xml.preferences);
88
89 ActionBar actionBar = getSherlock().getActionBar();
90 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
91 actionBar.setDisplayHomeAsUpEnabled(true);
92 actionBar.setTitle(R.string.actionbar_settings);
93
94 loadInstantUploadPath();
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 = obj.toString();
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 pSaveLocation = (CheckBoxPreferenceWithLongTitle) findPreference("save_last_upload_location");
140 if(pSaveLocation != null){
141 pSaveLocation.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
142 @Override
143 public boolean onPreferenceChange(Preference preference, Object newValue) {
144 //The saved path is removed when the preference is turned off
145 if( newValue instanceof Boolean && !(Boolean) newValue) {
146 SharedPreferences.Editor appPrefs = PreferenceManager
147 .getDefaultSharedPreferences(getApplicationContext()).edit();
148 appPrefs.remove("last_upload_path");
149 appPrefs.commit();
150 }
151 return true;
152 }
153 });
154 }
155
156
157 PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference("more");
158
159 boolean helpEnabled = getResources().getBoolean(R.bool.help_enabled);
160 Preference pHelp = findPreference("help");
161 if (pHelp != null ){
162 if (helpEnabled) {
163 pHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
164 @Override
165 public boolean onPreferenceClick(Preference preference) {
166 String helpWeb =(String) getText(R.string.url_help);
167 if (helpWeb != null && helpWeb.length() > 0) {
168 Uri uriUrl = Uri.parse(helpWeb);
169 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
170 startActivity(intent);
171 }
172 return true;
173 }
174 });
175 } else {
176 preferenceCategory.removePreference(pHelp);
177 }
178
179 }
180
181
182 boolean recommendEnabled = getResources().getBoolean(R.bool.recommend_enabled);
183 Preference pRecommend = findPreference("recommend");
184 if (pRecommend != null){
185 if (recommendEnabled) {
186 pRecommend.setOnPreferenceClickListener(new OnPreferenceClickListener() {
187 @Override
188 public boolean onPreferenceClick(Preference preference) {
189
190 Intent intent = new Intent(Intent.ACTION_SENDTO);
191 intent.setType("text/plain");
192 intent.setData(Uri.parse(getString(R.string.mail_recommend)));
193 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
194
195 String appName = getString(R.string.app_name);
196 String downloadUrl = getString(R.string.url_app_download);
197 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(Preferences.this);
198 String username = currentAccount.name.substring(0, currentAccount.name.lastIndexOf('@'));
199
200 String recommendSubject = String.format(getString(R.string.recommend_subject), appName);
201 String recommendText = String.format(getString(R.string.recommend_text), appName, downloadUrl, username);
202
203 intent.putExtra(Intent.EXTRA_SUBJECT, recommendSubject);
204 intent.putExtra(Intent.EXTRA_TEXT, recommendText);
205 startActivity(intent);
206
207
208 return(true);
209
210 }
211 });
212 } else {
213 preferenceCategory.removePreference(pRecommend);
214 }
215
216 }
217
218 boolean feedbackEnabled = getResources().getBoolean(R.bool.feedback_enabled);
219 Preference pFeedback = findPreference("feedback");
220 if (pFeedback != null){
221 if (feedbackEnabled) {
222 pFeedback.setOnPreferenceClickListener(new OnPreferenceClickListener() {
223 @Override
224 public boolean onPreferenceClick(Preference preference) {
225 String feedbackMail =(String) getText(R.string.mail_feedback);
226 String feedback =(String) getText(R.string.prefs_feedback);
227 Intent intent = new Intent(Intent.ACTION_SENDTO);
228 intent.setType("text/plain");
229 intent.putExtra(Intent.EXTRA_SUBJECT, feedback);
230
231 intent.setData(Uri.parse(feedbackMail));
232 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
233 startActivity(intent);
234
235 return true;
236 }
237 });
238 } else {
239 preferenceCategory.removePreference(pFeedback);
240 }
241
242 }
243
244 boolean imprintEnabled = getResources().getBoolean(R.bool.imprint_enabled);
245 Preference pImprint = findPreference("imprint");
246 if (pImprint != null) {
247 if (imprintEnabled) {
248 pImprint.setOnPreferenceClickListener(new OnPreferenceClickListener() {
249 @Override
250 public boolean onPreferenceClick(Preference preference) {
251 String imprintWeb = (String) getText(R.string.url_imprint);
252 if (imprintWeb != null && imprintWeb.length() > 0) {
253 Uri uriUrl = Uri.parse(imprintWeb);
254 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
255 startActivity(intent);
256 }
257 //ImprintDialog.newInstance(true).show(preference.get, "IMPRINT_DIALOG");
258 return true;
259 }
260 });
261 } else {
262 preferenceCategory.removePreference(pImprint);
263 }
264 }
265
266 Preference pInstantUploadPathApp = (Preference) findPreference("instant_upload_path");
267
268 pInstantUploadPathApp.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
269 @Override
270 public boolean onPreferenceChange(Preference preference, Object newValue) {
271 mUploadPath = updateInstantUploadPath(newValue.toString());
272 return true;
273 }
274 });
275
276 /* About App */
277 pAboutApp = (Preference) findPreference("about_app");
278 if (pAboutApp != null) {
279 pAboutApp.setTitle(String.format(getString(R.string.about_android), getString(R.string.app_name)));
280 PackageInfo pkg;
281 try {
282 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
283 pAboutApp.setSummary(String.format(getString(R.string.about_version), pkg.versionName));
284 } catch (NameNotFoundException e) {
285 Log_OC.e(TAG, "Error while showing about dialog", e);
286 }
287 }
288 }
289
290 @Override
291 protected void onPause() {
292 saveInstantUploadPathOnPreferences();
293 super.onPause();
294 }
295
296 @Override
297 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
298
299 // Filter for only showing contextual menu when long press on the
300 // accounts
301 if (mShowContextMenu) {
302 getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
303 mShowContextMenu = false;
304 }
305 super.onCreateContextMenu(menu, v, menuInfo);
306 }
307
308 /**
309 * Called when the user clicked on an item into the context menu created at
310 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} for
311 * every ownCloud {@link Account} , containing 'secondary actions' for them.
312 *
313 * {@inheritDoc}
314 */
315 @Override
316 public boolean onContextItemSelected(android.view.MenuItem item) {
317 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
318 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
319 for (Account a : accounts) {
320 if (a.name.equals(mAccountName)) {
321 if (item.getItemId() == R.id.change_password) {
322
323 // Change account password
324 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
325 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, a);
326 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
327 AuthenticatorActivity.ACTION_UPDATE_TOKEN);
328 startActivity(updateAccountCredentials);
329
330 } else if (item.getItemId() == R.id.delete_account) {
331
332 // Remove account
333 am.removeAccount(a, this, mHandler);
334 }
335 }
336 }
337
338 return true;
339 }
340
341 @Override
342 public void run(AccountManagerFuture<Boolean> future) {
343 if (future.isDone()) {
344 Account a = AccountUtils.getCurrentOwnCloudAccount(this);
345 String accountName = "";
346 if (a == null) {
347 Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
348 if (accounts.length != 0)
349 accountName = accounts[0].name;
350 AccountUtils.setCurrentOwnCloudAccount(this, accountName);
351 }
352 addAccountsCheckboxPreferences();
353 }
354 }
355
356 @Override
357 protected void onResume() {
358 super.onResume();
359 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
360 boolean state = appPrefs.getBoolean("set_pincode", false);
361 pCode.setChecked(state);
362
363 // Populate the accounts category with the list of accounts
364 addAccountsCheckboxPreferences();
365 }
366
367 @Override
368 public boolean onCreateOptionsMenu(Menu menu) {
369 super.onCreateOptionsMenu(menu);
370 return true;
371 }
372
373 @Override
374 public boolean onMenuItemSelected(int featureId, MenuItem item) {
375 super.onMenuItemSelected(featureId, item);
376 Intent intent;
377
378 switch (item.getItemId()) {
379 case android.R.id.home:
380 intent = new Intent(getBaseContext(), FileDisplayActivity.class);
381 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
382 startActivity(intent);
383 break;
384 default:
385 Log_OC.w(TAG, "Unknown menu item triggered");
386 return false;
387 }
388 return true;
389 }
390
391 @Override
392 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
393 super.onActivityResult(requestCode, resultCode, data);
394 }
395
396 @Override
397 protected void onDestroy() {
398 mDbHandler.close();
399 super.onDestroy();
400 }
401
402 /**
403 * Create the list of accounts that has been added into the app
404 */
405 @SuppressWarnings("deprecation")
406 private void addAccountsCheckboxPreferences() {
407
408 // Remove accounts in case list is refreshing for avoiding to have
409 // duplicate items
410 if (mAccountsPrefCategory.getPreferenceCount() > 0) {
411 mAccountsPrefCategory.removeAll();
412 }
413
414 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
415 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
416 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
417
418 if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
419 // Show create account screen if there isn't any account
420 am.addAccount(MainApp.getAccountType(), null, null, null, this,
421 null,
422 null);
423 }
424 else {
425
426 for (Account a : accounts) {
427 LongClickableCheckBoxPreference accountPreference = new LongClickableCheckBoxPreference(this);
428 accountPreference.setKey(a.name);
429 accountPreference.setTitle(a.name);
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 * Update the upload path checking that it is a correct path
506 * @param uploadPath: path write by user
507 * @return String: uploadPath
508 */
509 private String updateInstantUploadPath(String uploadPath) {
510 String slashString = "/";
511
512 // If slashes are duplicated, replace them for only one slash
513 uploadPath = uploadPath.replaceAll("/+", slashString);
514
515 // Remove last slash from path
516 if (uploadPath.length() > 0 && uploadPath.charAt(uploadPath.length()-1) == slashString.charAt(0)) {
517 uploadPath = uploadPath.substring(0, uploadPath.length()-1);
518 }
519
520 if (uploadPath.isEmpty()) { // Set default instant upload path
521 uploadPath = getString(R.string.instant_upload_path);
522 }else {
523 if (!uploadPath.startsWith(slashString)) { // Add initial slash on path if necessary
524 uploadPath = slashString.concat(uploadPath);
525 }
526 }
527 return uploadPath;
528 }
529
530 /**
531 * Load upload path set on preferences
532 */
533 private void loadInstantUploadPath() {
534 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
535 mUploadPath = appPrefs.getString("instant_upload_path", getString(R.string.instant_upload_path));
536 }
537
538 /**
539 * Save the "Instant Upload Path" on preferences
540 */
541 private void saveInstantUploadPathOnPreferences() {
542 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
543 SharedPreferences.Editor editor = appPrefs.edit();
544 editor.putString("instant_upload_path", mUploadPath);
545 editor.commit();
546 }
547 }