DisplayUtils.java 17 KB

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