private void populateSecondForm(LinearLayout formLayout) {
    formLayout.addView(createTitle(mContext.getString(R.string.account_create_password_title)));
    EditText passwordEditText =
        createEditText(
            mContext.getString(R.string.account_create_password_hint),
            InputType.TYPE_CLASS_TEXT,
            EditorInfo.IME_ACTION_DONE,
            false,
            PASSWORD_KEY);
    passwordEditText.setTransformationMethod(new PasswordTransformationMethod());

    formLayout.addView(passwordEditText);
    formLayout.addView(createErrorView(PASSWORD_KEY));

    formLayout.addView(createTitle(mContext.getString(R.string.account_create_gender_title)));
    Spinner spinner = new Spinner(mContext);
    LinearLayout.LayoutParams params =
        new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    params.bottomMargin = 17;
    spinner.setLayoutParams(params);

    final ArrayAdapter<CharSequence> adapter =
        ArrayAdapter.createFromResource(
            mContext, R.array.sexes_array, android.R.layout.simple_spinner_item);
    spinner.setAdapter(adapter);
    spinner.setPrompt(mContext.getString(R.string.account_create_sex_spinner_prompt));
    spinner.setOnItemSelectedListener(
        new OnItemSelectedListener() {

          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

            mFormData.put(GENDER_KEY, adapter.getItem(pos).toString());
          }

          @Override
          public void onNothingSelected(AdapterView<?> arg0) {}
        });

    if (mFormData.get(GENDER_KEY) != null) {
      spinner.setSelection(adapter.getPosition(mFormData.get(GENDER_KEY)));
    }

    formLayout.addView(spinner);
  }
 private void showPassword() {
   if (isShown) {
     passwordEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
   } else {
     passwordEdit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
   }
   isShown = !isShown;
   if (isShown) {
     showPassword.setImageResource(R.drawable.ic_hide);
   } else {
     showPassword.setImageResource(R.drawable.ic_show);
   }
 }
Beispiel #3
0
 public void showHidePassword(View view) {
   switch (view.getId()) {
     case R.id.login_show_button:
       showPasswordImgButton.setVisibility(View.GONE);
       hidePasswordImgButton.setVisibility(View.VISIBLE);
       passwordLogin.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
       break;
     case R.id.login_hide_button:
       hidePasswordImgButton.setVisibility(View.GONE);
       showPasswordImgButton.setVisibility(View.VISIBLE);
       passwordLogin.setTransformationMethod(PasswordTransformationMethod.getInstance());
       break;
   }
 }
Beispiel #4
0
  public void requestPassword(final Bundle savedInstanceState) {
    mPasswordView = new EditText(this);
    mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
    mPasswordView.setTransformationMethod(new PasswordTransformationMethod());

    AlertDialog alert = mAlertBuilder.create();
    alert.setTitle(R.string.enter_password);
    alert.setView(mPasswordView);
    alert.setButton(
        AlertDialog.BUTTON_POSITIVE,
        getString(R.string.okay),
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            if (core.authenticatePassword(mPasswordView.getText().toString())) {
              createUI(savedInstanceState);
            } else {
              requestPassword(savedInstanceState);
            }
          }
        });
    alert.setButton(
        AlertDialog.BUTTON_NEGATIVE,
        getString(R.string.cancel),
        new DialogInterface.OnClickListener() {

          public void onClick(DialogInterface dialog, int which) {
            finish();
          }
        });
    alert.show();
  }
 private void initControls() {
   // init
   mContainer = (RelativeLayout) findViewById(R.id.activity_scan_code_capture_containter);
   mCropLayout = (RelativeLayout) findViewById(R.id.activity_scan_code_capture_crop_layout);
   mEditOrder = (EditText) findViewById(R.id.activity_scan_code_et_bar_code);
   Button mBtnAddOrder = (Button) findViewById(R.id.activity_scan_code_bt_add);
   Button mBtnLookOrder = (Button) findViewById(R.id.activity_scan_code_bt_look);
   Button mBtnOrderComplete = (Button) findViewById(R.id.activity_scan_code_bt_complete);
   mTextScanCount = (TextView) findViewById(R.id.activity_scan_code_tv_scan_order_count);
   mTextOrderNum = (TextView) findViewById(R.id.activity_scan_code_tv_scan_order_number);
   TextView mTextTitle = (TextView) findViewById(R.id.common_view_title_text);
   ImageView mImgBack = (ImageView) findViewById(R.id.common_view_title_img);
   mImgFlash = (ImageView) findViewById(R.id.common_view_title_img_menu);
   // init ui data;
   mEditOrder.setHint(String.format(getString(R.string.barcode_hint), PreferencesUtil.ordtitle));
   mEditOrder.setTransformationMethod(new AllCapTransformationMethod());
   mEditOrder.setKeyListener(new MyNumberKeyListener());
   mBtnLookOrder.setText(
       String.format(getString(R.string.barcode_record), PreferencesUtil.ordtitle));
   mTextTitle.setText(mNewOrder.getBtnname());
   mImgFlash.setVisibility(View.VISIBLE);
   LayoutParams lp = mImgFlash.getLayoutParams();
   lp.width = UtilsAndroid.UI.dip2px(this, 40);
   lp.height = UtilsAndroid.UI.dip2px(this, 40);
   mImgFlash.setLayoutParams(lp);
   mImgFlash.setImageResource(R.drawable.flash_light_white);
   mTextScanCount.setText(
       String.format(getString(R.string.barcode_total), PreferencesUtil.ordtitle, 0));
   // init ui listener;
   mImgBack.setOnClickListener(this);
   mBtnAddOrder.setOnClickListener(this);
   mImgFlash.setOnClickListener(this);
   mBtnLookOrder.setOnClickListener(this);
   mBtnOrderComplete.setOnClickListener(this);
 }
  private void obterSenha() {
    final String saida = "";
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    Resources res = getResources();

    alert.setMessage(res.getString(R.string.msg_informar_senha_backup));

    // Set an EditText view to get user input
    final EditText input = new EditText(this.getApplicationContext());
    input.setTransformationMethod(android.text.method.PasswordTransformationMethod.getInstance());
    alert.setView(input);

    alert.setPositiveButton(
        res.getString(R.string.opc_ok),
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            Editable value = input.getText();
            comandarRestaurar(value.toString());
          }
        });

    alert.setNegativeButton(
        res.getString(R.string.opc_cancelar),
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            // Canceled.
          }
        });

    alert.show();
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    //
    //	this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.main_login);

    mEtAccount = (EditText) findViewById(R.id.mainLoginEditAccount);
    mEtPassword = (EditText) findViewById(R.id.mainLoginEditPassword);
    mBtnLogin = (Button) findViewById(R.id.mainLoginBtn);
    mBtnRegister = (Button) findViewById(R.id.main_btn_register);

    /* this is to render the password edittext font to be default */
    mEtPassword.setTypeface(Typeface.DEFAULT);
    mEtPassword.setTransformationMethod(new PasswordTransformationMethod());

    mBtnLogin.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            MainActivity.this.tryLogin();
          }
        });

    mBtnRegister.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            Intent intent0 = new Intent(MainActivity.this, RegisterActivity.class);
            startActivity(intent0);
          }
        });
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.facebook_login_ui);

    // start login sub activity
    loghelper = FacebookLoginHelper.instance(this);
    handler = new LoginHandler();

    facebook_info_span = (View) this.findViewById(R.id.facebook_info_span);
    facebook_info = (TextView) this.findViewById(R.id.facebook_info);
    facebook_info_span.setVisibility(View.VISIBLE);
    orm = SocialORM.instance(this);
    boolean forinvalidsession = getIntent().getBooleanExtra("forinvalidsession", false);
    if (forinvalidsession) {
      Log.d(TAG, "for invalid session issue=" + this);
      loghelper.clearSesion();
      AccountListener.AccountManager.logout();
    }

    // for UI
    email = (EditText) this.findViewById(R.id.facebook_login_email);
    email.setHint(R.string.facebook_email_address);
    pwd = (EditText) this.findViewById(R.id.facebook_login_pwd);
    pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
    pwd.setHint(R.string.facebook_password);

    login = (Button) this.findViewById(R.id.facebook_login_ok_button);
    sign_up = (Button) this.findViewById(R.id.facebook_login_sign_up_button);

    Paint p = login.getPaint();
    float width1 = p.measureText(login.getText().toString());
    p = null;

    p = sign_up.getPaint();
    float width2 = p.measureText(sign_up.getText().toString());
    int width = Math.round(Math.max(width1, width1));

    width = width + 40;
    login.getLayoutParams().width = width;
    sign_up.getLayoutParams().width = width;
    p = null;

    login.setText(R.string.facebook_login_ok);
    sign_up.setText(R.string.facebook_login_sign_up);
    checkbox_sync_phonebook = (CheckBox) this.findViewById(R.id.checkbox_sync_phonebook);
    checkbox_sync_phonebook.setChecked(orm.isEnableSyncPhonebook());
    checkbox_sync_phonebook.setOnCheckedChangeListener(checkedListener);

    login.setOnClickListener(loginClick);
    sign_up.setOnClickListener(signupClick);

    SocialORM.Account ac = orm.getFacebookAccount();
    email.setText(ac.email);
    pwd.setText(ac.password);

    setTitle(R.string.menu_title_login);
  }
  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {
      case PASSWORD_DIALOG:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog passwordDialog = builder.create();

        passwordDialog.setTitle(getString(R.string.enter_admin_password));
        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
        input.setTransformationMethod(PasswordTransformationMethod.getInstance());
        passwordDialog.setView(input, 20, 10, 20, 10);

        passwordDialog.setButton(
            AlertDialog.BUTTON_POSITIVE,
            getString(R.string.ok),
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                String value = input.getText().toString();
                String pw = mAdminPreferences.getString(AdminPreferencesActivity.KEY_ADMIN_PW, "");
                if (pw.compareTo(value) == 0) {
                  Intent i = new Intent(getApplicationContext(), AdminPreferencesActivity.class);
                  startActivity(i);
                  input.setText("");
                  passwordDialog.dismiss();
                } else {
                  Toast.makeText(
                          MainMenuActivity.this,
                          getString(R.string.admin_password_incorrect),
                          Toast.LENGTH_SHORT)
                      .show();
                  MyStatus.getInstance()
                      .getActivityLogger()
                      .logAction(this, "adminPasswordDialog", "PASSWORD_INCORRECT");
                }
              }
            });

        passwordDialog.setButton(
            AlertDialog.BUTTON_NEGATIVE,
            getString(R.string.cancel),
            new DialogInterface.OnClickListener() {

              public void onClick(DialogInterface dialog, int which) {
                MyStatus.getInstance()
                    .getActivityLogger()
                    .logAction(this, "adminPasswordDialog", "cancel");
                input.setText("");
                return;
              }
            });

        passwordDialog
            .getWindow()
            .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        return passwordDialog;
    }
    return null;
  }
Beispiel #10
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String accountUuid = getIntent().getStringExtra("account");
    mAccount = Preferences.getPreferences(this).getAccount(accountUuid);

    setContentView(R.layout.encryption_pin);
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) {
      accountUuid = savedInstanceState.getString(EXTRA_ACCOUNT);
      mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
    }

    pinStatus = (TextView) findViewById(R.id.pin_status);
    firstPin = (EditText) findViewById(R.id.pin);
    firstPin.setInputType(InputType.TYPE_CLASS_PHONE);
    firstPin.setTransformationMethod(
        android.text.method.PasswordTransformationMethod.getInstance());

    confirmPin = (EditText) findViewById(R.id.confirm_pin);
    confirmPin.setInputType(InputType.TYPE_CLASS_PHONE);
    confirmPin.setTransformationMethod(
        android.text.method.PasswordTransformationMethod.getInstance());

    nextButton = (Button) findViewById(R.id.next);
    nextButton.setOnClickListener(this);
    nextButton.setEnabled(true);

    deleteButton = (Button) findViewById(R.id.delete_pin);
    deleteButton.setOnClickListener(this);
    deleteButton.setEnabled(false);

    // If pin exists, enable delete button and disable next button
    if (Hash.pinExists(this, mAccount.getEmail())) {
      nextButton.setEnabled(false);
      deleteButton.setEnabled(true);
    }
    redraw();
  }
  @SuppressWarnings("deprecation")
  protected void setPasswordButtonShown(boolean shouldShow) {
    // Changing input type loses position in edit text; let's try to maintain it.
    int start = passwordEdit.getSelectionStart();
    int stop = passwordEdit.getSelectionEnd();

    if (!shouldShow) {
      passwordEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
      showPasswordButton.setText(R.string.fxaccount_password_show);
      showPasswordButton.setBackgroundDrawable(
          getResources().getDrawable(R.drawable.fxaccount_password_button_show_background));
      showPasswordButton.setTextColor(
          getResources().getColor(R.color.fxaccount_password_show_textcolor));
    } else {
      passwordEdit.setTransformationMethod(SingleLineTransformationMethod.getInstance());
      showPasswordButton.setText(R.string.fxaccount_password_hide);
      showPasswordButton.setBackgroundDrawable(
          getResources().getDrawable(R.drawable.fxaccount_password_button_hide_background));
      showPasswordButton.setTextColor(
          getResources().getColor(R.color.fxaccount_password_hide_textcolor));
    }
    passwordEdit.setSelection(start, stop);
  }
  /**
   * Get the phone user pwd (the same for all the accounts)
   *
   * <p>If the password was not set it will ask for a password
   *
   * @param context The context where the dialog should be displayed
   * @return The user password
   */
  private void initPassword(final Context context) {

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    password = prefs.getString("password", "");

    // Request a new pwd if it is the first access
    if (password == "") {

      // Alert dialog
      AlertDialog.Builder alert = new AlertDialog.Builder(context);
      alert.setTitle(R.string.set_pwd);
      alert.setMessage(R.string.set_pwd_info);

      // Input text
      final EditText input = new EditText(context);
      input.setTransformationMethod(new PasswordTransformationMethod());
      alert.setView(input);

      // Listener
      alert.setPositiveButton(
          R.string.set_pwd_button,
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              SharedPreferences.Editor editor = prefs.edit();
              editor.putString("password", input.getText().toString());
              editor.commit();

              // Now we can create the new user
              getUserFromServer(context);
            }
          });

      alert.show();

      // Get the user from the server
    } else {
      getUserFromServer(context);
    }

    // If the user doesn't set up a password it can continue
  }
  private void buildDialog() {

    AlertDialog.Builder builder =
        new AlertDialog.Builder(context)
            .setTitle(context.getString(R.string.passcode_dialog_title))
            .setIcon(R.drawable.ten20_logo_transparent)
            .setPositiveButton(context.getString(R.string.passcode_dialog_ok), mOkClickListener)
            .setNegativeButton(
                context.getString(R.string.passcode_dialog_cancel), mCancelClickListener);

    passcodeEditText = new EditText(context);
    passcodeEditText.setTransformationMethod(new PasswordTransformationMethod());
    passcodeEditText.setKeyListener(new DigitsKeyListener());

    builder.setView(passcodeEditText);

    dialog = builder.create();
    dialog.setOnDismissListener(this);
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
  }
Beispiel #14
0
  // Delete account pin file
  private void deletePin() {
    if (Hash.pinExists(this, mAccount.getEmail().toLowerCase())) {
      AlertDialog.Builder alert = new AlertDialog.Builder(this);
      alert.setTitle("Confirm PIN");
      alert.setMessage("Enter your PIN to unlink it from this account");

      // Set an EditText view to get user input
      final EditText input = new EditText(this);
      input.setInputType(InputType.TYPE_CLASS_PHONE);
      input.setTransformationMethod(android.text.method.PasswordTransformationMethod.getInstance());

      alert.setView(input);

      alert.setPositiveButton(
          "Ok",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
              if (input.getText().length() < 4) {
                Toast.makeText(
                        EncryptionPin.this, "Pin must be at least 4 characters", Toast.LENGTH_LONG)
                    .show();
                return;
              }

              // Check .pin2
              FileInputStream fis1;
              try {
                fis1 = openFileInput((mAccount.getEmail().toLowerCase()) + ".pin2");
                BufferedReader in1 = new BufferedReader(new InputStreamReader(fis1));
                String test = in1.readLine();
                String storedHash = "";
                while (test != null) {
                  storedHash = storedHash + test;
                  test = in1.readLine();
                }

                char[] inputPin = new char[input.getText().length()];
                for (int i = 0; i < input.getText().length(); i++)
                  inputPin[i] = input.getText().charAt(i);

                String storedStatic =
                    Hash.getStatic(storedHash, input.getText().length(), EncryptionPin.this);
                String storedRand =
                    Hash.getRandom(storedHash, input.getText().length(), EncryptionPin.this);
                String userHash =
                    Hash.verify(mAccount.getEmail().toString(), inputPin, storedRand, storedStatic);

                if (storedHash != null && userHash != null)
                  if (Hash.compareHashes(storedHash, userHash)) {
                    Toast.makeText(
                            EncryptionPin.this, "Hashes match. Pin deleted.", Toast.LENGTH_SHORT)
                        .show();

                    EncryptionPin.this.deleteFile((mAccount.getEmail() + ".pin").toLowerCase());
                    EncryptionPin.this.deleteFile((mAccount.getEmail() + ".pin2").toLowerCase());

                    mAccount.setAskForPin("Never");
                    redraw();
                    MessageList.actionHandleFolder(
                        EncryptionPin.this, mAccount, mAccount.getAutoExpandFolderName());
                    finish();
                  } else
                    Toast.makeText(EncryptionPin.this, "Hash mismatch", Toast.LENGTH_SHORT).show();

              } catch (FileNotFoundException e) {
                Toast.makeText(EncryptionPin.this, "Hashed PIN not found", Toast.LENGTH_LONG)
                    .show();

              } catch (IOException e) {
                Toast.makeText(EncryptionPin.this, "Error retreiving PIN", Toast.LENGTH_SHORT)
                    .show();
              }

              char[] pinFromFile = new char[input.getText().length()];
              for (int i = 0; i < input.getText().length(); i++)
                pinFromFile[i] = input.getText().charAt(i);

              // Check .pin
              FileInputStream fis;
              try {
                fis = openFileInput((mAccount.getEmail().toLowerCase()) + ".pin");
                BufferedReader in = new BufferedReader(new InputStreamReader(fis));
                char[] pin = in.readLine().toCharArray();

                if (Arrays.equals(pin, pinFromFile)) {
                  mAccount.setAskForPin("0");
                  EncryptionPin.this.deleteFile(
                      mAccount.getEmail().toString().toLowerCase() + ".pin");
                  Toast.makeText(EncryptionPin.this, "PIN removed", Toast.LENGTH_SHORT).show();
                  redraw();
                  ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                      .hideSoftInputFromWindow(input.getWindowToken(), 0);

                  mAccount.setAskForPin("Never");

                  // Return to settings
                  EncryptionSettings.encryptionSettings(EncryptionPin.this, mAccount);
                } else
                  Toast.makeText(EncryptionPin.this, "Incorrect PIN", Toast.LENGTH_SHORT).show();

                if (pin != null) Arrays.fill(pin, '0');
                if (pinFromFile != null) Arrays.fill(pinFromFile, '0');

              } catch (FileNotFoundException e) {

              } catch (IOException e) {
              }
            }
          });

      alert.setNegativeButton(
          "Cancel",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
              // Canceled.

            }
          });

      alert.setIcon(R.drawable.pin);
      alert.show();

    } else
      Toast.makeText(
              EncryptionPin.this, "PIN not yet created for this account.", Toast.LENGTH_SHORT)
          .show();
  }
  @Override
  public void propertyChanged(String key, Object oldValue, Object newValue, TiProxy proxy) {
    if (DBG) {
      Log.d(LCAT, "Property: " + key + " old: " + oldValue + " new: " + newValue);
    }
    if (key.equals("enabled")) {
      tv.setEnabled(TiConvert.toBoolean(newValue));
    } else if (key.equals("value")) {
      tv.setText((String) newValue);
    } else if (key.equals("color")) {
      tv.setTextColor(TiConvert.toColor((String) newValue));
    } else if (key.equals("passwordMask")) {
      if (TiConvert.toBoolean(newValue) == true) {
        // This shouldn't be needed but it's belts & braces
        tv.setKeyListener(TextKeyListener.getInstance(false, Capitalize.NONE));
        // Both setTransform & keyboard type are required
        tv.setTransformationMethod(PasswordTransformationMethod.getInstance());
        // We also need to set the keyboard type - otherwise the password mask won't be applied
        handleKeyboardType(KEYBOARD_PASSWORD, false);
      } else {
        handleKeyboardType(KEYBOARD_DEFAULT, false);
      }
    } else if (key.equals("hintText")) {
      tv.setHint((String) newValue);
    } else if (key.equals("textAlign") || key.equals("verticalAlign")) {
      String textAlign = null;
      String verticalAlign = null;
      if (key.equals("textAlign")) {
        textAlign = TiConvert.toString(newValue);
      }
      if (key.equals("verticalAlign")) {
        verticalAlign = TiConvert.toString(newValue);
      }
      handleTextAlign(textAlign, verticalAlign);
    } else if (key.equals("autocapitalization")) {

      // TODO Missing
      Capitalize autoCapValue = null;

      switch (TiConvert.toInt(newValue)) {
        case TEXT_AUTOCAPITALIZATION_NONE:
          autoCapValue = Capitalize.NONE;
          break;

        case TEXT_AUTOCAPITALIZATION_ALL:
          autoCapValue = Capitalize.CHARACTERS;
          break;

        case TEXT_AUTOCAPITALIZATION_SENTENCES:
          autoCapValue = Capitalize.SENTENCES;
          break;

        case TEXT_AUTOCAPITALIZATION_WORDS:
          autoCapValue = Capitalize.WORDS;
          break;

        default:
          Log.w(LCAT, "Unknown AutoCapitalization Value [" + TiConvert.toString(newValue) + "]");
          break;
      }

      if (null != autoCapValue) {
        tv.setKeyListener(TextKeyListener.getInstance(false, autoCapValue));
      }

    } else if (key.equals("keyboardType") || (key.equals("autocorrect"))) {
      TiDict d = proxy.getDynamicProperties();
      boolean autocorrect = false;
      if (d.containsKey("autocorrect")) {
        autocorrect = d.getBoolean("autocorrect");
      }

      handleKeyboardType(TiConvert.toInt(d, "keyboardType"), autocorrect);
    } else if (key.equals("returnKeyType")) {
      handleReturnKeyType(TiConvert.toInt(newValue));
    } else if (key.equals("font")) {
      TiUIHelper.styleText(tv, (TiDict) newValue);
    } else {
      super.propertyChanged(key, oldValue, newValue, proxy);
    }
  }
  @Override
  public void processProperties(TiDict d) {
    super.processProperties(d);

    if (d.containsKey("enabled")) {
      tv.setEnabled(d.getBoolean("enabled"));
    }
    if (d.containsKey("value")) {
      tv.setText(d.getString("value"));
    }
    if (d.containsKey("color")) {
      tv.setTextColor(TiConvert.toColor(d, "color"));
    }
    if (d.containsKey("hintText")) {
      tv.setHint(d.getString("hintText"));
    }
    if (d.containsKey("font")) {
      TiUIHelper.styleText(tv, d.getTiDict("font"));
    }
    if (d.containsKey("textAlign") || d.containsKey("verticalAlign")) {
      String textAlign = null;
      String verticalAlign = null;
      if (d.containsKey("textAlign")) {
        textAlign = d.getString("textAlign");
      }
      if (d.containsKey("verticalAlign")) {
        verticalAlign = d.getString("verticalAlign");
      }
      handleTextAlign(textAlign, verticalAlign);
    }
    if (d.containsKey("returnKeyType")) {
      handleReturnKeyType(d.getInt("returnKeyType"));
    }
    if (d.containsKey("keyboardType")) {
      boolean autocorrect = true;
      if (d.containsKey("autocorrect")) {
        autocorrect = d.getBoolean("autocorrect");
      }
      handleKeyboardType(d.getInt("keyboardType"), autocorrect);
    }

    if (d.containsKey("autocapitalization")) {

      Capitalize autoCapValue = null;

      switch (d.getInt("autocapitalization")) {
        case TEXT_AUTOCAPITALIZATION_NONE:
          autoCapValue = Capitalize.NONE;
          break;

        case TEXT_AUTOCAPITALIZATION_ALL:
          autoCapValue = Capitalize.CHARACTERS;
          break;

        case TEXT_AUTOCAPITALIZATION_SENTENCES:
          autoCapValue = Capitalize.SENTENCES;
          break;

        case TEXT_AUTOCAPITALIZATION_WORDS:
          autoCapValue = Capitalize.WORDS;
          break;

        default:
          Log.w(
              LCAT, "Unknown AutoCapitalization Value [" + d.getString("autocapitalization") + "]");
          break;
      }

      if (null != autoCapValue) {
        tv.setKeyListener(TextKeyListener.getInstance(false, autoCapValue));
      }
    }

    if (d.containsKey("passwordMask")) {
      if (TiConvert.toBoolean(d.get("passwordMask"))) {
        // This shouldn't be needed but it's belts & braces
        tv.setKeyListener(TextKeyListener.getInstance(false, Capitalize.NONE));
        // Both setTransform & keyboard type are required
        tv.setTransformationMethod(PasswordTransformationMethod.getInstance());
        // We also need to set the keyboard type - otherwise the password mask won't be applied
        handleKeyboardType(KEYBOARD_PASSWORD, false);
      }
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate");

    scroll = new ScrollView(this);
    setContentView(scroll);

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setLayoutParams(
        new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    layout.setPadding(10, 10, 10, 10);
    scroll.addView(
        layout,
        new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

    viewNetwork = new Button(this);
    viewNetwork.setLayoutParams(
        new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    viewNetwork.setText(getResources().getString(R.string.view_network_button));
    viewNetwork.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            final String[] networkTreeCopy = networkTree;
            AlertDialog.Builder builder = new AlertDialog.Builder(AddPrinterActivity.this);
            // builder.setTitle(R.string.network);
            builder.setItems(
                networkTreeCopy,
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, final int which) {
                    dialog.dismiss();
                    String selected = networkTreeCopy[which];
                    selected = selected.trim();
                    if (!selected.startsWith("\\\\")) return;
                    selected = selected.substring(2);
                    if (selected.indexOf("\\") == -1) return;
                    String server = selected.substring(0, selected.indexOf("\\"));
                    String share = selected.substring(selected.indexOf("\\") + 1);
                    share = share.split("\\s+")[0];
                    AddPrinterActivity.this.server.setText(server);
                    AddPrinterActivity.this.printer.setText(share);
                    AddPrinterActivity.this.name.setText(server + "-" + share);
                    String workgroup = "";
                    for (int i = 0; i < which; i++) {
                      if (networkTreeCopy[i].indexOf("\\") == -1) workgroup = networkTreeCopy[i];
                    }
                    if (workgroup.length() > 0) AddPrinterActivity.this.domain.setText(workgroup);
                  }
                });
            builder.setNegativeButton(
                R.string.close,
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface d, int s) {
                    d.dismiss();
                    if (user.getText().toString().length() == 0
                        || password.getText().toString().length() == 0)
                      Toast.makeText(
                              AddPrinterActivity.this,
                              R.string.login_password_hint,
                              Toast.LENGTH_LONG)
                          .show();
                  }
                });
            builder.setPositiveButton(
                R.string.view_network_button_scan_again,
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface d, int s) {
                    d.dismiss();
                    updateNetworkTree();
                    if (user.getText().toString().length() == 0
                        || password.getText().toString().length() == 0)
                      Toast.makeText(
                              AddPrinterActivity.this,
                              R.string.login_password_hint,
                              Toast.LENGTH_LONG)
                          .show();
                  }
                });
            AlertDialog alert = builder.create();
            alert.setOwnerActivity(AddPrinterActivity.this);
            alert.show();
          }
        });
    layout.addView(viewNetwork);

    TextView text = null;

    text = new TextView(this);
    text.setText(R.string.name_desc);
    text.setTextSize(20);
    layout.addView(text);

    name = new EditText(this);
    name.setHint(R.string.name_hint);
    name.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    layout.addView(name);

    text = new TextView(this);
    text.setText(R.string.server_desc);
    text.setTextSize(20);
    layout.addView(text);

    server = new EditText(this);
    server.setHint(R.string.server_hint);
    server.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    layout.addView(server);

    text = new TextView(this);
    text.setText(R.string.printer_desc);
    text.setTextSize(20);
    layout.addView(text);

    printer = new EditText(this);
    printer.setHint(R.string.printer_hint);
    printer.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    layout.addView(printer);

    text = new TextView(this);
    text.setText(R.string.model_desc);
    text.setTextSize(20);
    layout.addView(text);

    model = new EditText(this);
    model.setHint(R.string.model_button_reading);
    model.setEnabled(false);
    model.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    model.addTextChangedListener(
        new TextWatcher() {
          public void afterTextChanged(Editable s) {
            if (s.length() >= 1 && modelList != null) {
              // selectModel.setEnabled(true);
              selectModel.setText(getResources().getString(R.string.model_button_search));
            } else {
              // selectModel.setEnabled(false);
              selectModel.setText(getResources().getString(R.string.model_button_type));
            }
          }

          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          public void onTextChanged(CharSequence s, int start, int before, int count) {}
        });
    layout.addView(model);

    selectModel = new Button(this);
    selectModel.setText(getResources().getString(R.string.model_button_reading));
    selectModel.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            if (!model.isEnabled()) {
              model.setEnabled(true);
              model.setText("");
              return;
            }
            String search = model.getText().toString().toLowerCase();
            final ArrayList<CharSequence> values = new ArrayList<CharSequence>();
            AlertDialog.Builder builder = new AlertDialog.Builder(AddPrinterActivity.this);
            builder.setTitle(R.string.select_printer_model);
            for (String s : modelList.keySet()) {
              if (s.toLowerCase().indexOf(search) != -1) {
                Log.d(TAG, "Found model: " + s);
                values.add(s);
              }
            }
            if (values.size() == 0) {
              builder.setMessage(R.string.no_models_found);
              builder.setPositiveButton(
                  R.string.ok,
                  new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface d, int s) {
                      d.dismiss();
                    }
                  });
            } else {
              builder.setItems(
                  values.toArray(new CharSequence[0]),
                  new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                      model.setText(values.get(which));
                      model.setEnabled(false);
                      selectModel.setText(getResources().getString(R.string.model_button_clear));
                    }
                  });
            }
            AlertDialog alert = builder.create();
            alert.setOwnerActivity(AddPrinterActivity.this);
            alert.show();
          }
        });
    selectModel.setEnabled(false);
    layout.addView(selectModel);

    text = new TextView(this);
    text.setText(R.string.domain_desc);
    text.setTextSize(20);
    layout.addView(text);

    domain = new EditText(this);
    domain.setHint(R.string.domain_hint);
    domain.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    layout.addView(domain);

    text = new TextView(this);
    text.setText(R.string.user_desc);
    text.setTextSize(20);
    layout.addView(text);

    user = new EditText(this);
    user.setHint(R.string.user_hint);
    user.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    layout.addView(user);

    text = new TextView(this);
    text.setText(R.string.password_desc);
    text.setTextSize(20);
    text.setLayoutParams(
        new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));

    CheckBox showPassword = new CheckBox(this);
    showPassword.setText(R.string.show_password);
    showPassword.setTextSize(20);
    showPassword.setLayoutParams(
        new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.0f));
    showPassword.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int selection = password.getSelectionStart();
            if (isChecked) {
              password.setInputType(
                  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
              password.setTransformationMethod(null);
            } else {
              password.setInputType(
                  InputType.TYPE_CLASS_TEXT
                      | InputType.TYPE_TEXT_VARIATION_PASSWORD
                      | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
              password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            password.setSelection(selection);
          }
        });

    LinearLayout layout2 = new LinearLayout(this);
    layout2.setOrientation(LinearLayout.HORIZONTAL);
    layout2.setLayoutParams(
        new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    layout2.addView(text);
    layout2.addView(showPassword);

    layout.addView(layout2);

    password = new EditText(this);
    password.setHint(R.string.password_hint);
    password.setInputType(
        InputType.TYPE_CLASS_TEXT
            | InputType.TYPE_TEXT_VARIATION_PASSWORD
            | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
    layout.addView(password);

    text = new TextView(this);
    text.setText("");
    layout.addView(text);

    addPrinter = new Button(this);
    addPrinter.setEnabled(false);
    addPrinter.setText(
        getResources().getString(R.string.add_printer_button)
            + " - "
            + getResources().getString(R.string.model_button_reading));
    addPrinter.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            if (name.getText().length() == 0
                || server.getText().length() == 0
                || printer.getText().length() == 0
                || model.isEnabled()
                || model.getText().length() == 0) {
              AlertDialog.Builder builder = new AlertDialog.Builder(AddPrinterActivity.this);
              builder.setTitle(R.string.error);
              builder.setMessage(R.string.error_empty_fields);
              builder.setPositiveButton(
                  R.string.ok,
                  new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface d, int s) {
                      d.dismiss();
                    }
                  });
              AlertDialog alert = builder.create();
              alert.setOwnerActivity(AddPrinterActivity.this);
              alert.show();
              return;
            }
            progressCircle.show();
            new Thread(
                    new Runnable() {
                      public void run() {
                        Cups.addPrinter(
                            AddPrinterActivity.this,
                            name.getText().toString(),
                            server.getText().toString(),
                            printer.getText().toString(),
                            modelList.get(model.getText().toString()),
                            domain.getText().toString().toUpperCase(),
                            user.getText().toString(),
                            password.getText().toString());
                        Cups.updatePrintersInfo(AddPrinterActivity.this);
                        runOnUiThread(
                            new Runnable() {
                              public void run() {
                                progressCircle.dismiss();
                                Toast.makeText(
                                        AddPrinterActivity.this,
                                        R.string.printer_added_successfully,
                                        Toast.LENGTH_LONG)
                                    .show();
                                finish();
                              }
                            });
                      }
                    })
                .start();
          }
        });
    layout.addView(addPrinter);

    progressCircle = new ProgressDialog(this);
    progressCircle.setMessage(getResources().getString(R.string.please_wait));

    updateNetworkTree();

    Uri uri = getIntent() != null ? getIntent().getData() : null;
    if (uri != null
        && uri.getScheme() != null
        && uri.getHost() != null
        && getResources().getString(R.string.add_printer_scheme).equals(uri.getScheme())
        && getResources().getString(R.string.add_printer_host).equals(uri.getHost())) {
      name.setText(uri.getQueryParameter("n"));
      server.setText(uri.getQueryParameter("s"));
      printer.setText(uri.getQueryParameter("p"));
      model.setText(uri.getQueryParameter("m"));
      domain.setText(uri.getQueryParameter("d"));
      user.setText(uri.getQueryParameter("u"));
      password.setText(uri.getQueryParameter("pw"));
    }

    updateModelList();
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_repo);

    // Check to see if extras were passed to the intent. In that case, edit the repository
    if (getIntent().getExtras() != null) {
      Bundle rec_bundle = getIntent().getExtras();

      // Get the repository to edit
      edit_repo = rec_bundle.getLong("editRepo", -1);

      // If the repository id is valid, set the activity to edit mode
      if (edit_repo >= 0) {
        edit_mode = true;
        this.setTitle(R.string.add_repo_edit_title);
      }
    }

    encrypt_helper =
        EncryptionHelper.getInstance("DEADBEEF".toCharArray(), new byte[] {'L', 'O', 'L'});
    db_helper = DatabaseHelper.getInstance(this);

    repo_name = (EditText) findViewById(R.id.repo_name);

    username = (EditText) findViewById(R.id.add_repo_username);
    password = (EditText) findViewById(R.id.add_repo_password);
    password.setRawInputType(
        InputType.TYPE_TEXT_VARIATION_PASSWORD); // Make this into a password box
    password.setTransformationMethod(new PasswordTransformationMethod());

    key = (EditText) findViewById(R.id.add_repo_key);

    url = (EditText) findViewById(R.id.add_repo_url);

    repo_types = (Spinner) findViewById(R.id.repo_type_spinner);
    repo_auth = (Spinner) findViewById(R.id.repo_authentication_spinner);

    // Create a new list for storing the services the program can handle
    ArrayList<String> services = new ArrayList<String>();

    // Add the services supported by the program
    services.add("HGWeb Served");
    services.add("Google Code");
    services.add("Bitbucket");
    services.add("CodePlex");

    // Create a new adapter with the list of services
    AddRepoAdapter type_adapter = new AddRepoAdapter(this, services);

    // Add the adapter to the spinner that stores the list of services
    repo_types.setAdapter(type_adapter);

    // Create a new list to store authentication types
    ArrayList<String> authentication = new ArrayList<String>();

    // Add the authentication types
    authentication.add(0, "None");
    authentication.add(Mercury.AuthenticationTypes.HTTP, "HTTP");
    authentication.add(Mercury.AuthenticationTypes.TOKEN, "Token");
    // authentication.add(SSH, "SSH");

    // Create a new adapter based on the authentication types
    AddRepoAdapter auth_adapter = new AddRepoAdapter(this, authentication);

    // Add the adapter to the authentication spinner
    repo_auth.setAdapter(auth_adapter);

    // Create a listener that triggers whenever the authentication type is changed
    repo_auth.setOnItemSelectedListener(
        new OnItemSelectedListener() {

          @Override
          public void onItemSelected(AdapterView<?> adapterview, View view, int position, long id) {
            // If anything other than "None" is selected, enable the username and password or ssh
            // fields
            if (position > Mercury.AuthenticationTypes.NONE) {
              if (position == Mercury.AuthenticationTypes.TOKEN) {
                if (username.getVisibility() != View.GONE
                    || password.getVisibility() != View.GONE) {
                  // Hide both the username and password if they're not already gone
                  username.setVisibility(View.GONE);
                  password.setVisibility(View.GONE);
                }

                // Make the key text box visible
                key.setVisibility(View.VISIBLE);

                // Enable the controls on the key text box
                key.setEnabled(true);
                key.setFocusable(true);
                key.setClickable(true);
                key.setFocusableInTouchMode(true);

              } else {
                // Make the username and password visible
                username.setVisibility(View.VISIBLE);
                password.setVisibility(View.VISIBLE);

                key.setVisibility(View.GONE);
                key.setText("");

                // Re-enable the username and password text boxes
                username.setEnabled(true);
                username.setCursorVisible(true);
                username.setClickable(true);
                username.setFocusable(true);
                username.setFocusableInTouchMode(true);

                password.setEnabled(true);
                password.setCursorVisible(true);
                password.setClickable(true);
                password.setFocusable(true);
                password.setFocusableInTouchMode(true);
              }
              // Otherwise, disable all fields from user interaction
            } else {
              key.setEnabled(false);
              key.setFocusable(false);
              key.setClickable(false);

              username.setEnabled(false);
              username.setFocusable(false);
              username.setClickable(false);

              password.setEnabled(false);
              password.setClickable(false);
              password.setFocusable(false);
            }
          }

          @Override
          public void onNothingSelected(AdapterView<?> arg0) {
            // Will never be called on a spinner
          }
        });

    Button save_button = (Button) findViewById(R.id.add_repo_save);
    Button discard = (Button) findViewById(R.id.add_repo_discard);

    discard.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            killActivity(Activity.RESULT_CANCELED);
          }
        });

    save_button.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // Check the user input
            if (checkInput()) {
              // Attempt to save the repository
              if (saveRepository())
                // If successful go back to the list
                killActivity(Activity.RESULT_OK);
            }
          }
        });

    if (edit_mode) {
      // Get the information for this repository
      Beans.RepositoryBean repo_info = db_helper.getRepository(edit_repo, null);

      // Set the information in the activity
      repo_name.setText(repo_info.getTitle());
      url.setText(repo_info.getUrl());

      username.setText(repo_info.getUsername());
      password.setText(repo_info.getPassword());
      key.setText(repo_info.getSSHKey());

      repo_types.setSelection(repo_info.getType());
      repo_auth.setSelection(repo_info.getAuthentication());
    }
  }
  private void askForPW(final int type) {

    final EditText entry = new EditText(this);
    final View userpwlayout = getLayoutInflater().inflate(R.layout.openvpn_userpass, null, false);

    entry.setSingleLine();
    entry.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    entry.setTransformationMethod(new PasswordTransformationMethod());

    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Need " + getString(type));
    dialog.setMessage("Enter the password for profile " + mSelectedProfile.mName);

    if (type == R.string.openvpn_password) {
      ((EditText) userpwlayout.findViewById(R.id.openvpn_username))
          .setText(mSelectedProfile.mUsername);
      ((EditText) userpwlayout.findViewById(R.id.openvpn_password))
          .setText(mSelectedProfile.mPassword);
      ((CheckBox) userpwlayout.findViewById(R.id.openvpn_save_password))
          .setChecked(!TextUtils.isEmpty(mSelectedProfile.mPassword));
      ((CheckBox) userpwlayout.findViewById(R.id.openvpn_show_password))
          .setOnCheckedChangeListener(
              new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                  if (isChecked)
                    ((EditText) userpwlayout.findViewById(R.id.openvpn_password))
                        .setInputType(
                            InputType.TYPE_CLASS_TEXT
                                | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                  else
                    ((EditText) userpwlayout.findViewById(R.id.openvpn_password))
                        .setInputType(
                            InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
              });

      dialog.setView(userpwlayout);
    } else {
      dialog.setView(entry);
    }

    AlertDialog.Builder builder =
        dialog.setPositiveButton(
            android.R.string.ok,
            new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {

                if (type == R.string.openvpn_password) {
                  mSelectedProfile.mUsername =
                      ((EditText) userpwlayout.findViewById(R.id.openvpn_username))
                          .getText()
                          .toString();

                  String pw =
                      ((EditText) userpwlayout.findViewById(R.id.openvpn_password))
                          .getText()
                          .toString();
                  if (((CheckBox) userpwlayout.findViewById(R.id.openvpn_save_password))
                      .isChecked()) {
                    mSelectedProfile.mPassword = pw;
                  } else {
                    mSelectedProfile.mPassword = null;
                    mSelectedProfile.mTransientPW = pw;
                  }
                } else {
                  mSelectedProfile.mTransientPCKS12PW = entry.getText().toString();
                }
                onActivityResult(START_VPN_PROFILE, Activity.RESULT_OK, null);
              }
            });
    dialog.setNegativeButton(
        android.R.string.cancel,
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            VpnStatus.updateStateString(
                "USER_VPN_PASSWORD_CANCELLED",
                "",
                R.string.openvpn_state_user_vpn_password_cancelled,
                ConnectionStatus.LEVEL_NOTCONNECTED);
            finish();
          }
        });

    dialog.create().show();
  }
Beispiel #20
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // go full screen
    getWindow()
        .setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    mHomeWatcher = new HomeWatcher(getApplicationContext());
    mHomeWatcher.setOnHomePressedListener(
        new OnHomePressedListener() {
          @Override
          public void onHomePressed() {
            // home key is pressed...
            Toast.makeText(getApplicationContext(), "Not Suitable Button", Toast.LENGTH_SHORT)
                .show();

            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            finish();
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(intent);
          }

          @Override
          public void onHomeLongPressed() {
            // home key is Long pressed...
            Toast.makeText(getApplicationContext(), "Not Suitable Button", Toast.LENGTH_SHORT)
                .show();
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);

            // make activity sleep a while and start again
            // SystemClock.sleep(2000);//3senconds
            //                try {
            //                    Thread.sleep(3000);
            //                } catch (InterruptedException e) {
            //                    e.printStackTrace();
            //                }

            finish();
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(intent);
          }
        });
    mHomeWatcher.startWatch();

    // pin box purify
    myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    pw = (EditText) findViewById(R.id.pw);
    pw.setTypeface(Typeface.DEFAULT);
    pw.setTransformationMethod(new PasswordTransformationMethod());

    // disable softkeyboard
    imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(pw.getWindowToken(), 0);

    // Text copy and paste Solution for future use
    pw.setCustomSelectionActionModeCallback(
        new ActionMode.Callback() {
          @Override
          public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            return false;
          }

          @Override
          public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return false;
          }

          @Override
          public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
              case android.R.id.copy:
                int min = 0;
                int max = pw.getText().length();
                if (pw.isFocused()) {
                  final int selStart = pw.getSelectionStart();
                  final int selEnd = pw.getSelectionEnd();

                  min = Math.max(0, Math.min(selStart, selEnd));
                  max = Math.max(0, Math.max(selStart, selEnd));
                }
                // Perform your definition lookup with the selected text
                final CharSequence selectedText = pw.getText().subSequence(min, max);
                String text = selectedText.toString();

                myClip = ClipData.newPlainText("text", text);
                myClipboard.setPrimaryClip(myClip);
                Toast.makeText(getApplicationContext(), "Text Copied", Toast.LENGTH_SHORT).show();
                // Finish and close the ActionMode
                mode.finish();
                return true;
              case android.R.id.cut:
                // custom code to get cut functionality according
                // to customer requirement
                return true;
              case android.R.id.paste:
                // custom code to get paste functionality according
                // to customer requirement
                return true;

              default:
                break;
            }
            return false;
          }

          @Override
          public void onDestroyActionMode(ActionMode actionMode) {}
        });

    // _______________________________________//

    // initialize views
    db = new DBHelper(getApplicationContext());
    print = new PrintService();
    pers = new PersonalSale();

    try {
      db.truncateQueue();
      db.truncateRec();
      print.stopService();
      PersonalSale personal = new PersonalSale();
      Intent alarmIntent = new Intent(this, PrintService.class);
      PendingIntent pi = PendingIntent.getService(this, 0, alarmIntent, 0);
      AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
      pers.killAlarm(pi, am);
    } catch (NullPointerException e) {
      e.printStackTrace();
    }

    monitor = (TextView) findViewById(R.id.monitor);

    login = (Button) findViewById(R.id.login);
    login.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            // Starting login processing
            if (!pw.getText().toString().isEmpty()) {

              LoginAsync login = new LoginAsync();
              String pin = pw.getText().toString();
              login.execute(pin);

              //                loginPro(pw.getText().toString());
            } else monitor.setText("Empty Pin");
          }
        });
  }
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
      final Activity activity = getActivity();

      ContextThemeWrapper theme = ThemeChanger.getDialogThemeWrapper(activity);

      mRequiredInput = getArguments().getParcelable(EXTRA_REQUIRED_INPUT);

      CustomAlertDialogBuilder alert = new CustomAlertDialogBuilder(theme);

      // No title, see http://www.google.com/design/spec/components/dialogs.html#dialogs-alerts
      // alert.setTitle()

      if (mRequiredInput.mType == RequiredInputType.BACKUP_CODE) {
        LayoutInflater inflater = LayoutInflater.from(theme);
        View view = inflater.inflate(R.layout.passphrase_dialog_backup_code, null);
        alert.setView(view);

        mBackupCodeEditText = new EditText[4];
        mBackupCodeEditText[0] = (EditText) view.findViewById(R.id.backup_code_1);
        mBackupCodeEditText[1] = (EditText) view.findViewById(R.id.backup_code_2);
        mBackupCodeEditText[2] = (EditText) view.findViewById(R.id.backup_code_3);
        mBackupCodeEditText[3] = (EditText) view.findViewById(R.id.backup_code_4);
        setupEditTextFocusNext(mBackupCodeEditText);

        AlertDialog dialog = alert.create();
        dialog.setButton(
            DialogInterface.BUTTON_POSITIVE,
            activity.getString(R.string.btn_unlock),
            (DialogInterface.OnClickListener) null);
        return dialog;
      }

      long subKeyId = mRequiredInput.getSubKeyId();

      LayoutInflater inflater = LayoutInflater.from(theme);
      mLayout = (ViewAnimator) inflater.inflate(R.layout.passphrase_dialog, null);
      alert.setView(mLayout);

      mPassphraseText = (TextView) mLayout.findViewById(R.id.passphrase_text);
      mPassphraseEditText = (EditText) mLayout.findViewById(R.id.passphrase_passphrase);

      View vTimeToLiveLayout = mLayout.findViewById(R.id.remember_layout);
      vTimeToLiveLayout.setVisibility(mRequiredInput.mSkipCaching ? View.GONE : View.VISIBLE);

      mTimeToLiveSpinner = (CacheTTLSpinner) mLayout.findViewById(R.id.ttl_spinner);

      alert.setNegativeButton(
          android.R.string.cancel,
          new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int id) {
              dialog.cancel();
            }
          });

      String userId;
      CanonicalizedSecretKey.SecretKeyType keyType =
          CanonicalizedSecretKey.SecretKeyType.PASSPHRASE;

      String message;
      String hint;
      if (mRequiredInput.mType == RequiredInputType.PASSPHRASE_SYMMETRIC) {
        message = getString(R.string.passphrase_for_symmetric_encryption);
        hint = getString(R.string.label_passphrase);
      } else {
        try {
          ProviderHelper helper = new ProviderHelper(activity);
          mSecretRing =
              helper.getCanonicalizedSecretKeyRing(
                  KeychainContract.KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(subKeyId));
          // yes the inner try/catch block is necessary, otherwise the final variable
          // above can't be statically verified to have been set in all cases because
          // the catch clause doesn't return.
          try {
            String mainUserId = mSecretRing.getPrimaryUserIdWithFallback();
            KeyRing.UserId mainUserIdSplit = KeyRing.splitUserId(mainUserId);
            if (mainUserIdSplit.name != null) {
              userId = mainUserIdSplit.name;
            } else {
              userId = getString(R.string.user_id_no_name);
            }
          } catch (PgpKeyNotFoundException e) {
            userId = null;
          }

          keyType = mSecretRing.getSecretKey(subKeyId).getSecretKeyType();
          switch (keyType) {
            case PASSPHRASE:
              message = getString(R.string.passphrase_for, userId);
              hint = getString(R.string.label_passphrase);
              break;
            case PIN:
              message = getString(R.string.pin_for, userId);
              hint = getString(R.string.label_pin);
              break;
            case DIVERT_TO_CARD:
              message = getString(R.string.yubikey_pin_for, userId);
              hint = getString(R.string.label_pin);
              break;
              // special case: empty passphrase just returns the empty passphrase
            case PASSPHRASE_EMPTY:
              finishCaching(new Passphrase(""));
            default:
              throw new AssertionError("Unhandled SecretKeyType (should not happen)");
          }

        } catch (ProviderHelper.NotFoundException e) {
          alert.setTitle(R.string.title_key_not_found);
          alert.setMessage(getString(R.string.key_not_found, mRequiredInput.getSubKeyId()));
          alert.setPositiveButton(
              android.R.string.ok,
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  dismiss();
                }
              });
          alert.setCancelable(false);
          return alert.create();
        }
      }

      mPassphraseText.setText(message);
      mPassphraseEditText.setHint(hint);

      // Hack to open keyboard.
      // This is the only method that I found to work across all Android versions
      // http://turbomanage.wordpress.com/2012/05/02/show-soft-keyboard-automatically-when-edittext-receives-focus/
      // Notes: * onCreateView can't be used because we want to add buttons to the dialog
      //        * opening in onActivityCreated does not work on Android 4.4
      mPassphraseEditText.setOnFocusChangeListener(
          new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
              mPassphraseEditText.post(
                  new Runnable() {
                    @Override
                    public void run() {
                      if (getActivity() == null || mPassphraseEditText == null) {
                        return;
                      }
                      InputMethodManager imm =
                          (InputMethodManager)
                              getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                      imm.showSoftInput(mPassphraseEditText, InputMethodManager.SHOW_IMPLICIT);
                    }
                  });
            }
          });
      mPassphraseEditText.requestFocus();

      mPassphraseEditText.setImeActionLabel(
          getString(android.R.string.ok), EditorInfo.IME_ACTION_DONE);
      mPassphraseEditText.setOnEditorActionListener(this);

      if ((keyType == CanonicalizedSecretKey.SecretKeyType.DIVERT_TO_CARD
              && Preferences.getPreferences(activity).useNumKeypadForYubiKeyPin())
          || keyType == CanonicalizedSecretKey.SecretKeyType.PIN) {
        mPassphraseEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
        mPassphraseEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
      } else {
        mPassphraseEditText.setRawInputType(
            InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
      }

      mPassphraseEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());

      AlertDialog dialog = alert.create();
      dialog.setButton(
          DialogInterface.BUTTON_POSITIVE,
          activity.getString(R.string.btn_unlock),
          (DialogInterface.OnClickListener) null);

      return dialog;
    }