Merge branch 'develop' of https://github.com/owncloud/android into material_toolbar
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / PassCodeActivity.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Bartek Przybylski
5 * @author masensio
6 * @author David A. Velasco
7 * Copyright (C) 2011 Bartek Przybylski
8 * Copyright (C) 2015 ownCloud Inc.
9 *
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2,
12 * as published by the Free Software Foundation.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 */
23 package com.owncloud.android.ui.activity;
24
25 import java.util.Arrays;
26
27 import android.content.SharedPreferences;
28 import android.os.Bundle;
29 import android.preference.PreferenceManager;
30 import android.support.v7.app.ActionBar;
31 import android.support.v7.app.ActionBarActivity;
32 import android.text.Editable;
33 import android.text.TextWatcher;
34 import android.view.KeyEvent;
35 import android.view.View;
36 import android.view.View.OnClickListener;
37 import android.widget.Button;
38 import android.widget.EditText;
39 import android.widget.TextView;
40 import android.widget.Toast;
41
42 import com.owncloud.android.R;
43 import com.owncloud.android.lib.common.utils.Log_OC;
44 import com.owncloud.android.utils.DisplayUtils;
45
46 public class PassCodeActivity extends ActionBarActivity {
47
48
49 private static final String TAG = PassCodeActivity.class.getSimpleName();
50
51 public final static String ACTION_ENABLE = PassCodeActivity.class.getCanonicalName() +
52 ".ENABLE";
53 public final static String ACTION_DISABLE = PassCodeActivity.class.getCanonicalName() +
54 ".DISABLE";
55 public final static String ACTION_REQUEST = PassCodeActivity.class.getCanonicalName() +
56 ".REQUEST";
57
58 private Button mBCancel;
59 private TextView mPassCodeHdr;
60 private TextView mPassCodeHdrExplanation;
61 private EditText[] mPassCodeEditTexts = new EditText[4];
62
63 private String [] mPassCodeDigits = {"","","",""};
64 private static String KEY_PASSCODE_DIGITS = "PASSCODE_DIGITS";
65 private boolean mConfirmingPassCode = false;
66 private static String KEY_CONFIRMING_PASSCODE = "CONFIRMING_PASSCODE";
67
68 private boolean mBChange = true; // to control that only one blocks jump
69
70
71 /**
72 * Initializes the activity.
73 *
74 * An intent with a valid ACTION is expected; if none is found, an
75 * {@link IllegalArgumentException} will be thrown.
76 *
77 * @param savedInstanceState Previously saved state - irrelevant in this case
78 */
79 protected void onCreate(Bundle savedInstanceState) {
80 super.onCreate(savedInstanceState);
81 setContentView(R.layout.passcodelock);
82
83 mBCancel = (Button) findViewById(R.id.cancel);
84 mPassCodeHdr = (TextView) findViewById(R.id.header);
85 mPassCodeHdrExplanation = (TextView) findViewById(R.id.explanation);
86 mPassCodeEditTexts[0] = (EditText) findViewById(R.id.txt0);
87 mPassCodeEditTexts[0].requestFocus();
88 getWindow().setSoftInputMode(
89 android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
90 mPassCodeEditTexts[1] = (EditText) findViewById(R.id.txt1);
91 mPassCodeEditTexts[2] = (EditText) findViewById(R.id.txt2);
92 mPassCodeEditTexts[3] = (EditText) findViewById(R.id.txt3);
93
94 if (ACTION_REQUEST.equals(getIntent().getAction())) {
95 /// this is a pass code request; the user has to input the right value
96 mPassCodeHdr.setText(R.string.pass_code_enter_pass_code);
97 mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
98 setCancelButtonEnabled(false); // no option to cancel
99
100 } else if (ACTION_ENABLE.equals(getIntent().getAction())) {
101 if (savedInstanceState != null) {
102 mConfirmingPassCode = savedInstanceState.getBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE);
103 mPassCodeDigits = savedInstanceState.getStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS);
104 }
105 if(mConfirmingPassCode){
106 //the app was in the passcodeconfirmation
107 requestPassCodeConfirmation();
108 }else{
109 /// pass code preference has just been activated in Preferences;
110 // will receive and confirm pass code value
111 mPassCodeHdr.setText(R.string.pass_code_configure_your_pass_code);
112 //mPassCodeHdr.setText(R.string.pass_code_enter_pass_code);
113 // TODO choose a header, check iOS
114 mPassCodeHdrExplanation.setVisibility(View.VISIBLE);
115 setCancelButtonEnabled(true);
116 }
117
118 } else if (ACTION_DISABLE.equals(getIntent().getAction())) {
119 /// pass code preference has just been disabled in Preferences;
120 // will confirm user knows pass code, then remove it
121 mPassCodeHdr.setText(R.string.pass_code_remove_your_pass_code);
122 mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
123 setCancelButtonEnabled(true);
124
125 } else {
126 throw new IllegalArgumentException("A valid ACTION is needed in the Intent passed to "
127 + TAG);
128 }
129
130 setTextListeners();
131 }
132
133
134 /**
135 * Enables or disables the cancel button to allow the user interrupt the ACTION
136 * requested to the activity.
137 *
138 * @param enabled 'True' makes the cancel button available, 'false' hides it.
139 */
140 protected void setCancelButtonEnabled(boolean enabled){
141 if(enabled){
142 mBCancel.setVisibility(View.VISIBLE);
143 mBCancel.setOnClickListener(new OnClickListener() {
144 @Override
145 public void onClick(View v) {
146 revertActionAndExit();
147 }
148 });
149 } else {
150 mBCancel.setVisibility(View.GONE);
151 mBCancel.setVisibility(View.INVISIBLE);
152 mBCancel.setOnClickListener(null);
153 }
154 }
155
156
157 /**
158 * Binds the appropiate listeners to the input boxes receiving each digit of the pass code.
159 */
160 protected void setTextListeners() {
161
162 /// First input field
163 mPassCodeEditTexts[0].addTextChangedListener(new PassCodeDigitTextWatcher(0, false));
164
165
166 /*------------------------------------------------
167 * SECOND BOX
168 -------------------------------------------------*/
169 mPassCodeEditTexts[1].addTextChangedListener(new PassCodeDigitTextWatcher(1, false));
170
171 mPassCodeEditTexts[1].setOnKeyListener(new View.OnKeyListener() {
172
173 @Override
174 public boolean onKey(View v, int keyCode, KeyEvent event) {
175 if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) { // TODO WIP: event should be
176 // used to control what's exactly happening with DEL, not any custom field...
177 mPassCodeEditTexts[0].setText("");
178 mPassCodeEditTexts[0].requestFocus();
179 if (!mConfirmingPassCode)
180 mPassCodeDigits[0] = "";
181 mBChange = false;
182
183 } else if (!mBChange) {
184 mBChange = true;
185 }
186 return false;
187 }
188 });
189
190 mPassCodeEditTexts[1].setOnFocusChangeListener(new View.OnFocusChangeListener() {
191
192 @Override
193 public void onFocusChange(View v, boolean hasFocus) {
194 /// TODO WIP: should take advantage of hasFocus to reduce processing
195 if (mPassCodeEditTexts[0].getText().toString().equals("")) { // TODO WIP validation
196 // could be done in a global way, with a single OnFocusChangeListener for all the
197 // input fields
198 mPassCodeEditTexts[0].requestFocus();
199 }
200 }
201 });
202
203
204 /*------------------------------------------------
205 * THIRD BOX
206 -------------------------------------------------*/
207 mPassCodeEditTexts[2].addTextChangedListener(new PassCodeDigitTextWatcher(2, false));
208
209 mPassCodeEditTexts[2].setOnKeyListener(new View.OnKeyListener() {
210
211 @Override
212 public boolean onKey(View v, int keyCode, KeyEvent event) {
213 if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) {
214 mPassCodeEditTexts[1].requestFocus();
215 if (!mConfirmingPassCode)
216 mPassCodeDigits[1] = "";
217 mPassCodeEditTexts[1].setText("");
218 mBChange = false;
219
220 } else if (!mBChange) {
221 mBChange = true;
222
223 }
224 return false;
225 }
226 });
227
228 mPassCodeEditTexts[2].setOnFocusChangeListener(new View.OnFocusChangeListener() {
229
230 @Override
231 public void onFocusChange(View v, boolean hasFocus) {
232 if (mPassCodeEditTexts[0].getText().toString().equals("")) {
233 mPassCodeEditTexts[0].requestFocus();
234 } else if (mPassCodeEditTexts[1].getText().toString().equals("")) {
235 mPassCodeEditTexts[1].requestFocus();
236 }
237 }
238 });
239
240
241 /*------------------------------------------------
242 * FOURTH BOX
243 -------------------------------------------------*/
244 mPassCodeEditTexts[3].addTextChangedListener(new PassCodeDigitTextWatcher(3, true));
245
246 mPassCodeEditTexts[3].setOnKeyListener(new View.OnKeyListener() {
247
248 @Override
249 public boolean onKey(View v, int keyCode, KeyEvent event) {
250 if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) {
251 mPassCodeEditTexts[2].requestFocus();
252 if (!mConfirmingPassCode)
253 mPassCodeDigits[2] = "";
254 mPassCodeEditTexts[2].setText("");
255 mBChange = false;
256
257 } else if (!mBChange) {
258 mBChange = true;
259 }
260 return false;
261 }
262 });
263
264 mPassCodeEditTexts[3].setOnFocusChangeListener(new View.OnFocusChangeListener() {
265
266 @Override
267 public void onFocusChange(View v, boolean hasFocus) {
268
269 if (mPassCodeEditTexts[0].getText().toString().equals("")) {
270 mPassCodeEditTexts[0].requestFocus();
271 } else if (mPassCodeEditTexts[1].getText().toString().equals("")) {
272 mPassCodeEditTexts[1].requestFocus();
273 } else if (mPassCodeEditTexts[2].getText().toString().equals("")) {
274 mPassCodeEditTexts[2].requestFocus();
275 }
276
277 }
278 });
279
280 } // end setTextListener
281
282
283 /**
284 * Processes the pass code entered by the user just after the last digit was in.
285 *
286 * Takes into account the action requested to the activity, the currently saved pass code and
287 * the previously typed pass code, if any.
288 */
289 private void processFullPassCode() {
290 if (ACTION_REQUEST.equals(getIntent().getAction())) {
291 if (checkPassCode()) {
292 /// pass code accepted in request, user is allowed to access the app
293 finish();
294
295 } else {
296 showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code,
297 View.INVISIBLE);
298 }
299
300 } else if (ACTION_DISABLE.equals(getIntent().getAction())) {
301 if (checkPassCode()) {
302 /// pass code accepted when disabling, pass code is removed
303 SharedPreferences.Editor appPrefs = PreferenceManager
304 .getDefaultSharedPreferences(getApplicationContext()).edit();
305 appPrefs.putBoolean("set_pincode", false); // TODO remove; this should be
306 // unnecessary, was done before entering in the activity
307 appPrefs.commit();
308
309 Toast.makeText(PassCodeActivity.this, R.string.pass_code_removed, Toast.LENGTH_LONG).show();
310 finish();
311
312 } else {
313 showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code,
314 View.INVISIBLE);
315 }
316
317 } else if (ACTION_ENABLE.equals(getIntent().getAction())) {
318 /// enabling pass code
319 if (!mConfirmingPassCode) {
320 requestPassCodeConfirmation();
321
322 } else if (confirmPassCode()) {
323 /// confirmed: user typed the same pass code twice
324 savePassCodeAndExit();
325
326 } else {
327 showErrorAndRestart(
328 R.string.pass_code_mismatch, R.string.pass_code_configure_your_pass_code, View.VISIBLE
329 );
330 }
331 }
332 }
333
334
335 private void showErrorAndRestart(int errorMessage, int headerMessage,
336 int explanationVisibility) {
337 Arrays.fill(mPassCodeDigits, null);
338 CharSequence errorSeq = getString(errorMessage);
339 Toast.makeText(this, errorSeq, Toast.LENGTH_LONG).show();
340 mPassCodeHdr.setText(headerMessage); // TODO check if really needed
341 mPassCodeHdrExplanation.setVisibility(explanationVisibility); // TODO check if really needed
342 clearBoxes();
343 }
344
345
346 /**
347 * Ask to the user for retyping the pass code just entered before saving it as the current pass
348 * code.
349 */
350 protected void requestPassCodeConfirmation(){
351 clearBoxes();
352 mPassCodeHdr.setText(R.string.pass_code_reenter_your_pass_code);
353 mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
354 mConfirmingPassCode = true;
355 }
356
357 /**
358 * Compares pass code entered by the user with the value currently saved in the app.
359 *
360 * @return 'True' if entered pass code equals to the saved one.
361 */
362 protected boolean checkPassCode(){
363 SharedPreferences appPrefs = PreferenceManager
364 .getDefaultSharedPreferences(getApplicationContext());
365
366 String savedPassCodeDigits[] = new String[4];
367 savedPassCodeDigits[0] = appPrefs.getString("PrefPinCode1", null);
368 savedPassCodeDigits[1] = appPrefs.getString("PrefPinCode2", null);
369 savedPassCodeDigits[2] = appPrefs.getString("PrefPinCode3", null);
370 savedPassCodeDigits[3] = appPrefs.getString("PrefPinCode4", null);
371
372 boolean result = true;
373 for (int i = 0; i < mPassCodeDigits.length && result; i++) {
374 result = result && (mPassCodeDigits[i] != null) &&
375 mPassCodeDigits[i].equals(savedPassCodeDigits[i]);
376 }
377 return result;
378 }
379
380 /**
381 * Compares pass code retyped by the user in the input fields with the value entered just
382 * before.
383 *
384 * @return 'True' if retyped pass code equals to the entered before.
385 */
386 protected boolean confirmPassCode(){
387 mConfirmingPassCode = false;
388
389 boolean result = true;
390 for (int i = 0; i < mPassCodeEditTexts.length && result; i++) {
391 result = result &&
392 ((mPassCodeEditTexts[i].getText().toString()).equals(mPassCodeDigits[i]));
393 }
394 return result;
395 }
396
397 /**
398 * Sets the input fields to empty strings and puts the focus on the first one.
399 */
400 protected void clearBoxes(){
401 for (int i=0; i < mPassCodeEditTexts.length; i++) {
402 mPassCodeEditTexts[i].setText("");
403 }
404 mPassCodeEditTexts[0].requestFocus();
405 }
406
407 /**
408 * Overrides click on the BACK arrow to correctly cancel ACTION_ENABLE or ACTION_DISABLE, while
409 * preventing than ACTION_REQUEST may be worked around.
410 *
411 * @param keyCode Key code of the key that triggered the down event.
412 * @param event Event triggered.
413 * @return 'True' when the key event was processed by this method.
414 */
415 @Override
416 public boolean onKeyDown(int keyCode, KeyEvent event){
417 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()== 0){
418 if (ACTION_ENABLE.equals(getIntent().getAction()) ||
419 ACTION_DISABLE.equals(getIntent().getAction())) {
420 revertActionAndExit();
421 }
422 return true;
423 }
424 return super.onKeyDown(keyCode, event);
425 }
426
427 /**
428 * Saves the pass code input by the user as the current pass code.
429 */
430 protected void savePassCodeAndExit() {
431 SharedPreferences.Editor appPrefs = PreferenceManager
432 .getDefaultSharedPreferences(getApplicationContext()).edit();
433
434 appPrefs.putString("PrefPinCode1", mPassCodeDigits[0]);
435 appPrefs.putString("PrefPinCode2", mPassCodeDigits[1]);
436 appPrefs.putString("PrefPinCode3", mPassCodeDigits[2]);
437 appPrefs.putString("PrefPinCode4", mPassCodeDigits[3]);
438 appPrefs.putBoolean("set_pincode", true); /// TODO remove; unnecessary,
439 // Preferences did it before entering here
440 appPrefs.commit();
441
442 Toast.makeText(this, R.string.pass_code_stored, Toast.LENGTH_LONG).show();
443 finish();
444 }
445
446 /**
447 * Cancellation of ACTION_ENABLE or ACTION_DISABLE; reverts the enable or disable action done by
448 * {@link Preferences}, then finishes.
449 */
450 protected void revertActionAndExit() {
451 SharedPreferences.Editor appPrefsE = PreferenceManager
452 .getDefaultSharedPreferences(getApplicationContext()).edit();
453
454 SharedPreferences appPrefs = PreferenceManager
455 .getDefaultSharedPreferences(getApplicationContext());
456
457 boolean state = appPrefs.getBoolean("set_pincode", false);
458 appPrefsE.putBoolean("set_pincode", !state);
459 // TODO WIP: this is reverting the value of the preference because it was changed BEFORE
460 // entering
461 // TODO in this activity; was the PreferenceCheckBox in the caller who did it
462 appPrefsE.commit();
463 finish();
464 }
465
466 @Override
467 public void onSaveInstanceState(Bundle outState) {
468 super.onSaveInstanceState(outState);
469 outState.putBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE, mConfirmingPassCode);
470 outState.putStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS, mPassCodeDigits);
471 }
472
473
474 private class PassCodeDigitTextWatcher implements TextWatcher {
475
476 private int mIndex = -1;
477 private boolean mLastOne = false;
478
479 /**
480 * Constructor
481 *
482 * @param index Position in the pass code of the input field that will be bound to
483 * this watcher.
484 * @param lastOne 'True' means that watcher corresponds to the last position of the
485 * pass code.
486 */
487 public PassCodeDigitTextWatcher(int index, boolean lastOne) {
488 mIndex = index;
489 mLastOne = lastOne;
490 if (mIndex < 0) {
491 throw new IllegalArgumentException(
492 "Invalid index in " + PassCodeDigitTextWatcher.class.getSimpleName() +
493 " constructor"
494 );
495 }
496 }
497
498 private int next() {
499 return mLastOne ? 0 : mIndex + 1;
500 }
501
502 /**
503 * Performs several actions when the user types a digit in an input field:
504 * - saves the input digit to the state of the activity; this will allow retyping the
505 * pass code to confirm it.
506 * - moves the focus automatically to the next field
507 * - for the last field, triggers the processing of the full pass code
508 *
509 * @param s
510 */
511 @Override
512 public void afterTextChanged(Editable s) {
513 if (s.length() > 0) {
514 if (!mConfirmingPassCode) {
515 mPassCodeDigits[mIndex] = mPassCodeEditTexts[mIndex].getText().toString();
516 }
517 mPassCodeEditTexts[next()].requestFocus();
518
519 if (mLastOne) {
520 processFullPassCode();
521 }
522
523 } else {
524 Log_OC.d(TAG, "Text box " + mIndex + " was cleaned");
525 }
526 }
527
528 @Override
529 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
530 // nothing to do
531 }
532
533 @Override
534 public void onTextChanged(CharSequence s, int start, int before, int count) {
535 // nothing to do
536 }
537
538 }
539
540
541 }