DisplayUtils.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /**
  2. * Nextcloud Android client application
  3. *
  4. * @author Andy Scherzinger
  5. * @author Bartek Przybylski
  6. * @author David A. Velasco
  7. * Copyright (C) 2011 Bartek Przybylski
  8. * Copyright (C) 2015 ownCloud Inc.
  9. * Copyright (C) 2016 Andy Scherzinger
  10. *
  11. * This program is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  13. * License as published by the Free Software Foundation; either
  14. * version 3 of the License, or any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public
  22. * License along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. package com.owncloud.android.utils;
  25. import android.accounts.Account;
  26. import android.annotation.TargetApi;
  27. import android.app.Activity;
  28. import android.content.Context;
  29. import android.content.res.Resources;
  30. import android.graphics.Bitmap;
  31. import android.graphics.Point;
  32. import android.graphics.PorterDuff;
  33. import android.graphics.drawable.Drawable;
  34. import android.os.Build;
  35. import android.support.annotation.ColorInt;
  36. import android.support.design.widget.Snackbar;
  37. import android.support.v4.app.FragmentActivity;
  38. import android.support.v4.content.ContextCompat;
  39. import android.text.format.DateUtils;
  40. import android.view.View;
  41. import android.widget.ProgressBar;
  42. import android.widget.SeekBar;
  43. import com.owncloud.android.MainApp;
  44. import com.owncloud.android.R;
  45. import com.owncloud.android.datamodel.FileDataStorageManager;
  46. import com.owncloud.android.datamodel.OCFile;
  47. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  48. import com.owncloud.android.lib.common.OwnCloudAccount;
  49. import com.owncloud.android.lib.common.utils.Log_OC;
  50. import com.owncloud.android.ui.TextDrawable;
  51. import com.owncloud.android.ui.activity.ToolbarActivity;
  52. import java.math.BigDecimal;
  53. import java.net.IDN;
  54. import java.text.DateFormat;
  55. import java.util.Date;
  56. import java.util.HashMap;
  57. import java.util.Map;
  58. /**
  59. * A helper class for UI/display related operations.
  60. */
  61. public class DisplayUtils {
  62. private static final String TAG = DisplayUtils.class.getSimpleName();
  63. private static final String[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
  64. private static final int[] sizeScales = { 0, 0, 1, 1, 1, 2, 2, 2, 2 };
  65. public static final int RELATIVE_THRESHOLD_WARNING = 90;
  66. public static final int RELATIVE_THRESHOLD_CRITICAL = 95;
  67. public static final String MIME_TYPE_UNKNOWN = "Unknown type";
  68. private static Map<String, String> mimeType2HumanReadable;
  69. static {
  70. mimeType2HumanReadable = new HashMap<>();
  71. // images
  72. mimeType2HumanReadable.put("image/jpeg", "JPEG image");
  73. mimeType2HumanReadable.put("image/jpg", "JPEG image");
  74. mimeType2HumanReadable.put("image/png", "PNG image");
  75. mimeType2HumanReadable.put("image/bmp", "Bitmap image");
  76. mimeType2HumanReadable.put("image/gif", "GIF image");
  77. mimeType2HumanReadable.put("image/svg+xml", "JPEG image");
  78. mimeType2HumanReadable.put("image/tiff", "TIFF image");
  79. // music
  80. mimeType2HumanReadable.put("audio/mpeg", "MP3 music file");
  81. mimeType2HumanReadable.put("application/ogg", "OGG music file");
  82. }
  83. /**
  84. * Converts the file size in bytes to human readable output.
  85. * <ul>
  86. * <li>appends a size suffix, e.g. B, KB, MB etc.</li>
  87. * <li>rounds the size based on the suffix to 0,1 or 2 decimals</li>
  88. * </ul>
  89. *
  90. * @param bytes Input file size
  91. * @return something readable like "12 MB", {@link com.owncloud.android.R.string#common_pending} for negative
  92. * byte values
  93. */
  94. public static String bytesToHumanReadable(long bytes) {
  95. if (bytes < 0) {
  96. return MainApp.getAppContext().getString(R.string.common_pending);
  97. } else {
  98. double result = bytes;
  99. int suffixIndex = 0;
  100. while (result > 1024 && suffixIndex < sizeSuffixes.length) {
  101. result /= 1024.;
  102. suffixIndex++;
  103. }
  104. return new BigDecimal(String.valueOf(result)).setScale(
  105. sizeScales[suffixIndex], BigDecimal.ROUND_HALF_UP) + " " + sizeSuffixes[suffixIndex];
  106. }
  107. }
  108. /**
  109. * Converts MIME types like "image/jpg" to more end user friendly output
  110. * like "JPG image".
  111. *
  112. * @param mimetype MIME type to convert
  113. * @return A human friendly version of the MIME type, {@link #MIME_TYPE_UNKNOWN} if it can't be converted
  114. */
  115. public static String convertMIMEtoPrettyPrint(String mimetype) {
  116. if (mimeType2HumanReadable.containsKey(mimetype)) {
  117. return mimeType2HumanReadable.get(mimetype);
  118. }
  119. if (mimetype.split("/").length >= 2) {
  120. return mimetype.split("/")[1].toUpperCase() + " file";
  121. }
  122. return MIME_TYPE_UNKNOWN;
  123. }
  124. /**
  125. * Converts Unix time to human readable format
  126. *
  127. * @param milliseconds that have passed since 01/01/1970
  128. * @return The human readable time for the users locale
  129. */
  130. public static String unixTimeToHumanReadable(long milliseconds) {
  131. Date date = new Date(milliseconds);
  132. DateFormat df = DateFormat.getDateTimeInstance();
  133. return df.format(date);
  134. }
  135. /**
  136. * Converts an internationalized domain name (IDN) in an URL to and from ASCII/Unicode.
  137. *
  138. * @param url the URL where the domain name should be converted
  139. * @param toASCII if true converts from Unicode to ASCII, if false converts from ASCII to Unicode
  140. * @return the URL containing the converted domain name
  141. */
  142. @TargetApi(Build.VERSION_CODES.GINGERBREAD)
  143. public static String convertIdn(String url, boolean toASCII) {
  144. String urlNoDots = url;
  145. String dots="";
  146. while (urlNoDots.startsWith(".")) {
  147. urlNoDots = url.substring(1);
  148. dots = dots + ".";
  149. }
  150. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
  151. // Find host name after '//' or '@'
  152. int hostStart = 0;
  153. if (urlNoDots.contains("//")) {
  154. hostStart = url.indexOf("//") + "//".length();
  155. } else if (url.contains("@")) {
  156. hostStart = url.indexOf('@') + "@".length();
  157. }
  158. int hostEnd = url.substring(hostStart).indexOf("/");
  159. // Handle URL which doesn't have a path (path is implicitly '/')
  160. hostEnd = (hostEnd == -1 ? urlNoDots.length() : hostStart + hostEnd);
  161. String host = urlNoDots.substring(hostStart, hostEnd);
  162. host = (toASCII ? IDN.toASCII(host) : IDN.toUnicode(host));
  163. return dots + urlNoDots.substring(0, hostStart) + host + urlNoDots.substring(hostEnd);
  164. } else {
  165. return dots + url;
  166. }
  167. }
  168. /**
  169. * creates the display string for an account.
  170. *
  171. * @param context the actual activity
  172. * @param savedAccount the actual, saved account
  173. * @param accountName the account name
  174. * @param fallbackString String to be used in case of an error
  175. * @return the display string for the given account data
  176. */
  177. public static String getAccountNameDisplayText(Context context, Account savedAccount, String accountName, String
  178. fallbackString) {
  179. try {
  180. return new OwnCloudAccount(savedAccount, context).getDisplayName()
  181. + " @ "
  182. + convertIdn(accountName.substring(accountName.lastIndexOf('@') + 1), false);
  183. } catch (Exception e) {
  184. Log_OC.w(TAG, "Couldn't get display name for account, using old style");
  185. return fallbackString;
  186. }
  187. }
  188. /**
  189. * calculates the relative time string based on the given modificaion timestamp.
  190. *
  191. * @param context the app's context
  192. * @param modificationTimestamp the UNIX timestamp of the file modification time.
  193. * @return a relative time string
  194. */
  195. public static CharSequence getRelativeTimestamp(Context context, long modificationTimestamp) {
  196. return getRelativeDateTimeString(context, modificationTimestamp, DateUtils.SECOND_IN_MILLIS,
  197. DateUtils.WEEK_IN_MILLIS, 0);
  198. }
  199. /**
  200. * determines the info level color based on certain thresholds
  201. * {@link #RELATIVE_THRESHOLD_WARNING} and {@link #RELATIVE_THRESHOLD_CRITICAL}.
  202. *
  203. * @param context the app's context
  204. * @param relative relative value for which the info level color should be looked up
  205. * @return info level color
  206. */
  207. public static int getRelativeInfoColor(Context context, int relative) {
  208. if (relative < RELATIVE_THRESHOLD_WARNING) {
  209. return context.getResources().getColor(R.color.infolevel_info);
  210. } else if (relative >= RELATIVE_THRESHOLD_WARNING && relative < RELATIVE_THRESHOLD_CRITICAL) {
  211. return context.getResources().getColor(R.color.infolevel_warning);
  212. } else {
  213. return context.getResources().getColor(R.color.infolevel_critical);
  214. }
  215. }
  216. public static CharSequence getRelativeDateTimeString(
  217. Context c, long time, long minResolution, long transitionResolution, int flags) {
  218. CharSequence dateString = "";
  219. // in Future
  220. if (time > System.currentTimeMillis()) {
  221. return DisplayUtils.unixTimeToHumanReadable(time);
  222. }
  223. // < 60 seconds -> seconds ago
  224. else if ((System.currentTimeMillis() - time) < 60 * 1000) {
  225. return c.getString(R.string.file_list_seconds_ago);
  226. } else {
  227. dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags);
  228. }
  229. String[] parts = dateString.toString().split(",");
  230. if (parts.length == 2) {
  231. if (parts[1].contains(":") && !parts[0].contains(":")) {
  232. return parts[0];
  233. } else if (parts[0].contains(":") && !parts[1].contains(":")) {
  234. return parts[1];
  235. }
  236. }
  237. //dateString contains unexpected format. fallback: use relative date time string from android api as is.
  238. return dateString.toString();
  239. }
  240. /**
  241. * Update the passed path removing the last "/" if it is not the root folder.
  242. *
  243. * @param path the path to be trimmed
  244. */
  245. public static String getPathWithoutLastSlash(String path) {
  246. // Remove last slash from path
  247. if (path.length() > 1 && path.charAt(path.length()-1) == OCFile.PATH_SEPARATOR.charAt(0)) {
  248. path = path.substring(0, path.length()-1);
  249. }
  250. return path;
  251. }
  252. /**
  253. * Gets the screen size in pixels.
  254. *
  255. * @param caller Activity calling; needed to get access to the {@link android.view.WindowManager}
  256. * @return Size in pixels of the screen, or default {@link Point} if caller is null
  257. */
  258. public static Point getScreenSize(Activity caller) {
  259. Point size = new Point();
  260. if (caller != null) {
  261. caller.getWindowManager().getDefaultDisplay().getSize(size);
  262. }
  263. return size;
  264. }
  265. /**
  266. * sets the coloring of the given progress bar to color_accent.
  267. *
  268. * @param progressBar the progress bar to be colored
  269. */
  270. public static void colorPreLollipopHorizontalProgressBar(ProgressBar progressBar) {
  271. if (progressBar != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  272. colorHorizontalProgressBar(progressBar, progressBar.getResources().getColor(R.color.color_accent));
  273. }
  274. }
  275. /**
  276. * sets the coloring of the given progress bar to color_accent.
  277. *
  278. * @param progressBar the progress bar to be colored
  279. * @param color the color to be used
  280. */
  281. public static void colorHorizontalProgressBar(ProgressBar progressBar, @ColorInt int color) {
  282. if (progressBar != null) {
  283. progressBar.getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
  284. progressBar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
  285. }
  286. }
  287. /**
  288. * sets the coloring of the given seek bar to color_accent.
  289. *
  290. * @param seekBar the seek bar to be colored
  291. */
  292. public static void colorPreLollipopHorizontalSeekBar(SeekBar seekBar) {
  293. if (seekBar != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  294. colorPreLollipopHorizontalProgressBar(seekBar);
  295. if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
  296. int color = seekBar.getResources().getColor(R.color.color_accent);
  297. seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
  298. seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
  299. }
  300. }
  301. }
  302. /**
  303. * set the Nextcloud standard colors for the snackbar.
  304. *
  305. * @param context the context relevant for setting the color according to the context's theme
  306. * @param snackbar the snackbar to be colored
  307. */
  308. public static void colorSnackbar(Context context, Snackbar snackbar) {
  309. // Changing action button text color
  310. snackbar.setActionTextColor(ContextCompat.getColor(context, R.color.white));
  311. }
  312. /**
  313. * Sets the color of the status bar to {@code color} on devices with OS version lollipop or higher.
  314. *
  315. * @param fragmentActivity fragment activity
  316. * @param color the color
  317. */
  318. public static void colorStatusBar(FragmentActivity fragmentActivity, @ColorInt int color) {
  319. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  320. fragmentActivity.getWindow().setStatusBarColor(color);
  321. }
  322. }
  323. /**
  324. * Sets the color of the progressbar to {@code color} within the given toolbar.
  325. *
  326. * @param activity the toolbar activity instance
  327. * @param progressBarColor the color to be used for the toolbar's progress bar
  328. */
  329. public static void colorToolbarProgressBar(FragmentActivity activity, int progressBarColor) {
  330. if (activity instanceof ToolbarActivity) {
  331. ((ToolbarActivity) activity).setProgressBarBackgroundColor(progressBarColor);
  332. }
  333. }
  334. public interface AvatarGenerationListener {
  335. void avatarGenerated(Drawable avatarDrawable, Object callContext);
  336. boolean shouldCallGeneratedCallback(String tag, Object callContext);
  337. }
  338. /**
  339. * fetches and sets the avatar of the current account in the drawer in case the drawer is available.
  340. *
  341. * @param account the account to be set in the drawer
  342. * @param avatarRadius the avatar radius
  343. * @param resources reference for density information
  344. * @param storageManager reference for caching purposes
  345. */
  346. public static void setAvatar(Account account, AvatarGenerationListener listener, float avatarRadius, Resources resources,
  347. FileDataStorageManager storageManager, Object callContext) {
  348. if (account != null) {
  349. if (callContext instanceof View) {
  350. ((View) callContext).setContentDescription(account.name);
  351. }
  352. // Thumbnail in Cache?
  353. Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache("a_" + account.name);
  354. if (thumbnail != null) {
  355. listener.avatarGenerated(
  356. BitmapUtils.bitmapToCircularBitmapDrawable(MainApp.getAppContext().getResources(), thumbnail),
  357. callContext);
  358. } else {
  359. // generate new avatar
  360. if (ThumbnailsCacheManager.cancelPotentialAvatarWork(account.name, callContext)) {
  361. final ThumbnailsCacheManager.AvatarGenerationTask task =
  362. new ThumbnailsCacheManager.AvatarGenerationTask(listener, callContext, storageManager, account);
  363. if (thumbnail == null) {
  364. try {
  365. listener.avatarGenerated(TextDrawable.createAvatar(account.name, avatarRadius), callContext);
  366. } catch (Exception e) {
  367. Log_OC.e(TAG, "Error calculating RGB value for active account icon.", e);
  368. listener.avatarGenerated(resources.getDrawable(R.drawable.ic_account_circle), callContext);
  369. }
  370. } else {
  371. final ThumbnailsCacheManager.AsyncAvatarDrawable asyncDrawable =
  372. new ThumbnailsCacheManager.AsyncAvatarDrawable(resources, thumbnail, task);
  373. listener.avatarGenerated(BitmapUtils.bitmapToCircularBitmapDrawable(
  374. resources, asyncDrawable.getBitmap()), callContext);
  375. }
  376. task.execute(account.name);
  377. }
  378. }
  379. }
  380. }
  381. }