Search in sources :

Example 1 with SimpleTextWatcher

use of com.amaze.filemanager.utils.SimpleTextWatcher in project AmazeFileManager by TeamAmaze.

the class SftpConnectDialog method onCreateDialog.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    context = getActivity();
    final boolean edit = getArguments().getBoolean("edit", false);
    final View v2 = getActivity().getLayoutInflater().inflate(R.layout.sftp_dialog, null);
    final EditText connectionET = v2.findViewById(R.id.connectionET);
    final EditText addressET = v2.findViewById(R.id.ipET);
    final EditText portET = v2.findViewById(R.id.portET);
    final EditText usernameET = v2.findViewById(R.id.usernameET);
    final EditText passwordET = v2.findViewById(R.id.passwordET);
    final Button selectPemBTN = v2.findViewById(R.id.selectPemBTN);
    // Otherwise, use given Bundle instance for filling in the blanks
    if (!edit) {
        connectionET.setText(R.string.scp_con);
        portET.setText(Integer.toString(SshConnectionPool.SSH_DEFAULT_PORT));
    } else {
        connectionET.setText(getArguments().getString("name"));
        addressET.setText(getArguments().getString("address"));
        portET.setText(getArguments().getString("port"));
        usernameET.setText(getArguments().getString("username"));
        if (getArguments().getBoolean("hasPassword")) {
            passwordET.setHint(R.string.password_unchanged);
        } else {
            selectedParsedKeyPairName = getArguments().getString("keypairName");
            selectPemBTN.setText(selectedParsedKeyPairName);
        }
    }
    // For convenience, so I don't need to press backspace all the time
    portET.setOnFocusChangeListener((v, hasFocus) -> {
        if (hasFocus)
            portET.selectAll();
    });
    int accentColor = utilsProvider.getColorPreference().getColor(ColorUsage.ACCENT);
    // Use system provided action to get Uri to PEM.
    // If MaterialDialog.Builder can be upgraded we may use their file selection dialog too
    selectPemBTN.setOnClickListener(v -> {
        Intent intent = new Intent().setType("*/*").setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PEM_INTENT);
    });
    // Define action for buttons
    final MaterialDialog.Builder dialogBuilder = new MaterialDialog.Builder(context);
    dialogBuilder.title((R.string.scp_con));
    dialogBuilder.autoDismiss(false);
    dialogBuilder.customView(v2, true);
    dialogBuilder.theme(utilsProvider.getAppTheme().getMaterialDialogTheme());
    dialogBuilder.negativeText(R.string.cancel);
    dialogBuilder.positiveText(edit ? R.string.update : R.string.create);
    dialogBuilder.positiveColor(accentColor);
    dialogBuilder.negativeColor(accentColor);
    dialogBuilder.neutralColor(accentColor);
    dialogBuilder.onPositive((dialog, which) -> {
        final String connectionName = connectionET.getText().toString();
        final String hostname = addressET.getText().toString();
        final int port = Integer.parseInt(portET.getText().toString());
        final String username = usernameET.getText().toString();
        final String password = passwordET.getText() != null ? passwordET.getText().toString() : null;
        String sshHostKey = utilsHandler.getSshHostKey(deriveSftpPathFrom(hostname, port, username, password, selectedParsedKeyPair));
        if (sshHostKey != null) {
            authenticateAndSaveSetup(connectionName, hostname, port, sshHostKey, username, password, selectedParsedKeyPairName, selectedParsedKeyPair, edit);
        } else {
            new GetSshHostFingerprintTask(hostname, port, taskResult -> {
                PublicKey hostKey = taskResult.result;
                if (hostKey != null) {
                    final String hostKeyFingerprint = SecurityUtils.getFingerprint(hostKey);
                    StringBuilder sb = new StringBuilder(hostname);
                    if (port != SshConnectionPool.SSH_DEFAULT_PORT && port > 0)
                        sb.append(':').append(port);
                    final String hostAndPort = sb.toString();
                    new AlertDialog.Builder(context).setTitle(R.string.ssh_host_key_verification_prompt_title).setMessage(String.format(getResources().getString(R.string.ssh_host_key_verification_prompt), hostAndPort, hostKey.getAlgorithm(), hostKeyFingerprint)).setCancelable(true).setPositiveButton(R.string.yes, (dialog1, which1) -> {
                        // This closes the host fingerprint verification dialog
                        dialog1.dismiss();
                        if (authenticateAndSaveSetup(connectionName, hostname, port, hostKeyFingerprint, username, password, selectedParsedKeyPairName, selectedParsedKeyPair, edit)) {
                            dialog1.dismiss();
                            Log.d(TAG, "Saved setup");
                            dismiss();
                        }
                    }).setNegativeButton(R.string.no, (dialog1, which1) -> dialog1.dismiss()).show();
                }
            }).execute();
        }
    }).onNegative((dialog, which) -> dialog.dismiss());
    // If we are editing connection settings, give new actions for neutral and negative buttons
    if (edit) {
        Log.d(TAG, "Edit? " + edit);
        dialogBuilder.negativeText(R.string.delete).onNegative((dialog, which) -> {
            final String connectionName = connectionET.getText().toString();
            final String hostname = addressET.getText().toString();
            final int port = Integer.parseInt(portET.getText().toString());
            final String username = usernameET.getText().toString();
            final String path = deriveSftpPathFrom(hostname, port, username, getArguments().getString("password", null), selectedParsedKeyPair);
            int i = DataUtils.getInstance().containsServer(new String[] { connectionName, path });
            if (i != -1) {
                DataUtils.getInstance().removeServer(i);
                AppConfig.runInBackground(() -> {
                    utilsHandler.removeSftpPath(connectionName, path);
                });
                ((MainActivity) getActivity()).getDrawer().refreshDrawer();
            }
            dialog.dismiss();
        }).neutralText(R.string.cancel).onNeutral((dialog, which) -> dialog.dismiss());
    }
    MaterialDialog dialog = dialogBuilder.build();
    // Some validations to make sure the Create/Update button is clickable only when required
    // setting values are given
    final View okBTN = dialog.getActionButton(DialogAction.POSITIVE);
    if (!edit)
        okBTN.setEnabled(false);
    TextWatcher validator = new SimpleTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            int port = portET.getText().toString().length() > 0 ? Integer.parseInt(portET.getText().toString()) : -1;
            okBTN.setEnabled((connectionET.getText().length() > 0 && addressET.getText().length() > 0 && port > 0 && port < 65536 && usernameET.getText().length() > 0 && (passwordET.getText().length() > 0 || selectedParsedKeyPair != null)));
        }
    };
    addressET.addTextChangedListener(validator);
    portET.addTextChangedListener(validator);
    usernameET.addTextChangedListener(validator);
    passwordET.addTextChangedListener(validator);
    return dialog;
}
Also used : EditText(android.widget.EditText) Context(android.content.Context) KeyPair(java.security.KeyPair) BookSorter(com.amaze.filemanager.utils.BookSorter) Bundle(android.os.Bundle) AppConfig(com.amaze.filemanager.utils.application.AppConfig) ColorUsage(com.amaze.filemanager.utils.color.ColorUsage) Uri(android.net.Uri) MainFragment(com.amaze.filemanager.fragments.MainFragment) UtilsHandler(com.amaze.filemanager.database.UtilsHandler) Dialog(android.app.Dialog) Intent(android.content.Intent) AsyncTaskResult(com.amaze.filemanager.asynchronous.asynctasks.AsyncTaskResult) Editable(android.text.Editable) MainActivity(com.amaze.filemanager.activities.MainActivity) MDButton(com.afollestad.materialdialogs.internal.MDButton) SecurityUtils(net.schmizz.sshj.common.SecurityUtils) SshClientUtils(com.amaze.filemanager.filesystem.ssh.SshClientUtils) GetSshHostFingerprintTask(com.amaze.filemanager.asynchronous.asynctasks.ssh.GetSshHostFingerprintTask) DataUtils(com.amaze.filemanager.utils.DataUtils) View(android.view.View) Button(android.widget.Button) DialogFragment(android.app.DialogFragment) Log(android.util.Log) UtilitiesProvider(com.amaze.filemanager.utils.provider.UtilitiesProvider) SshConnectionPool(com.amaze.filemanager.filesystem.ssh.SshConnectionPool) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) PublicKey(java.security.PublicKey) InputStreamReader(java.io.InputStreamReader) FileNotFoundException(java.io.FileNotFoundException) AlertDialog(android.app.AlertDialog) SshAuthenticationTask(com.amaze.filemanager.asynchronous.asynctasks.ssh.SshAuthenticationTask) PemToKeyPairTask(com.amaze.filemanager.asynchronous.asynctasks.ssh.PemToKeyPairTask) SSHClient(net.schmizz.sshj.SSHClient) R(com.amaze.filemanager.R) BufferedReader(java.io.BufferedReader) Snackbar(android.support.design.widget.Snackbar) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Activity(android.app.Activity) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) OpenMode(com.amaze.filemanager.utils.OpenMode) Collections(java.util.Collections) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) InputStream(java.io.InputStream) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) PublicKey(java.security.PublicKey) Intent(android.content.Intent) View(android.view.View) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) MDButton(com.afollestad.materialdialogs.internal.MDButton) Button(android.widget.Button) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) GetSshHostFingerprintTask(com.amaze.filemanager.asynchronous.asynctasks.ssh.GetSshHostFingerprintTask)

Example 2 with SimpleTextWatcher

use of com.amaze.filemanager.utils.SimpleTextWatcher in project AmazeFileManager by TeamAmaze.

the class SmbConnectDialog method onCreateDialog.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final boolean edit = getArguments().getBoolean("edit", false);
    final String path = getArguments().getString("path");
    final String name = getArguments().getString("name");
    context = getActivity();
    emptyAddress = String.format(getString(R.string.cantbeempty), getString(R.string.ip));
    emptyName = String.format(getString(R.string.cantbeempty), getString(R.string.connectionname));
    invalidDomain = String.format(getString(R.string.invalid), getString(R.string.domain));
    invalidUsername = String.format(getString(R.string.invalid), getString(R.string.username).toLowerCase());
    if (getActivity() instanceof SmbConnectionListener) {
        smbConnectionListener = (SmbConnectionListener) getActivity();
    }
    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    final MaterialDialog.Builder ba3 = new MaterialDialog.Builder(context);
    ba3.title((R.string.smb_con));
    ba3.autoDismiss(false);
    final View v2 = getActivity().getLayoutInflater().inflate(R.layout.smb_dialog, null);
    final TextInputLayout connectionTIL = (TextInputLayout) v2.findViewById(R.id.connectionTIL);
    final TextInputLayout ipTIL = (TextInputLayout) v2.findViewById(R.id.ipTIL);
    final TextInputLayout domainTIL = (TextInputLayout) v2.findViewById(R.id.domainTIL);
    final TextInputLayout usernameTIL = (TextInputLayout) v2.findViewById(R.id.usernameTIL);
    final AppCompatEditText conName = (AppCompatEditText) v2.findViewById(R.id.connectionET);
    conName.addTextChangedListener(new SimpleTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (conName.getText().toString().length() == 0)
                connectionTIL.setError(emptyName);
            else
                connectionTIL.setError("");
        }
    });
    final AppCompatEditText ip = (AppCompatEditText) v2.findViewById(R.id.ipET);
    ip.addTextChangedListener(new SimpleTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (ip.getText().toString().length() == 0)
                ipTIL.setError(emptyAddress);
            else
                ipTIL.setError("");
        }
    });
    final AppCompatEditText domain = (AppCompatEditText) v2.findViewById(R.id.domainET);
    domain.addTextChangedListener(new SimpleTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (domain.getText().toString().contains(";"))
                domainTIL.setError(invalidDomain);
            else
                domainTIL.setError("");
        }
    });
    final AppCompatEditText user = (AppCompatEditText) v2.findViewById(R.id.usernameET);
    user.addTextChangedListener(new SimpleTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (user.getText().toString().contains(":"))
                usernameTIL.setError(invalidUsername);
            else
                usernameTIL.setError("");
        }
    });
    int accentColor = utilsProvider.getColorPreference().getColor(ColorUsage.ACCENT);
    final AppCompatEditText pass = (AppCompatEditText) v2.findViewById(R.id.passwordET);
    final AppCompatCheckBox ch = (AppCompatCheckBox) v2.findViewById(R.id.checkBox2);
    TextView help = (TextView) v2.findViewById(R.id.wanthelp);
    EditTextColorStateUtil.setTint(context, conName, accentColor);
    EditTextColorStateUtil.setTint(context, user, accentColor);
    EditTextColorStateUtil.setTint(context, pass, accentColor);
    Utils.setTint(context, ch, accentColor);
    help.setOnClickListener(v -> {
        int accentColor1 = ((ThemedActivity) getActivity()).getColorPreference().getColor(ColorUsage.ACCENT);
        GeneralDialogCreation.showSMBHelpDialog(context, accentColor1);
    });
    ch.setOnClickListener(view -> {
        if (ch.isChecked()) {
            user.setEnabled(false);
            pass.setEnabled(false);
        } else {
            user.setEnabled(true);
            pass.setEnabled(true);
        }
    });
    if (edit) {
        String userp = "", passp = "", ipp = "", domainp = "";
        conName.setText(name);
        try {
            jcifs.Config.registerSmbURLHandler();
            URL a = new URL(path);
            String userinfo = a.getUserInfo();
            if (userinfo != null) {
                String inf = URLDecoder.decode(userinfo, "UTF-8");
                int domainDelim = !inf.contains(";") ? 0 : inf.indexOf(';');
                domainp = inf.substring(0, domainDelim);
                if (domainp != null && domainp.length() > 0)
                    inf = inf.substring(domainDelim + 1);
                userp = inf.substring(0, inf.indexOf(":"));
                passp = inf.substring(inf.indexOf(":") + 1, inf.length());
                domain.setText(domainp);
                user.setText(userp);
                pass.setText(passp);
            } else
                ch.setChecked(true);
            ipp = a.getHost();
            ip.setText(ipp);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    } else if (path != null && path.length() > 0) {
        conName.setText(name);
        ip.setText(path);
        user.requestFocus();
    } else {
        conName.setText(R.string.smb_con);
        conName.requestFocus();
    }
    ba3.customView(v2, true);
    ba3.theme(utilsProvider.getAppTheme().getMaterialDialogTheme());
    ba3.neutralText(R.string.cancel);
    ba3.positiveText(R.string.create);
    if (edit)
        ba3.negativeText(R.string.delete);
    ba3.positiveColor(accentColor).negativeColor(accentColor).neutralColor(accentColor);
    ba3.onPositive((dialog, which) -> {
        String[] s;
        String ipa = ip.getText().toString();
        String con_nam = conName.getText().toString();
        String sDomain = domain.getText().toString();
        String username = user.getText().toString();
        TextInputLayout firstInvalidField = null;
        if (con_nam == null || con_nam.length() == 0) {
            connectionTIL.setError(emptyName);
            firstInvalidField = connectionTIL;
        }
        if (ipa == null || ipa.length() == 0) {
            ipTIL.setError(emptyAddress);
            if (firstInvalidField == null)
                firstInvalidField = ipTIL;
        }
        if (sDomain.contains(";")) {
            domainTIL.setError(invalidDomain);
            if (firstInvalidField == null)
                firstInvalidField = domainTIL;
        }
        if (username.contains(":")) {
            usernameTIL.setError(invalidUsername);
            if (firstInvalidField == null)
                firstInvalidField = usernameTIL;
        }
        if (firstInvalidField != null) {
            firstInvalidField.requestFocus();
            return;
        }
        SmbFile smbFile;
        String domaind = domain.getText().toString();
        if (ch.isChecked())
            smbFile = createSMBPath(new String[] { ipa, "", "", domaind }, true);
        else {
            String useraw = user.getText().toString();
            String useru = useraw.replaceAll(" ", "\\ ");
            String passp = pass.getText().toString();
            smbFile = createSMBPath(new String[] { ipa, useru, passp, domaind }, false);
        }
        if (smbFile == null)
            return;
        try {
            s = new String[] { conName.getText().toString(), SmbUtil.getSmbEncryptedPath(getActivity(), smbFile.getPath()) };
        } catch (GeneralSecurityException | IOException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), getResources().getString(R.string.error), Toast.LENGTH_LONG).show();
            return;
        }
        if (smbConnectionListener != null) {
            // encrypted path means path with encrypted pass
            smbConnectionListener.addConnection(edit, s[0], smbFile.getPath(), s[1], name, path);
        }
        dismiss();
    });
    ba3.onNegative((dialog, which) -> {
        if (smbConnectionListener != null) {
            smbConnectionListener.deleteConnection(name, path);
        }
        dismiss();
    });
    ba3.onNeutral((dialog, which) -> dismiss());
    return ba3.build();
}
Also used : MalformedURLException(java.net.MalformedURLException) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) SharedPreferences(android.content.SharedPreferences) GeneralSecurityException(java.security.GeneralSecurityException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) View(android.view.View) TextView(android.widget.TextView) URL(java.net.URL) AppCompatCheckBox(android.support.v7.widget.AppCompatCheckBox) SmbFile(jcifs.smb.SmbFile) AppCompatEditText(android.support.v7.widget.AppCompatEditText) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) Editable(android.text.Editable) TextView(android.widget.TextView) TextInputLayout(android.support.design.widget.TextInputLayout)

Example 3 with SimpleTextWatcher

use of com.amaze.filemanager.utils.SimpleTextWatcher in project AmazeFileManager by TeamAmaze.

the class GeneralDialogCreation method showEncryptAuthenticateDialog.

public static void showEncryptAuthenticateDialog(final Context c, final Intent intent, final MainActivity main, AppTheme appTheme, final EncryptDecryptUtils.EncryptButtonCallbackInterface encryptButtonCallbackInterface) {
    int accentColor = main.getColorPreference().getColor(ColorUsage.ACCENT);
    MaterialDialog.Builder builder = new MaterialDialog.Builder(c);
    builder.title(main.getResources().getString(R.string.crypt_encrypt));
    View rootView = View.inflate(c, R.layout.dialog_encrypt_authenticate, null);
    final AppCompatEditText passwordEditText = rootView.findViewById(R.id.edit_text_dialog_encrypt_password);
    final AppCompatEditText passwordConfirmEditText = rootView.findViewById(R.id.edit_text_dialog_encrypt_password_confirm);
    passwordEditText.post(() -> {
        InputMethodManager imm = (InputMethodManager) main.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(passwordEditText, InputMethodManager.SHOW_IMPLICIT);
    });
    TextInputLayout textInputLayoutPassword = rootView.findViewById(R.id.til_encrypt_password);
    TextInputLayout textInputLayoutPasswordConfirm = rootView.findViewById(R.id.til_encrypt_password_confirm);
    passwordEditText.addTextChangedListener(new SimpleTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            if (!TextUtils.isEmpty(s.toString())) {
                textInputLayoutPassword.setError("");
            }
        }
    });
    passwordConfirmEditText.addTextChangedListener(new SimpleTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            if (s.toString().equals(passwordEditText.getText().toString())) {
                textInputLayoutPasswordConfirm.setError("");
            }
        }
    });
    passwordConfirmEditText.setOnFocusChangeListener((v, hasFocus) -> {
        if (TextUtils.isEmpty(passwordEditText.getText().toString())) {
            textInputLayoutPassword.setError(c.getResources().getString(R.string.error) + ": " + String.format(c.getResources().getString(R.string.cantbeempty), c.getResources().getString(R.string.password)));
        } else {
            textInputLayoutPassword.setError("");
        }
    });
    passwordEditText.setOnFocusChangeListener((v, hasFocus) -> {
        boolean isPasswordSame = passwordConfirmEditText.getText().toString().equals(passwordEditText.getText().toString());
        if (!isPasswordSame && !TextUtils.isEmpty(passwordConfirmEditText.getText().toString())) {
            textInputLayoutPasswordConfirm.setError(c.getResources().getString(R.string.error) + ": " + c.getResources().getString(R.string.password_no_match));
        }
    });
    builder.customView(rootView, true);
    builder.positiveText(c.getString(R.string.ok));
    builder.negativeText(c.getString(R.string.cancel));
    builder.theme(appTheme.getMaterialDialogTheme());
    builder.positiveColor(accentColor);
    builder.negativeColor(accentColor);
    builder.onNegative((dialog, which) -> dialog.cancel());
    builder.autoDismiss(false);
    builder.onPositive((dialog, which) -> {
        if (TextUtils.isEmpty(passwordEditText.getText().toString())) {
            textInputLayoutPassword.setError(c.getResources().getString(R.string.error) + ": " + String.format(c.getResources().getString(R.string.cantbeempty), c.getResources().getString(R.string.password)));
        } else if (!passwordConfirmEditText.getText().toString().equals(passwordEditText.getText().toString())) {
            textInputLayoutPasswordConfirm.setError(c.getResources().getString(R.string.error) + ": " + c.getResources().getString(R.string.password_no_match));
        } else {
            try {
                encryptButtonCallbackInterface.onButtonPressed(intent, passwordEditText.getText().toString());
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(c, c.getString(R.string.crypt_encryption_fail), Toast.LENGTH_LONG).show();
            } finally {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
Also used : MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) InputMethodManager(android.view.inputmethod.InputMethodManager) View(android.view.View) TextView(android.widget.TextView) ShellNotRunningException(com.amaze.filemanager.exceptions.ShellNotRunningException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AppCompatEditText(android.support.v7.widget.AppCompatEditText) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) Editable(android.text.Editable) TextInputLayout(android.support.design.widget.TextInputLayout)

Example 4 with SimpleTextWatcher

use of com.amaze.filemanager.utils.SimpleTextWatcher in project AmazeFileManager by TeamAmaze.

the class RenameBookmark method onCreateDialog.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Context c = getActivity();
    if (getActivity() instanceof BookmarkCallback)
        bookmarkCallback = (BookmarkCallback) getActivity();
    title = getArguments().getString("title");
    path = getArguments().getString("path");
    int accentColor = getArguments().getInt("accentColor");
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
    studiomode = sp.getInt("studio", 0);
    if (dataUtils.containsBooks(new String[] { title, path }) != -1) {
        final MaterialDialog materialDialog;
        String pa = path;
        MaterialDialog.Builder builder = new MaterialDialog.Builder(c);
        builder.title(R.string.renamebookmark);
        builder.positiveColor(accentColor);
        builder.negativeColor(accentColor);
        builder.neutralColor(accentColor);
        builder.positiveText(R.string.save);
        builder.neutralText(R.string.cancel);
        builder.negativeText(R.string.delete);
        builder.theme(((BasicActivity) getActivity()).getAppTheme().getMaterialDialogTheme());
        builder.autoDismiss(false);
        View v2 = getActivity().getLayoutInflater().inflate(R.layout.rename, null);
        builder.customView(v2, true);
        final TextInputLayout t1 = v2.findViewById(R.id.t1);
        final TextInputLayout t2 = v2.findViewById(R.id.t2);
        final AppCompatEditText conName = v2.findViewById(R.id.editText4);
        conName.setText(title);
        final String s1 = String.format(getString(R.string.cantbeempty), c.getResources().getString(R.string.name));
        final String s2 = String.format(getString(R.string.cantbeempty), c.getResources().getString(R.string.path));
        conName.addTextChangedListener(new SimpleTextWatcher() {

            @Override
            public void afterTextChanged(Editable s) {
                if (conName.getText().toString().length() == 0)
                    t1.setError(s2);
                else
                    t1.setError("");
            }
        });
        final AppCompatEditText ip = v2.findViewById(R.id.editText);
        if (studiomode != 0) {
            if (path.startsWith("smb:/")) {
                try {
                    jcifs.Config.registerSmbURLHandler();
                    URL a = new URL(path);
                    String userinfo = a.getUserInfo();
                    if (userinfo != null) {
                        String inf = URLDecoder.decode(userinfo, "UTF-8");
                        user = inf.substring(0, inf.indexOf(":"));
                        pass = inf.substring(inf.indexOf(":") + 1, inf.length());
                        String ipp = a.getHost();
                        pa = "smb://" + ipp + a.getPath();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            ip.addTextChangedListener(new SimpleTextWatcher() {

                @Override
                public void afterTextChanged(Editable s) {
                    if (ip.getText().toString().length() == 0)
                        t2.setError(s1);
                    else
                        t2.setError("");
                }
            });
        } else
            t2.setVisibility(View.GONE);
        ip.setText(pa);
        builder.onNeutral((dialog, which) -> dialog.dismiss());
        materialDialog = builder.build();
        materialDialog.getActionButton(DialogAction.POSITIVE).setOnClickListener(v -> {
            String t = ip.getText().toString();
            String name = conName.getText().toString();
            if (studiomode != 0 && t.startsWith("smb://")) {
                try {
                    URL a = new URL(t);
                    String userinfo = a.getUserInfo();
                    if (userinfo == null && user.length() > 0) {
                        t = "smb://" + ((URLEncoder.encode(user, "UTF-8") + ":" + URLEncoder.encode(pass, "UTF-8") + "@")) + a.getHost() + a.getPath();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            int i = -1;
            if ((i = dataUtils.containsBooks(new String[] { title, path })) != -1) {
                if (!t.equals(title) && t.length() >= 1) {
                    dataUtils.removeBook(i);
                    dataUtils.addBook(new String[] { name, t });
                    dataUtils.sortBook();
                    if (bookmarkCallback != null) {
                        bookmarkCallback.modify(path, title, t, name);
                    }
                }
            }
            materialDialog.dismiss();
        });
        materialDialog.getActionButton(DialogAction.NEGATIVE).setOnClickListener(v -> {
            int i;
            if ((i = dataUtils.containsBooks(new String[] { title, path })) != -1) {
                dataUtils.removeBook(i);
                if (bookmarkCallback != null) {
                    bookmarkCallback.delete(title, path);
                }
            }
            materialDialog.dismiss();
        });
        return materialDialog;
    }
    return null;
}
Also used : Context(android.content.Context) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) SharedPreferences(android.content.SharedPreferences) BasicActivity(com.amaze.filemanager.activities.superclasses.BasicActivity) View(android.view.View) URL(java.net.URL) AppCompatEditText(android.support.v7.widget.AppCompatEditText) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) Editable(android.text.Editable) TextInputLayout(android.support.design.widget.TextInputLayout)

Aggregations

Editable (android.text.Editable)4 View (android.view.View)4 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)4 SimpleTextWatcher (com.amaze.filemanager.utils.SimpleTextWatcher)4 TextInputLayout (android.support.design.widget.TextInputLayout)3 AppCompatEditText (android.support.v7.widget.AppCompatEditText)3 IOException (java.io.IOException)3 Context (android.content.Context)2 SharedPreferences (android.content.SharedPreferences)2 TextView (android.widget.TextView)2 Activity (android.app.Activity)1 AlertDialog (android.app.AlertDialog)1 Dialog (android.app.Dialog)1 DialogFragment (android.app.DialogFragment)1 Intent (android.content.Intent)1 Uri (android.net.Uri)1 Bundle (android.os.Bundle)1 Snackbar (android.support.design.widget.Snackbar)1 AppCompatCheckBox (android.support.v7.widget.AppCompatCheckBox)1 TextWatcher (android.text.TextWatcher)1