Search in sources :

Example 1 with MainActivity

use of com.amaze.filemanager.activities.MainActivity in project AmazeFileManager by TeamAmaze.

the class GeneralDialogCreation method deleteFilesDialog.

@SuppressWarnings("ConstantConditions")
public static void deleteFilesDialog(final Context c, final ArrayList<LayoutElementParcelable> layoutElements, final MainActivity mainActivity, final List<LayoutElementParcelable> positions, AppTheme appTheme) {
    final ArrayList<HybridFileParcelable> itemsToDelete = new ArrayList<>();
    int accentColor = mainActivity.getColorPreference().getColor(ColorUsage.ACCENT);
    // Build dialog with custom view layout and accent color.
    MaterialDialog dialog = new MaterialDialog.Builder(c).title(c.getString(R.string.dialog_delete_title)).customView(R.layout.dialog_delete, true).theme(appTheme.getMaterialDialogTheme()).negativeText(c.getString(R.string.cancel).toUpperCase()).positiveText(c.getString(R.string.delete).toUpperCase()).positiveColor(accentColor).negativeColor(accentColor).onPositive((dialog1, which) -> {
        Toast.makeText(c, c.getString(R.string.deleting), Toast.LENGTH_SHORT).show();
        mainActivity.mainActivityHelper.deleteFiles(itemsToDelete);
    }).build();
    // Get views from custom layout to set text values.
    final TextView categoryDirectories = (TextView) dialog.getCustomView().findViewById(R.id.category_directories);
    final TextView categoryFiles = (TextView) dialog.getCustomView().findViewById(R.id.category_files);
    final TextView listDirectories = (TextView) dialog.getCustomView().findViewById(R.id.list_directories);
    final TextView listFiles = (TextView) dialog.getCustomView().findViewById(R.id.list_files);
    final TextView total = (TextView) dialog.getCustomView().findViewById(R.id.total);
    // Parse items to delete.
    new AsyncTask<Void, Object, Void>() {

        long sizeTotal = 0;

        StringBuilder files = new StringBuilder();

        StringBuilder directories = new StringBuilder();

        int counterDirectories = 0;

        int counterFiles = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            listFiles.setText(c.getString(R.string.loading));
            listDirectories.setText(c.getString(R.string.loading));
            total.setText(c.getString(R.string.loading));
        }

        @Override
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < positions.size(); i++) {
                final LayoutElementParcelable layoutElement = positions.get(i);
                itemsToDelete.add(layoutElement.generateBaseFile());
                // Build list of directories to delete.
                if (layoutElement.isDirectory) {
                    // Don't add newline between category and list.
                    if (counterDirectories != 0) {
                        directories.append("\n");
                    }
                    long sizeDirectory = layoutElement.generateBaseFile().folderSize(c);
                    directories.append(++counterDirectories).append(". ").append(layoutElement.title).append(" (").append(Formatter.formatFileSize(c, sizeDirectory)).append(")");
                    sizeTotal += sizeDirectory;
                // Build list of files to delete.
                } else {
                    // Don't add newline between category and list.
                    if (counterFiles != 0) {
                        files.append("\n");
                    }
                    files.append(++counterFiles).append(". ").append(layoutElement.title).append(" (").append(layoutElement.size).append(")");
                    sizeTotal += layoutElement.longSize;
                }
                publishProgress(sizeTotal, counterFiles, counterDirectories, files, directories);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Object... result) {
            super.onProgressUpdate(result);
            int tempCounterFiles = (int) result[1];
            int tempCounterDirectories = (int) result[2];
            long tempSizeTotal = (long) result[0];
            StringBuilder tempFilesStringBuilder = (StringBuilder) result[3];
            StringBuilder tempDirectoriesStringBuilder = (StringBuilder) result[4];
            updateViews(tempSizeTotal, tempFilesStringBuilder, tempDirectoriesStringBuilder, tempCounterFiles, tempCounterDirectories);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            updateViews(sizeTotal, files, directories, counterFiles, counterDirectories);
        }

        private void updateViews(long tempSizeTotal, StringBuilder filesStringBuilder, StringBuilder directoriesStringBuilder, int... values) {
            int tempCounterFiles = values[0];
            int tempCounterDirectories = values[1];
            // Hide category and list for directories when zero.
            if (tempCounterDirectories == 0) {
                if (tempCounterDirectories == 0) {
                    categoryDirectories.setVisibility(View.GONE);
                    listDirectories.setVisibility(View.GONE);
                }
            // Hide category and list for files when zero.
            }
            if (tempCounterFiles == 0) {
                categoryFiles.setVisibility(View.GONE);
                listFiles.setVisibility(View.GONE);
            }
            if (tempCounterDirectories != 0 || tempCounterFiles != 0) {
                listDirectories.setText(directoriesStringBuilder);
                if (listDirectories.getVisibility() != View.VISIBLE && tempCounterDirectories != 0)
                    listDirectories.setVisibility(View.VISIBLE);
                listFiles.setText(filesStringBuilder);
                if (listFiles.getVisibility() != View.VISIBLE && tempCounterFiles != 0)
                    listFiles.setVisibility(View.VISIBLE);
                if (categoryDirectories.getVisibility() != View.VISIBLE && tempCounterDirectories != 0)
                    categoryDirectories.setVisibility(View.VISIBLE);
                if (categoryFiles.getVisibility() != View.VISIBLE && tempCounterFiles != 0)
                    categoryFiles.setVisibility(View.VISIBLE);
            }
            // Show total size with at least one directory or file and size is not zero.
            if (tempCounterFiles + tempCounterDirectories > 1 && tempSizeTotal > 0) {
                StringBuilder builderTotal = new StringBuilder().append(c.getString(R.string.total)).append(" ").append(Formatter.formatFileSize(c, tempSizeTotal));
                total.setText(builderTotal);
                if (total.getVisibility() != View.VISIBLE)
                    total.setVisibility(View.VISIBLE);
            } else {
                total.setVisibility(View.GONE);
            }
        }
    }.execute();
    // Set category text color for Jelly Bean (API 16) and later.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        categoryDirectories.setTextColor(accentColor);
        categoryFiles.setTextColor(accentColor);
    }
    // Show dialog on screen.
    dialog.show();
}
Also used : LinearLayout(android.widget.LinearLayout) PreferencesConstants(com.amaze.filemanager.fragments.preference_fragments.PreferencesConstants) ColorUsage(com.amaze.filemanager.utils.color.ColorUsage) ShellNotRunningException(com.amaze.filemanager.exceptions.ShellNotRunningException) Uri(android.net.Uri) WindowManager(android.view.WindowManager) TextInputLayout(android.support.design.widget.TextInputLayout) ThemedActivity(com.amaze.filemanager.activities.superclasses.ThemedActivity) AppTheme(com.amaze.filemanager.utils.theme.AppTheme) CompressedHelper(com.amaze.filemanager.filesystem.compressed.CompressedHelper) RootHelper(com.amaze.filemanager.filesystem.RootHelper) GeneralSecurityException(java.security.GeneralSecurityException) CheckBox(android.widget.CheckBox) View(android.view.View) Button(android.widget.Button) RootUtils(com.amaze.filemanager.utils.RootUtils) PreferenceManager(android.preference.PreferenceManager) PieChart(com.github.mikephil.charting.charts.PieChart) PieData(com.github.mikephil.charting.data.PieData) LoadFolderSpaceDataTask(com.amaze.filemanager.asynchronous.asynctasks.LoadFolderSpaceDataTask) LayoutElementParcelable(com.amaze.filemanager.adapters.data.LayoutElementParcelable) M(android.os.Build.VERSION_CODES.M) AsyncTask(android.os.AsyncTask) Entry(com.github.mikephil.charting.data.Entry) InputType(android.text.InputType) FingerprintManager(android.hardware.fingerprint.FingerprintManager) Executors(java.util.concurrent.Executors) CryptUtil(com.amaze.filemanager.utils.files.CryptUtil) List(java.util.List) TextView(android.widget.TextView) HiddenAdapter(com.amaze.filemanager.adapters.HiddenAdapter) R(com.amaze.filemanager.R) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) CountItemsOrAndSizeTask(com.amaze.filemanager.asynchronous.asynctasks.CountItemsOrAndSizeTask) AppCompatEditText(android.support.v7.widget.AppCompatEditText) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) Legend(com.github.mikephil.charting.components.Legend) Typeface(android.graphics.Typeface) Context(android.content.Context) IValueFormatter(com.github.mikephil.charting.formatter.IValueFormatter) HybridFile(com.amaze.filemanager.filesystem.HybridFile) MainFragment(com.amaze.filemanager.fragments.MainFragment) FingerprintHandler(com.amaze.filemanager.utils.FingerprintHandler) Intent(android.content.Intent) RequiresApi(android.support.annotation.RequiresApi) FileUtils.toHybridFileArrayList(com.amaze.filemanager.utils.files.FileUtils.toHybridFileArrayList) AppsListFragment(com.amaze.filemanager.fragments.AppsListFragment) Editable(android.text.Editable) InputMethodManager(android.view.inputmethod.InputMethodManager) MainActivity(com.amaze.filemanager.activities.MainActivity) ArrayList(java.util.ArrayList) AppCompatButton(android.support.v7.widget.AppCompatButton) HybridFileParcelable(com.amaze.filemanager.filesystem.HybridFileParcelable) PieDataSet(com.github.mikephil.charting.data.PieDataSet) Toast(android.widget.Toast) DataUtils(com.amaze.filemanager.utils.DataUtils) Build(android.os.Build) WeakReference(java.lang.ref.WeakReference) ExecutorService(java.util.concurrent.ExecutorService) Formatter(android.text.format.Formatter) GenerateHashesTask(com.amaze.filemanager.asynchronous.asynctasks.GenerateHashesTask) SpannableString(android.text.SpannableString) TextUtils(android.text.TextUtils) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) File(java.io.File) Theme(com.afollestad.materialdialogs.Theme) EncryptDecryptUtils(com.amaze.filemanager.utils.files.EncryptDecryptUtils) Color(android.graphics.Color) Utils(com.amaze.filemanager.utils.Utils) SharedPreferences(android.content.SharedPreferences) BasicActivity(com.amaze.filemanager.activities.superclasses.BasicActivity) ViewPortHandler(com.github.mikephil.charting.utils.ViewPortHandler) FileUtils(com.amaze.filemanager.utils.files.FileUtils) DialogUtils(com.afollestad.materialdialogs.util.DialogUtils) TextInputEditText(android.support.design.widget.TextInputEditText) PieEntry(com.github.mikephil.charting.data.PieEntry) OpenMode(com.amaze.filemanager.utils.OpenMode) EditText(android.widget.EditText) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) FileUtils.toHybridFileArrayList(com.amaze.filemanager.utils.files.FileUtils.toHybridFileArrayList) ArrayList(java.util.ArrayList) LayoutElementParcelable(com.amaze.filemanager.adapters.data.LayoutElementParcelable) HybridFileParcelable(com.amaze.filemanager.filesystem.HybridFileParcelable) TextView(android.widget.TextView)

Example 2 with MainActivity

use of com.amaze.filemanager.activities.MainActivity 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 3 with MainActivity

use of com.amaze.filemanager.activities.MainActivity in project AmazeFileManager by TeamAmaze.

the class AppsListFragment method onActivityCreated.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);
    MainActivity mainActivity = (MainActivity) getActivity();
    mainActivity.getAppbar().setTitle(R.string.apps);
    mainActivity.floatingActionButton.getMenuButton().hide();
    mainActivity.getAppbar().getBottomBar().setVisibility(View.GONE);
    mainActivity.supportInvalidateOptionsMenu();
    vl = getListView();
    Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    getSortModes();
    ListView vl = getListView();
    vl.setDivider(null);
    if (utilsProvider.getAppTheme().equals(AppTheme.DARK))
        getActivity().getWindow().getDecorView().setBackgroundColor(Utils.getColor(getContext(), R.color.holo_dark_background));
    else if (utilsProvider.getAppTheme().equals(AppTheme.BLACK))
        getActivity().getWindow().getDecorView().setBackgroundColor(Utils.getColor(getContext(), android.R.color.black));
    modelProvider = new AppsAdapterPreloadModel(app);
    ViewPreloadSizeProvider<String> sizeProvider = new ViewPreloadSizeProvider<>();
    ListPreloader<String> preloader = new ListPreloader<>(GlideApp.with(app), modelProvider, sizeProvider, GlideConstants.MAX_PRELOAD_APPSADAPTER);
    adapter = new AppsAdapter(getContext(), (ThemedActivity) getActivity(), utilsProvider, modelProvider, sizeProvider, R.layout.rowlayout, app);
    getListView().setOnScrollListener(preloader);
    setListAdapter(adapter);
    setListShown(false);
    setEmptyText(getResources().getString(R.string.no_applications));
    getLoaderManager().initLoader(ID_LOADER_APP_LIST, null, this);
    if (savedInstanceState != null) {
        index = savedInstanceState.getInt(KEY_INDEX);
        top = savedInstanceState.getInt(KEY_TOP);
    }
}
Also used : ListPreloader(com.bumptech.glide.ListPreloader) AppsAdapter(com.amaze.filemanager.adapters.AppsAdapter) ListView(android.widget.ListView) ThemedActivity(com.amaze.filemanager.activities.superclasses.ThemedActivity) MainActivity(com.amaze.filemanager.activities.MainActivity) AppsAdapterPreloadModel(com.amaze.filemanager.adapters.glide.AppsAdapterPreloadModel) ViewPreloadSizeProvider(com.bumptech.glide.util.ViewPreloadSizeProvider)

Example 4 with MainActivity

use of com.amaze.filemanager.activities.MainActivity in project AmazeFileManager by TeamAmaze.

the class HiddenAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(HiddenViewHolder holder, int position) {
    HybridFile file = items.get(position);
    holder.txtTitle.setText(file.getName());
    String a = file.getReadablePath(file.getPath());
    holder.txtDesc.setText(a);
    if (hide) {
        holder.image.setVisibility(View.GONE);
    }
    // TODO: move the listeners to the constructor
    holder.image.setOnClickListener(view -> {
        if (!file.isSmb() && file.isDirectory()) {
            ArrayList<HybridFileParcelable> a1 = new ArrayList<>();
            HybridFileParcelable baseFile = new HybridFileParcelable(items.get(position).getPath() + "/.nomedia");
            baseFile.setMode(OpenMode.FILE);
            a1.add(baseFile);
            new DeleteTask(context.getActivity().getContentResolver(), c).execute((a1));
        }
        dataUtils.removeHiddenFile(items.get(position).getPath());
        items.remove(items.get(position));
        notifyDataSetChanged();
    });
    holder.row.setOnClickListener(view -> {
        materialDialog.dismiss();
        new Thread(() -> {
            if (file.isDirectory()) {
                context.getActivity().runOnUiThread(() -> {
                    context.loadlist(file.getPath(), false, OpenMode.UNKNOWN);
                });
            } else {
                if (!file.isSmb()) {
                    context.getActivity().runOnUiThread(() -> {
                        FileUtils.openFile(new File(file.getPath()), (MainActivity) context.getActivity(), sharedPrefs);
                    });
                }
            }
        }).start();
    });
}
Also used : HybridFileParcelable(com.amaze.filemanager.filesystem.HybridFileParcelable) HybridFile(com.amaze.filemanager.filesystem.HybridFile) ArrayList(java.util.ArrayList) MainActivity(com.amaze.filemanager.activities.MainActivity) HybridFile(com.amaze.filemanager.filesystem.HybridFile) File(java.io.File) DeleteTask(com.amaze.filemanager.asynchronous.asynctasks.DeleteTask)

Example 5 with MainActivity

use of com.amaze.filemanager.activities.MainActivity in project AmazeFileManager by TeamAmaze.

the class GeneralDialogCreation method showPropertiesDialog.

private static void showPropertiesDialog(final HybridFileParcelable baseFile, final String permissions, ThemedActivity base, boolean isRoot, AppTheme appTheme, boolean showPermissions, boolean forStorage) {
    final ExecutorService executor = Executors.newFixedThreadPool(3);
    final Context c = base.getApplicationContext();
    int accentColor = base.getColorPreference().getColor(ColorUsage.ACCENT);
    long last = baseFile.getDate();
    final String date = Utils.getDate(last), items = c.getString(R.string.calculating), name = baseFile.getName(), parent = baseFile.getReadablePath(baseFile.getParent(c));
    MaterialDialog.Builder builder = new MaterialDialog.Builder(base);
    builder.title(c.getString(R.string.properties));
    builder.theme(appTheme.getMaterialDialogTheme());
    View v = base.getLayoutInflater().inflate(R.layout.properties_dialog, null);
    TextView itemsText = (TextView) v.findViewById(R.id.t7);
    /*View setup*/
    {
        TextView mNameTitle = (TextView) v.findViewById(R.id.title_name);
        mNameTitle.setTextColor(accentColor);
        TextView mDateTitle = (TextView) v.findViewById(R.id.title_date);
        mDateTitle.setTextColor(accentColor);
        TextView mSizeTitle = (TextView) v.findViewById(R.id.title_size);
        mSizeTitle.setTextColor(accentColor);
        TextView mLocationTitle = (TextView) v.findViewById(R.id.title_location);
        mLocationTitle.setTextColor(accentColor);
        TextView md5Title = (TextView) v.findViewById(R.id.title_md5);
        md5Title.setTextColor(accentColor);
        TextView sha256Title = (TextView) v.findViewById(R.id.title_sha256);
        sha256Title.setTextColor(accentColor);
        ((TextView) v.findViewById(R.id.t5)).setText(name);
        ((TextView) v.findViewById(R.id.t6)).setText(parent);
        itemsText.setText(items);
        ((TextView) v.findViewById(R.id.t8)).setText(date);
        LinearLayout mNameLinearLayout = (LinearLayout) v.findViewById(R.id.properties_dialog_name);
        LinearLayout mLocationLinearLayout = (LinearLayout) v.findViewById(R.id.properties_dialog_location);
        LinearLayout mSizeLinearLayout = (LinearLayout) v.findViewById(R.id.properties_dialog_size);
        LinearLayout mDateLinearLayout = (LinearLayout) v.findViewById(R.id.properties_dialog_date);
        // setting click listeners for long press
        mNameLinearLayout.setOnLongClickListener(v1 -> {
            FileUtils.copyToClipboard(c, name);
            Toast.makeText(c, c.getResources().getString(R.string.name) + " " + c.getResources().getString(R.string.properties_copied_clipboard), Toast.LENGTH_SHORT).show();
            return false;
        });
        mLocationLinearLayout.setOnLongClickListener(v12 -> {
            FileUtils.copyToClipboard(c, parent);
            Toast.makeText(c, c.getResources().getString(R.string.location) + " " + c.getResources().getString(R.string.properties_copied_clipboard), Toast.LENGTH_SHORT).show();
            return false;
        });
        mSizeLinearLayout.setOnLongClickListener(v13 -> {
            FileUtils.copyToClipboard(c, items);
            Toast.makeText(c, c.getResources().getString(R.string.size) + " " + c.getResources().getString(R.string.properties_copied_clipboard), Toast.LENGTH_SHORT).show();
            return false;
        });
        mDateLinearLayout.setOnLongClickListener(v14 -> {
            FileUtils.copyToClipboard(c, date);
            Toast.makeText(c, c.getResources().getString(R.string.date) + " " + c.getResources().getString(R.string.properties_copied_clipboard), Toast.LENGTH_SHORT).show();
            return false;
        });
    }
    CountItemsOrAndSizeTask countItemsOrAndSizeTask = new CountItemsOrAndSizeTask(c, itemsText, baseFile, forStorage);
    countItemsOrAndSizeTask.executeOnExecutor(executor);
    GenerateHashesTask hashGen = new GenerateHashesTask(baseFile, c, v);
    hashGen.executeOnExecutor(executor);
    /*Chart creation and data loading*/
    {
        boolean isRightToLeft = c.getResources().getBoolean(R.bool.is_right_to_left);
        boolean isDarkTheme = appTheme.getMaterialDialogTheme() == Theme.DARK;
        PieChart chart = (PieChart) v.findViewById(R.id.chart);
        chart.setTouchEnabled(false);
        chart.setDrawEntryLabels(false);
        chart.setDescription(null);
        chart.setNoDataText(c.getString(R.string.loading));
        chart.setRotationAngle(!isRightToLeft ? 0f : 180f);
        chart.setHoleColor(Color.TRANSPARENT);
        chart.setCenterTextColor(isDarkTheme ? Color.WHITE : Color.BLACK);
        chart.getLegend().setEnabled(true);
        chart.getLegend().setForm(Legend.LegendForm.CIRCLE);
        chart.getLegend().setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        chart.getLegend().setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
        chart.getLegend().setTextColor(isDarkTheme ? Color.WHITE : Color.BLACK);
        chart.animateY(1000);
        if (forStorage) {
            final String[] LEGENDS = new String[] { c.getString(R.string.used), c.getString(R.string.free) };
            final int[] COLORS = { Utils.getColor(c, R.color.piechart_red), Utils.getColor(c, R.color.piechart_green) };
            long totalSpace = baseFile.getTotal(c), freeSpace = baseFile.getUsableSpace(), usedSpace = totalSpace - freeSpace;
            List<PieEntry> entries = new ArrayList<>();
            entries.add(new PieEntry(usedSpace, LEGENDS[0]));
            entries.add(new PieEntry(freeSpace, LEGENDS[1]));
            PieDataSet set = new PieDataSet(entries, null);
            set.setColors(COLORS);
            set.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
            set.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
            set.setSliceSpace(5f);
            set.setAutomaticallyDisableSliceSpacing(true);
            set.setValueLinePart2Length(1.05f);
            set.setSelectionShift(0f);
            PieData pieData = new PieData(set);
            pieData.setValueFormatter(new SizeFormatter(c));
            pieData.setValueTextColor(isDarkTheme ? Color.WHITE : Color.BLACK);
            String totalSpaceFormatted = Formatter.formatFileSize(c, totalSpace);
            chart.setCenterText(new SpannableString(c.getString(R.string.total) + "\n" + totalSpaceFormatted));
            chart.setData(pieData);
        } else {
            LoadFolderSpaceDataTask loadFolderSpaceDataTask = new LoadFolderSpaceDataTask(c, appTheme, chart, baseFile);
            loadFolderSpaceDataTask.executeOnExecutor(executor);
        }
        chart.invalidate();
    }
    if (!forStorage && showPermissions) {
        final MainFragment main = ((MainActivity) base).mainFragment;
        AppCompatButton appCompatButton = (AppCompatButton) v.findViewById(R.id.permissionsButton);
        appCompatButton.setAllCaps(true);
        final View permissionsTable = v.findViewById(R.id.permtable);
        final View button = v.findViewById(R.id.set);
        if (isRoot && permissions.length() > 6) {
            appCompatButton.setVisibility(View.VISIBLE);
            appCompatButton.setOnClickListener(v15 -> {
                if (permissionsTable.getVisibility() == View.GONE) {
                    permissionsTable.setVisibility(View.VISIBLE);
                    button.setVisibility(View.VISIBLE);
                    setPermissionsDialog(permissionsTable, button, baseFile, permissions, c, main);
                } else {
                    button.setVisibility(View.GONE);
                    permissionsTable.setVisibility(View.GONE);
                }
            });
        }
    }
    builder.customView(v, true);
    builder.positiveText(base.getResources().getString(R.string.ok));
    builder.positiveColor(accentColor);
    builder.dismissListener(dialog -> executor.shutdown());
    MaterialDialog materialDialog = builder.build();
    materialDialog.show();
    materialDialog.getActionButton(DialogAction.NEGATIVE).setEnabled(false);
/*
        View bottomSheet = c.findViewById(R.id.design_bottom_sheet);
        BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        bottomSheetBehavior.setPeekHeight(BottomSheetBehavior.STATE_DRAGGING);
        */
}
Also used : LinearLayout(android.widget.LinearLayout) PreferencesConstants(com.amaze.filemanager.fragments.preference_fragments.PreferencesConstants) ColorUsage(com.amaze.filemanager.utils.color.ColorUsage) ShellNotRunningException(com.amaze.filemanager.exceptions.ShellNotRunningException) Uri(android.net.Uri) WindowManager(android.view.WindowManager) TextInputLayout(android.support.design.widget.TextInputLayout) ThemedActivity(com.amaze.filemanager.activities.superclasses.ThemedActivity) AppTheme(com.amaze.filemanager.utils.theme.AppTheme) CompressedHelper(com.amaze.filemanager.filesystem.compressed.CompressedHelper) RootHelper(com.amaze.filemanager.filesystem.RootHelper) GeneralSecurityException(java.security.GeneralSecurityException) CheckBox(android.widget.CheckBox) View(android.view.View) Button(android.widget.Button) RootUtils(com.amaze.filemanager.utils.RootUtils) PreferenceManager(android.preference.PreferenceManager) PieChart(com.github.mikephil.charting.charts.PieChart) PieData(com.github.mikephil.charting.data.PieData) LoadFolderSpaceDataTask(com.amaze.filemanager.asynchronous.asynctasks.LoadFolderSpaceDataTask) LayoutElementParcelable(com.amaze.filemanager.adapters.data.LayoutElementParcelable) M(android.os.Build.VERSION_CODES.M) AsyncTask(android.os.AsyncTask) Entry(com.github.mikephil.charting.data.Entry) InputType(android.text.InputType) FingerprintManager(android.hardware.fingerprint.FingerprintManager) Executors(java.util.concurrent.Executors) CryptUtil(com.amaze.filemanager.utils.files.CryptUtil) List(java.util.List) TextView(android.widget.TextView) HiddenAdapter(com.amaze.filemanager.adapters.HiddenAdapter) R(com.amaze.filemanager.R) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) CountItemsOrAndSizeTask(com.amaze.filemanager.asynchronous.asynctasks.CountItemsOrAndSizeTask) AppCompatEditText(android.support.v7.widget.AppCompatEditText) SimpleTextWatcher(com.amaze.filemanager.utils.SimpleTextWatcher) Legend(com.github.mikephil.charting.components.Legend) Typeface(android.graphics.Typeface) Context(android.content.Context) IValueFormatter(com.github.mikephil.charting.formatter.IValueFormatter) HybridFile(com.amaze.filemanager.filesystem.HybridFile) MainFragment(com.amaze.filemanager.fragments.MainFragment) FingerprintHandler(com.amaze.filemanager.utils.FingerprintHandler) Intent(android.content.Intent) RequiresApi(android.support.annotation.RequiresApi) FileUtils.toHybridFileArrayList(com.amaze.filemanager.utils.files.FileUtils.toHybridFileArrayList) AppsListFragment(com.amaze.filemanager.fragments.AppsListFragment) Editable(android.text.Editable) InputMethodManager(android.view.inputmethod.InputMethodManager) MainActivity(com.amaze.filemanager.activities.MainActivity) ArrayList(java.util.ArrayList) AppCompatButton(android.support.v7.widget.AppCompatButton) HybridFileParcelable(com.amaze.filemanager.filesystem.HybridFileParcelable) PieDataSet(com.github.mikephil.charting.data.PieDataSet) Toast(android.widget.Toast) DataUtils(com.amaze.filemanager.utils.DataUtils) Build(android.os.Build) WeakReference(java.lang.ref.WeakReference) ExecutorService(java.util.concurrent.ExecutorService) Formatter(android.text.format.Formatter) GenerateHashesTask(com.amaze.filemanager.asynchronous.asynctasks.GenerateHashesTask) SpannableString(android.text.SpannableString) TextUtils(android.text.TextUtils) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) File(java.io.File) Theme(com.afollestad.materialdialogs.Theme) EncryptDecryptUtils(com.amaze.filemanager.utils.files.EncryptDecryptUtils) Color(android.graphics.Color) Utils(com.amaze.filemanager.utils.Utils) SharedPreferences(android.content.SharedPreferences) BasicActivity(com.amaze.filemanager.activities.superclasses.BasicActivity) ViewPortHandler(com.github.mikephil.charting.utils.ViewPortHandler) FileUtils(com.amaze.filemanager.utils.files.FileUtils) DialogUtils(com.afollestad.materialdialogs.util.DialogUtils) TextInputEditText(android.support.design.widget.TextInputEditText) PieEntry(com.github.mikephil.charting.data.PieEntry) OpenMode(com.amaze.filemanager.utils.OpenMode) EditText(android.widget.EditText) PieEntry(com.github.mikephil.charting.data.PieEntry) SpannableString(android.text.SpannableString) MainActivity(com.amaze.filemanager.activities.MainActivity) MainFragment(com.amaze.filemanager.fragments.MainFragment) PieChart(com.github.mikephil.charting.charts.PieChart) PieDataSet(com.github.mikephil.charting.data.PieDataSet) TextView(android.widget.TextView) List(java.util.List) FileUtils.toHybridFileArrayList(com.amaze.filemanager.utils.files.FileUtils.toHybridFileArrayList) ArrayList(java.util.ArrayList) Context(android.content.Context) GenerateHashesTask(com.amaze.filemanager.asynchronous.asynctasks.GenerateHashesTask) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) View(android.view.View) TextView(android.widget.TextView) CountItemsOrAndSizeTask(com.amaze.filemanager.asynchronous.asynctasks.CountItemsOrAndSizeTask) AppCompatButton(android.support.v7.widget.AppCompatButton) SpannableString(android.text.SpannableString) LoadFolderSpaceDataTask(com.amaze.filemanager.asynchronous.asynctasks.LoadFolderSpaceDataTask) ExecutorService(java.util.concurrent.ExecutorService) PieData(com.github.mikephil.charting.data.PieData) LinearLayout(android.widget.LinearLayout)

Aggregations

MainActivity (com.amaze.filemanager.activities.MainActivity)10 Intent (android.content.Intent)4 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)4 MainFragment (com.amaze.filemanager.fragments.MainFragment)4 IOException (java.io.IOException)4 Context (android.content.Context)3 Uri (android.net.Uri)3 Editable (android.text.Editable)3 View (android.view.View)3 Button (android.widget.Button)3 EditText (android.widget.EditText)3 HybridFile (com.amaze.filemanager.filesystem.HybridFile)3 HybridFileParcelable (com.amaze.filemanager.filesystem.HybridFileParcelable)3 File (java.io.File)3 SharedPreferences (android.content.SharedPreferences)2 Color (android.graphics.Color)2 Typeface (android.graphics.Typeface)2 FingerprintManager (android.hardware.fingerprint.FingerprintManager)2 AsyncTask (android.os.AsyncTask)2 Build (android.os.Build)2