DisplayUtils.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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.Configuration;
  26. import android.content.res.Resources;
  27. import android.graphics.Bitmap;
  28. import android.graphics.Canvas;
  29. import android.graphics.Paint;
  30. import android.graphics.Typeface;
  31. import android.graphics.drawable.Animatable;
  32. import android.graphics.drawable.BitmapDrawable;
  33. import android.graphics.drawable.Drawable;
  34. import android.graphics.drawable.VectorDrawable;
  35. import android.net.Uri;
  36. import android.os.Build;
  37. import android.text.*;
  38. import android.text.method.LinkMovementMethod;
  39. import android.text.style.*;
  40. import android.util.Log;
  41. import android.util.TypedValue;
  42. import android.view.View;
  43. import android.view.ViewGroup;
  44. import android.widget.TextView;
  45. import androidx.annotation.*;
  46. import androidx.appcompat.widget.AppCompatDrawableManager;
  47. import androidx.core.content.ContextCompat;
  48. import androidx.core.graphics.drawable.DrawableCompat;
  49. import com.facebook.common.executors.UiThreadImmediateExecutorService;
  50. import com.facebook.common.references.CloseableReference;
  51. import com.facebook.datasource.DataSource;
  52. import com.facebook.drawee.backends.pipeline.Fresco;
  53. import com.facebook.drawee.controller.ControllerListener;
  54. import com.facebook.drawee.view.SimpleDraweeView;
  55. import com.facebook.imagepipeline.common.RotationOptions;
  56. import com.facebook.imagepipeline.core.ImagePipeline;
  57. import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
  58. import com.facebook.imagepipeline.image.CloseableImage;
  59. import com.facebook.imagepipeline.image.ImageInfo;
  60. import com.facebook.imagepipeline.postprocessors.RoundAsCirclePostprocessor;
  61. import com.facebook.imagepipeline.postprocessors.RoundPostprocessor;
  62. import com.facebook.imagepipeline.request.ImageRequest;
  63. import com.facebook.imagepipeline.request.ImageRequestBuilder;
  64. import com.google.android.material.chip.ChipDrawable;
  65. import com.nextcloud.talk.R;
  66. import com.nextcloud.talk.application.NextcloudTalkApplication;
  67. import com.nextcloud.talk.events.UserMentionClickEvent;
  68. import com.nextcloud.talk.models.database.UserEntity;
  69. import com.nextcloud.talk.utils.text.Spans;
  70. import com.vanniktech.emoji.EmojiEditText;
  71. import com.vanniktech.emoji.EmojiTextView;
  72. import org.greenrobot.eventbus.EventBus;
  73. import javax.annotation.Nonnull;
  74. import javax.annotation.Nullable;
  75. import java.lang.reflect.Constructor;
  76. import java.lang.reflect.InvocationTargetException;
  77. import java.lang.reflect.Method;
  78. import java.util.HashMap;
  79. import java.util.Map;
  80. import java.util.regex.Matcher;
  81. import java.util.regex.Pattern;
  82. public class DisplayUtils {
  83. private static final String TAG = "DisplayUtils";
  84. public static void setClickableString(String string, String url, TextView textView) {
  85. SpannableString spannableString = new SpannableString(string);
  86. spannableString.setSpan(new ClickableSpan() {
  87. @Override
  88. public void onClick(@Nonnull View widget) {
  89. Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
  90. browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  91. NextcloudTalkApplication.getSharedApplication().getApplicationContext().startActivity(browserIntent);
  92. }
  93. @Override
  94. public void updateDrawState(@NonNull TextPaint ds) {
  95. super.updateDrawState(ds);
  96. ds.setUnderlineText(false);
  97. }
  98. }, 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
  99. textView.setText(spannableString);
  100. textView.setMovementMethod(LinkMovementMethod.getInstance());
  101. }
  102. private static void updateViewSize(@Nullable ImageInfo imageInfo, SimpleDraweeView draweeView) {
  103. if (imageInfo != null) {
  104. int maxSize = draweeView.getContext().getResources().getDimensionPixelSize(R.dimen.maximum_file_preview_size);
  105. draweeView.getLayoutParams().width = imageInfo.getWidth() > maxSize ? maxSize : imageInfo.getWidth();
  106. draweeView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
  107. draweeView.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight());
  108. draweeView.requestLayout();
  109. }
  110. }
  111. public static Drawable getRoundedDrawable(Drawable drawable) {
  112. Bitmap bitmap = getBitmap(drawable);
  113. new RoundAsCirclePostprocessor(true).process(bitmap);
  114. return new BitmapDrawable(bitmap);
  115. }
  116. public static Bitmap getRoundedBitmapFromVectorDrawableResource(Resources resources, int resource) {
  117. VectorDrawable vectorDrawable = (VectorDrawable) resources.getDrawable(resource);
  118. Bitmap bitmap = getBitmap(vectorDrawable);
  119. new RoundPostprocessor(true).process(bitmap);
  120. return bitmap;
  121. }
  122. public static Drawable getRoundedBitmapDrawableFromVectorDrawableResource(Resources resources, int resource) {
  123. return new BitmapDrawable(getRoundedBitmapFromVectorDrawableResource(resources, resource));
  124. }
  125. public static float getDefaultEmojiFontSize(EmojiTextView emojiTextView) {
  126. final Paint.FontMetrics fontMetrics = emojiTextView.getPaint().getFontMetrics();
  127. return fontMetrics.descent - fontMetrics.ascent;
  128. }
  129. private static Bitmap getBitmap(Drawable drawable) {
  130. Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
  131. drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
  132. Canvas canvas = new Canvas(bitmap);
  133. drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
  134. drawable.draw(canvas);
  135. return bitmap;
  136. }
  137. public static ImageRequest getImageRequestForUrl(String url, @Nullable UserEntity userEntity) {
  138. Map<String, String> headers = new HashMap<>();
  139. if (userEntity != null && url.startsWith(userEntity.getBaseUrl()) && url.contains("index.php/core/preview?fileId=")) {
  140. headers.put("Authorization", ApiUtils.getCredentials(userEntity.getUsername(),
  141. userEntity.getToken()));
  142. }
  143. return ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
  144. .setProgressiveRenderingEnabled(true)
  145. .setRotationOptions(RotationOptions.autoRotate())
  146. .disableDiskCache()
  147. .setHeaders(headers)
  148. .build();
  149. }
  150. public static ControllerListener getImageControllerListener(SimpleDraweeView draweeView) {
  151. return new ControllerListener() {
  152. @Override
  153. public void onSubmit(String id, Object callerContext) {
  154. }
  155. @Override
  156. public void onFinalImageSet(String id, @javax.annotation.Nullable Object imageInfo, @javax.annotation.Nullable Animatable animatable) {
  157. updateViewSize((ImageInfo) imageInfo, draweeView);
  158. }
  159. @Override
  160. public void onIntermediateImageSet(String id, @javax.annotation.Nullable Object imageInfo) {
  161. updateViewSize((ImageInfo) imageInfo, draweeView);
  162. }
  163. @Override
  164. public void onIntermediateImageFailed(String id, Throwable throwable) {
  165. }
  166. @Override
  167. public void onFailure(String id, Throwable throwable) {
  168. }
  169. @Override
  170. public void onRelease(String id) {
  171. }
  172. };
  173. }
  174. public static float convertDpToPixel(float dp, Context context) {
  175. return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
  176. context.getResources().getDisplayMetrics()) + 0.5f);
  177. }
  178. // Solution inspired by https://stackoverflow.com/questions/34936590/why-isnt-my-vector-drawable-scaling-as-expected
  179. public static void useCompatVectorIfNeeded() {
  180. if (Build.VERSION.SDK_INT < 23) {
  181. try {
  182. @SuppressLint("RestrictedApi") AppCompatDrawableManager drawableManager = AppCompatDrawableManager.get();
  183. Class<?> inflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$InflateDelegate");
  184. Class<?> vdcInflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate");
  185. Constructor<?> constructor = vdcInflateDelegateClass.getDeclaredConstructor();
  186. constructor.setAccessible(true);
  187. Object vdcInflateDelegate = constructor.newInstance();
  188. Class<?> args[] = {String.class, inflateDelegateClass};
  189. Method addDelegate = AppCompatDrawableManager.class.getDeclaredMethod("addDelegate", args);
  190. addDelegate.setAccessible(true);
  191. addDelegate.invoke(drawableManager, "vector", vdcInflateDelegate);
  192. } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
  193. InvocationTargetException | IllegalAccessException e) {
  194. Log.e(TAG, "Failed to use reflection to enable proper vector scaling");
  195. }
  196. }
  197. }
  198. public static Drawable getTintedDrawable(Resources res, @DrawableRes int drawableResId, @ColorRes int colorResId) {
  199. Drawable drawable = res.getDrawable(drawableResId);
  200. int color = res.getColor(colorResId);
  201. drawable.setTint(color);
  202. return drawable;
  203. }
  204. public static Drawable getDrawableForMentionChipSpan(Context context, String id, String label,
  205. UserEntity conversationUser, String type,
  206. @XmlRes int chipResource,
  207. @Nullable EmojiEditText emojiEditText) {
  208. ChipDrawable chip = ChipDrawable.createFromResource(context, chipResource);
  209. chip.setText(label);
  210. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  211. Configuration config = context.getResources().getConfiguration();
  212. chip.setLayoutDirection(config.getLayoutDirection());
  213. }
  214. int drawable;
  215. boolean isCall = "call".equals(type) || "calls".equals(type);
  216. if (!isCall) {
  217. if (chipResource == R.xml.chip_outgoing_others || chipResource == R.xml.chip_accent_background) {
  218. drawable = R.drawable.white_circle;
  219. } else {
  220. drawable = R.drawable.accent_circle;
  221. }
  222. chip.setChipIcon(context.getDrawable(drawable));
  223. } else {
  224. chip.setChipIcon(getRoundedDrawable(context.getDrawable(R.drawable.ic_people_group_white_24px)));
  225. }
  226. chip.setBounds(0, 0, chip.getIntrinsicWidth(), chip.getIntrinsicHeight());
  227. if (!isCall) {
  228. ImageRequest imageRequest =
  229. getImageRequestForUrl(ApiUtils.getUrlForAvatarWithName(conversationUser.getBaseUrl(), id, R.dimen.avatar_size_big), null);
  230. ImagePipeline imagePipeline = Fresco.getImagePipeline();
  231. DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
  232. dataSource.subscribe(
  233. new BaseBitmapDataSubscriber() {
  234. @Override
  235. protected void onNewResultImpl(Bitmap bitmap) {
  236. if (bitmap != null) {
  237. chip.setChipIcon(getRoundedDrawable(new BitmapDrawable(bitmap)));
  238. // A hack to refresh the chip icon
  239. if (emojiEditText != null) {
  240. emojiEditText.post(() -> emojiEditText.setTextKeepState(emojiEditText.getText(), TextView.BufferType.SPANNABLE));
  241. }
  242. }
  243. }
  244. @Override
  245. protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
  246. }
  247. },
  248. UiThreadImmediateExecutorService.getInstance());
  249. }
  250. return chip;
  251. }
  252. public static Spannable searchAndReplaceWithMentionSpan(Context context, Spannable text,
  253. String id, String label, String type,
  254. UserEntity conversationUser,
  255. @XmlRes int chipXmlRes) {
  256. Spannable spannableString = new SpannableString(text);
  257. String stringText = text.toString();
  258. Matcher m = Pattern.compile("@" + label,
  259. Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.MULTILINE)
  260. .matcher(spannableString);
  261. ClickableSpan clickableSpan = new ClickableSpan() {
  262. @Override
  263. public void onClick(@NonNull View widget) {
  264. EventBus.getDefault().post(new UserMentionClickEvent(id));
  265. }
  266. };
  267. int lastStartIndex = -1;
  268. Spans.MentionChipSpan mentionChipSpan;
  269. while (m.find()) {
  270. int start = stringText.indexOf(m.group(), lastStartIndex);
  271. int end = start + m.group().length();
  272. lastStartIndex = end;
  273. mentionChipSpan = new Spans.MentionChipSpan(DisplayUtils.getDrawableForMentionChipSpan(context,
  274. id, label, conversationUser, type, chipXmlRes, null),
  275. DynamicDrawableSpan.ALIGN_BASELINE, id,
  276. label);
  277. spannableString.setSpan(mentionChipSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  278. if ("user".equals(type) && !conversationUser.getUserId().equals(id)) {
  279. spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
  280. }
  281. }
  282. return spannableString;
  283. }
  284. public static Spannable searchAndColor(Spannable text, String searchText, @ColorInt int color) {
  285. Spannable spannableString = new SpannableString(text);
  286. String stringText = text.toString();
  287. if (TextUtils.isEmpty(text) || TextUtils.isEmpty(searchText)) {
  288. return spannableString;
  289. }
  290. Matcher m = Pattern.compile(searchText,
  291. Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.MULTILINE)
  292. .matcher(spannableString);
  293. int textSize = NextcloudTalkApplication.getSharedApplication().getResources().getDimensionPixelSize(R.dimen
  294. .chat_text_size);
  295. int lastStartIndex = -1;
  296. while (m.find()) {
  297. int start = stringText.indexOf(m.group(), lastStartIndex);
  298. int end = start + m.group().length();
  299. lastStartIndex = end;
  300. spannableString.setSpan(new ForegroundColorSpan(color), start, end,
  301. Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  302. spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  303. spannableString.setSpan(new AbsoluteSizeSpan(textSize), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  304. }
  305. return spannableString;
  306. }
  307. public static Drawable getMessageSelector(@ColorInt int normalColor, @ColorInt int selectedColor,
  308. @ColorInt int pressedColor, @DrawableRes int shape) {
  309. Drawable vectorDrawable = ContextCompat.getDrawable(NextcloudTalkApplication.getSharedApplication()
  310. .getApplicationContext(),
  311. shape);
  312. Drawable drawable = DrawableCompat.wrap(vectorDrawable).mutate();
  313. DrawableCompat.setTintList(
  314. drawable,
  315. new ColorStateList(
  316. new int[][]{
  317. new int[]{android.R.attr.state_selected},
  318. new int[]{android.R.attr.state_pressed},
  319. new int[]{-android.R.attr.state_pressed, -android.R.attr.state_selected}
  320. },
  321. new int[]{selectedColor, pressedColor, normalColor}
  322. ));
  323. return drawable;
  324. }
  325. }