Search in sources :

Example 6 with R

use of me.ccrama.redditslide.R in project Slide by ccrama.

the class SettingsSubAdapter method showSubThemeEditor.

/**
 * Displays the subreddit color chooser
 * It is possible to color multiple subreddits at the same time
 *
 * @param subreddits   Subreddits as an array
 * @param context      Context for getting colors
 * @param dialoglayout The subchooser layout (R.layout.colorsub)
 */
public static void showSubThemeEditor(final ArrayList<String> subreddits, final Activity context, View dialoglayout) {
    if (subreddits.isEmpty()) {
        return;
    }
    final boolean multipleSubs = (subreddits.size() > 1);
    boolean isAlternateLayout;
    int currentColor;
    int currentAccentColor;
    final ColorPreferences colorPrefs = new ColorPreferences(context);
    final String subreddit = multipleSubs ? null : subreddits.get(0);
    final SwitchCompat bigPics = dialoglayout.findViewById(R.id.bigpics);
    final SwitchCompat selftext = dialoglayout.findViewById(R.id.selftext);
    // Selected multiple subreddits
    if (multipleSubs) {
        // Check if all selected subs have the same settings
        int previousSubColor = 0;
        int previousSubAccent = 0;
        bigPics.setChecked(SettingValues.bigPicEnabled);
        selftext.setChecked(SettingValues.cardText);
        boolean sameMainColor = true;
        boolean sameAccentColor = true;
        for (String sub : subreddits) {
            int currentSubColor = Palette.getColor(sub);
            int currentSubAccent = colorPrefs.getColor("");
            if (previousSubColor != 0 && previousSubAccent != 0) {
                if (currentSubColor != previousSubColor) {
                    sameMainColor = false;
                } else if (currentSubAccent != previousSubAccent) {
                    sameAccentColor = false;
                }
            }
            if (!sameMainColor && !sameAccentColor) {
                break;
            }
            previousSubAccent = currentSubAccent;
            previousSubColor = currentSubColor;
        }
        currentColor = Palette.getDefaultColor();
        currentAccentColor = colorPrefs.getColor("");
        isAlternateLayout = false;
        // If all selected subs have the same settings, display them
        if (sameMainColor) {
            currentColor = previousSubColor;
        }
        if (sameAccentColor) {
            currentAccentColor = previousSubAccent;
        }
    } else {
        // Is only one selected sub
        currentColor = Palette.getColor(subreddit);
        isAlternateLayout = SettingValues.prefs.contains(Reddit.PREF_LAYOUT + subreddit);
        currentAccentColor = colorPrefs.getColor(subreddit);
        bigPics.setChecked(SettingValues.isPicsEnabled(subreddit));
        selftext.setChecked(SettingValues.isSelftextEnabled(subreddit));
    }
    final TextView title = dialoglayout.findViewById(R.id.title);
    title.setBackgroundColor(currentColor);
    if (multipleSubs) {
        StringBuilder titleStringBuilder = new StringBuilder();
        for (String sub : subreddits) {
            // if the subreddit is the frontpage, don't put "/r/" in front of it
            if (sub.equals("frontpage")) {
                titleStringBuilder.append(sub).append(", ");
            } else {
                if (sub.contains("/m/")) {
                    titleStringBuilder.append(sub).append(", ");
                } else {
                    titleStringBuilder.append("/r/").append(sub).append(", ");
                }
            }
        }
        String titleString = titleStringBuilder.toString();
        titleString = titleString.substring(0, titleString.length() - 2);
        title.setMaxLines(3);
        title.setText(titleString);
    } else {
        if (subreddit.contains("/m/")) {
            title.setText(subreddit);
        } else {
            // if the subreddit is the frontpage, don't put "/r/" in front of it
            title.setText(((subreddit.equals("frontpage")) ? "frontpage" : "/r/" + subreddit));
        }
    }
    {
        // Primary color pickers
        final LineColorPicker colorPickerPrimary = dialoglayout.findViewById(R.id.picker);
        // shades of primary colors
        final LineColorPicker colorPickerPrimaryShades = dialoglayout.findViewById(R.id.picker2);
        colorPickerPrimary.setColors(ColorPreferences.getBaseColors(context));
        // Iterate through all colors and check if it matches the current color of the sub, then select it
        for (int i : colorPickerPrimary.getColors()) {
            for (int i2 : ColorPreferences.getColors(context, i)) {
                if (i2 == currentColor) {
                    colorPickerPrimary.setSelectedColor(i);
                    colorPickerPrimaryShades.setColors(ColorPreferences.getColors(context, i));
                    colorPickerPrimaryShades.setSelectedColor(i2);
                    break;
                }
            }
        }
        // Base color changed
        colorPickerPrimary.setOnColorChangedListener(new OnColorChangedListener() {

            @Override
            public void onColorChanged(int c) {
                // Show variations of the base color
                colorPickerPrimaryShades.setColors(ColorPreferences.getColors(context, c));
                colorPickerPrimaryShades.setSelectedColor(c);
            }
        });
        colorPickerPrimaryShades.setOnColorChangedListener(new OnColorChangedListener() {

            @Override
            public void onColorChanged(int i) {
                if (context instanceof MainActivity) {
                    ((MainActivity) context).updateColor(colorPickerPrimaryShades.getColor(), subreddit);
                }
                title.setBackgroundColor(colorPickerPrimaryShades.getColor());
            }
        });
        {
        /* TODO   TextView dialogButton = (TextView) dialoglayout.findViewById(R.id.reset);

                            // if button is clicked, close the custom dialog
                            dialogButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Palette.removeColor(subreddit);
                                    hea.setBackgroundColor(Palette.getDefaultColor());
                                    findViewById(R.id.header).setBackgroundColor(Palette.getDefaultColor());
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        Window window = getWindow();
                                        window.setStatusBarColor(Palette.getDarkerColor(Palette.getDefaultColor()));
                                        context.setTaskDescription(new ActivityManager.TaskDescription(subreddit, ((BitmapDrawable) getResources().getDrawable(R.drawable.ic_launcher)).getBitmap(), colorPicker2.getColor()));

                                    }
                                    title.setBackgroundColor(Palette.getDefaultColor());


                                    int cx = center.getWidth() / 2;
                                    int cy = center.getHeight() / 2;

                                    int initialRadius = body.getWidth();
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

                                        Animator anim =
                                                ViewAnimationUtils.createCircularReveal(body, cx, cy, initialRadius, 0);

                                        anim.addListener(new AnimatorListenerAdapter() {
                                            @Override
                                            public void onAnimationEnd(Animator animation) {
                                                super.onAnimationEnd(animation);
                                                body.setVisibility(View.GONE);
                                            }
                                        });
                                        anim.start();

                                    } else {
                                        body.setVisibility(View.GONE);

                                    }

                                }
                            });*/
        }
        // Accent color picker
        final LineColorPicker colorPickerAcc = dialoglayout.findViewById(R.id.picker3);
        {
            // Get all possible accent colors (for day theme)
            int[] arrs = new int[ColorPreferences.getNumColorsFromThemeType(0)];
            int i = 0;
            for (ColorPreferences.Theme type : ColorPreferences.Theme.values()) {
                if (type.getThemeType() == ColorPreferences.ColorThemeOptions.Dark.getValue()) {
                    arrs[i] = ContextCompat.getColor(context, type.getColor());
                    i++;
                }
                colorPickerAcc.setColors(arrs);
                colorPickerAcc.setSelectedColor(currentAccentColor);
            }
        }
        new AlertDialog.Builder(context).setView(dialoglayout).setCancelable(false).setNegativeButton(R.string.btn_cancel, (dialog, which) -> {
            if (context instanceof MainActivity) {
                ((MainActivity) context).updateColor(Palette.getColor(subreddit), subreddit);
            }
        }).setNeutralButton(R.string.btn_reset, (dialog, which) -> {
            String subTitles;
            if (multipleSubs) {
                StringBuilder subTitlesBuilder = new StringBuilder();
                for (String sub : subreddits) {
                    // if the subreddit is the frontpage, don't put "/r/" in front of it
                    if (sub.equals("frontpage")) {
                        subTitlesBuilder.append(sub).append(", ");
                    } else {
                        subTitlesBuilder.append("/r/").append(sub).append(", ");
                    }
                }
                subTitles = subTitlesBuilder.toString();
                subTitles = subTitles.substring(0, subTitles.length() - 2);
            } else {
                // if the subreddit is the frontpage, don't put "/r/" in front of it
                subTitles = (subreddit.equals("frontpage") ? "frontpage" : "/r/" + subreddit);
            }
            String titleStart = context.getString(R.string.settings_delete_sub_settings, subTitles);
            titleStart = titleStart.replace("/r//r/", "/r/");
            if (titleStart.contains("/r/frontpage")) {
                titleStart = titleStart.replace("/r/frontpage", "frontpage");
            }
            new AlertDialog.Builder(context).setTitle(titleStart).setPositiveButton(R.string.btn_yes, (dialog1, which1) -> {
                for (String sub : subreddits) {
                    Palette.removeColor(sub);
                    // Remove layout settings
                    SettingValues.prefs.edit().remove(Reddit.PREF_LAYOUT + sub).apply();
                    // Remove accent / font color settings
                    new ColorPreferences(context).removeFontStyle(sub);
                    SettingValues.resetPicsEnabled(sub);
                    SettingValues.resetSelftextEnabled(sub);
                }
                if (context instanceof MainActivity) {
                    ((MainActivity) context).reloadSubs();
                } else if (context instanceof SettingsSubreddit) {
                    ((SettingsSubreddit) context).reloadSubList();
                } else if (context instanceof SubredditView) {
                    ((SubredditView) context).restartTheme();
                }
            }).setNegativeButton(R.string.btn_no, null).show();
        }).setPositiveButton(R.string.btn_ok, (dialog, which) -> {
            final int newPrimaryColor = colorPickerPrimaryShades.getColor();
            final int newAccentColor = colorPickerAcc.getColor();
            for (String sub : subreddits) {
                // Set main color
                if (bigPics.isChecked() != SettingValues.isPicsEnabled(sub)) {
                    SettingValues.setPicsEnabled(sub, bigPics.isChecked());
                }
                if (selftext.isChecked() != SettingValues.isSelftextEnabled(sub)) {
                    SettingValues.setSelftextEnabled(sub, selftext.isChecked());
                }
                // Only do set colors if either subreddit theme color has changed
                if (Palette.getColor(sub) != newPrimaryColor || Palette.getDarkerColor(sub) != newAccentColor) {
                    if (newPrimaryColor != Palette.getDefaultColor()) {
                        Palette.setColor(sub, newPrimaryColor);
                    } else {
                        Palette.removeColor(sub);
                    }
                    // Set accent color
                    ColorPreferences.Theme t = null;
                    // Do not save accent color if it matches the default accent color
                    if (newAccentColor != ContextCompat.getColor(context, colorPrefs.getFontStyle().getColor()) || newAccentColor != ContextCompat.getColor(context, colorPrefs.getFontStyleSubreddit(sub).getColor())) {
                        LogUtil.v("Accent colors not equal");
                        int back = new ColorPreferences(context).getFontStyle().getThemeType();
                        for (ColorPreferences.Theme type : ColorPreferences.Theme.values()) {
                            if (ContextCompat.getColor(context, type.getColor()) == newAccentColor && back == type.getThemeType()) {
                                t = type;
                                LogUtil.v("Setting accent color to " + t.getTitle());
                                break;
                            }
                        }
                    } else {
                        new ColorPreferences(context).removeFontStyle(sub);
                    }
                    if (t != null) {
                        colorPrefs.setFontStyle(t, sub);
                    }
                }
                // Set layout
                SettingValues.prefs.edit().putBoolean(Reddit.PREF_LAYOUT + sub, true).apply();
            }
            // Only refresh stuff if the user changed something
            if (Palette.getColor(subreddit) != newPrimaryColor || Palette.getDarkerColor(subreddit) != newAccentColor) {
                if (context instanceof MainActivity) {
                    ((MainActivity) context).reloadSubs();
                } else if (context instanceof SettingsSubreddit) {
                    ((SettingsSubreddit) context).reloadSubList();
                } else if (context instanceof SubredditView) {
                    ((SubredditView) context).restartTheme();
                }
            }
        }).show();
    }
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) Context(android.content.Context) OnColorChangedListener(uz.shift.colorpicker.OnColorChangedListener) SettingValues(me.ccrama.redditslide.SettingValues) AlertDialog(androidx.appcompat.app.AlertDialog) R(me.ccrama.redditslide.R) SwitchCompat(androidx.appcompat.widget.SwitchCompat) LayoutInflater(android.view.LayoutInflater) MainActivity(me.ccrama.redditslide.Activities.MainActivity) Reddit(me.ccrama.redditslide.Reddit) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) Palette(me.ccrama.redditslide.Visuals.Palette) BlendModeUtil(me.ccrama.redditslide.util.BlendModeUtil) LogUtil(me.ccrama.redditslide.util.LogUtil) ViewGroup(android.view.ViewGroup) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) ArrayList(java.util.ArrayList) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) View(android.view.View) LineColorPicker(uz.shift.colorpicker.LineColorPicker) RecyclerView(androidx.recyclerview.widget.RecyclerView) Activity(android.app.Activity) ContextCompat(androidx.core.content.ContextCompat) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) SubredditView(me.ccrama.redditslide.Activities.SubredditView) MainActivity(me.ccrama.redditslide.Activities.MainActivity) LineColorPicker(uz.shift.colorpicker.LineColorPicker) OnColorChangedListener(uz.shift.colorpicker.OnColorChangedListener) TextView(android.widget.TextView) SwitchCompat(androidx.appcompat.widget.SwitchCompat)

Example 7 with R

use of me.ccrama.redditslide.R in project Slide by ccrama.

the class SettingsSubAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    View convertView = holder.itemView;
    final TextView t = convertView.findViewById(R.id.name);
    t.setText(objects.get(position));
    final String subreddit = objects.get(position);
    final View colorView = convertView.findViewById(R.id.color);
    colorView.setBackgroundResource(R.drawable.circle);
    BlendModeUtil.tintDrawableAsModulate(colorView.getBackground(), Palette.getColor(subreddit));
    final String DELETE_SUB_SETTINGS_TITLE = (subreddit.contains("/m/")) ? subreddit : ("/r/" + subreddit);
    convertView.findViewById(R.id.remove).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(context).setTitle(context.getString(R.string.settings_delete_sub_settings, DELETE_SUB_SETTINGS_TITLE)).setPositiveButton(R.string.btn_yes, (dialog, which) -> {
                Palette.removeColor(subreddit);
                // Remove layout settings
                SettingValues.prefs.edit().remove(Reddit.PREF_LAYOUT + subreddit).apply();
                // Remove accent / font color settings
                new ColorPreferences(context).removeFontStyle(subreddit);
                SettingValues.resetPicsEnabled(subreddit);
                SettingValues.resetSelftextEnabled(subreddit);
                dialog.dismiss();
                objects.remove(subreddit);
                notifyDataSetChanged();
            }).setNegativeButton(R.string.btn_no, (dialog, which) -> dialog.dismiss()).show();
        }
    });
    convertView.findViewById(R.id.edit).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            prepareAndShowSubEditor(subreddit);
        }
    });
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) Context(android.content.Context) OnColorChangedListener(uz.shift.colorpicker.OnColorChangedListener) SettingValues(me.ccrama.redditslide.SettingValues) AlertDialog(androidx.appcompat.app.AlertDialog) R(me.ccrama.redditslide.R) SwitchCompat(androidx.appcompat.widget.SwitchCompat) LayoutInflater(android.view.LayoutInflater) MainActivity(me.ccrama.redditslide.Activities.MainActivity) Reddit(me.ccrama.redditslide.Reddit) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) Palette(me.ccrama.redditslide.Visuals.Palette) BlendModeUtil(me.ccrama.redditslide.util.BlendModeUtil) LogUtil(me.ccrama.redditslide.util.LogUtil) ViewGroup(android.view.ViewGroup) ContextThemeWrapper(androidx.appcompat.view.ContextThemeWrapper) ArrayList(java.util.ArrayList) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) View(android.view.View) LineColorPicker(uz.shift.colorpicker.LineColorPicker) RecyclerView(androidx.recyclerview.widget.RecyclerView) Activity(android.app.Activity) ContextCompat(androidx.core.content.ContextCompat) ColorPreferences(me.ccrama.redditslide.Visuals.ColorPreferences) TextView(android.widget.TextView) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView)

Example 8 with R

use of me.ccrama.redditslide.R in project Slide by ccrama.

the class PopulateNewsViewHolder method showBottomSheet.

public <T extends Contribution> void showBottomSheet(final Activity mContext, final Submission submission, final NewsViewHolder holder, final List<T> posts, final String baseSub, final RecyclerView recyclerview, final boolean full) {
    int[] attrs = new int[] { R.attr.tintColor };
    TypedArray ta = mContext.obtainStyledAttributes(attrs);
    int color = ta.getColor(0, Color.WHITE);
    Drawable profile = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_account_circle, null);
    final Drawable sub = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_bookmark_border, null);
    Drawable saved = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_star, null);
    Drawable hide = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_visibility_off, null);
    final Drawable report = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_report, null);
    Drawable copy = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_content_copy, null);
    final Drawable readLater = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_download, null);
    Drawable open = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_open_in_browser, null);
    Drawable link = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_link, null);
    Drawable reddit = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_forum, null);
    Drawable filter = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_filter_list, null);
    final List<Drawable> drawableSet = Arrays.asList(profile, sub, saved, hide, report, copy, open, link, reddit, readLater, filter);
    BlendModeUtil.tintDrawablesAsSrcAtop(drawableSet, color);
    ta.recycle();
    final BottomSheet.Builder b = new BottomSheet.Builder(mContext).title(CompatUtil.fromHtml(submission.getTitle()));
    final boolean isReadLater = mContext instanceof PostReadLater;
    final boolean isAddedToReadLaterList = ReadLater.isToBeReadLater(submission);
    if (Authentication.didOnline) {
        b.sheet(1, profile, "/u/" + submission.getAuthor()).sheet(2, sub, "/r/" + submission.getSubredditName());
        String save = mContext.getString(R.string.btn_save);
        if (ActionStates.isSaved(submission)) {
            save = mContext.getString(R.string.comment_unsave);
        }
        if (Authentication.isLoggedIn) {
            b.sheet(3, saved, save);
        }
    }
    if (isAddedToReadLaterList) {
        b.sheet(28, readLater, "Mark As Read");
    } else {
        b.sheet(28, readLater, "Read later");
    }
    if (Authentication.didOnline) {
        if (Authentication.isLoggedIn) {
            b.sheet(12, report, mContext.getString(R.string.btn_report));
        }
    }
    if (submission.getSelftext() != null && !submission.getSelftext().isEmpty() && full) {
        b.sheet(25, copy, mContext.getString(R.string.submission_copy_text));
    }
    boolean hidden = submission.isHidden();
    if (!full && Authentication.didOnline) {
        if (!hidden) {
            b.sheet(5, hide, mContext.getString(R.string.submission_hide));
        } else {
            b.sheet(5, hide, mContext.getString(R.string.submission_unhide));
        }
    }
    b.sheet(7, open, mContext.getString(R.string.open_externally));
    b.sheet(4, link, mContext.getString(R.string.submission_share_permalink)).sheet(8, reddit, mContext.getString(R.string.submission_share_reddit_url));
    if ((mContext instanceof MainActivity) || (mContext instanceof SubredditView)) {
        b.sheet(10, filter, mContext.getString(R.string.filter_content));
    }
    b.listener(new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch(which) {
                case 1:
                    {
                        Intent i = new Intent(mContext, Profile.class);
                        i.putExtra(Profile.EXTRA_PROFILE, submission.getAuthor());
                        mContext.startActivity(i);
                    }
                    break;
                case 2:
                    {
                        Intent i = new Intent(mContext, SubredditView.class);
                        i.putExtra(SubredditView.EXTRA_SUBREDDIT, submission.getSubredditName());
                        mContext.startActivityForResult(i, 14);
                    }
                    break;
                case 10:
                    String[] choices;
                    final String flair = submission.getSubmissionFlair().getText() != null ? submission.getSubmissionFlair().getText() : "";
                    if (flair.isEmpty()) {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()) };
                        chosen = new boolean[] { SettingValues.subredditFilters.contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), SettingValues.userFilters.contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), SettingValues.domainFilters.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), SettingValues.alwaysExternal.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)) };
                        oldChosen = chosen.clone();
                    } else {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()), mContext.getString(R.string.filter_posts_flair, flair, baseSub) };
                    }
                    chosen = new boolean[] { SettingValues.subredditFilters.contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), SettingValues.userFilters.contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), SettingValues.domainFilters.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), SettingValues.alwaysExternal.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), SettingValues.flairFilters.contains(baseSub + ":" + flair.toLowerCase(Locale.ENGLISH).trim()) };
                    oldChosen = chosen.clone();
                    new AlertDialog.Builder(mContext).setTitle(R.string.filter_title).setMultiChoiceItems(choices, chosen, (dialog1, which1, isChecked) -> chosen[which1] = isChecked).setPositiveButton(R.string.filter_btn, (dialog12, which12) -> {
                        boolean filtered = false;
                        SharedPreferences.Editor e = SettingValues.prefs.edit();
                        if (chosen[0] && chosen[0] != oldChosen[0]) {
                            SettingValues.subredditFilters.add(submission.getSubredditName().toLowerCase(Locale.ENGLISH).trim());
                            filtered = true;
                            e.putStringSet(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                        } else if (!chosen[0] && chosen[0] != oldChosen[0]) {
                            SettingValues.subredditFilters.remove(submission.getSubredditName().toLowerCase(Locale.ENGLISH).trim());
                            filtered = false;
                            e.putStringSet(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                            e.apply();
                        }
                        if (chosen[1] && chosen[1] != oldChosen[1]) {
                            SettingValues.userFilters.add(submission.getAuthor().toLowerCase(Locale.ENGLISH).trim());
                            filtered = true;
                            e.putStringSet(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                        } else if (!chosen[1] && chosen[1] != oldChosen[1]) {
                            SettingValues.userFilters.remove(submission.getAuthor().toLowerCase(Locale.ENGLISH).trim());
                            filtered = false;
                            e.putStringSet(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                            e.apply();
                        }
                        if (chosen[2] && chosen[2] != oldChosen[2]) {
                            SettingValues.domainFilters.add(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            filtered = true;
                            e.putStringSet(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                        } else if (!chosen[2] && chosen[2] != oldChosen[2]) {
                            SettingValues.domainFilters.remove(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            filtered = false;
                            e.putStringSet(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                            e.apply();
                        }
                        if (chosen[3] && chosen[3] != oldChosen[3]) {
                            SettingValues.alwaysExternal.add(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            e.putStringSet(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                            e.apply();
                        } else if (!chosen[3] && chosen[3] != oldChosen[3]) {
                            SettingValues.alwaysExternal.remove(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            e.putStringSet(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                            e.apply();
                        }
                        if (chosen.length > 4) {
                            String s = (baseSub + ":" + flair).toLowerCase(Locale.ENGLISH).trim();
                            if (chosen[4] && chosen[4] != oldChosen[4]) {
                                SettingValues.flairFilters.add(s);
                                e.putStringSet(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                e.apply();
                                filtered = true;
                            } else if (!chosen[4] && chosen[4] != oldChosen[4]) {
                                SettingValues.flairFilters.remove(s);
                                e.putStringSet(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                e.apply();
                            }
                        }
                        if (filtered) {
                            e.apply();
                            ArrayList<Contribution> toRemove = new ArrayList<>();
                            for (Contribution s : posts) {
                                if (s instanceof Submission && PostMatch.doesMatch((Submission) s)) {
                                    toRemove.add(s);
                                }
                            }
                            OfflineSubreddit s = OfflineSubreddit.getSubreddit(baseSub, false, mContext);
                            for (Contribution remove : toRemove) {
                                final int pos = posts.indexOf(remove);
                                posts.remove(pos);
                                if (baseSub != null) {
                                    s.hideMulti(pos);
                                }
                            }
                            s.writeToMemoryNoStorage();
                            recyclerview.getAdapter().notifyDataSetChanged();
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                    break;
                case 5:
                    hideSubmission(submission, posts, baseSub, recyclerview, mContext);
                    break;
                case 7:
                    LinkUtil.openExternally(submission.getUrl());
                    if (submission.isNsfw() && !SettingValues.storeNSFWHistory) {
                    // Do nothing if the post is NSFW and storeNSFWHistory is not enabled
                    } else if (SettingValues.storeHistory) {
                        HasSeen.addSeen(submission.getFullName());
                    }
                    break;
                case 28:
                    if (!isAddedToReadLaterList) {
                        ReadLater.setReadLater(submission, true);
                        Snackbar s = Snackbar.make(holder.itemView, "Added to read later!", Snackbar.LENGTH_SHORT);
                        View view = s.getView();
                        TextView tv = view.findViewById(com.google.android.material.R.id.snackbar_text);
                        tv.setTextColor(Color.WHITE);
                        s.setAction(R.string.btn_undo, new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                ReadLater.setReadLater(submission, false);
                                Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                                LayoutUtils.showSnackbar(s2);
                            }
                        });
                        if (NetworkUtil.isConnected(mContext)) {
                            new CommentCacheAsync(Collections.singletonList(submission), mContext, CommentCacheAsync.SAVED_SUBMISSIONS, new boolean[] { true, true }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                        s.show();
                    } else {
                        ReadLater.setReadLater(submission, false);
                        if (isReadLater || !Authentication.didOnline) {
                            final int pos = posts.indexOf(submission);
                            posts.remove(submission);
                            recyclerview.getAdapter().notifyItemRemoved(holder.getBindingAdapterPosition());
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = view2.findViewById(com.google.android.material.R.id.snackbar_text);
                            tv2.setTextColor(Color.WHITE);
                            s2.setAction(R.string.btn_undo, new View.OnClickListener() {

                                @Override
                                public void onClick(View view) {
                                    posts.add(pos, (T) submission);
                                    recyclerview.getAdapter().notifyDataSetChanged();
                                }
                            });
                        } else {
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = view2.findViewById(com.google.android.material.R.id.snackbar_text);
                            s2.show();
                        }
                        OfflineSubreddit.newSubreddit(CommentCacheAsync.SAVED_SUBMISSIONS).deleteFromMemory(submission.getFullName());
                    }
                    break;
                case 4:
                    Reddit.defaultShareText(CompatUtil.fromHtml(submission.getTitle()).toString(), StringEscapeUtils.escapeHtml4(submission.getUrl()), mContext);
                    break;
                case 12:
                    final MaterialDialog reportDialog = new MaterialDialog.Builder(mContext).customView(R.layout.report_dialog, true).title(R.string.report_post).positiveText(R.string.btn_report).negativeText(R.string.btn_cancel).onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            RadioGroup reasonGroup = dialog.getCustomView().findViewById(R.id.report_reasons);
                            String reportReason;
                            if (reasonGroup.getCheckedRadioButtonId() == R.id.report_other) {
                                reportReason = ((EditText) dialog.getCustomView().findViewById(R.id.input_report_reason)).getText().toString();
                            } else {
                                reportReason = ((RadioButton) reasonGroup.findViewById(reasonGroup.getCheckedRadioButtonId())).getText().toString();
                            }
                            new PopulateBase.AsyncReportTask(submission, holder.itemView).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, reportReason);
                        }
                    }).build();
                    final RadioGroup reasonGroup = reportDialog.getCustomView().findViewById(R.id.report_reasons);
                    reasonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            if (checkedId == R.id.report_other)
                                reportDialog.getCustomView().findViewById(R.id.input_report_reason).setVisibility(View.VISIBLE);
                            else
                                reportDialog.getCustomView().findViewById(R.id.input_report_reason).setVisibility(View.GONE);
                        }
                    });
                    // Load sub's report reasons and show the appropriate ones
                    new AsyncTask<Void, Void, Ruleset>() {

                        @Override
                        protected Ruleset doInBackground(Void... voids) {
                            return Authentication.reddit.getRules(submission.getSubredditName());
                        }

                        @Override
                        protected void onPostExecute(Ruleset rules) {
                            reportDialog.getCustomView().findViewById(R.id.report_loading).setVisibility(View.GONE);
                            if (rules.getSubredditRules().size() > 0) {
                                TextView subHeader = new TextView(mContext);
                                subHeader.setText(mContext.getString(R.string.report_sub_rules, submission.getSubredditName()));
                                reasonGroup.addView(subHeader, reasonGroup.getChildCount() - 2);
                            }
                            for (SubredditRule rule : rules.getSubredditRules()) {
                                if (rule.getKind() == SubredditRule.RuleKind.LINK || rule.getKind() == SubredditRule.RuleKind.ALL) {
                                    RadioButton btn = new RadioButton(mContext);
                                    btn.setText(rule.getViolationReason());
                                    reasonGroup.addView(btn, reasonGroup.getChildCount() - 2);
                                    btn.getLayoutParams().width = WindowManager.LayoutParams.MATCH_PARENT;
                                }
                            }
                            if (rules.getSiteRules().size() > 0) {
                                TextView siteHeader = new TextView(mContext);
                                siteHeader.setText(R.string.report_site_rules);
                                reasonGroup.addView(siteHeader, reasonGroup.getChildCount() - 2);
                            }
                            for (String rule : rules.getSiteRules()) {
                                RadioButton btn = new RadioButton(mContext);
                                btn.setText(rule);
                                reasonGroup.addView(btn, reasonGroup.getChildCount() - 2);
                                btn.getLayoutParams().width = WindowManager.LayoutParams.MATCH_PARENT;
                            }
                        }
                    }.execute();
                    reportDialog.show();
                    break;
                case 8:
                    Reddit.defaultShareText(CompatUtil.fromHtml(submission.getTitle()).toString(), "https://reddit.com" + submission.getPermalink(), mContext);
                    break;
                case 6:
                    {
                        ClipboardUtil.copyToClipboard(mContext, "Link", submission.getUrl());
                        Toast.makeText(mContext, R.string.submission_link_copied, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 25:
                    final TextView showText = new TextView(mContext);
                    showText.setText(StringEscapeUtils.unescapeHtml4(submission.getTitle() + "\n\n" + submission.getSelftext()));
                    showText.setTextIsSelectable(true);
                    int sixteen = DisplayUtil.dpToPxVertical(24);
                    showText.setPadding(sixteen, 0, sixteen, 0);
                    new AlertDialog.Builder(mContext).setView(showText).setTitle("Select text to copy").setCancelable(true).setPositiveButton("COPY SELECTED", (dialog13, which13) -> {
                        String selected = showText.getText().toString().substring(showText.getSelectionStart(), showText.getSelectionEnd());
                        if (!selected.isEmpty()) {
                            ClipboardUtil.copyToClipboard(mContext, "Selftext", selected);
                        } else {
                            ClipboardUtil.copyToClipboard(mContext, "Selftext", CompatUtil.fromHtml(submission.getTitle() + "\n\n" + submission.getSelftext()));
                        }
                        Toast.makeText(mContext, R.string.submission_comment_copied, Toast.LENGTH_SHORT).show();
                    }).setNegativeButton(R.string.btn_cancel, null).setNeutralButton("COPY ALL", (dialog14, which14) -> {
                        ClipboardUtil.copyToClipboard(mContext, "Selftext", StringEscapeUtils.unescapeHtml4(submission.getTitle() + "\n\n" + submission.getSelftext()));
                        Toast.makeText(mContext, R.string.submission_text_copied, Toast.LENGTH_SHORT).show();
                    }).show();
                    break;
            }
        }
    });
    b.show();
}
Also used : Arrays(java.util.Arrays) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) R(me.ccrama.redditslide.R) MainActivity(me.ccrama.redditslide.Activities.MainActivity) MediaView(me.ccrama.redditslide.Activities.MediaView) WindowManager(android.view.WindowManager) ImageView(android.widget.ImageView) RadioButton(android.widget.RadioButton) PostMatch(me.ccrama.redditslide.PostMatch) ContentType(me.ccrama.redditslide.ContentType) AbsoluteSizeSpan(android.text.style.AbsoluteSizeSpan) DataShare(me.ccrama.redditslide.DataShare) Drawable(android.graphics.drawable.Drawable) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) Tumblr(me.ccrama.redditslide.Activities.Tumblr) Locale(java.util.Locale) View(android.view.View) MultiredditOverview(me.ccrama.redditslide.Activities.MultiredditOverview) RecyclerView(androidx.recyclerview.widget.RecyclerView) ContextCompat(androidx.core.content.ContextCompat) SubredditRule(net.dean.jraw.models.SubredditRule) NewsViewHolder(me.ccrama.redditslide.Adapters.NewsViewHolder) AsyncTask(android.os.AsyncTask) FullscreenVideo(me.ccrama.redditslide.Activities.FullscreenVideo) Album(me.ccrama.redditslide.Activities.Album) Ruleset(net.dean.jraw.models.Ruleset) Authentication(me.ccrama.redditslide.Authentication) DisplayUtil(me.ccrama.redditslide.util.DisplayUtil) Palette(me.ccrama.redditslide.Visuals.Palette) BlendModeUtil(me.ccrama.redditslide.util.BlendModeUtil) Profile(me.ccrama.redditslide.Activities.Profile) SubmissionCache(me.ccrama.redditslide.SubmissionCache) PeekViewActivity(me.ccrama.redditslide.ForceTouch.PeekViewActivity) AlbumPager(me.ccrama.redditslide.Activities.AlbumPager) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) List(java.util.List) NetworkUtil(me.ccrama.redditslide.util.NetworkUtil) TextView(android.widget.TextView) Nullable(androidx.annotation.Nullable) Contribution(net.dean.jraw.models.Contribution) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Snackbar(com.google.android.material.snackbar.Snackbar) BottomSheet(com.cocosw.bottomsheet.BottomSheet) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) Context(android.content.Context) SettingValues(me.ccrama.redditslide.SettingValues) AlertDialog(androidx.appcompat.app.AlertDialog) ResourcesCompat(androidx.core.content.res.ResourcesCompat) HasSeen(me.ccrama.redditslide.HasSeen) Submission(net.dean.jraw.models.Submission) Intent(android.content.Intent) Hidden(me.ccrama.redditslide.Hidden) RadioGroup(android.widget.RadioGroup) TypedArray(android.content.res.TypedArray) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) TumblrPager(me.ccrama.redditslide.Activities.TumblrPager) Toast(android.widget.Toast) Search(me.ccrama.redditslide.Activities.Search) SubredditView(me.ccrama.redditslide.Activities.SubredditView) OpenRedditLink(me.ccrama.redditslide.OpenRedditLink) DialogInterface(android.content.DialogInterface) ClipboardUtil(me.ccrama.redditslide.util.ClipboardUtil) Reddit(me.ccrama.redditslide.Reddit) DialogAction(com.afollestad.materialdialogs.DialogAction) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) CompatUtil(me.ccrama.redditslide.util.CompatUtil) Color(android.graphics.Color) SharedPreferences(android.content.SharedPreferences) PostReadLater(me.ccrama.redditslide.Activities.PostReadLater) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) GifUtils(me.ccrama.redditslide.util.GifUtils) ActionStates(me.ccrama.redditslide.ActionStates) CommentAdapter(me.ccrama.redditslide.Adapters.CommentAdapter) LastComments(me.ccrama.redditslide.LastComments) Activity(android.app.Activity) Collections(java.util.Collections) EditText(android.widget.EditText) LinkUtil(me.ccrama.redditslide.util.LinkUtil) EXTRA_SUBMISSION_TITLE(me.ccrama.redditslide.Notifications.ImageDownloadNotificationService.EXTRA_SUBMISSION_TITLE) Ruleset(net.dean.jraw.models.Ruleset) RadioGroup(android.widget.RadioGroup) DialogInterface(android.content.DialogInterface) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) PostReadLater(me.ccrama.redditslide.Activities.PostReadLater) SubredditView(me.ccrama.redditslide.Activities.SubredditView) MainActivity(me.ccrama.redditslide.Activities.MainActivity) TypedArray(android.content.res.TypedArray) TextView(android.widget.TextView) SubredditRule(net.dean.jraw.models.SubredditRule) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Submission(net.dean.jraw.models.Submission) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) Drawable(android.graphics.drawable.Drawable) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) RadioButton(android.widget.RadioButton) MediaView(me.ccrama.redditslide.Activities.MediaView) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) DialogAction(com.afollestad.materialdialogs.DialogAction) BottomSheet(com.cocosw.bottomsheet.BottomSheet) Contribution(net.dean.jraw.models.Contribution) Snackbar(com.google.android.material.snackbar.Snackbar)

Example 9 with R

use of me.ccrama.redditslide.R in project Slide by ccrama.

the class PopulateSubmissionViewHolder method showBottomSheet.

public <T extends Contribution> void showBottomSheet(final Activity mContext, final Submission submission, final SubmissionViewHolder holder, final List<T> posts, final String baseSub, final RecyclerView recyclerview, final boolean full) {
    int[] attrs = new int[] { R.attr.tintColor };
    TypedArray ta = mContext.obtainStyledAttributes(attrs);
    int color = ta.getColor(0, Color.WHITE);
    Drawable profile = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_account_circle, null);
    final Drawable sub = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_bookmark_border, null);
    Drawable saved = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_star, null);
    Drawable hide = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_visibility_off, null);
    final Drawable report = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_report, null);
    Drawable copy = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_content_copy, null);
    final Drawable readLater = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_download, null);
    Drawable open = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_open_in_browser, null);
    Drawable link = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_link, null);
    Drawable reddit = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_forum, null);
    Drawable filter = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_filter_list, null);
    Drawable crosspost = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_forward, null);
    final List<Drawable> drawableSet = Arrays.asList(profile, sub, saved, hide, report, copy, open, link, reddit, readLater, filter, crosspost);
    BlendModeUtil.tintDrawablesAsSrcAtop(drawableSet, color);
    ta.recycle();
    final BottomSheet.Builder b = new BottomSheet.Builder(mContext).title(CompatUtil.fromHtml(submission.getTitle()));
    final boolean isReadLater = mContext instanceof PostReadLater;
    final boolean isAddedToReadLaterList = ReadLater.isToBeReadLater(submission);
    if (Authentication.didOnline) {
        b.sheet(1, profile, "/u/" + submission.getAuthor()).sheet(2, sub, "/r/" + submission.getSubredditName());
        String save = mContext.getString(R.string.btn_save);
        if (ActionStates.isSaved(submission)) {
            save = mContext.getString(R.string.comment_unsave);
        }
        if (Authentication.isLoggedIn) {
            b.sheet(3, saved, save);
        }
    }
    if (isAddedToReadLaterList) {
        b.sheet(28, readLater, "Mark As Read");
    } else {
        b.sheet(28, readLater, "Read later");
    }
    if (Authentication.didOnline) {
        if (Authentication.isLoggedIn) {
            b.sheet(12, report, mContext.getString(R.string.btn_report));
            b.sheet(13, crosspost, mContext.getString(R.string.btn_crosspost));
        }
    }
    if (submission.getSelftext() != null && !submission.getSelftext().isEmpty() && full) {
        b.sheet(25, copy, mContext.getString(R.string.submission_copy_text));
    }
    boolean hidden = submission.isHidden();
    if (!full && Authentication.didOnline) {
        if (!hidden) {
            b.sheet(5, hide, mContext.getString(R.string.submission_hide));
        } else {
            b.sheet(5, hide, mContext.getString(R.string.submission_unhide));
        }
    }
    b.sheet(7, open, mContext.getString(R.string.open_externally));
    b.sheet(4, link, mContext.getString(R.string.submission_share_permalink)).sheet(8, reddit, mContext.getString(R.string.submission_share_reddit_url));
    if ((mContext instanceof MainActivity) || (mContext instanceof SubredditView)) {
        b.sheet(10, filter, mContext.getString(R.string.filter_content));
    }
    b.listener(new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch(which) {
                case 1:
                    {
                        Intent i = new Intent(mContext, Profile.class);
                        i.putExtra(Profile.EXTRA_PROFILE, submission.getAuthor());
                        mContext.startActivity(i);
                    }
                    break;
                case 2:
                    {
                        Intent i = new Intent(mContext, SubredditView.class);
                        i.putExtra(SubredditView.EXTRA_SUBREDDIT, submission.getSubredditName());
                        mContext.startActivityForResult(i, 14);
                    }
                    break;
                case 10:
                    String[] choices;
                    final String flair = submission.getSubmissionFlair().getText() != null ? submission.getSubmissionFlair().getText() : "";
                    if (flair.isEmpty()) {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()) };
                        chosen = new boolean[] { SettingValues.subredditFilters.contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), SettingValues.userFilters.contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), SettingValues.domainFilters.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), SettingValues.alwaysExternal.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)) };
                        oldChosen = chosen.clone();
                    } else {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()), mContext.getString(R.string.filter_posts_flair, flair, baseSub) };
                    }
                    chosen = new boolean[] { SettingValues.subredditFilters.contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), SettingValues.userFilters.contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), SettingValues.domainFilters.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), SettingValues.alwaysExternal.contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), SettingValues.flairFilters.contains(baseSub + ":" + flair.toLowerCase(Locale.ENGLISH).trim()) };
                    oldChosen = chosen.clone();
                    new AlertDialog.Builder(mContext).setTitle(R.string.filter_title).setMultiChoiceItems(choices, chosen, (dialog1, which1, isChecked) -> chosen[which1] = isChecked).setPositiveButton(R.string.filter_btn, (dialog12, which12) -> {
                        boolean filtered = false;
                        SharedPreferences.Editor e = SettingValues.prefs.edit();
                        if (chosen[0] && chosen[0] != oldChosen[0]) {
                            SettingValues.subredditFilters.add(submission.getSubredditName().toLowerCase(Locale.ENGLISH).trim());
                            filtered = true;
                            e.putStringSet(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                        } else if (!chosen[0] && chosen[0] != oldChosen[0]) {
                            SettingValues.subredditFilters.remove(submission.getSubredditName().toLowerCase(Locale.ENGLISH).trim());
                            filtered = false;
                            e.putStringSet(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                            e.apply();
                        }
                        if (chosen[1] && chosen[1] != oldChosen[1]) {
                            SettingValues.userFilters.add(submission.getAuthor().toLowerCase(Locale.ENGLISH).trim());
                            filtered = true;
                            e.putStringSet(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                        } else if (!chosen[1] && chosen[1] != oldChosen[1]) {
                            SettingValues.userFilters.remove(submission.getAuthor().toLowerCase(Locale.ENGLISH).trim());
                            filtered = false;
                            e.putStringSet(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                            e.apply();
                        }
                        if (chosen[2] && chosen[2] != oldChosen[2]) {
                            SettingValues.domainFilters.add(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            filtered = true;
                            e.putStringSet(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                        } else if (!chosen[2] && chosen[2] != oldChosen[2]) {
                            SettingValues.domainFilters.remove(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            filtered = false;
                            e.putStringSet(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                            e.apply();
                        }
                        if (chosen[3] && chosen[3] != oldChosen[3]) {
                            SettingValues.alwaysExternal.add(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            e.putStringSet(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                            e.apply();
                        } else if (!chosen[3] && chosen[3] != oldChosen[3]) {
                            SettingValues.alwaysExternal.remove(submission.getDomain().toLowerCase(Locale.ENGLISH).trim());
                            e.putStringSet(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                            e.apply();
                        }
                        if (chosen.length > 4) {
                            String s = (baseSub + ":" + flair).toLowerCase(Locale.ENGLISH).trim();
                            if (chosen[4] && chosen[4] != oldChosen[4]) {
                                SettingValues.flairFilters.add(s);
                                e.putStringSet(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                e.apply();
                                filtered = true;
                            } else if (!chosen[4] && chosen[4] != oldChosen[4]) {
                                SettingValues.flairFilters.remove(s);
                                e.putStringSet(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                e.apply();
                            }
                        }
                        if (filtered) {
                            e.apply();
                            ArrayList<Contribution> toRemove = new ArrayList<>();
                            for (Contribution s : posts) {
                                if (s instanceof Submission && PostMatch.doesMatch((Submission) s)) {
                                    toRemove.add(s);
                                }
                            }
                            OfflineSubreddit s = OfflineSubreddit.getSubreddit(baseSub, false, mContext);
                            for (Contribution remove : toRemove) {
                                final int pos = posts.indexOf(remove);
                                posts.remove(pos);
                                if (baseSub != null) {
                                    s.hideMulti(pos);
                                }
                            }
                            s.writeToMemoryNoStorage();
                            recyclerview.getAdapter().notifyDataSetChanged();
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                    break;
                case 3:
                    saveSubmission(submission, mContext, holder, full);
                    break;
                case 5:
                    {
                        hideSubmission(submission, posts, baseSub, recyclerview, mContext);
                    }
                    break;
                case 7:
                    LinkUtil.openExternally(submission.getUrl());
                    if (submission.isNsfw() && !SettingValues.storeNSFWHistory) {
                    // Do nothing if the post is NSFW and storeNSFWHistory is not enabled
                    } else if (SettingValues.storeHistory) {
                        HasSeen.addSeen(submission.getFullName());
                    }
                    break;
                case 13:
                    LinkUtil.crosspost(submission, mContext);
                    break;
                case 28:
                    if (!isAddedToReadLaterList) {
                        ReadLater.setReadLater(submission, true);
                        Snackbar s = Snackbar.make(holder.itemView, "Added to read later!", Snackbar.LENGTH_SHORT);
                        View view = s.getView();
                        TextView tv = view.findViewById(com.google.android.material.R.id.snackbar_text);
                        tv.setTextColor(Color.WHITE);
                        s.setAction(R.string.btn_undo, new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                ReadLater.setReadLater(submission, false);
                                Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                                LayoutUtils.showSnackbar(s2);
                            }
                        });
                        if (NetworkUtil.isConnected(mContext)) {
                            new CommentCacheAsync(Collections.singletonList(submission), mContext, CommentCacheAsync.SAVED_SUBMISSIONS, new boolean[] { true, true }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                        s.show();
                    } else {
                        ReadLater.setReadLater(submission, false);
                        if (isReadLater || !Authentication.didOnline) {
                            final int pos = posts.indexOf(submission);
                            posts.remove(submission);
                            recyclerview.getAdapter().notifyItemRemoved(holder.getBindingAdapterPosition());
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = view2.findViewById(com.google.android.material.R.id.snackbar_text);
                            tv2.setTextColor(Color.WHITE);
                            s2.setAction(R.string.btn_undo, new View.OnClickListener() {

                                @Override
                                public void onClick(View view) {
                                    posts.add(pos, (T) submission);
                                    recyclerview.getAdapter().notifyDataSetChanged();
                                }
                            });
                        } else {
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = view2.findViewById(com.google.android.material.R.id.snackbar_text);
                            s2.show();
                        }
                        OfflineSubreddit.newSubreddit(CommentCacheAsync.SAVED_SUBMISSIONS).deleteFromMemory(submission.getFullName());
                    }
                    break;
                case 4:
                    Reddit.defaultShareText(CompatUtil.fromHtml(submission.getTitle()).toString(), StringEscapeUtils.escapeHtml4(submission.getUrl()), mContext);
                    break;
                case 12:
                    final MaterialDialog reportDialog = new MaterialDialog.Builder(mContext).customView(R.layout.report_dialog, true).title(R.string.report_post).positiveText(R.string.btn_report).negativeText(R.string.btn_cancel).onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            RadioGroup reasonGroup = dialog.getCustomView().findViewById(R.id.report_reasons);
                            String reportReason;
                            if (reasonGroup.getCheckedRadioButtonId() == R.id.report_other) {
                                reportReason = ((EditText) dialog.getCustomView().findViewById(R.id.input_report_reason)).getText().toString();
                            } else {
                                reportReason = ((RadioButton) reasonGroup.findViewById(reasonGroup.getCheckedRadioButtonId())).getText().toString();
                            }
                            new AsyncReportTask(submission, holder.itemView).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, reportReason);
                        }
                    }).build();
                    final RadioGroup reasonGroup = reportDialog.getCustomView().findViewById(R.id.report_reasons);
                    reasonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            if (checkedId == R.id.report_other)
                                reportDialog.getCustomView().findViewById(R.id.input_report_reason).setVisibility(View.VISIBLE);
                            else
                                reportDialog.getCustomView().findViewById(R.id.input_report_reason).setVisibility(View.GONE);
                        }
                    });
                    // Load sub's report reasons and show the appropriate ones
                    new AsyncTask<Void, Void, Ruleset>() {

                        @Override
                        protected Ruleset doInBackground(Void... voids) {
                            return Authentication.reddit.getRules(submission.getSubredditName());
                        }

                        @Override
                        protected void onPostExecute(Ruleset rules) {
                            reportDialog.getCustomView().findViewById(R.id.report_loading).setVisibility(View.GONE);
                            if (rules.getSubredditRules().size() > 0) {
                                TextView subHeader = new TextView(mContext);
                                subHeader.setText(mContext.getString(R.string.report_sub_rules, submission.getSubredditName()));
                                reasonGroup.addView(subHeader, reasonGroup.getChildCount() - 2);
                            }
                            for (SubredditRule rule : rules.getSubredditRules()) {
                                if (rule.getKind() == SubredditRule.RuleKind.LINK || rule.getKind() == SubredditRule.RuleKind.ALL) {
                                    RadioButton btn = new RadioButton(mContext);
                                    btn.setText(rule.getViolationReason());
                                    reasonGroup.addView(btn, reasonGroup.getChildCount() - 2);
                                    btn.getLayoutParams().width = WindowManager.LayoutParams.MATCH_PARENT;
                                }
                            }
                            if (rules.getSiteRules().size() > 0) {
                                TextView siteHeader = new TextView(mContext);
                                siteHeader.setText(R.string.report_site_rules);
                                reasonGroup.addView(siteHeader, reasonGroup.getChildCount() - 2);
                            }
                            for (String rule : rules.getSiteRules()) {
                                RadioButton btn = new RadioButton(mContext);
                                btn.setText(rule);
                                reasonGroup.addView(btn, reasonGroup.getChildCount() - 2);
                                btn.getLayoutParams().width = WindowManager.LayoutParams.MATCH_PARENT;
                            }
                        }
                    }.execute();
                    reportDialog.show();
                    break;
                case 8:
                    if (SettingValues.shareLongLink) {
                        Reddit.defaultShareText(submission.getTitle(), "https://reddit.com" + submission.getPermalink(), mContext);
                    } else {
                        Reddit.defaultShareText(submission.getTitle(), "https://redd.it/" + submission.getId(), mContext);
                    }
                    break;
                case 6:
                    {
                        ClipboardUtil.copyToClipboard(mContext, "Link", submission.getUrl());
                        Toast.makeText(mContext, R.string.submission_link_copied, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 25:
                    final TextView showText = new TextView(mContext);
                    showText.setText(StringEscapeUtils.unescapeHtml4(submission.getTitle() + "\n\n" + submission.getSelftext()));
                    showText.setTextIsSelectable(true);
                    int sixteen = DisplayUtil.dpToPxVertical(24);
                    showText.setPadding(sixteen, 0, sixteen, 0);
                    new AlertDialog.Builder(mContext).setView(showText).setTitle("Select text to copy").setCancelable(true).setPositiveButton("COPY SELECTED", (dialog13, which13) -> {
                        String selected = showText.getText().toString().substring(showText.getSelectionStart(), showText.getSelectionEnd());
                        if (!selected.isEmpty()) {
                            ClipboardUtil.copyToClipboard(mContext, "Selftext", selected);
                        } else {
                            ClipboardUtil.copyToClipboard(mContext, "Selftext", CompatUtil.fromHtml(submission.getTitle() + "\n\n" + submission.getSelftext()));
                        }
                        Toast.makeText(mContext, R.string.submission_comment_copied, Toast.LENGTH_SHORT).show();
                    }).setNegativeButton(R.string.btn_cancel, null).setNeutralButton("COPY ALL", (dialog14, which14) -> {
                        ClipboardUtil.copyToClipboard(mContext, "Selftext", StringEscapeUtils.unescapeHtml4(submission.getTitle() + "\n\n" + submission.getSelftext()));
                        Toast.makeText(mContext, R.string.submission_text_copied, Toast.LENGTH_SHORT).show();
                    }).show();
                    break;
            }
        }
    });
    b.show();
}
Also used : Arrays(java.util.Arrays) Bundle(android.os.Bundle) R(me.ccrama.redditslide.R) RobotoTypefaces(com.devspark.robototextview.RobotoTypefaces) Thing(net.dean.jraw.models.Thing) MainActivity(me.ccrama.redditslide.Activities.MainActivity) MediaView(me.ccrama.redditslide.Activities.MediaView) AnimatorUtil(me.ccrama.redditslide.util.AnimatorUtil) JsonUtil(me.ccrama.redditslide.util.JsonUtil) ImageView(android.widget.ImageView) RadioButton(android.widget.RadioButton) DistinguishedStatus(net.dean.jraw.models.DistinguishedStatus) PostMatch(me.ccrama.redditslide.PostMatch) ContentType(me.ccrama.redditslide.ContentType) AbsoluteSizeSpan(android.text.style.AbsoluteSizeSpan) DataShare(me.ccrama.redditslide.DataShare) Drawable(android.graphics.drawable.Drawable) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) MultiredditOverview(me.ccrama.redditslide.Activities.MultiredditOverview) ContextCompat(androidx.core.content.ContextCompat) Ruleset(net.dean.jraw.models.Ruleset) DisplayUtil(me.ccrama.redditslide.util.DisplayUtil) GalleryImage(me.ccrama.redditslide.Activities.GalleryImage) Palette(me.ccrama.redditslide.Visuals.Palette) BlendModeUtil(me.ccrama.redditslide.util.BlendModeUtil) Profile(me.ccrama.redditslide.Activities.Profile) PeekViewActivity(me.ccrama.redditslide.ForceTouch.PeekViewActivity) Nullable(androidx.annotation.Nullable) Contribution(net.dean.jraw.models.Contribution) Reauthenticate(me.ccrama.redditslide.Activities.Reauthenticate) SubmissionParser(me.ccrama.redditslide.util.SubmissionParser) DoEditorActions(me.ccrama.redditslide.Views.DoEditorActions) HasSeen(me.ccrama.redditslide.HasSeen) Vote(me.ccrama.redditslide.Vote) Dialog(android.app.Dialog) SubmissionViewHolder(me.ccrama.redditslide.Adapters.SubmissionViewHolder) RadioGroup(android.widget.RadioGroup) AccountManager(net.dean.jraw.managers.AccountManager) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) TumblrPager(me.ccrama.redditslide.Activities.TumblrPager) Toast(android.widget.Toast) UserSubscriptions(me.ccrama.redditslide.UserSubscriptions) OpenRedditLink(me.ccrama.redditslide.OpenRedditLink) InvalidScopeException(net.dean.jraw.http.oauth.InvalidScopeException) FluentRedditClient(net.dean.jraw.fluent.FluentRedditClient) FlairTemplate(net.dean.jraw.models.FlairTemplate) Reddit(me.ccrama.redditslide.Reddit) VoteDirection(net.dean.jraw.models.VoteDirection) ModQueue(me.ccrama.redditslide.Activities.ModQueue) SharedPreferences(android.content.SharedPreferences) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) GifUtils(me.ccrama.redditslide.util.GifUtils) ActionStates(me.ccrama.redditslide.ActionStates) EditText(android.widget.EditText) LinkUtil(me.ccrama.redditslide.util.LinkUtil) EXTRA_SUBMISSION_TITLE(me.ccrama.redditslide.Notifications.ImageDownloadNotificationService.EXTRA_SUBMISSION_TITLE) LinearLayout(android.widget.LinearLayout) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) WindowManager(android.view.WindowManager) Tumblr(me.ccrama.redditslide.Activities.Tumblr) Locale(java.util.Locale) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) SubredditRule(net.dean.jraw.models.SubredditRule) ToolboxUI(me.ccrama.redditslide.Toolbox.ToolboxUI) AsyncTask(android.os.AsyncTask) FullscreenVideo(me.ccrama.redditslide.Activities.FullscreenVideo) Album(me.ccrama.redditslide.Activities.Album) Authentication(me.ccrama.redditslide.Authentication) InputType(android.text.InputType) ApiException(net.dean.jraw.ApiException) SubmissionCache(me.ccrama.redditslide.SubmissionCache) AlbumPager(me.ccrama.redditslide.Activities.AlbumPager) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) List(java.util.List) NetworkUtil(me.ccrama.redditslide.util.NetworkUtil) TextView(android.widget.TextView) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Snackbar(com.google.android.material.snackbar.Snackbar) BottomSheet(com.cocosw.bottomsheet.BottomSheet) RedditGalleryPager(me.ccrama.redditslide.Activities.RedditGalleryPager) Typeface(android.graphics.Typeface) LayoutUtils(me.ccrama.redditslide.util.LayoutUtils) Context(android.content.Context) SettingValues(me.ccrama.redditslide.SettingValues) AlertDialog(androidx.appcompat.app.AlertDialog) ResourcesCompat(androidx.core.content.res.ResourcesCompat) ModerationManager(net.dean.jraw.managers.ModerationManager) FontPreferences(me.ccrama.redditslide.Visuals.FontPreferences) Submission(net.dean.jraw.models.Submission) Intent(android.content.Intent) Hidden(me.ccrama.redditslide.Hidden) TypedArray(android.content.res.TypedArray) Search(me.ccrama.redditslide.Activities.Search) SubredditView(me.ccrama.redditslide.Activities.SubredditView) DialogInterface(android.content.DialogInterface) ClipboardUtil(me.ccrama.redditslide.util.ClipboardUtil) LayoutInflater(android.view.LayoutInflater) DialogAction(com.afollestad.materialdialogs.DialogAction) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) CompatUtil(me.ccrama.redditslide.util.CompatUtil) Color(android.graphics.Color) FlairReference(net.dean.jraw.fluent.FlairReference) RedditGallery(me.ccrama.redditslide.Activities.RedditGallery) PostReadLater(me.ccrama.redditslide.Activities.PostReadLater) CommentAdapter(me.ccrama.redditslide.Adapters.CommentAdapter) LastComments(me.ccrama.redditslide.LastComments) Activity(android.app.Activity) NetworkException(net.dean.jraw.http.NetworkException) Collections(java.util.Collections) Resources(android.content.res.Resources) Ruleset(net.dean.jraw.models.Ruleset) RadioGroup(android.widget.RadioGroup) DialogInterface(android.content.DialogInterface) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) PostReadLater(me.ccrama.redditslide.Activities.PostReadLater) SubredditView(me.ccrama.redditslide.Activities.SubredditView) MainActivity(me.ccrama.redditslide.Activities.MainActivity) TypedArray(android.content.res.TypedArray) TextView(android.widget.TextView) SubredditRule(net.dean.jraw.models.SubredditRule) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Submission(net.dean.jraw.models.Submission) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) Drawable(android.graphics.drawable.Drawable) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) RadioButton(android.widget.RadioButton) MediaView(me.ccrama.redditslide.Activities.MediaView) ImageView(android.widget.ImageView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) DialogAction(com.afollestad.materialdialogs.DialogAction) BottomSheet(com.cocosw.bottomsheet.BottomSheet) Contribution(net.dean.jraw.models.Contribution) Snackbar(com.google.android.material.snackbar.Snackbar)

Aggregations

View (android.view.View)9 AlertDialog (androidx.appcompat.app.AlertDialog)9 ArrayList (java.util.ArrayList)9 R (me.ccrama.redditslide.R)9 SettingValues (me.ccrama.redditslide.SettingValues)9 LayoutInflater (android.view.LayoutInflater)8 Reddit (me.ccrama.redditslide.Reddit)8 Activity (android.app.Activity)7 ViewGroup (android.view.ViewGroup)7 Snackbar (com.google.android.material.snackbar.Snackbar)7 List (java.util.List)7 Locale (java.util.Locale)7 Authentication (me.ccrama.redditslide.Authentication)7 Context (android.content.Context)6 Intent (android.content.Intent)6 RecyclerView (androidx.recyclerview.widget.RecyclerView)6 LayoutUtils (me.ccrama.redditslide.util.LayoutUtils)6 OnSingleClickListener (me.ccrama.redditslide.util.OnSingleClickListener)6 Submission (net.dean.jraw.models.Submission)6 AsyncTask (android.os.AsyncTask)5