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