public class SimplicityApplication extends Application {

    @SuppressLint("StaticFieldLeak")
    public static Context mContext;

    public static Context getContextOfApplication() {
        return mContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        PreferenceManager.setDefaultValues(mContext, R.xml.settings, true);
        PreferenceManager.setDefaultValues(mContext, R.xml.flags_settings, true);
        PreferenceManager.setDefaultValues(mContext, R.xml.plugin_settings, true);
        createNotificationChannel();
       

    }

    //notification channel for Simplicity's downloader
    private void createNotificationChannel() {
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                CharSequence widget_name = getString(R.string.notifications_widget);
                String widget_description = getString(R.string.notifications_widget_description);
                int wimp = NotificationManager.IMPORTANCE_LOW;

                NotificationChannel channel5 = new NotificationChannel(getString(R.string.notification_widget_channel), widget_name, wimp);
                channel5.setDescription(widget_description);
                channel5.setShowBadge(true);
                channel5.enableVibration(false);
                channel5.enableLights(true);

                NotificationManager notificationManager = getSystemService(NotificationManager.class);
                assert notificationManager != null;
                if (notificationManager.getNotificationChannel(getString(R.string.notification_widget_channel)) == null) {
                    notificationManager.createNotificationChannel(channel5);

                }

            }
    }

} public class BookmarkItems {
    private String title;
    private String url;
    private String letter;
    private int color;

    public void setTitle(String title) {
        this.title = title;
    }

    public void setImage(int color) {
        this.color = color;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setLetter(String letter) {
        this.letter = letter;
    }


    public String getTitle() {
        return title;
    }

    public int getImage() {
        return color;
    }


    public String getUrl() {
        return url;
    }

    public String getLetter() {
        return letter;
    }
} public class SuggestionsAdapterPrivate extends BaseAdapter implements Filterable {
    private final ArrayList<String> mItems = new ArrayList<>();
    private final LayoutInflater mInflater;
    private final ItemFilter mFilter;
    private String mQueryText;

    public SuggestionsAdapterPrivate(Context context) {
        super();
        mInflater = LayoutInflater.from(context);
        mFilter = new ItemFilter();
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Object getItem(int position) {
        return mItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.header_suggestions, parent, false);
        }
        return super.getDropDownView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.layout_suggest_items_private, parent, false);
        }

        ImageView arrow = convertView.findViewById(R.id.search_arrow);

        TextView title = convertView.findViewById(R.id.suggestion_text);
        String suggestion = mItems.get(position);

        if (mQueryText != null) {
            SpannableStringBuilder spannable = new SpannableStringBuilder(suggestion);
            String lcSuggestion = suggestion.toLowerCase(Locale.getDefault());
            int queryTextPos = lcSuggestion.indexOf(mQueryText);
            while (queryTextPos >= 0) {
                spannable.setSpan(new StyleSpan(Typeface.BOLD), queryTextPos, queryTextPos + mQueryText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                queryTextPos = lcSuggestion.indexOf(mQueryText, queryTextPos + mQueryText.length());
            }
            title.setText(spannable);
        } else {
            title.setText(suggestion);
        }
        try {
            arrow.setOnClickListener(v -> new Handler().postDelayed(() -> {
                ((PrivateActivity) PrivateActivity.getPriavteActivity()).mSearchView.setText(suggestion);
                ((PrivateActivity) PrivateActivity.getPriavteActivity()).mSearchView.setSelection(suggestion.length());
            }, 200));
        }catch (Exception i){
            i.printStackTrace();
        }
        return convertView;
    }

    @Override
    public Filter getFilter() {
        return mFilter;
    }

    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (constraint == null || constraint.length() == 0) {
                return results;
            }

            SuggestionProvider provider = new SearchSuggestions();
            String query = constraint.toString().toLowerCase(Locale.getDefault()).trim();

            List<String> items = provider.fetchResults(query);
            results.count = items.size();
            results.values = items;

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            mItems.clear();
            if (results.values != null) {
                List<String> items = (List<String>) results.values;
                mItems.addAll(items);
            }
            mQueryText = constraint != null ? constraint.toString().toLowerCase(Locale.getDefault()).trim() : null;
            notifyDataSetChanged();
        }



    }
} public class Cardbar {

    public static @CheckResult
        Toast snackBar(Context context, CharSequence message_to_show, boolean duration) {
        @SuppressLint("InflateParams")
        View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_snackbar, null);
        AppCompatTextView message = view.findViewById(R.id.message);
        message.setText(message_to_show);
        Toast toast = new Toast(context);
        toast.setView(view);
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
        if (duration) {
            toast.setDuration(Toast.LENGTH_LONG);
        } else {
            toast.setDuration(Toast.LENGTH_SHORT);
        }
        return toast;
    }

} public class SimpleAutoComplete extends AppCompatAutoCompleteTextView {
    private View.OnFocusChangeListener mFocusChangeListener;
    private int mPositionX;

    public SimpleAutoComplete(Context context) {
        super(context);
    }

    public SimpleAutoComplete(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SimpleAutoComplete(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setOnFocusChangeListener(OnFocusChangeListener l) {
        mFocusChangeListener = l;
    }

    @Override
    public OnFocusChangeListener getOnFocusChangeListener() {
        return mFocusChangeListener;
    }

    @Override
    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
        try {
            if (mFocusChangeListener != null) {
                mFocusChangeListener.onFocusChange(this, gainFocus);
            }
            super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
        }catch (NullPointerException i){
            i.printStackTrace();
        }catch (Exception p){
            p.printStackTrace();
        }
    }

    private static LinearGradient getGradient(float widthEnd, float fadeStart, float stopStart, float stopEnd, int color) {
        return new LinearGradient(0, 0, widthEnd, 0,
                new int[]{color, Color.TRANSPARENT, color, color, Color.TRANSPARENT},
                new float[]{0, fadeStart, stopStart, stopEnd, 1f}, Shader.TileMode.CLAMP);
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        try {
            super.onScrollChanged(x, y, oldX, oldY);
            mPositionX = x;
            requestLayout();
        }catch (NullPointerException i){
            i.printStackTrace();
        }catch (Exception p){
            p.printStackTrace();
        }
    }

    @Override
    public void onDraw(Canvas canvas) {
        try {
            float lineWidth = getLayout().getLineWidth(0);
            float width = getMeasuredWidth();

            if (getText() == null || getText().length() == 0 || lineWidth <= width) {
                getPaint().setShader(null);
                super.onDraw(canvas);
                return;
            }

            int textColor = getCurrentTextColor();
            float widthEnd = width + mPositionX;
            float percent = (int) (width * 0.2);

            float fadeStart = mPositionX / widthEnd;

            float stopStart = mPositionX > 0 ? ((mPositionX + percent) / widthEnd) : 0;
            float stopEnd = (widthEnd - (lineWidth > widthEnd ? percent : 0)) / widthEnd;
            getPaint().setShader(getGradient(widthEnd, fadeStart, stopStart, stopEnd, textColor));
            super.onDraw(canvas);
        }catch (NullPointerException i){
            i.printStackTrace();
        }catch (Exception p){
            p.printStackTrace();
        }
    }
} public class SimplicitySslCertificate extends DialogFragment {
    @NonNull
    @SuppressLint("InflateParams")
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Get the activity's layout inflater.
        LayoutInflater layoutInflater   = Objects.requireNonNull(getActivity()).getLayoutInflater();

        // Create a drawable version of the favorite icon.
        Drawable favoriteIconDrawable = new BitmapDrawable(getResources(), MainActivity.favoriteIcon);

        // Use `AlertDialog.Builder` to create the `AlertDialog`.  `R.style.LightAlertDialog` formats the color of the button text.
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
        dialogBuilder.setIcon(favoriteIconDrawable);

        // Set an `onClick` listener on the negative button.  Using `null` closes the dialog without doing anything else.
        dialogBuilder.setNegativeButton(R.string.ok, null);

        // Check to see if the website is encrypted.
        if (MainActivity.sslCertificate == null) {  // The website is not encrypted.
            // Set the title.
            dialogBuilder.setTitle(R.string.unencrypted_website);

            // Set the Layout.  The parent view is `null` because it will be assigned by `AlertDialog`.
            dialogBuilder.setView(layoutInflater.inflate(R.layout.layout_none_https, null));

            // Create an `AlertDialog` from the `AlertDialog.Builder`
            final AlertDialog alertDialog = dialogBuilder.create();

            // Show `alertDialog`.
            alertDialog.show();

            // `onCreateDialog` requires the return of an `AlertDialog`.
            return alertDialog;

        } else {  // Display the SSL certificate information
            // Set the title.
            dialogBuilder.setTitle(R.string.ssl_certificate);

            // Set the layout.  The parent view is `null` because it will be assigned by `AlertDialog`.
            dialogBuilder.setView(layoutInflater.inflate(R.layout.layout_https, null));

            // Create an `AlertDialog` from the `AlertDialog.Builder`
            final AlertDialog alertDialog = dialogBuilder.create();

            // We need to show the `AlertDialog` before we can modify items in the layout.
            alertDialog.show();

            // Get handles for the `TextViews`.
            TextView issuedToCNameTextView = alertDialog.findViewById(R.id.issued_to_cname);
            TextView issuedToONameTextView = alertDialog.findViewById(R.id.issued_to_oname);
            TextView issuedToUNameTextView = alertDialog.findViewById(R.id.issued_to_uname);
            TextView issuedByCNameTextView = alertDialog.findViewById(R.id.issued_by_cname);
            TextView issuedByONameTextView = alertDialog.findViewById(R.id.issued_by_oname);
            TextView issuedByUNameTextView = alertDialog.findViewById(R.id.issued_by_uname);
            TextView startDateTextView = alertDialog.findViewById(R.id.start_date);
            TextView endDateTextView = alertDialog.findViewById(R.id.end_date);

            // Setup the labels.
            String cNameLabel = getString(R.string.common_name) + "  ";
            String oNameLabel = getString(R.string.organization) + "  ";
            String uNameLabel = getString(R.string.organizational_unit) + "  ";
            String startDateLabel = getString(R.string.start_date) + "  ";
            String endDateLabel = getString(R.string.end_date) + "  ";

            // Get the SSL certificate.
            SslCertificate sslCertificate = MainActivity.sslCertificate;

            // Get the strings from the SSL certificate.
            String issuedToCNameString = sslCertificate.getIssuedTo().getCName();
            String issuedToONameString = sslCertificate.getIssuedTo().getOName();
            String issuedToUNameString = sslCertificate.getIssuedTo().getUName();
            String issuedByCNameString = sslCertificate.getIssuedBy().getCName();
            String issuedByONameString = sslCertificate.getIssuedBy().getOName();
            String issuedByUNameString = sslCertificate.getIssuedBy().getUName();
            Date startDate = sslCertificate.getValidNotBeforeDate();
            Date endDate = sslCertificate.getValidNotAfterDate();

            // Create a `SpannableStringBuilder` for each `TextView` that needs multiple colors of text.
            SpannableStringBuilder issuedToCNameStringBuilder = new SpannableStringBuilder(cNameLabel + issuedToCNameString);
            SpannableStringBuilder issuedToONameStringBuilder = new SpannableStringBuilder(oNameLabel + issuedToONameString);
            SpannableStringBuilder issuedToUNameStringBuilder = new SpannableStringBuilder(uNameLabel + issuedToUNameString);
            SpannableStringBuilder issuedByCNameStringBuilder = new SpannableStringBuilder(cNameLabel + issuedByCNameString);
            SpannableStringBuilder issuedByONameStringBuilder = new SpannableStringBuilder(oNameLabel + issuedByONameString);
            SpannableStringBuilder issuedByUNameStringBuilder = new SpannableStringBuilder(uNameLabel + issuedByUNameString);
            SpannableStringBuilder startDateStringBuilder = new SpannableStringBuilder(startDateLabel + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(startDate));
            SpannableStringBuilder endDateStringBuilder = new SpannableStringBuilder(endDateLabel + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(endDate));



            // Display the strings.
            if (issuedToCNameTextView != null) {
                issuedToCNameTextView.setText(issuedToCNameStringBuilder);
            }
            if (issuedToONameTextView != null) {
                issuedToONameTextView.setText(issuedToONameStringBuilder);
            }
            if (issuedToUNameTextView != null) {
                issuedToUNameTextView.setText(issuedToUNameStringBuilder);
            }
            if (issuedByCNameTextView != null) {
                issuedByCNameTextView.setText(issuedByCNameStringBuilder);
            }
            if (issuedByONameTextView != null) {
                issuedByONameTextView.setText(issuedByONameStringBuilder);
            }
            if (issuedByUNameTextView != null) {
                issuedByUNameTextView.setText(issuedByUNameStringBuilder);
            }
            if (startDateTextView != null) {
                startDateTextView.setText(startDateStringBuilder);
            }
            if (endDateTextView != null) {
                endDateTextView.setText(endDateStringBuilder);
            }

            // `onCreateDialog` requires the return of an `AlertDialog`.
            return alertDialog;
        }
    }
} public class FileSize extends AsyncTask<Void, Void, Void> {

    private String mUrl;
    private int fileLength;
    private static final String TAG;
    static {
        TAG = FileSize.class.getSimpleName();
    }
    public FileSize(String url) {
        mUrl = url;

    }


    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL(mUrl);
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            fileLength = url.openConnection().getContentLength();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        MainActivity.file_size_main = getFileSize((long) fileLength);
        Log.d(TAG, getFileSize((long) fileLength));
    }

    private static String getFileSize(long size){
        if (size <= 0)
            return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
} public class SimplicityDownloader extends AsyncTask<String, Integer, String> {
    private final int id = 101;
    @SuppressLint("StaticFieldLeak")
    private Context context;
    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder build;
    private int fileLength;
    private long total = 0;
    private String filename;
    private File imageStorageDir;

    public SimplicityDownloader(Context context) {
        this.context = context;
        mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        build = new NotificationCompat.Builder(context, context.getString(R.string.notification_widget_channel));
    }

    private static String getFileNameTwitter(String url) {
        int index = url.indexOf("?format=");
        if (index > -1) {
            url = url.substring(0, index);
        }

        index = url.lastIndexOf("/");
        if (index > -1) {
            return url.substring(index + 1);
        } else {
            return Long.toString(System.currentTimeMillis());
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        build.setProgress(0, 0, true);
        build.setAutoCancel(true);
        build.setContentTitle(context.getString(R.string.downloading));
        build.setSmallIcon(android.R.drawable.stat_sys_download);
        build.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), android.R.drawable.stat_sys_download)).build();
        build.setWhen(System.currentTimeMillis());
        mNotifyManager.notify(id, build.build());
    }

    @Override
    protected String doInBackground(String... string) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "/Simplicity/Simplicity Downloads");

            if (!imageStorageDir.exists()) {
                //noinspection ResultOfMethodCallIgnored
                imageStorageDir.mkdirs();
            }
            URL url = new URL(string[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
            }

            String twitterExtension = ".jpg";
            if (string[0].contains(".gif"))
                twitterExtension = ".gif";
            else if (string[0].contains(".png"))
                twitterExtension = ".png";
            else if (string[0].contains(".3gp"))
                twitterExtension = ".3gp";

            fileLength = connection.getContentLength();
            if (string[0].contains("pbs.twimg.com")) {
                filename = getFileNameTwitter(string[0]) + twitterExtension;
            } else {
                filename = URLUtil.guessFileName(string[0], null, Helpers.getMimeType(Uri.parse(string[0]).toString()));
            }
            input = connection.getInputStream();
            output = new FileOutputStream(imageStorageDir + File.separator + filename);
            byte[] data = new byte[1024 * 4];
            int count;
            /*Calendar lastUpdate = Calendar.getInstance();*/
            while ((count = input.read(data)) > 0) {
                total += count;
                /*Calendar now = Calendar.getInstance();
                if (now.getTimeInMillis() - lastUpdate.getTimeInMillis() >= 1500) {
                    lastUpdate = now;
                    publishProgress((int) ((total * 100 / fileLength)));
                }*/
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {

            }
            if (connection != null)
                connection.disconnect();
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        build.setProgress(0, 0, true);
        if (!StaticUtils.isNetworkConnected(context)) {
            cancel(true);
        }
    }

    @Override
    protected void onPostExecute(String file_url) {
        if (file_url != null) {
            mNotifyManager.cancel(id);
            build.setContentText(context.getResources().getString(android.R.string.httpErrorBadUrl))
                    .setContentTitle(filename)
                    .setShowWhen(true)
                    .setWhen(System.currentTimeMillis())
                    .setAutoCancel(true)
                    .setTimeoutAfter(10000)
                    .setProgress(0, 0, false)
                    .setSmallIcon(R.drawable.ic_error);
            Notification notification = build.build();
            mNotifyManager.notify(id, notification);
            Cardbar.snackBar(context, context.getString(R.string.download_failed), true).show();
        } else {
            try {
                mNotifyManager.cancel(id);
                File newFile = new File(imageStorageDir + File.separator, filename);
                Uri files = FileProvider.getUriForFile(context, context.getString(R.string.auth), newFile);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(files, getMimeType(files));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                PendingIntent resultPendingIntent = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                build.setContentIntent(resultPendingIntent)
                        .setShowWhen(true)
                        .setWhen(System.currentTimeMillis())
                        .setContentTitle(filename)
                        .setContentText("Download complete " + context.getString(R.string.bullet) + " " + getFileSize(fileLength))
                        .setAutoCancel(true)
                        .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_download_done))
                        .setProgress(0, 0, false)
                        .setSmallIcon(R.drawable.ic_check_download);
                Notification notification = build.build();
                mNotifyManager.notify(id, notification);
                Cardbar.snackBar(context, context.getString(R.string.download_successful), true).show();
                MediaScannerConnection.scanFile(context, new String[]{imageStorageDir + File.separator + filename}, null, (path, uri) -> Log.i("Saved and scanned to", path));
            } catch (ActivityNotFoundException e) {
                Cardbar.snackBar(context, "Cannot open file.", true).show();

            }

        }
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        Cardbar.snackBar(context, context.getString(R.string.download_cancelled), true).show();

    }

    private String getMimeType(Uri uri) {
        String mimeType;
        if (Objects.equals(uri.getScheme(), ContentResolver.SCHEME_CONTENT)) {
            ContentResolver cr = context.getContentResolver();
            mimeType = cr.getType(uri);
        } else {
            String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                    .toString());
            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                    fileExtension.toLowerCase());
        }
        return mimeType;
    }
} public class StaticUtils {
    private static final String ALLOWED_CHARACTERS = UUID.randomUUID().toString().replace("-", "_").replace("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "").replace("abcdefghijklmnopqrztuvwxyz", "") + "JANAETYKESHIAJORELLSHARELL"+ SimplicityApplication.getContextOfApplication().getResources().getString(R.string.app_name);


    public static int darkColor(int color) {
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        hsv[2] *= 1.0f;
        return Color.HSVToColor(hsv);
    }

    public static int colorNav(int color) {
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        hsv[2] *= 1.0f;
        return Color.HSVToColor(hsv);
    }

    public static int lightColor(int color) {
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        hsv[1] *= 0.6f;
        return Color.HSVToColor(hsv);
    }


    public static boolean isColorDark(int color) {
        double darkness = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255;
        return darkness >= 0.5;
    }

    public static int getColor(Bitmap bitmap, boolean incognito) {
        Palette palette = Palette.from(bitmap).generate();
        final int fallback = Color.TRANSPARENT;
        return incognito ? palette.getMutedColor(fallback) : palette.getVibrantColor(fallback);
    }


    public static int adjustAlpha(int color, @SuppressWarnings("SameParameterValue") float factor) {
        int alpha = Math.round(Color.alpha(color) * factor);
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        return Color.argb(alpha, red, green, blue);
    }
    public static int parseColor (String color, @SuppressWarnings("SameParameterValue") float factor){
        int alpha = Math.round(Color.alpha(Color.parseColor(color)) * factor);
        int red = Color.red(Color.parseColor(color));
        int green = Color.green(Color.parseColor(color));
        int blue = Color.blue(Color.parseColor(color));
        return Color.argb(alpha, red, green, blue);
    }


    public static int getColor(Context context){
        TypedValue typedValue = new TypedValue();
        Resources.Theme theme = context.getTheme();
        theme.resolveAttribute(R.attr.iconPrefColor, typedValue, true);
        @ColorInt int color = typedValue.data;
        return color;
    }



    public static void hideKeyboard(View view) {
        InputMethodManager imm = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            imm = view.getContext().getSystemService(InputMethodManager.class);
        }
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    public static boolean isLollipop() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    }

    public static boolean isOreo() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1;
    }

    public static boolean isMarshmallow() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }


    public static int fetchColorPrimary(Context context) {
        int colorAttr;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            colorAttr = android.R.attr.colorPrimary;
        } else {

            colorAttr = context.getResources().getIdentifier("colorPrimary", "attr", context.getPackageName());
        }
        TypedValue outValue = new TypedValue();
        context.getTheme().resolveAttribute(colorAttr, outValue, true);
        return outValue.data;
    }

    public static int fetchColorPrimaryDark(Context context) {
        int colorAttr;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            colorAttr = android.R.attr.colorPrimaryDark;
        } else {

            colorAttr = context.getResources().getIdentifier("colorPrimaryDark", "attr", context.getPackageName());
        }
        TypedValue outValue = new TypedValue();
        context.getTheme().resolveAttribute(colorAttr, outValue, true);
        return outValue.data;
    }


    public static String getAppVersionName(Context context) {
        String res = "0.0.0.0";
        try {
            res = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    // method for clearing cache
    public static void deleteCache(Context context) {
        File cache = context.getCacheDir();
        File appDir = new File(cache.getParent());
        if (appDir.exists()) {
            String[] children = appDir.list();
            for (String s : children) {
                if (!s.equals("lib") && !s.equals("shared_prefs") && !s.equals("databases")) {
                    deleteDir(new File(appDir, s));
                }
            }
        }
    }

    // helper method for clearing cache
    private static boolean deleteDir(File dir) {
        if (dir == null)
            return false;
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (String child : children) {
                boolean success = deleteDir(new File(dir, child));
                if (!success)
                    return false;
            }
        }
        return dir.delete();
    }


    public static Bitmap getCircleBitmap(Bitmap bitmap) {
        Bitmap out = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(out);
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getWidth());
        @SuppressWarnings("IntegerDivisionInFloatingPointContext")
        float radius = bitmap.getWidth() / 2;
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawCircle(radius, radius, radius, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return Bitmap.createScaledBitmap(out, 192, 192, true);
    }


    @WorkerThread
    public static Bitmap createScaledBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
        if (bitmap.getWidth() <= maxWidth && bitmap.getHeight() <= maxHeight) {
            return bitmap;
        }

        if (maxWidth <= 0 || maxHeight <= 0) {
            return bitmap;
        }

        int newWidth  = maxWidth;
        int newHeight = maxHeight;

        float widthRatio  = bitmap.getWidth()  / (float) maxWidth;
        float heightRatio = bitmap.getHeight() / (float) maxHeight;

        if (widthRatio > heightRatio) {
            newHeight = (int) (bitmap.getHeight() / widthRatio);
        } else {
            newWidth = (int) (bitmap.getWidth() / heightRatio);
        }

        return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
    }

    public static Bitmap getCroppedBitmap(Bitmap circle) {
        final Bitmap bitmap = Bitmap.createBitmap(circle.getWidth(), circle.getHeight(), Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, circle.getWidth(), circle.getHeight());
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawCircle(circle.getWidth() >> 1, circle.getHeight() >> 1, circle.getWidth() >> 1, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(circle, rect, rect, paint);
        return bitmap;
    }


    @SuppressWarnings (value="unused")
    public static boolean appInstalledOrNot(Context content, String uri) {
        PackageManager pm = content.getPackageManager();
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return false;
    }



    public static void setLightStatusBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int flags = activity.getWindow().getDecorView().getSystemUiVisibility(); // get current flag
            flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;   // add LIGHT_STATUS_BAR to flag
            activity.getWindow().getDecorView().setSystemUiVisibility(flags);
        }
    }

    public static void clearLightStatusBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int flags = activity.getWindow().getDecorView().getSystemUiVisibility(); // get current flag
            flags &= ~ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; // use XOR here for remove LIGHT_STATUS_BAR from flags_settings
            activity.getWindow().getDecorView().setSystemUiVisibility(flags);
        }
    }

    public static void setLightNavigationBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int flags = activity.getWindow().getDecorView().getSystemUiVisibility(); // get current flag
            flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;   // add LIGHT_STATUS_BAR to flag
            activity.getWindow().getDecorView().setSystemUiVisibility(flags);
        }
    }

    public static void clearNavigationBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int flags = activity.getWindow().getDecorView().getSystemUiVisibility(); // get current flag
            flags &= ~ View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; // use XOR here for remove LIGHT_STATUS_BAR from flags_settings
            activity.getWindow().getDecorView().setSystemUiVisibility(flags);
        }
    }

    public static void copyTextToClipboard(Context context, View view, String label, String text) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(label, text);
        clipboard.setPrimaryClip(clip);
        Cardbar.snackBar(context, "Copied to clipboard", true).show();

    }

    public static String getRandomString(final int sizeOfRandomString) {
        final Random random = new Random();
        final StringBuilder sb = new StringBuilder(sizeOfRandomString);
        for(int i=0;i <sizeOfRandomString;++i)
            sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
        return sb.toString();
    }

    public static String getDomainName(@NonNull String url) throws URISyntaxException {
        URI uri = new URI(url);
        String domain = uri.getHost();
        domain = domain.startsWith("www.") ? domain.substring(4) : domain;
        try {
            //Try to get the domain without subdomain. Ex: mobile.twitter.com would returns twitter.com
            //Note: InternetDomainName is from Guava library
            return InternetDomainName.from(domain).topPrivateDomain().toString();
        } catch (IllegalStateException e) {
            Log.e("getDomainName()", "Illegal url");
        }
        return domain;
    }


    public static String fixURL(String q){
        while (q.endsWith(" "))
            q= q.substring(0, q.length()-1);
        if (q.contains(".") && !q.contains(" ")){
            if (q.startsWith("http://")||q.startsWith("https://"))
                return q;
            else if (q.startsWith("www."))
                return "http://"+q;
            else if (q.startsWith("file:"))
                return q;
            else
                return "http://"+q;
        }
        else if (q.startsWith("about:")||q.startsWith("file:"))
            return q;
        else
            return UserPreferences.getString("search_engine", "")+q.replace(" ", "%20").replace("+", "%2B").replace("&","%26");
    }


    public static String getFileSize(long size){
        if (size <= 0)
            return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }


    public static void openDownloads(@NonNull Activity activity) {
        try {
            if (isSamsung()) {
                Intent intent = activity.getPackageManager().getLaunchIntentForPackage("com.sec.android.app.myfiles");
                assert intent != null;
                intent.setAction("samsung.myfiles.intent.action.LAUNCH_MY_FILES");
                intent.putExtra("samsung.myfiles.intent.extra.START_PATH", getDownloadsFile().getPath());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(intent);
            } else {
                Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
                downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(downloadManagerIntent);
            }
        }catch (ActivityNotFoundException | NullPointerException z){
            z.printStackTrace();
        }
    }

    private static boolean isSamsung() {
        String manufacturer = Build.MANUFACTURER;
        if (manufacturer != null) return manufacturer.toLowerCase().equals("samsung");
        return false;
    }

    private static File getDownloadsFile() {
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    }

    public static boolean isNetworkConnected(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return connectivityManager.getActiveNetworkInfo() != null;
    }

} public final class UserPreferences {
    private static final String FONT_SIZE = "font_pref";
    private static final String TOOLBAR_STYLE = "address_bar";
    private static final String SIMPLICITY_BOOKMARKS = "simplicity_bookmarks";
    private static final String SIMPLICITY_HISTORY = "simplicity_history";
    private static final String CUSTOM_FONT_PREF = "custom_font";
    private static SharedPreferences mPreferences;
    @SuppressLint("StaticFieldLeak")
    private static UserPreferences sInstance;
    @SuppressLint("StaticFieldLeak")
    private static Context mContext;


    public static ArrayList<String> list = new ArrayList<>();
    UserPreferences(final Context context) {
        mContext = context;
        mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    }


    public static UserPreferences getInstance(final Context context) {
        if (sInstance == null) {
            sInstance = new UserPreferences(context.getApplicationContext());
        }
        return sInstance;
    }



    public static boolean getBoolean(String key, boolean defValue) {
        return PreferenceManager.getDefaultSharedPreferences(SimplicityApplication.getContextOfApplication()).getBoolean(key, defValue);
    }

    @SuppressLint("ApplySharedPref")
    public static boolean putBoolean(String key, boolean value) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(SimplicityApplication.getContextOfApplication()).edit();
        editor.putBoolean(key, value);
        editor.commit();
        return value;
    }

    public static String getString(String key) {
        return PreferenceManager.getDefaultSharedPreferences(SimplicityApplication.getContextOfApplication()).getString(key, "[]");
    }

    @SuppressWarnings (value="unused")
    public static int getInt(String key, int defValue) {
        return PreferenceManager.getDefaultSharedPreferences(SimplicityApplication.getContextOfApplication()).getInt(key, defValue);
    }


    public static String getString(String key, String value) {
        return PreferenceManager.getDefaultSharedPreferences(SimplicityApplication.getContextOfApplication()).getString(key, value);
    }

    public static void putString(String key, String value) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(SimplicityApplication.getContextOfApplication()).edit();
        editor.putString(key, value);
        editor.apply();
    }

    public static void clearPrefrence(String key) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(SimplicityApplication.getContextOfApplication()).edit();
        editor.remove(key);
        editor.apply();
    }

    @SuppressWarnings (value="unused")
    public static int putInt(String key, int defValue) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(SimplicityApplication.getContextOfApplication()).edit();
        editor.putInt(key, defValue);
        editor.apply();
        return defValue;
    }


    public String getTabs() {
        return mPreferences.getString(TOOLBAR_STYLE, "top");
    }

    @SuppressWarnings (value="unused")
    public String getCustomFontPref() {
        return mPreferences.getString(CUSTOM_FONT_PREF, "");
    }

    public String getFont() {
        return mPreferences.getString(FONT_SIZE, "default_font");
    }


    public static ArrayList<String> getSimpleDownloads() {
        String bookmarks = PreferenceManager.getDefaultSharedPreferences(mContext).getString("simple_downloads", "[]");
        ArrayList<String> listFilters = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(bookmarks);
            for (int i = 0; i < array.length(); i++) {
                String filter = (String) array.get(i);
                listFilters.add(filter);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return listFilters;
    }


    public static void saveSimpleDownloads(ArrayList<String> listFilters) {
        JSONArray array = new JSONArray();
        for (String string : listFilters) {
            array.put(string);
        }
        PreferenceManager.getDefaultSharedPreferences(mContext).edit().putString("simple_downloads", array.toString()).apply();
    }


    //bookmarks
    public static ArrayList<BookmarkItems> getBookmarks() {
        String bookmarks = getString("simplicity_bookmarks");
        ArrayList<BookmarkItems> listBookmarks = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(bookmarks);
            for (int i = 0; i < array.length(); i++) {
                JSONObject ob = array.getJSONObject(i);
                BookmarkItems bookmark = new BookmarkItems();
                bookmark.setTitle(ob.getString("title"));
                bookmark.setUrl(ob.optString("url"));
                bookmark.setLetter(ob.getString("letter"));
                bookmark.setImage(ob.getInt("color"));
                listBookmarks.add(bookmark);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return listBookmarks;
    }

    public static void saveBookmarks(ArrayList<BookmarkItems> listBookmarks) {
        JSONArray array = new JSONArray();
        Iterator it = listBookmarks.iterator();
        if (it.hasNext()) {
            do {
                BookmarkItems bookmark = (BookmarkItems) it.next();
                JSONObject ob = new JSONObject();
                try {
                    ob.put("title", bookmark.getTitle());
                    ob.put("url", bookmark.getUrl());
                    ob.put("letter", bookmark.getLetter());
                    ob.put("color", bookmark.getImage());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                array.put(ob);
            } while (it.hasNext());
        }
        putString("simplicity_bookmarks", array.toString());
    }


    //history
    public static ArrayList<HistoryItems> getHistory() {
        String historyItem = getString("simplicity_history");
        ArrayList<HistoryItems> listBookmarks = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(historyItem);
            for (int i = 0; i < array.length(); i++) {
                JSONObject ob = array.getJSONObject(i);
                HistoryItems history = new HistoryItems();
                history.setTitle(ob.getString("title"));
                history.setUrl(ob.getString("url"));
                history.setDate(ob.optString("date"));
                listBookmarks.add(history);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return listBookmarks;
    }

    public static void saveHistory(ArrayList<HistoryItems> listBookmarks) {
        JSONArray array = new JSONArray();
        Iterator it = listBookmarks.iterator();
        if (it.hasNext()) {
            do {
                HistoryItems bookmark = (HistoryItems) it.next();
                JSONObject ob = new JSONObject();
                try {
                    ob.put("title", bookmark.getTitle());
                    ob.put("url", bookmark.getUrl());
                    ob.put("date", bookmark.getDate());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                array.put(ob);
            } while (it.hasNext());
        }
        putString("simplicity_history", array.toString());
    }


    String getSimplicityBookmarks() {
        return mPreferences.getString(SIMPLICITY_BOOKMARKS, "");
    }

    void setSimplicityBookmarks(String marks) {
        PreferenceManager.getDefaultSharedPreferences(mContext).edit().putString(SIMPLICITY_BOOKMARKS, marks).apply();
    }

    String getSimplicityHistory() {
        return mPreferences.getString(SIMPLICITY_HISTORY , "");
    }

    void setSimplicityHistory(String his) {
        PreferenceManager.getDefaultSharedPreferences(mContext).edit().putString(SIMPLICITY_HISTORY , his).apply();
    }


    public static boolean isStarred(String bookmark) {
        if (bookmark == null || bookmark.isEmpty()) {
            return false;
        }
        String removeStart = removeStart(bookmark);
        for (BookmarkItems url : getBookmarks()) {
            if (removeStart(url.getUrl()).equals(removeStart)) {
                return true;
            }
        }
        return false;
    }

    private static String removeStart(String url) {
        return url.replaceFirst("^(http(?>s)://\\.|http(?>s)://)", "");
    }



    public static boolean isHistory(String history) {
        if (history == null || history.isEmpty()) {
            return false;
        }
        String removeStart = getHome(history);
        for (HistoryItems url : getHistory()) {
            if (getHome(url.getUrl()).equals(removeStart)) {
                return true;
            }
        }
        return false;
    }

    private static String getHome(String url) {
        return url.replaceFirst("^(http(?>s)://\\.|http(?>s)://)", "");
    }


    public static boolean isDangerousFileExtension(String url) {
        int index = url.indexOf("?");
        if (index > -1) {
            url = url.substring(0, index);
        }
        url = url.toLowerCase();

        for (String type : DOWNLOAD_FILE_TYPES) {
            if (url.endsWith(type)) return true;
        }

        return false;
    }

    private static final String[] DOWNLOAD_FILE_TYPES = {
            ".apk", ".exe", ".jar", ".bat", ".xls",
            ".js", ".sh", ".bin", "app", "com", "scr",
            "vbs", "cmd", "xlsx", "docx", "pdf", "msi", "dmg",
            "wsh", "wsf", "ws", "vbscript", "workflow", "vbe", "vs",
            "run", "rgs", "reg", "ps1", "paf", "pif", "osx", "out",
            "lnk", "jse", "job", "ksh", "ipa", "csh", "command", "action",
            "chm",
    };

} public class PrivateWebview extends WebView implements NestedScrollingChild {
    private int mLastY;
    private final int[] mScrollOffset = new int[2];
    private final int[] mScrollConsumed = new int[2];
    private int mNestedOffsetY;
    private NestedScrollingChildHelper mChildHelper;

    private OnScrollChangedCallback mOnScrollChangedCallback;

    public PrivateWebview(Context context) {
        this(context, null);
    }

    public PrivateWebview(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.webViewStyle);
    }

    public PrivateWebview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mChildHelper = new NestedScrollingChildHelper(this);
        setNestedScrollingEnabled(true);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        final MotionEvent event = MotionEvent.obtain(ev);
        final int action = ev.getActionMasked();
        if (action == MotionEvent.ACTION_DOWN) {
            mNestedOffsetY = 0;
        }

        final int eventY = (int) event.getY();
        event.offsetLocation(0, mNestedOffsetY);

        switch (action) {
            case MotionEvent.ACTION_MOVE:
                int deltaY = mLastY - eventY;

                if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) {
                    deltaY -= mScrollConsumed[1];
                    event.offsetLocation(0, -mScrollOffset[1]);
                    mNestedOffsetY += mScrollOffset[1];
                }

                mLastY = eventY - mScrollOffset[1];

                if (dispatchNestedScroll(0, mScrollOffset[1], 0, deltaY, mScrollOffset)) {
                    mLastY -= mScrollOffset[1];
                    event.offsetLocation(0, mScrollOffset[1]);
                    mNestedOffsetY += mScrollOffset[1];
                }
                break;

            case MotionEvent.ACTION_DOWN:
                mLastY = eventY;
                startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);

                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                stopNestedScroll();
                break;

            default:
                // We don't care about other touch events
        }

        // Execute event handler from parent class in all cases
        boolean eventHandled = super.onTouchEvent(event);

        // Recycle previously obtained event
        event.recycle();

        return eventHandled;
    }

    // Nested Scroll implements
    @Override
    public void setNestedScrollingEnabled(boolean enabled) {
        mChildHelper.setNestedScrollingEnabled(enabled);
    }

    @Override
    public boolean isNestedScrollingEnabled() {
        return mChildHelper.isNestedScrollingEnabled();
    }

    @Override
    public boolean startNestedScroll(int axes) {
        return mChildHelper.startNestedScroll(axes);
    }

    @Override
    public void stopNestedScroll() {
        mChildHelper.stopNestedScroll();
    }

    @Override
    public boolean hasNestedScrollingParent() {
        return mChildHelper.hasNestedScrollingParent();
    }

    @Override
    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed,
                                        int[] offsetInWindow) {
        return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);
    }

    @Override
    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
        return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
    }

    @Override
    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
        return mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
    }

    @Override
    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
        return mChildHelper.dispatchNestedPreFling(velocityX, velocityY);
    }

    @Override
    protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (mOnScrollChangedCallback != null) mOnScrollChangedCallback.onScroll(l, t);
    }

    public OnScrollChangedCallback getOnScrollChangedCallback() {
        return mOnScrollChangedCallback;
    }

    public void setOnScrollChangedCallback(final OnScrollChangedCallback onScrollChangedCallback) {
        mOnScrollChangedCallback = onScrollChangedCallback;
    }

    /**
     * Impliment in the activity/fragment/view that you want to listen to the webview
     */
    public interface OnScrollChangedCallback {
        void onScroll(int l, int t);
    }

} public class BottomSheetBuilder {

    public static final int MODE_LIST = 0;
    public static final int MODE_GRID = 1;

    @DrawableRes
    private int mBackgroundDrawable;

    @DrawableRes
    private int mDividerBackground;

    @DrawableRes
    private int mItemBackground;

    @StyleRes
    private int mTheme;

    private int mBackgroundColor;
    private int mItemTextColor;
    private int mTitleTextColor;

    private boolean mExpandOnStart = false;
    private int mIconTintColor = -1;
    private int mMode;
    private Menu mMenu;
    private BottomSheetAdapterBuilder mAdapterBuilder;
    private CoordinatorLayout mCoordinatorLayout;
    private AppBarLayout mAppBarLayout;
    private Context mContext;
    private BottomSheetItemClickListener mItemClickListener;

    public BottomSheetBuilder(Context context, CoordinatorLayout coordinatorLayout) {
        mContext = context;
        mCoordinatorLayout = coordinatorLayout;
        mAdapterBuilder = new BottomSheetAdapterBuilder(mContext);
    }

    public BottomSheetBuilder(Context context) {
        this(context, 0);
    }

    public BottomSheetBuilder(Context context, @StyleRes int theme) {
        mContext = context;
        mTheme = theme;
        mAdapterBuilder = new BottomSheetAdapterBuilder(mContext);
    }

    public BottomSheetBuilder setMode(int mode) {
        if (mode != MODE_LIST && mode != MODE_GRID) {
            throw new IllegalArgumentException("Mode must be one of BottomSheetBuilder.MODE_LIST" +
                    "or BottomSheetBuilder.MODE_GRID");
        }
        mMode = mode;
        mAdapterBuilder.setMode(mode);
        return this;
    }

    public BottomSheetBuilder setItemClickListener(BottomSheetItemClickListener listener) {
        mItemClickListener = listener;
        return this;
    }

    public BottomSheetBuilder setMenu(@MenuRes int menu) {
        @SuppressWarnings("ConstantConditions")
        PopupMenu popupMenu = new PopupMenu(mContext, null);
        mMenu = popupMenu.getMenu();
        popupMenu.getMenuInflater().inflate(menu, mMenu);
        return setMenu(mMenu);
    }

    public BottomSheetBuilder setMenu(Menu menu) {
        mMenu = menu;
        mAdapterBuilder.setMenu(mMenu);
        return this;
    }

    public BottomSheetBuilder addTitleItem(@StringRes int title) {
        return addTitleItem(mContext.getString(title));
    }

    public BottomSheetBuilder addTitleItem(String title) {
        if (mMode == BottomSheetBuilder.MODE_GRID) {
            throw new IllegalStateException("You can't add a title with MODE_GRID. " +
                    "Use MODE_LIST instead");
        }
        mAdapterBuilder.addTitleItem(title, mTitleTextColor);
        return this;
    }

    public BottomSheetBuilder addDividerItem() {
        if (mMode == BottomSheetBuilder.MODE_GRID) {
            throw new IllegalStateException("You can't add a divider with MODE_GRID. " +
                    "Use MODE_LIST instead");
        }
        mAdapterBuilder.addDividerItem(mDividerBackground);
        return this;
    }

    public BottomSheetBuilder addItem(int id, @StringRes int title, @DrawableRes int icon) {
        return addItem(id, mContext.getString(title), ContextCompat.getDrawable(mContext, icon));
    }

    public BottomSheetBuilder addItem(int id, @StringRes int title, Drawable icon) {
        return addItem(id, mContext.getString(title), icon);
    }

    public BottomSheetBuilder addItem(int id, String title, @DrawableRes int icon) {
        return addItem(id, title, ContextCompat.getDrawable(mContext, icon));
    }

    public BottomSheetBuilder addItem(int id, String title, Drawable icon) {
        mAdapterBuilder.addItem(id, title, icon, mItemTextColor, mItemBackground, mIconTintColor);
        return this;
    }

    public BottomSheetBuilder setItemTextColor(@ColorInt int color) {
        mItemTextColor = color;
        return this;
    }

    public BottomSheetBuilder setTitleTextColor(@ColorInt int color) {
        mTitleTextColor = color;
        return this;
    }

    public BottomSheetBuilder setBackgroundColor(@ColorInt int color) {
        mBackgroundColor = color;
        return this;
    }

    public BottomSheetBuilder setItemTextColorResource(@ColorRes int color) {
        mItemTextColor = ResourcesCompat.getColor(mContext.getResources(), color,
                mContext.getTheme());
        return this;
    }

    public BottomSheetBuilder setTitleTextColorResource(@ColorRes int color) {
        mTitleTextColor = ResourcesCompat.getColor(mContext.getResources(), color,
                mContext.getTheme());
        return this;
    }

    public BottomSheetBuilder setBackground(@DrawableRes int background) {
        mBackgroundDrawable = background;
        return this;
    }

    public BottomSheetBuilder setBackgroundColorResource(@ColorRes int background) {
        mBackgroundColor = ResourcesCompat.getColor(mContext.getResources(), background,
                mContext.getTheme());
        return this;
    }

    public BottomSheetBuilder setDividerBackground(@DrawableRes int background) {
        mDividerBackground = background;
        return this;
    }

    public BottomSheetBuilder setItemBackground(@DrawableRes int background) {
        mItemBackground = background;
        return this;
    }

    public BottomSheetBuilder expandOnStart(boolean expand) {
        mExpandOnStart = expand;
        return this;
    }

    public BottomSheetBuilder setAppBarLayout(AppBarLayout appbar) {
        mAppBarLayout = appbar;
        return this;
    }

    public BottomSheetBuilder setIconTintColorResource(@ColorRes int color) {
        mIconTintColor = ContextCompat.getColor(mContext, color);
        return this;
    }

    public BottomSheetBuilder setIconTintColor(int color) {
        mIconTintColor = color;
        return this;
    }

    public View createView() {

        if (mMenu == null && mAdapterBuilder.getItems().isEmpty()) {
            throw new IllegalStateException("You need to provide at least one Menu " +
                    "or an item with addItem");
        }

        if (mCoordinatorLayout == null) {
            throw new IllegalStateException("You need to provide a coordinatorLayout" +
                    "so the view can be placed on it");
        }

        View sheet = mAdapterBuilder.createView(mTitleTextColor, mBackgroundDrawable,
                mBackgroundColor, mDividerBackground, mItemTextColor, mItemBackground,
                mIconTintColor, mItemClickListener);

        ViewCompat.setElevation(sheet, mContext.getResources()
                .getDimensionPixelSize(R.dimen.bottomsheet_elevation));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            sheet.findViewById(R.id.fakeShadow).setVisibility(View.GONE);
        }

        CoordinatorLayout.LayoutParams layoutParams
                = new CoordinatorLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT,
                CoordinatorLayout.LayoutParams.WRAP_CONTENT);

        layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
        layoutParams.setBehavior(new BottomSheetBehavior());

        if (mContext.getResources().getBoolean(R.bool.tablet_landscape)) {
            layoutParams.width = mContext.getResources()
                    .getDimensionPixelSize(R.dimen.bottomsheet_width);
        }

        mCoordinatorLayout.addView(sheet, layoutParams);
        mCoordinatorLayout.postInvalidate();
        return sheet;
    }

    public BottomSheetMenuDialog createDialog() {

        if (mMenu == null && mAdapterBuilder.getItems().isEmpty()) {
            throw new IllegalStateException("You need to provide at least one Menu " +
                    "or an item with addItem");
        }

        BottomSheetMenuDialog dialog = mTheme == 0
                ? new BottomSheetMenuDialog(mContext, R.style.BottomSheetBuilder_DialogStyle)
                : new BottomSheetMenuDialog(mContext, mTheme);

        if (mTheme != 0) {
            setupThemeColors(mContext.obtainStyledAttributes(mTheme, new int[]{
                    R.attr.bottomSheetBuilderBackgroundColor,
                    R.attr.bottomSheetBuilderItemTextColor,
                    R.attr.bottomSheetBuilderTitleTextColor}));
        } else {
            setupThemeColors(mContext.getTheme().obtainStyledAttributes(new int[]{
                    R.attr.bottomSheetBuilderBackgroundColor,
                    R.attr.bottomSheetBuilderItemTextColor,
                    R.attr.bottomSheetBuilderTitleTextColor,}));
        }

        View sheet = mAdapterBuilder.createView(mTitleTextColor, mBackgroundDrawable,
                mBackgroundColor, mDividerBackground, mItemTextColor, mItemBackground,
                mIconTintColor, dialog);

        sheet.findViewById(R.id.fakeShadow).setVisibility(View.GONE);
        dialog.setAppBar(mAppBarLayout);
        dialog.expandOnStart(mExpandOnStart);
        dialog.setBottomSheetItemClickListener(mItemClickListener);

        if (mContext.getResources().getBoolean(R.bool.tablet_landscape)) {
            FrameLayout.LayoutParams layoutParams
                    = new FrameLayout.LayoutParams(mContext.getResources()
                    .getDimensionPixelSize(R.dimen.bottomsheet_width),
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            dialog.setContentView(sheet, layoutParams);
        } else {
            dialog.setContentView(sheet);
        }

        return dialog;
    }

    @SuppressWarnings("ResourceType")
    private void setupThemeColors(TypedArray typedArray) {
        int backgroundRes = typedArray.getResourceId(0, mBackgroundColor);
        int textRes = typedArray.getResourceId(1, mItemTextColor);
        int titleRes = typedArray.getResourceId(2, mTitleTextColor);

        if (backgroundRes != mBackgroundColor) {
            mBackgroundColor = ContextCompat.getColor(mContext, backgroundRes);
        }

        if (titleRes != mTitleTextColor) {
            mTitleTextColor = ContextCompat.getColor(mContext, titleRes);
        }

        if (textRes != mItemTextColor) {
            mItemTextColor = ContextCompat.getColor(mContext, textRes);
        }

        typedArray.recycle();
    }

} public class BottomSheetMenuDialog extends BottomSheetDialog implements BottomSheetItemClickListener {

    BottomSheetBehavior.BottomSheetCallback mCallback;
    BottomSheetBehavior mBehavior;
    private BottomSheetItemClickListener mClickListener;
    private AppBarLayout mAppBarLayout;
    private boolean mExpandOnStart;
    boolean mRequestedExpand;
    boolean mClicked;
    boolean mRequestCancel;
    boolean mRequestDismiss;
    OnCancelListener mOnCancelListener;

    public BottomSheetMenuDialog(Context context) {
        super(context);
    }

    public BottomSheetMenuDialog(Context context, int theme) {
        super(context, theme);
    }

    /**
     * Dismiss the BottomSheetDialog while animating the sheet.
     */
    public void dismissWithAnimation() {
        if (mBehavior != null) {
            mBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        }
    }

    @Override
    public void setOnCancelListener(OnCancelListener listener) {
        super.setOnCancelListener(listener);
        mOnCancelListener = listener;
    }

    @Override
    public void cancel() {
        mRequestCancel = true;
        super.cancel();
    }

    @Override
    public void dismiss() {
        mRequestDismiss = true;
        if (mRequestCancel) {
            dismissWithAnimation();
        } else {
            super.dismiss();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        final FrameLayout sheet = findViewById(R.id.design_bottom_sheet);

        if (sheet != null) {
            mBehavior = BottomSheetBehavior.from(sheet);
            mBehavior.setBottomSheetCallback(mBottomSheetCallback);

            if (getContext().getResources().getBoolean(R.bool.tablet_landscape)) {
                CoordinatorLayout.LayoutParams layoutParams
                        = (CoordinatorLayout.LayoutParams) sheet.getLayoutParams();
                layoutParams.width = getContext().getResources()
                        .getDimensionPixelSize(R.dimen.bottomsheet_width);
                sheet.setLayoutParams(layoutParams);
            }

            // Make sure the sheet doesn't overlap the appbar
            if (mAppBarLayout != null) {
                if (mAppBarLayout.getHeight() == 0) {
                    mAppBarLayout.getViewTreeObserver()
                            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                                @Override
                                public void onGlobalLayout() {
                                    applyAppbarMargin(sheet);
                                }
                            });
                } else {
                    applyAppbarMargin(sheet);
                }
            }


            if (mExpandOnStart) {
                sheet.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        mBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                        if (mBehavior.getState() == BottomSheetBehavior.STATE_SETTLING
                                && mRequestedExpand) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                sheet.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            } else {
                                //noinspection deprecation
                                sheet.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            }
                        }
                        mRequestedExpand = true;
                    }
                });
            } else if (getContext().getResources().getBoolean(R.bool.landscape)) {
                fixLandscapePeekHeight(sheet);
            }
        }
    }

    public void setAppBar(AppBarLayout appBar) {
        mAppBarLayout = appBar;
    }

    public void expandOnStart(boolean expand) {
        mExpandOnStart = expand;
    }

    public void setBottomSheetCallback(BottomSheetBehavior.BottomSheetCallback callback) {
        mCallback = callback;
    }

    public void setBottomSheetItemClickListener(BottomSheetItemClickListener listener) {
        mClickListener = listener;
    }

    public BottomSheetBehavior getBehavior() {
        return mBehavior;
    }

    @Override
    public void onBottomSheetItemClick(MenuItem item) {
        if (!mClicked) {

            if (mBehavior != null) {
                mBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
            }

            if (mClickListener != null) {
                mClickListener.onBottomSheetItemClick(item);
            }

            mClicked = true;
        }
    }

    private BottomSheetBehavior.BottomSheetCallback mBottomSheetCallback
            = new BottomSheetBehavior.BottomSheetCallback() {
        @Override
        public void onStateChanged(@NonNull View bottomSheet,
                                   @BottomSheetBehavior.State int newState) {

            if (mCallback != null) {
                mCallback.onStateChanged(bottomSheet, newState);
            }

            //noinspection WrongConstant
            if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                mBehavior.setBottomSheetCallback(null);
                try {
                    BottomSheetMenuDialog.super.dismiss();
                } catch (IllegalArgumentException e) {
                    // Ignore exception handling
                }

                // User dragged the sheet.
                if (!mClicked && !mRequestDismiss && !mRequestCancel && mOnCancelListener != null) {
                    mOnCancelListener.onCancel(BottomSheetMenuDialog.this);
                }
            }
        }

        @Override
        public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            if (mCallback != null) {
                mCallback.onSlide(bottomSheet, slideOffset);
            }
        }
    };

    private void fixLandscapePeekHeight(final View sheet) {
        // On landscape, we shouldn't use the 16:9 keyline alignment
        final int peek = sheet.getResources()
                .getDimensionPixelOffset(R.dimen.bottomsheet_landscape_peek);
        if (sheet.getHeight() != 0) {
            mBehavior.setPeekHeight(Math.max(sheet.getHeight() / 2, peek));
        } else {
            sheet.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (sheet.getHeight() > 0) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            sheet.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        } else {
                            //noinspection deprecation
                            sheet.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        }
                        mBehavior.setPeekHeight(Math.max(sheet.getHeight() / 2, peek));
                    }
                }
            });
        }
    }

    private void applyAppbarMargin(View sheet) {
        CoordinatorLayout.LayoutParams layoutParams
                = (CoordinatorLayout.LayoutParams) sheet.getLayoutParams();
        layoutParams.topMargin = mAppBarLayout.getHeight();
        sheet.setLayoutParams(layoutParams);
    }
}
import android.Manifest;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.preference.PreferenceManager;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.MimeTypeMap;
import android.webkit.PermissionRequest;
import android.webkit.RenderProcessGoneDetail;
import android.webkit.SafeBrowsingResponse;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebViewDatabase;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.drawable.IconCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.DialogFragment;
import androidx.palette.graphics.Palette;
import com.anthonycr.progress.AnimatedProgressBar;
import com.creativetrends.app.simplicity.SimplicityApplication;
import com.creativetrends.app.simplicity.adapters.BookmarkItems;
import com.creativetrends.app.simplicity.suggestions.SuggestionsAdapterPrivate;
import com.creativetrends.app.simplicity.ui.Cardbar;
import com.creativetrends.app.simplicity.ui.SimpleAutoComplete;
import com.creativetrends.app.simplicity.ui.SimplicitySslCertificate;
import com.creativetrends.app.simplicity.utils.FileSize;
import com.creativetrends.app.simplicity.utils.SimplicityDownloader;
import com.creativetrends.app.simplicity.utils.StaticUtils;
import com.creativetrends.app.simplicity.utils.UserPreferences;
import com.creativetrends.app.simplicity.webview.PrivateWebview;
import com.creativetrends.simplicity.app.R;
import com.github.rubensousa.bottomsheetbuilder.BottomSheetBuilder;
import com.github.rubensousa.bottomsheetbuilder.BottomSheetMenuDialog;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.navigation.NavigationView;
import com.google.common.base.Strings;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.Vector;
import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
import static android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                if (!PrivateActivity.this.isDestroyed()) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(PrivateActivity.this);
                    String message = "SSL Certificate error.";
                    switch (error.getPrimaryError()) {
                        case SslError.SSL_UNTRUSTED:
                            message = "The certificate authority is not trusted.";
                            break;
                        case SslError.SSL_EXPIRED:
                            message = "The certificate has expired.";
                            break;
                        case SslError.SSL_IDMISMATCH:
                            message = "The certificate Hostname mismatch.";
                            break;
                        case SslError.SSL_NOTYETVALID:
                            message = "The certificate is not yet valid.";
                            break;
                    }
                    message += " Do you want to continue anyway?";

                    builder.setTitle("SSL Certificate Error");
                    builder.setMessage(message);
                    builder.setPositiveButton("continue", (dialog, which) -> handler.proceed());
                    builder.setNegativeButton("cancel", (dialog, which) -> handler.cancel());
                    final AlertDialog dialog = builder.create();
                    dialog.show();
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                String str;
                if (view.getUrl().contains("https://")) {
                    str = view.getUrl().replace("https://", "https://");
                    if (!mSearchView.hasFocus()) {
                        mSearchView.setText(Html.fromHtml(str), TextView.BufferType.SPANNABLE);
                    }
                    mSecure.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_secure_white));
                    mSecure.setVisibility(View.VISIBLE);
                } else {
                    str = view.getUrl().replace("http://", "http://");
                    if (!mSearchView.hasFocus()) {
                        mSearchView.setText(Html.fromHtml(str), TextView.BufferType.SPANNABLE);
                    }
                    mSecure.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_unsecure_white));
                    mSecure.setVisibility(View.VISIBLE);
                }

                if (isLoading) {
                    mStop_rel.setVisibility(View.VISIBLE);
                    mRefresh_rel.setVisibility(View.GONE);
                    mRefresh.setColorFilter(ContextCompat.getColor(SimplicityApplication.getContextOfApplication(), R.color.white), PorterDuff.Mode.SRC_IN);
                    mStop.setColorFilter(ContextCompat.getColor(SimplicityApplication.getContextOfApplication(), R.color.white), PorterDuff.Mode.SRC_IN);
                } else {
                    mStop_rel.setVisibility(View.GONE);
                    mRefresh_rel.setVisibility(View.VISIBLE);
                    mRefresh.setColorFilter(ContextCompat.getColor(SimplicityApplication.getContextOfApplication(), R.color.white), PorterDuff.Mode.SRC_IN);
                    mStop.setColorFilter(ContextCompat.getColor(SimplicityApplication.getContextOfApplication(), R.color.white), PorterDuff.Mode.SRC_IN);
                }


                if (view.getUrl() != null) {
                    onAmpPage(view.getUrl().contains("/amp/"));
                }

                if (mWebView.canGoForward()) {
                    mForward.setAlpha(0.9f);
                } else {
                    mForward.setAlpha(0.2f);
                }


            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                isLoading = !(mWebView != null && mWebView.getProgress() == 100);
                if (mWebView.getTitle().equals("No Connection")) {
                    mSearchView.setText(mWebView.getTitle());
                } else {
                    mSearchView.setText(mWebView.getUrl());
                }
                sslCertificate = view.getCertificate();
            }

        });



        mWebChromeClient = new MyWebChromeClient();
        mWebView.setWebChromeClient(mWebChromeClient);

        mWebView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            filename1 = URLUtil.guessFileName(url, contentDisposition, getMimeType(url));
            urlToGrab = url;
            new FileSize(url).execute();
            if (StaticUtils.isMarshmallow()) {
                if (ActivityCompat.checkSelfPermission(PrivateActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(PrivateActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
                } else {
                    try {
                        if (UserPreferences.getBoolean("rename", false)) {
                            createDownload();
                        } else {
                            Cardbar.snackBar(getApplicationContext(), getString(R.string.downloading), true).show();
                            new SimplicityDownloader(this).execute(urlToGrab);
                        }
                    } catch (Exception exc) {
                        Cardbar.snackBar(getApplicationContext(), exc.toString(), true).show();


                    }
                }
            }
        });

        mSearchView.setAdapter(new SuggestionsAdapterPrivate(this));