DisplayUtils.java 18 KB

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