DisplayUtils.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017 Mario Danic <mario@lovelyhq.com>
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.nextcloud.talk.utils;
  21. import android.annotation.SuppressLint;
  22. import android.content.Context;
  23. import android.content.Intent;
  24. import android.content.res.ColorStateList;
  25. import android.content.res.Resources;
  26. import android.graphics.Bitmap;
  27. import android.graphics.Canvas;
  28. import android.graphics.Paint;
  29. import android.graphics.Typeface;
  30. import android.graphics.drawable.*;
  31. import android.net.Uri;
  32. import android.os.Build;
  33. import android.text.*;
  34. import android.text.method.LinkMovementMethod;
  35. import android.text.style.*;
  36. import android.util.Log;
  37. import android.util.TypedValue;
  38. import android.view.View;
  39. import android.view.ViewGroup;
  40. import android.widget.TextView;
  41. import androidx.annotation.*;
  42. import androidx.appcompat.widget.AppCompatDrawableManager;
  43. import androidx.core.content.ContextCompat;
  44. import androidx.core.graphics.drawable.DrawableCompat;
  45. import com.facebook.common.executors.UiThreadImmediateExecutorService;
  46. import com.facebook.common.references.CloseableReference;
  47. import com.facebook.datasource.DataSource;
  48. import com.facebook.drawee.backends.pipeline.Fresco;
  49. import com.facebook.drawee.controller.ControllerListener;
  50. import com.facebook.drawee.drawable.RoundedColorDrawable;
  51. import com.facebook.drawee.view.SimpleDraweeView;
  52. import com.facebook.imagepipeline.common.RotationOptions;
  53. import com.facebook.imagepipeline.core.ImagePipeline;
  54. import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
  55. import com.facebook.imagepipeline.image.CloseableImage;
  56. import com.facebook.imagepipeline.image.ImageInfo;
  57. import com.facebook.imagepipeline.postprocessors.RoundAsCirclePostprocessor;
  58. import com.facebook.imagepipeline.request.ImageRequest;
  59. import com.facebook.imagepipeline.request.ImageRequestBuilder;
  60. import com.google.android.material.chip.ChipDrawable;
  61. import com.nextcloud.talk.R;
  62. import com.nextcloud.talk.application.NextcloudTalkApplication;
  63. import com.nextcloud.talk.models.database.UserEntity;
  64. import com.nextcloud.talk.utils.text.Spans;
  65. import com.vanniktech.emoji.EmojiTextView;
  66. import java.lang.reflect.Constructor;
  67. import java.lang.reflect.InvocationTargetException;
  68. import java.lang.reflect.Method;
  69. import java.util.regex.Matcher;
  70. import java.util.regex.Pattern;
  71. public class DisplayUtils {
  72. private static final String TAG = "DisplayUtils";
  73. public static void setClickableString(String string, String url, TextView textView) {
  74. SpannableString spannableString = new SpannableString(string);
  75. spannableString.setSpan(new ClickableSpan() {
  76. @Override
  77. public void onClick(@NonNull View widget) {
  78. Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
  79. browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  80. NextcloudTalkApplication.getSharedApplication().getApplicationContext().startActivity(browserIntent);
  81. }
  82. @Override
  83. public void updateDrawState(TextPaint ds) {
  84. super.updateDrawState(ds);
  85. ds.setUnderlineText(false);
  86. }
  87. }, 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
  88. textView.setText(spannableString);
  89. textView.setMovementMethod(LinkMovementMethod.getInstance());
  90. }
  91. private static void updateViewSize(@Nullable ImageInfo imageInfo, SimpleDraweeView draweeView) {
  92. if (imageInfo != null) {
  93. draweeView.getLayoutParams().width = imageInfo.getWidth() > 480 ? 480 : imageInfo.getWidth();
  94. draweeView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
  95. draweeView.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight());
  96. draweeView.requestLayout();
  97. }
  98. }
  99. public static Drawable getRoundedDrawable(Drawable drawable) {
  100. Bitmap bitmap = getBitmap(drawable);
  101. new RoundAsCirclePostprocessor(true).process(bitmap);
  102. return new BitmapDrawable(bitmap);
  103. }
  104. public static Bitmap getRoundedBitmapFromVectorDrawableResource(Resources resources, int resource) {
  105. VectorDrawable vectorDrawable = (VectorDrawable) resources.getDrawable(resource);
  106. Bitmap bitmap = getBitmap(vectorDrawable);
  107. new RoundAsCirclePostprocessor(true).process(bitmap);
  108. return bitmap;
  109. }
  110. public static Drawable getRoundedBitmapDrawableFromVectorDrawableResource(Resources resources, int resource) {
  111. return new BitmapDrawable(getRoundedBitmapFromVectorDrawableResource(resources, resource));
  112. }
  113. public static float getDefaultEmojiFontSize(EmojiTextView emojiTextView) {
  114. final Paint.FontMetrics fontMetrics = emojiTextView.getPaint().getFontMetrics();
  115. return fontMetrics.descent - fontMetrics.ascent;
  116. }
  117. private static Bitmap getBitmap(Drawable drawable) {
  118. Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
  119. drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
  120. Canvas canvas = new Canvas(bitmap);
  121. drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
  122. drawable.draw(canvas);
  123. return bitmap;
  124. }
  125. public static ImageRequest getImageRequestForUrl(String url) {
  126. return ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
  127. .setProgressiveRenderingEnabled(true)
  128. .setRotationOptions(RotationOptions.autoRotate())
  129. .disableDiskCache()
  130. .build();
  131. }
  132. public static ControllerListener getImageControllerListener(SimpleDraweeView draweeView) {
  133. return new ControllerListener() {
  134. @Override
  135. public void onSubmit(String id, Object callerContext) {
  136. }
  137. @Override
  138. public void onFinalImageSet(String id, @javax.annotation.Nullable Object imageInfo, @javax.annotation.Nullable Animatable animatable) {
  139. updateViewSize((ImageInfo) imageInfo, draweeView);
  140. }
  141. @Override
  142. public void onIntermediateImageSet(String id, @javax.annotation.Nullable Object imageInfo) {
  143. updateViewSize((ImageInfo) imageInfo, draweeView);
  144. }
  145. @Override
  146. public void onIntermediateImageFailed(String id, Throwable throwable) {
  147. }
  148. @Override
  149. public void onFailure(String id, Throwable throwable) {
  150. }
  151. @Override
  152. public void onRelease(String id) {
  153. }
  154. };
  155. }
  156. public static float convertDpToPixel(float dp, Context context) {
  157. return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
  158. context.getResources().getDisplayMetrics()) + 0.5f);
  159. }
  160. // Solution inspired by https://stackoverflow.com/questions/34936590/why-isnt-my-vector-drawable-scaling-as-expected
  161. public static void useCompatVectorIfNeeded() {
  162. if (Build.VERSION.SDK_INT < 23) {
  163. try {
  164. @SuppressLint("RestrictedApi") AppCompatDrawableManager drawableManager = AppCompatDrawableManager.get();
  165. Class<?> inflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$InflateDelegate");
  166. Class<?> vdcInflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate");
  167. Constructor<?> constructor = vdcInflateDelegateClass.getDeclaredConstructor();
  168. constructor.setAccessible(true);
  169. Object vdcInflateDelegate = constructor.newInstance();
  170. Class<?> args[] = {String.class, inflateDelegateClass};
  171. Method addDelegate = AppCompatDrawableManager.class.getDeclaredMethod("addDelegate", args);
  172. addDelegate.setAccessible(true);
  173. addDelegate.invoke(drawableManager, "vector", vdcInflateDelegate);
  174. } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
  175. InvocationTargetException | IllegalAccessException e) {
  176. Log.e(TAG, "Failed to use reflection to enable proper vector scaling");
  177. }
  178. }
  179. }
  180. public static Drawable getTintedDrawable(Resources res, @DrawableRes int drawableResId, @ColorRes int colorResId) {
  181. Drawable drawable = res.getDrawable(drawableResId);
  182. int color = res.getColor(colorResId);
  183. drawable.setTint(color);
  184. return drawable;
  185. }
  186. public static Drawable getDrawableForMentionChipSpan(Context context, String id, String label,
  187. UserEntity conversationUser,
  188. @XmlRes int chipResource) {
  189. ChipDrawable chip = ChipDrawable.createFromResource(context, chipResource);
  190. chip.setText(label);
  191. int drawable;
  192. if (chipResource == R.xml.chip_accent_background) {
  193. drawable = R.drawable.white_circle;
  194. } else {
  195. drawable = R.drawable.accent_circle;
  196. }
  197. chip.setChipIcon(context.getDrawable(drawable));
  198. chip.setBounds(0, 0, chip.getIntrinsicWidth(), chip.getIntrinsicHeight());
  199. ImageRequest imageRequest =
  200. getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(conversationUser.getBaseUrl(), id, R.dimen.avatar_size_big));
  201. ImagePipeline imagePipeline = Fresco.getImagePipeline();
  202. DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
  203. dataSource.subscribe(
  204. new BaseBitmapDataSubscriber() {
  205. @Override
  206. protected void onNewResultImpl(Bitmap bitmap) {
  207. if (bitmap != null) {
  208. chip.setChipIcon(getRoundedDrawable(new BitmapDrawable(bitmap)));
  209. chip.invalidateSelf();
  210. }
  211. }
  212. @Override
  213. protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
  214. }
  215. },
  216. UiThreadImmediateExecutorService.getInstance());
  217. return chip;
  218. }
  219. public static Spannable searchAndReplaceWithMentionSpan(Context context, Spannable text,
  220. String id, String label,
  221. UserEntity conversationUser,
  222. @XmlRes int chipXmlRes) {
  223. Spannable spannableString = new SpannableString(text);
  224. String stringText = text.toString();
  225. Matcher m = Pattern.compile("@" + label,
  226. Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.MULTILINE)
  227. .matcher(spannableString);
  228. int lastStartIndex = -1;
  229. Spans.MentionChipSpan mentionChipSpan;
  230. while (m.find()) {
  231. int start = stringText.indexOf(m.group(), lastStartIndex);
  232. int end = start + m.group().length();
  233. lastStartIndex = end;
  234. mentionChipSpan = new Spans.MentionChipSpan(DisplayUtils.getDrawableForMentionChipSpan(context,
  235. id, label, conversationUser, chipXmlRes),
  236. DynamicDrawableSpan.ALIGN_BASELINE, id,
  237. label);
  238. spannableString.setSpan(mentionChipSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  239. }
  240. return spannableString;
  241. }
  242. public static Spannable searchAndColor(Spannable text, String searchText, @ColorInt int color) {
  243. Spannable spannableString = new SpannableString(text);
  244. String stringText = text.toString();
  245. if (TextUtils.isEmpty(text) || TextUtils.isEmpty(searchText)) {
  246. return spannableString;
  247. }
  248. Matcher m = Pattern.compile(searchText,
  249. Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.MULTILINE)
  250. .matcher(spannableString);
  251. int textSize = NextcloudTalkApplication.getSharedApplication().getResources().getDimensionPixelSize(R.dimen
  252. .chat_text_size);
  253. int lastStartIndex = -1;
  254. while (m.find()) {
  255. int start = stringText.indexOf(m.group(), lastStartIndex);
  256. int end = start + m.group().length();
  257. lastStartIndex = end;
  258. spannableString.setSpan(new ForegroundColorSpan(color), start, end,
  259. Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  260. spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  261. spannableString.setSpan(new AbsoluteSizeSpan(textSize), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  262. }
  263. return spannableString;
  264. }
  265. public static Drawable getMessageSelector(@ColorInt int normalColor, @ColorInt int selectedColor,
  266. @ColorInt int pressedColor, @DrawableRes int shape) {
  267. Drawable vectorDrawable = ContextCompat.getDrawable(NextcloudTalkApplication.getSharedApplication()
  268. .getApplicationContext(),
  269. shape);
  270. Drawable drawable = DrawableCompat.wrap(vectorDrawable).mutate();
  271. DrawableCompat.setTintList(
  272. drawable,
  273. new ColorStateList(
  274. new int[][]{
  275. new int[]{android.R.attr.state_selected},
  276. new int[]{android.R.attr.state_pressed},
  277. new int[]{-android.R.attr.state_pressed, -android.R.attr.state_selected}
  278. },
  279. new int[]{selectedColor, pressedColor, normalColor}
  280. ));
  281. return drawable;
  282. }
  283. }