PassCodeActivity.java 21 KB

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