PassCodeActivity.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. import java.util.Arrays;
  25. import android.content.Intent;
  26. import android.content.SharedPreferences;
  27. import android.os.Bundle;
  28. import android.preference.PreferenceManager;
  29. import android.support.v7.app.AppCompatActivity;
  30. import android.text.Editable;
  31. import android.text.TextWatcher;
  32. import android.view.KeyEvent;
  33. import android.view.View;
  34. import android.view.View.OnClickListener;
  35. import android.view.inputmethod.InputMethodManager;
  36. import android.widget.Button;
  37. import android.widget.EditText;
  38. import android.widget.TextView;
  39. import android.widget.Toast;
  40. import com.owncloud.android.R;
  41. import com.owncloud.android.lib.common.utils.Log_OC;
  42. public class PassCodeActivity extends AppCompatActivity {
  43. private static final String TAG = PassCodeActivity.class.getSimpleName();
  44. public final static String ACTION_REQUEST_WITH_RESULT = "ACTION_REQUEST_WITH_RESULT";
  45. public final static String ACTION_CHECK_WITH_RESULT = "ACTION_CHECK_WITH_RESULT";
  46. public final static String ACTION_CHECK = "ACTION_CHECK";
  47. public final static String KEY_PASSCODE = "KEY_PASSCODE";
  48. public final static String KEY_CHECK_RESULT = "KEY_CHECK_RESULT";
  49. // NOTE: PREFERENCE_SET_PASSCODE must have the same value as preferences.xml-->android:key for passcode preference
  50. public final static String PREFERENCE_SET_PASSCODE = "set_pincode";
  51. public final static String PREFERENCE_PASSCODE_D = "PrefPinCode";
  52. public final static String PREFERENCE_PASSCODE_D1 = "PrefPinCode1";
  53. public final static String PREFERENCE_PASSCODE_D2 = "PrefPinCode2";
  54. public final static String PREFERENCE_PASSCODE_D3 = "PrefPinCode3";
  55. public final static String PREFERENCE_PASSCODE_D4 = "PrefPinCode4";
  56. private Button mBCancel;
  57. private TextView mPassCodeHdr;
  58. private TextView mPassCodeHdrExplanation;
  59. private EditText[] mPassCodeEditTexts = new EditText[4];
  60. private String [] mPassCodeDigits = {"","","",""};
  61. private static final String KEY_PASSCODE_DIGITS = "PASSCODE_DIGITS";
  62. private boolean mConfirmingPassCode = false;
  63. private static final String KEY_CONFIRMING_PASSCODE = "CONFIRMING_PASSCODE";
  64. private boolean mBChange = true; // to control that only one blocks jump
  65. /**
  66. * Initializes the activity.
  67. *
  68. * An intent with a valid ACTION is expected; if none is found, an
  69. * {@link IllegalArgumentException} will be thrown.
  70. *
  71. * @param savedInstanceState Previously saved state - irrelevant in this case
  72. */
  73. protected void onCreate(Bundle savedInstanceState) {
  74. super.onCreate(savedInstanceState);
  75. setContentView(R.layout.passcodelock);
  76. mBCancel = (Button) findViewById(R.id.cancel);
  77. mPassCodeHdr = (TextView) findViewById(R.id.header);
  78. mPassCodeHdrExplanation = (TextView) findViewById(R.id.explanation);
  79. mPassCodeEditTexts[0] = (EditText) findViewById(R.id.txt0);
  80. mPassCodeEditTexts[0].requestFocus();
  81. getWindow().setSoftInputMode(
  82. android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
  83. mPassCodeEditTexts[1] = (EditText) findViewById(R.id.txt1);
  84. mPassCodeEditTexts[2] = (EditText) findViewById(R.id.txt2);
  85. mPassCodeEditTexts[3] = (EditText) findViewById(R.id.txt3);
  86. if (ACTION_CHECK.equals(getIntent().getAction())) {
  87. /// this is a pass code request; the user has to input the right value
  88. mPassCodeHdr.setText(R.string.pass_code_enter_pass_code);
  89. mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
  90. setCancelButtonEnabled(false); // no option to cancel
  91. } else if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) {
  92. if (savedInstanceState != null) {
  93. mConfirmingPassCode = savedInstanceState.getBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE);
  94. mPassCodeDigits = savedInstanceState.getStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS);
  95. }
  96. if(mConfirmingPassCode){
  97. //the app was in the passcodeconfirmation
  98. requestPassCodeConfirmation();
  99. }else{
  100. /// pass code preference has just been activated in Preferences;
  101. // will receive and confirm pass code value
  102. mPassCodeHdr.setText(R.string.pass_code_configure_your_pass_code);
  103. //mPassCodeHdr.setText(R.string.pass_code_enter_pass_code);
  104. // TODO choose a header, check iOS
  105. mPassCodeHdrExplanation.setVisibility(View.VISIBLE);
  106. setCancelButtonEnabled(true);
  107. }
  108. } else if (ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
  109. /// pass code preference has just been disabled in Preferences;
  110. // will confirm user knows pass code, then remove it
  111. mPassCodeHdr.setText(R.string.pass_code_remove_your_pass_code);
  112. mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
  113. setCancelButtonEnabled(true);
  114. } else {
  115. throw new IllegalArgumentException("A valid ACTION is needed in the Intent passed to "
  116. + TAG);
  117. }
  118. setTextListeners();
  119. }
  120. /**
  121. * Enables or disables the cancel button to allow the user interrupt the ACTION
  122. * requested to the activity.
  123. *
  124. * @param enabled 'True' makes the cancel button available, 'false' hides it.
  125. */
  126. protected void setCancelButtonEnabled(boolean enabled){
  127. if(enabled){
  128. mBCancel.setVisibility(View.VISIBLE);
  129. mBCancel.setOnClickListener(new OnClickListener() {
  130. @Override
  131. public void onClick(View v) {
  132. finish();
  133. }
  134. });
  135. } else {
  136. mBCancel.setVisibility(View.GONE);
  137. mBCancel.setVisibility(View.INVISIBLE);
  138. mBCancel.setOnClickListener(null);
  139. }
  140. }
  141. /**
  142. * Binds the appropiate listeners to the input boxes receiving each digit of the pass code.
  143. */
  144. protected void setTextListeners() {
  145. /// First input field
  146. mPassCodeEditTexts[0].addTextChangedListener(new PassCodeDigitTextWatcher(0, false));
  147. /*------------------------------------------------
  148. * SECOND BOX
  149. -------------------------------------------------*/
  150. mPassCodeEditTexts[1].addTextChangedListener(new PassCodeDigitTextWatcher(1, false));
  151. mPassCodeEditTexts[1].setOnKeyListener(new View.OnKeyListener() {
  152. @Override
  153. public boolean onKey(View v, int keyCode, KeyEvent event) {
  154. if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) { // TODO WIP: event should be
  155. // used to control what's exactly happening with DEL, not any custom field...
  156. mPassCodeEditTexts[0].setText("");
  157. mPassCodeEditTexts[0].requestFocus();
  158. if (!mConfirmingPassCode) {
  159. mPassCodeDigits[0] = "";
  160. }
  161. mBChange = false;
  162. } else if (!mBChange) {
  163. mBChange = true;
  164. }
  165. return false;
  166. }
  167. });
  168. mPassCodeEditTexts[1].setOnFocusChangeListener(new View.OnFocusChangeListener() {
  169. @Override
  170. public void onFocusChange(View v, boolean hasFocus) {
  171. /// TODO WIP: should take advantage of hasFocus to reduce processing
  172. if (mPassCodeEditTexts[0].getText().toString().equals("")) { // TODO WIP validation
  173. // could be done in a global way, with a single OnFocusChangeListener for all the
  174. // input fields
  175. mPassCodeEditTexts[0].requestFocus();
  176. }
  177. }
  178. });
  179. /*------------------------------------------------
  180. * THIRD BOX
  181. -------------------------------------------------*/
  182. mPassCodeEditTexts[2].addTextChangedListener(new PassCodeDigitTextWatcher(2, false));
  183. mPassCodeEditTexts[2].setOnKeyListener(new View.OnKeyListener() {
  184. @Override
  185. public boolean onKey(View v, int keyCode, KeyEvent event) {
  186. if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) {
  187. mPassCodeEditTexts[1].requestFocus();
  188. if (!mConfirmingPassCode) {
  189. mPassCodeDigits[1] = "";
  190. }
  191. mPassCodeEditTexts[1].setText("");
  192. mBChange = false;
  193. } else if (!mBChange) {
  194. mBChange = true;
  195. }
  196. return false;
  197. }
  198. });
  199. mPassCodeEditTexts[2].setOnFocusChangeListener(new View.OnFocusChangeListener() {
  200. @Override
  201. public void onFocusChange(View v, boolean hasFocus) {
  202. if (mPassCodeEditTexts[0].getText().toString().equals("")) {
  203. mPassCodeEditTexts[0].requestFocus();
  204. } else if (mPassCodeEditTexts[1].getText().toString().equals("")) {
  205. mPassCodeEditTexts[1].requestFocus();
  206. }
  207. }
  208. });
  209. /*------------------------------------------------
  210. * FOURTH BOX
  211. -------------------------------------------------*/
  212. mPassCodeEditTexts[3].addTextChangedListener(new PassCodeDigitTextWatcher(3, true));
  213. mPassCodeEditTexts[3].setOnKeyListener(new View.OnKeyListener() {
  214. @Override
  215. public boolean onKey(View v, int keyCode, KeyEvent event) {
  216. if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) {
  217. mPassCodeEditTexts[2].requestFocus();
  218. if (!mConfirmingPassCode) {
  219. mPassCodeDigits[2] = "";
  220. }
  221. mPassCodeEditTexts[2].setText("");
  222. mBChange = false;
  223. } else if (!mBChange) {
  224. mBChange = true;
  225. }
  226. return false;
  227. }
  228. });
  229. mPassCodeEditTexts[3].setOnFocusChangeListener(new View.OnFocusChangeListener() {
  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. } else if (mPassCodeEditTexts[2].getText().toString().equals("")) {
  237. mPassCodeEditTexts[2].requestFocus();
  238. }
  239. }
  240. });
  241. } // end setTextListener
  242. /**
  243. * Processes the pass code entered by the user just after the last digit was in.
  244. *
  245. * Takes into account the action requested to the activity, the currently saved pass code and
  246. * the previously typed pass code, if any.
  247. */
  248. private void processFullPassCode() {
  249. if (ACTION_CHECK.equals(getIntent().getAction())) {
  250. if (checkPassCode()) {
  251. /// pass code accepted in request, user is allowed to access the app
  252. hideSoftKeyboard();
  253. finish();
  254. } else {
  255. showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code,
  256. View.INVISIBLE);
  257. }
  258. } else if (ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
  259. if (checkPassCode()) {
  260. Intent resultIntent = new Intent();
  261. resultIntent.putExtra(KEY_CHECK_RESULT, true);
  262. setResult(RESULT_OK, resultIntent);
  263. hideSoftKeyboard();
  264. finish();
  265. } else {
  266. showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code,
  267. View.INVISIBLE);
  268. }
  269. } else if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) {
  270. /// enabling pass code
  271. if (!mConfirmingPassCode) {
  272. requestPassCodeConfirmation();
  273. } else if (confirmPassCode()) {
  274. /// confirmed: user typed the same pass code twice
  275. savePassCodeAndExit();
  276. } else {
  277. showErrorAndRestart(
  278. R.string.pass_code_mismatch, R.string.pass_code_configure_your_pass_code, View.VISIBLE
  279. );
  280. }
  281. }
  282. }
  283. private void hideSoftKeyboard() {
  284. View focusedView = getCurrentFocus();
  285. if (focusedView != null) {
  286. InputMethodManager inputMethodManager =
  287. (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
  288. inputMethodManager.hideSoftInputFromWindow(
  289. focusedView.getWindowToken(),
  290. 0
  291. );
  292. }
  293. }
  294. private void showErrorAndRestart(int errorMessage, int headerMessage,
  295. int explanationVisibility) {
  296. Arrays.fill(mPassCodeDigits, null);
  297. CharSequence errorSeq = getString(errorMessage);
  298. Toast.makeText(this, errorSeq, Toast.LENGTH_LONG).show();
  299. mPassCodeHdr.setText(headerMessage); // TODO check if really needed
  300. mPassCodeHdrExplanation.setVisibility(explanationVisibility); // TODO check if really needed
  301. clearBoxes();
  302. }
  303. /**
  304. * Ask to the user for retyping the pass code just entered before saving it as the current pass
  305. * code.
  306. */
  307. protected void requestPassCodeConfirmation(){
  308. clearBoxes();
  309. mPassCodeHdr.setText(R.string.pass_code_reenter_your_pass_code);
  310. mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
  311. mConfirmingPassCode = true;
  312. }
  313. /**
  314. * Compares pass code entered by the user with the value currently saved in the app.
  315. *
  316. * @return 'True' if entered pass code equals to the saved one.
  317. */
  318. protected boolean checkPassCode(){
  319. SharedPreferences appPrefs = PreferenceManager
  320. .getDefaultSharedPreferences(getApplicationContext());
  321. String savedPassCodeDigits[] = new String[4];
  322. savedPassCodeDigits[0] = appPrefs.getString(PREFERENCE_PASSCODE_D1, null);
  323. savedPassCodeDigits[1] = appPrefs.getString(PREFERENCE_PASSCODE_D2, null);
  324. savedPassCodeDigits[2] = appPrefs.getString(PREFERENCE_PASSCODE_D3, null);
  325. savedPassCodeDigits[3] = appPrefs.getString(PREFERENCE_PASSCODE_D4, null);
  326. boolean result = true;
  327. for (int i = 0; i < mPassCodeDigits.length && result; i++) {
  328. result = (mPassCodeDigits[i] != null) &&
  329. mPassCodeDigits[i].equals(savedPassCodeDigits[i]);
  330. }
  331. return result;
  332. }
  333. /**
  334. * Compares pass code retyped by the user in the input fields with the value entered just
  335. * before.
  336. *
  337. * @return 'True' if retyped pass code equals to the entered before.
  338. */
  339. protected boolean confirmPassCode(){
  340. mConfirmingPassCode = false;
  341. boolean result = true;
  342. for (int i = 0; i < mPassCodeEditTexts.length && result; i++) {
  343. result = ((mPassCodeEditTexts[i].getText().toString()).equals(mPassCodeDigits[i]));
  344. }
  345. return result;
  346. }
  347. /**
  348. * Sets the input fields to empty strings and puts the focus on the first one.
  349. */
  350. protected void clearBoxes(){
  351. for (int i=0; i < mPassCodeEditTexts.length; i++) {
  352. mPassCodeEditTexts[i].setText("");
  353. }
  354. mPassCodeEditTexts[0].requestFocus();
  355. }
  356. /**
  357. * Overrides click on the BACK arrow to correctly cancel ACTION_ENABLE or ACTION_DISABLE, while
  358. * preventing than ACTION_CHECK may be worked around.
  359. *
  360. * @param keyCode Key code of the key that triggered the down event.
  361. * @param event Event triggered.
  362. * @return 'True' when the key event was processed by this method.
  363. */
  364. @Override
  365. public boolean onKeyDown(int keyCode, KeyEvent event){
  366. if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()== 0){
  367. if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction()) ||
  368. ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
  369. finish();
  370. } // else, do nothing, but report that the key was consumed to stay alive
  371. return true;
  372. }
  373. return super.onKeyDown(keyCode, event);
  374. }
  375. /**
  376. * Saves the pass code input by the user as the current pass code.
  377. */
  378. protected void savePassCodeAndExit() {
  379. Intent resultIntent = new Intent();
  380. resultIntent.putExtra(KEY_PASSCODE,
  381. mPassCodeDigits[0] + mPassCodeDigits[1] + mPassCodeDigits[2] + mPassCodeDigits[3]);
  382. setResult(RESULT_OK, resultIntent);
  383. finish();
  384. }
  385. @Override
  386. public void onSaveInstanceState(Bundle outState) {
  387. super.onSaveInstanceState(outState);
  388. outState.putBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE, mConfirmingPassCode);
  389. outState.putStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS, mPassCodeDigits);
  390. }
  391. private class PassCodeDigitTextWatcher implements TextWatcher {
  392. private int mIndex = -1;
  393. private boolean mLastOne = false;
  394. /**
  395. * Constructor
  396. *
  397. * @param index Position in the pass code of the input field that will be bound to
  398. * this watcher.
  399. * @param lastOne 'True' means that watcher corresponds to the last position of the
  400. * pass code.
  401. */
  402. public PassCodeDigitTextWatcher(int index, boolean lastOne) {
  403. mIndex = index;
  404. mLastOne = lastOne;
  405. if (mIndex < 0) {
  406. throw new IllegalArgumentException(
  407. "Invalid index in " + PassCodeDigitTextWatcher.class.getSimpleName() +
  408. " constructor"
  409. );
  410. }
  411. }
  412. private int next() {
  413. return mLastOne ? 0 : mIndex + 1;
  414. }
  415. /**
  416. * Performs several actions when the user types a digit in an input field:
  417. * - saves the input digit to the state of the activity; this will allow retyping the
  418. * pass code to confirm it.
  419. * - moves the focus automatically to the next field
  420. * - for the last field, triggers the processing of the full pass code
  421. *
  422. * @param s Changed text
  423. */
  424. @Override
  425. public void afterTextChanged(Editable s) {
  426. if (s.length() > 0) {
  427. if (!mConfirmingPassCode) {
  428. mPassCodeDigits[mIndex] = mPassCodeEditTexts[mIndex].getText().toString();
  429. }
  430. mPassCodeEditTexts[next()].requestFocus();
  431. if (mLastOne) {
  432. processFullPassCode();
  433. }
  434. } else {
  435. Log_OC.d(TAG, "Text box " + mIndex + " was cleaned");
  436. }
  437. }
  438. @Override
  439. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  440. // nothing to do
  441. }
  442. @Override
  443. public void onTextChanged(CharSequence s, int start, int before, int count) {
  444. // nothing to do
  445. }
  446. }
  447. }