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