DisplayUtils.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017-2020 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.app.Activity;
  23. import android.content.Context;
  24. import android.content.Intent;
  25. import android.content.res.ColorStateList;
  26. import android.content.res.Configuration;
  27. import android.content.res.Resources;
  28. import android.graphics.Bitmap;
  29. import android.graphics.Canvas;
  30. import android.graphics.Color;
  31. import android.graphics.Typeface;
  32. import android.graphics.drawable.Animatable;
  33. import android.graphics.drawable.BitmapDrawable;
  34. import android.graphics.drawable.Drawable;
  35. import android.graphics.drawable.VectorDrawable;
  36. import android.net.Uri;
  37. import android.os.Build;
  38. import android.text.Spannable;
  39. import android.text.SpannableString;
  40. import android.text.Spanned;
  41. import android.text.TextPaint;
  42. import android.text.TextUtils;
  43. import android.text.method.LinkMovementMethod;
  44. import android.text.style.AbsoluteSizeSpan;
  45. import android.text.style.ClickableSpan;
  46. import android.text.style.ForegroundColorSpan;
  47. import android.text.style.StyleSpan;
  48. import android.util.Log;
  49. import android.util.TypedValue;
  50. import android.view.View;
  51. import android.view.ViewGroup;
  52. import android.view.Window;
  53. import android.view.WindowManager;
  54. import android.widget.EditText;
  55. import android.widget.ImageView;
  56. import android.widget.TextView;
  57. import androidx.annotation.ColorInt;
  58. import androidx.annotation.ColorRes;
  59. import androidx.annotation.DrawableRes;
  60. import androidx.annotation.NonNull;
  61. import androidx.annotation.Nullable;
  62. import androidx.annotation.XmlRes;
  63. import androidx.appcompat.app.AppCompatDelegate;
  64. import androidx.appcompat.widget.AppCompatDrawableManager;
  65. import androidx.appcompat.widget.SearchView;
  66. import androidx.core.content.ContextCompat;
  67. import androidx.core.content.res.ResourcesCompat;
  68. import androidx.core.graphics.ColorUtils;
  69. import androidx.core.graphics.drawable.DrawableCompat;
  70. import androidx.emoji.text.EmojiCompat;
  71. import androidx.viewpager.widget.ViewPager;
  72. import com.facebook.common.executors.UiThreadImmediateExecutorService;
  73. import com.facebook.common.references.CloseableReference;
  74. import com.facebook.datasource.DataSource;
  75. import com.facebook.drawee.backends.pipeline.Fresco;
  76. import com.facebook.drawee.controller.ControllerListener;
  77. import com.facebook.drawee.view.SimpleDraweeView;
  78. import com.facebook.imagepipeline.common.RotationOptions;
  79. import com.facebook.imagepipeline.core.ImagePipeline;
  80. import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
  81. import com.facebook.imagepipeline.image.CloseableImage;
  82. import com.facebook.imagepipeline.image.ImageInfo;
  83. import com.facebook.imagepipeline.postprocessors.RoundAsCirclePostprocessor;
  84. import com.facebook.imagepipeline.postprocessors.RoundPostprocessor;
  85. import com.facebook.imagepipeline.request.ImageRequest;
  86. import com.facebook.imagepipeline.request.ImageRequestBuilder;
  87. import com.facebook.widget.text.span.BetterImageSpan;
  88. import com.google.android.material.chip.ChipDrawable;
  89. import com.nextcloud.talk.R;
  90. import com.nextcloud.talk.application.NextcloudTalkApplication;
  91. import com.nextcloud.talk.events.UserMentionClickEvent;
  92. import com.nextcloud.talk.models.database.UserEntity;
  93. import com.nextcloud.talk.utils.preferences.AppPreferences;
  94. import com.nextcloud.talk.utils.text.Spans;
  95. import org.greenrobot.eventbus.EventBus;
  96. import java.lang.reflect.Constructor;
  97. import java.lang.reflect.InvocationTargetException;
  98. import java.lang.reflect.Method;
  99. import java.util.HashMap;
  100. import java.util.Map;
  101. import java.util.regex.Matcher;
  102. import java.util.regex.Pattern;
  103. public class DisplayUtils {
  104. private static final String TAG = "DisplayUtils";
  105. private static final int INDEX_LUMINATION = 2;
  106. private static final double MAX_LIGHTNESS = 0.92;
  107. public static void setClickableString(String string, String url, TextView textView) {
  108. SpannableString spannableString = new SpannableString(string);
  109. spannableString.setSpan(new ClickableSpan() {
  110. @Override
  111. public void onClick(@NonNull View widget) {
  112. Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
  113. browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  114. NextcloudTalkApplication.Companion.getSharedApplication().getApplicationContext().startActivity(browserIntent);
  115. }
  116. @Override
  117. public void updateDrawState(@NonNull TextPaint ds) {
  118. super.updateDrawState(ds);
  119. ds.setUnderlineText(false);
  120. }
  121. }, 0, string.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
  122. textView.setText(spannableString);
  123. textView.setMovementMethod(LinkMovementMethod.getInstance());
  124. }
  125. private static void updateViewSize(@Nullable ImageInfo imageInfo, SimpleDraweeView draweeView) {
  126. if (imageInfo != null) {
  127. int maxSize = draweeView.getContext().getResources().getDimensionPixelSize(R.dimen.maximum_file_preview_size);
  128. draweeView.getLayoutParams().width = imageInfo.getWidth() > maxSize ? maxSize : imageInfo.getWidth();
  129. draweeView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
  130. draweeView.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight());
  131. draweeView.requestLayout();
  132. }
  133. }
  134. public static Drawable getRoundedDrawable(Drawable drawable) {
  135. Bitmap bitmap = getBitmap(drawable);
  136. new RoundAsCirclePostprocessor(true).process(bitmap);
  137. return new BitmapDrawable(bitmap);
  138. }
  139. public static Bitmap getRoundedBitmapFromVectorDrawableResource(Resources resources, int resource) {
  140. VectorDrawable vectorDrawable = (VectorDrawable) resources.getDrawable(resource);
  141. Bitmap bitmap = getBitmap(vectorDrawable);
  142. new RoundPostprocessor(true).process(bitmap);
  143. return bitmap;
  144. }
  145. public static Drawable getRoundedBitmapDrawableFromVectorDrawableResource(Resources resources, int resource) {
  146. return new BitmapDrawable(getRoundedBitmapFromVectorDrawableResource(resources, resource));
  147. }
  148. private static Bitmap getBitmap(Drawable drawable) {
  149. Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
  150. drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
  151. Canvas canvas = new Canvas(bitmap);
  152. drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
  153. drawable.draw(canvas);
  154. return bitmap;
  155. }
  156. public static ImageRequest getImageRequestForUrl(String url, @Nullable UserEntity userEntity) {
  157. Map<String, String> headers = new HashMap<>();
  158. if (userEntity != null && url.startsWith(userEntity.getBaseUrl()) && (url.contains("index.php/core/preview?fileId=") || url.contains("/avatar/"))) {
  159. headers.put("Authorization", ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()));
  160. }
  161. return ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
  162. .setProgressiveRenderingEnabled(true)
  163. .setRotationOptions(RotationOptions.autoRotate())
  164. .disableDiskCache()
  165. .setHeaders(headers)
  166. .build();
  167. }
  168. public static ControllerListener getImageControllerListener(SimpleDraweeView draweeView) {
  169. return new ControllerListener() {
  170. @Override
  171. public void onSubmit(String id, Object callerContext) {
  172. }
  173. @Override
  174. public void onFinalImageSet(String id, @androidx.annotation.Nullable Object imageInfo, @androidx.annotation.Nullable Animatable animatable) {
  175. updateViewSize((ImageInfo) imageInfo, draweeView);
  176. }
  177. @Override
  178. public void onIntermediateImageSet(String id, @androidx.annotation.Nullable Object imageInfo) {
  179. updateViewSize((ImageInfo) imageInfo, draweeView);
  180. }
  181. @Override
  182. public void onIntermediateImageFailed(String id, Throwable throwable) {
  183. }
  184. @Override
  185. public void onFailure(String id, Throwable throwable) {
  186. }
  187. @Override
  188. public void onRelease(String id) {
  189. }
  190. };
  191. }
  192. public static float convertDpToPixel(float dp, Context context) {
  193. return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
  194. context.getResources().getDisplayMetrics()) + 0.5f);
  195. }
  196. // Solution inspired by https://stackoverflow.com/questions/34936590/why-isnt-my-vector-drawable-scaling-as-expected
  197. public static void useCompatVectorIfNeeded() {
  198. if (Build.VERSION.SDK_INT < 23) {
  199. try {
  200. @SuppressLint("RestrictedApi") AppCompatDrawableManager drawableManager = AppCompatDrawableManager.get();
  201. Class<?> inflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$InflateDelegate");
  202. Class<?> vdcInflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate");
  203. Constructor<?> constructor = vdcInflateDelegateClass.getDeclaredConstructor();
  204. constructor.setAccessible(true);
  205. Object vdcInflateDelegate = constructor.newInstance();
  206. Class<?> args[] = {String.class, inflateDelegateClass};
  207. Method addDelegate = AppCompatDrawableManager.class.getDeclaredMethod("addDelegate", args);
  208. addDelegate.setAccessible(true);
  209. addDelegate.invoke(drawableManager, "vector", vdcInflateDelegate);
  210. } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
  211. InvocationTargetException | IllegalAccessException e) {
  212. Log.e(TAG, "Failed to use reflection to enable proper vector scaling");
  213. }
  214. }
  215. }
  216. public static Drawable getTintedDrawable(Resources res, @DrawableRes int drawableResId, @ColorRes int colorResId) {
  217. Drawable drawable = res.getDrawable(drawableResId);
  218. int color = res.getColor(colorResId);
  219. drawable.setTint(color);
  220. return drawable;
  221. }
  222. public static Drawable getDrawableForMentionChipSpan(Context context, String id, CharSequence label,
  223. UserEntity conversationUser, String type,
  224. @XmlRes int chipResource,
  225. @Nullable EditText emojiEditText) {
  226. ChipDrawable chip = ChipDrawable.createFromResource(context, chipResource);
  227. chip.setText(EmojiCompat.get().process(label));
  228. chip.setEllipsize(TextUtils.TruncateAt.MIDDLE);
  229. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  230. Configuration config = context.getResources().getConfiguration();
  231. chip.setLayoutDirection(config.getLayoutDirection());
  232. }
  233. int drawable;
  234. boolean isCall = "call".equals(type) || "calls".equals(type);
  235. if (!isCall) {
  236. if (chipResource == R.xml.chip_you) {
  237. drawable = R.drawable.mention_chip;
  238. } else {
  239. drawable = R.drawable.accent_circle;
  240. }
  241. chip.setChipIcon(context.getDrawable(drawable));
  242. } else {
  243. chip.setChipIcon(getRoundedDrawable(context.getDrawable(R.drawable.ic_people_group_white_24px)));
  244. }
  245. chip.setBounds(0, 0, chip.getIntrinsicWidth(), chip.getIntrinsicHeight());
  246. if (!isCall) {
  247. String url = ApiUtils.getUrlForAvatarWithName(conversationUser.getBaseUrl(), id, R.dimen.avatar_size_big);
  248. if ("guests".equals(type) || "guest".equals(type)) {
  249. url = ApiUtils.getUrlForAvatarWithNameForGuests(conversationUser.getBaseUrl(), String.valueOf(label), R.dimen.avatar_size_big);
  250. }
  251. ImageRequest imageRequest = getImageRequestForUrl(url, null);
  252. ImagePipeline imagePipeline = Fresco.getImagePipeline();
  253. DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
  254. dataSource.subscribe(
  255. new BaseBitmapDataSubscriber() {
  256. @Override
  257. protected void onNewResultImpl(Bitmap bitmap) {
  258. if (bitmap != null) {
  259. chip.setChipIcon(getRoundedDrawable(new BitmapDrawable(bitmap)));
  260. // A hack to refresh the chip icon
  261. if (emojiEditText != null) {
  262. emojiEditText.post(() -> emojiEditText.setTextKeepState(emojiEditText.getText(), TextView.BufferType.SPANNABLE));
  263. }
  264. }
  265. }
  266. @Override
  267. protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
  268. }
  269. },
  270. UiThreadImmediateExecutorService.getInstance());
  271. }
  272. return chip;
  273. }
  274. public static Spannable searchAndReplaceWithMentionSpan(Context context, Spannable text,
  275. String id, String label, String type,
  276. UserEntity conversationUser,
  277. @XmlRes int chipXmlRes) {
  278. Spannable spannableString = new SpannableString(text);
  279. String stringText = text.toString();
  280. Matcher m = Pattern.compile("@" + label,
  281. Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.MULTILINE)
  282. .matcher(spannableString);
  283. ClickableSpan clickableSpan = new ClickableSpan() {
  284. @Override
  285. public void onClick(@NonNull View widget) {
  286. EventBus.getDefault().post(new UserMentionClickEvent(id));
  287. }
  288. };
  289. int lastStartIndex = -1;
  290. Spans.MentionChipSpan mentionChipSpan;
  291. while (m.find()) {
  292. int start = stringText.indexOf(m.group(), lastStartIndex);
  293. int end = start + m.group().length();
  294. lastStartIndex = end;
  295. mentionChipSpan = new Spans.MentionChipSpan(DisplayUtils.getDrawableForMentionChipSpan(context,
  296. id, label, conversationUser, type, chipXmlRes, null),
  297. BetterImageSpan.ALIGN_CENTER, id,
  298. label);
  299. spannableString.setSpan(mentionChipSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  300. if ("user".equals(type) && !conversationUser.getUserId().equals(id)) {
  301. spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
  302. }
  303. }
  304. return spannableString;
  305. }
  306. public static Spannable searchAndColor(Spannable text, String searchText, @ColorInt int color) {
  307. Spannable spannableString = new SpannableString(text);
  308. String stringText = text.toString();
  309. if (TextUtils.isEmpty(text) || TextUtils.isEmpty(searchText)) {
  310. return spannableString;
  311. }
  312. Matcher m = Pattern.compile(searchText,
  313. Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.MULTILINE)
  314. .matcher(spannableString);
  315. int textSize = NextcloudTalkApplication.Companion.getSharedApplication().getResources().getDimensionPixelSize(R.dimen
  316. .chat_text_size);
  317. int lastStartIndex = -1;
  318. while (m.find()) {
  319. int start = stringText.indexOf(m.group(), lastStartIndex);
  320. int end = start + m.group().length();
  321. lastStartIndex = end;
  322. spannableString.setSpan(new ForegroundColorSpan(color), start, end,
  323. Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  324. spannableString.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  325. spannableString.setSpan(new AbsoluteSizeSpan(textSize), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  326. }
  327. return spannableString;
  328. }
  329. public static Drawable getMessageSelector(@ColorInt int normalColor, @ColorInt int selectedColor,
  330. @ColorInt int pressedColor, @DrawableRes int shape) {
  331. Drawable vectorDrawable = ContextCompat.getDrawable(NextcloudTalkApplication.Companion.getSharedApplication()
  332. .getApplicationContext(),
  333. shape);
  334. Drawable drawable = DrawableCompat.wrap(vectorDrawable).mutate();
  335. DrawableCompat.setTintList(
  336. drawable,
  337. new ColorStateList(
  338. new int[][]{
  339. new int[]{android.R.attr.state_selected},
  340. new int[]{android.R.attr.state_pressed},
  341. new int[]{-android.R.attr.state_pressed, -android.R.attr.state_selected}
  342. },
  343. new int[]{selectedColor, pressedColor, normalColor}
  344. ));
  345. return drawable;
  346. }
  347. /**
  348. * Sets the color of the status bar to {@code color}.
  349. *
  350. * @param activity activity
  351. * @param color the color
  352. */
  353. public static void applyColorToStatusBar(Activity activity, @ColorInt int color) {
  354. Window window = activity.getWindow();
  355. boolean isLightTheme = lightTheme(color);
  356. if (window != null) {
  357. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  358. View decor = window.getDecorView();
  359. if (isLightTheme) {
  360. int systemUiFlagLightStatusBar;
  361. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  362. systemUiFlagLightStatusBar = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
  363. } else {
  364. systemUiFlagLightStatusBar = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
  365. }
  366. decor.setSystemUiVisibility(systemUiFlagLightStatusBar);
  367. } else {
  368. decor.setSystemUiVisibility(0);
  369. }
  370. window.setStatusBarColor(color);
  371. } else if (isLightTheme) {
  372. window.setStatusBarColor(Color.BLACK);
  373. }
  374. }
  375. }
  376. /**
  377. * Tests if light color is set
  378. *
  379. * @param color the color
  380. * @return true if primaryColor is lighter than MAX_LIGHTNESS
  381. */
  382. public static boolean lightTheme(int color) {
  383. float[] hsl = colorToHSL(color);
  384. return hsl[INDEX_LUMINATION] >= MAX_LIGHTNESS;
  385. }
  386. private static float[] colorToHSL(int color) {
  387. float[] hsl = new float[3];
  388. ColorUtils.RGBToHSL(Color.red(color), Color.green(color), Color.blue(color), hsl);
  389. return hsl;
  390. }
  391. public static void applyColorToNavigationBar(Window window, @ColorInt int color) {
  392. window.setNavigationBarColor(color);
  393. }
  394. /**
  395. * Theme search view
  396. *
  397. * @param searchView searchView to be changed
  398. * @param context the app's context
  399. */
  400. public static void themeSearchView(SearchView searchView, Context context) {
  401. // hacky as no default way is provided
  402. int fontColor = context.getResources().getColor(R.color.fontAppbar);
  403. SearchView.SearchAutoComplete editText = searchView.findViewById(R.id.search_src_text);
  404. editText.setTextSize(16);
  405. editText.setHintTextColor(context.getResources().getColor(R.color.fontSecondaryAppbar));
  406. }
  407. public static boolean isDarkModeActive(Context context, AppPreferences prefs) {
  408. if (prefs.getTheme().equals("night_yes")) {
  409. return true;
  410. }
  411. int currentNightMode =
  412. context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
  413. switch (currentNightMode) {
  414. case Configuration.UI_MODE_NIGHT_NO:
  415. return false;
  416. case Configuration.UI_MODE_NIGHT_YES:
  417. return true;
  418. default:
  419. return false;
  420. }
  421. }
  422. }