MediaAdapter.java

  1package eu.siacs.conversations.ui.adapter;
  2
  3import android.content.res.ColorStateList;
  4import android.content.res.Resources;
  5import android.graphics.Bitmap;
  6import android.graphics.Color;
  7import android.graphics.drawable.BitmapDrawable;
  8import android.graphics.drawable.Drawable;
  9import android.os.AsyncTask;
 10import android.view.LayoutInflater;
 11import android.view.ViewGroup;
 12import android.widget.ImageView;
 13import androidx.annotation.DimenRes;
 14import androidx.annotation.DrawableRes;
 15import androidx.annotation.NonNull;
 16import androidx.core.widget.ImageViewCompat;
 17import androidx.databinding.DataBindingUtil;
 18import androidx.recyclerview.widget.RecyclerView;
 19import com.google.android.material.color.MaterialColors;
 20import com.google.common.base.Strings;
 21import eu.siacs.conversations.R;
 22import eu.siacs.conversations.databinding.ItemMediaBinding;
 23import eu.siacs.conversations.ui.XmppActivity;
 24import eu.siacs.conversations.ui.util.Attachment;
 25import eu.siacs.conversations.ui.util.ViewUtil;
 26import eu.siacs.conversations.worker.ExportBackupWorker;
 27import java.lang.ref.WeakReference;
 28import java.util.ArrayList;
 29import java.util.Arrays;
 30import java.util.List;
 31import java.util.concurrent.RejectedExecutionException;
 32
 33public class MediaAdapter extends RecyclerView.Adapter<MediaAdapter.MediaViewHolder> {
 34
 35    public static final List<String> DOCUMENT_MIMES =
 36            Arrays.asList(
 37                    "application/pdf",
 38                    "application/vnd.oasis.opendocument.text",
 39                    "application/msword",
 40                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
 41                    "text/x-tex",
 42                    "text/plain");
 43    public static final List<String> SPREAD_SHEET_MIMES =
 44            Arrays.asList(
 45                    "text/comma-separated-values",
 46                    "application/vnd.ms-excel",
 47                    "application/vnd.stardivision.calc",
 48                    "application/vnd.oasis.opendocument.spreadsheet",
 49                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
 50
 51    public static final List<String> SLIDE_SHOW_MIMES =
 52            Arrays.asList(
 53                    "application/vnd.ms-powerpoint",
 54                    "application/vnd.stardivision.impress",
 55                    "application/vnd.oasis.opendocument.presentation",
 56                    "application/vnd.openxmlformats-officedocument.presentationml.presentation",
 57                    "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
 58
 59    private static final List<String> ARCHIVE_MIMES =
 60            Arrays.asList(
 61                    "application/x-7z-compressed",
 62                    "application/zip",
 63                    "application/rar",
 64                    "application/x-gtar",
 65                    "application/x-tar");
 66    public static final List<String> CODE_MIMES = Arrays.asList("text/html", "text/xml");
 67
 68    private final ArrayList<Attachment> attachments = new ArrayList<>();
 69
 70    private final XmppActivity activity;
 71
 72    private int mediaSize = 0;
 73
 74    public MediaAdapter(XmppActivity activity, @DimenRes int mediaSize) {
 75        this.activity = activity;
 76        this.mediaSize = Math.round(activity.getResources().getDimension(mediaSize));
 77    }
 78
 79    @SuppressWarnings("rawtypes")
 80    public static void setMediaSize(final RecyclerView recyclerView, int mediaSize) {
 81        final RecyclerView.Adapter adapter = recyclerView.getAdapter();
 82        if (adapter instanceof MediaAdapter mediaAdapter) {
 83            mediaAdapter.setMediaSize(mediaSize);
 84        }
 85    }
 86
 87    public static @DrawableRes int getImageDrawable(final Attachment attachment) {
 88        if (attachment.getType() == Attachment.Type.LOCATION) {
 89            return R.drawable.ic_location_pin_48dp;
 90        } else if (attachment.getType() == Attachment.Type.RECORDING) {
 91            return R.drawable.ic_mic_48dp;
 92        } else {
 93            return getImageDrawable(attachment.getMime());
 94        }
 95    }
 96
 97    private static @DrawableRes int getImageDrawable(final String mime) {
 98
 99        // TODO ideas for more mime types: XML, HTML documents, GPG/PGP files, eml files,
100        // spreadsheets (table symbol)
101
102        // add bz2 and tar.gz to archive detection
103
104        if (Strings.isNullOrEmpty(mime)) {
105            return R.drawable.ic_help_center_48dp;
106        } else if (mime.equals("audio/x-m4b")) {
107            return R.drawable.ic_play_lesson_48dp;
108        } else if (mime.startsWith("audio/")) {
109            return R.drawable.ic_headphones_48dp;
110        } else if (mime.equals("text/calendar") || (mime.equals("text/x-vcalendar"))) {
111            return R.drawable.ic_event_48dp;
112        } else if (mime.equals("text/x-vcard")) {
113            return R.drawable.ic_person_48dp;
114        } else if (mime.equals("application/vnd.android.package-archive")) {
115            return R.drawable.ic_adb_48dp;
116        } else if (ARCHIVE_MIMES.contains(mime)) {
117            return R.drawable.ic_archive_48dp;
118        } else if (mime.equals("application/epub+zip")
119                || mime.equals("application/vnd.amazon.mobi8-ebook")) {
120            return R.drawable.ic_book_48dp;
121        } else if (mime.equals(ExportBackupWorker.MIME_TYPE)) {
122            return R.drawable.ic_backup_48dp;
123        } else if (DOCUMENT_MIMES.contains(mime)) {
124            return R.drawable.ic_description_48dp;
125        } else if (SPREAD_SHEET_MIMES.contains(mime)) {
126            return R.drawable.ic_table_48dp;
127        } else if (SLIDE_SHOW_MIMES.contains(mime)) {
128            return R.drawable.ic_slideshow_48dp;
129        } else if (mime.equals("application/gpx+xml")) {
130            return R.drawable.ic_tour_48dp;
131        } else if (mime.startsWith("image/")) {
132            return R.drawable.ic_image_48dp;
133        } else if (mime.startsWith("video/")) {
134            return R.drawable.ic_movie_48dp;
135        } else if (CODE_MIMES.contains(mime)) {
136            return R.drawable.ic_code_48dp;
137        } else if (mime.equals("message/rfc822")) {
138            return R.drawable.ic_email_48dp;
139        } else {
140            return R.drawable.ic_help_center_48dp;
141        }
142    }
143
144    static void renderPreview(final Attachment attachment, final ImageView imageView) {
145        ImageViewCompat.setImageTintList(
146                imageView,
147                ColorStateList.valueOf(
148                        MaterialColors.getColor(
149                                imageView, com.google.android.material.R.attr.colorOnSurface)));
150        imageView.setImageResource(getImageDrawable(attachment));
151        imageView.setBackgroundColor(
152                MaterialColors.getColor(
153                        imageView,
154                        com.google.android.material.R.attr.colorSurfaceContainerHighest));
155    }
156
157    private static boolean cancelPotentialWork(Attachment attachment, ImageView imageView) {
158        final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
159
160        if (bitmapWorkerTask != null) {
161            final Attachment oldAttachment = bitmapWorkerTask.attachment;
162            if (oldAttachment == null || !oldAttachment.equals(attachment)) {
163                bitmapWorkerTask.cancel(true);
164            } else {
165                return false;
166            }
167        }
168        return true;
169    }
170
171    private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
172        if (imageView != null) {
173            final Drawable drawable = imageView.getDrawable();
174            if (drawable instanceof AsyncDrawable asyncDrawable) {
175                return asyncDrawable.getBitmapWorkerTask();
176            }
177        }
178        return null;
179    }
180
181    @NonNull
182    @Override
183    public MediaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
184        final LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
185        ItemMediaBinding binding =
186                DataBindingUtil.inflate(layoutInflater, R.layout.item_media, parent, false);
187        return new MediaViewHolder(binding);
188    }
189
190    @Override
191    public void onBindViewHolder(@NonNull MediaViewHolder holder, int position) {
192        final Attachment attachment = attachments.get(position);
193        if (attachment.renderThumbnail()) {
194            loadPreview(attachment, holder.binding.media);
195        } else {
196            cancelPotentialWork(attachment, holder.binding.media);
197            renderPreview(attachment, holder.binding.media);
198        }
199        holder.binding.getRoot().setOnClickListener(v -> ViewUtil.view(activity, attachment));
200    }
201
202    public void setAttachments(final List<Attachment> attachments) {
203        this.attachments.clear();
204        this.attachments.addAll(attachments);
205        notifyDataSetChanged();
206    }
207
208    private void setMediaSize(int mediaSize) {
209        this.mediaSize = mediaSize;
210    }
211
212    private void loadPreview(Attachment attachment, ImageView imageView) {
213        if (cancelPotentialWork(attachment, imageView)) {
214            final Bitmap bm =
215                    activity.xmppConnectionService
216                            .getFileBackend()
217                            .getPreviewForUri(attachment, mediaSize, true);
218            if (bm != null) {
219                cancelPotentialWork(attachment, imageView);
220                imageView.setImageBitmap(bm);
221                imageView.setBackgroundColor(Color.TRANSPARENT);
222            } else {
223                // TODO consider if this is still a good, general purpose loading color
224                imageView.setBackgroundColor(0xff333333);
225                imageView.setImageDrawable(null);
226                final BitmapWorkerTask task = new BitmapWorkerTask(mediaSize, imageView);
227                final AsyncDrawable asyncDrawable =
228                        new AsyncDrawable(activity.getResources(), null, task);
229                imageView.setImageDrawable(asyncDrawable);
230                try {
231                    task.execute(attachment);
232                } catch (final RejectedExecutionException ignored) {
233                }
234            }
235        }
236    }
237
238    @Override
239    public int getItemCount() {
240        return attachments.size();
241    }
242
243    static class AsyncDrawable extends BitmapDrawable {
244        private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
245
246        AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
247            super(res, bitmap);
248            bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
249        }
250
251        BitmapWorkerTask getBitmapWorkerTask() {
252            return bitmapWorkerTaskReference.get();
253        }
254    }
255
256    static class MediaViewHolder extends RecyclerView.ViewHolder {
257
258        private final ItemMediaBinding binding;
259
260        MediaViewHolder(ItemMediaBinding binding) {
261            super(binding.getRoot());
262            this.binding = binding;
263        }
264    }
265
266    private static class BitmapWorkerTask extends AsyncTask<Attachment, Void, Bitmap> {
267        private final WeakReference<ImageView> imageViewReference;
268        private Attachment attachment = null;
269        private final int mediaSize;
270
271        BitmapWorkerTask(int mediaSize, ImageView imageView) {
272            this.mediaSize = mediaSize;
273            imageViewReference = new WeakReference<>(imageView);
274        }
275
276        @Override
277        protected Bitmap doInBackground(final Attachment... params) {
278            this.attachment = params[0];
279            final XmppActivity activity = XmppActivity.find(imageViewReference);
280            if (activity == null) {
281                return null;
282            }
283            return activity.xmppConnectionService
284                    .getFileBackend()
285                    .getPreviewForUri(this.attachment, mediaSize, false);
286        }
287
288        @Override
289        protected void onPostExecute(Bitmap bitmap) {
290            if (bitmap != null && !isCancelled()) {
291                final ImageView imageView = imageViewReference.get();
292                if (imageView != null) {
293                    imageView.setImageBitmap(bitmap);
294                    imageView.setBackgroundColor(0x00000000);
295                }
296            }
297        }
298    }
299}