DisplayUtils.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author David A. Velasco
  6. * Copyright (C) 2011 Bartek Przybylski
  7. * Copyright (C) 2015 ownCloud Inc.
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. package com.owncloud.android.utils;
  23. import android.annotation.TargetApi;
  24. import android.app.Activity;
  25. import android.content.Context;
  26. import android.graphics.Point;
  27. import android.graphics.PorterDuff;
  28. import android.os.Build;
  29. import android.support.design.widget.Snackbar;
  30. import android.support.v4.content.ContextCompat;
  31. import android.text.format.DateUtils;
  32. import android.view.Display;
  33. import android.view.View;
  34. import android.widget.ProgressBar;
  35. import android.widget.SeekBar;
  36. import android.widget.TextView;
  37. import com.owncloud.android.MainApp;
  38. import com.owncloud.android.R;
  39. import com.owncloud.android.datamodel.OCFile;
  40. import java.math.BigDecimal;
  41. import java.net.IDN;
  42. import java.text.DateFormat;
  43. import java.util.Calendar;
  44. import java.util.Date;
  45. import java.util.HashMap;
  46. import java.util.Map;
  47. /**
  48. * A helper class for some string operations.
  49. */
  50. public class DisplayUtils {
  51. private static final String OWNCLOUD_APP_NAME = "ownCloud";
  52. private static final String[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
  53. private static final int[] sizeScales = { 0, 0, 1, 1, 1, 2, 2, 2, 2 };
  54. private static Map<String, String> mimeType2HumanReadable;
  55. static {
  56. mimeType2HumanReadable = new HashMap<String, String>();
  57. // images
  58. mimeType2HumanReadable.put("image/jpeg", "JPEG image");
  59. mimeType2HumanReadable.put("image/jpg", "JPEG image");
  60. mimeType2HumanReadable.put("image/png", "PNG image");
  61. mimeType2HumanReadable.put("image/bmp", "Bitmap image");
  62. mimeType2HumanReadable.put("image/gif", "GIF image");
  63. mimeType2HumanReadable.put("image/svg+xml", "JPEG image");
  64. mimeType2HumanReadable.put("image/tiff", "TIFF image");
  65. // music
  66. mimeType2HumanReadable.put("audio/mpeg", "MP3 music file");
  67. mimeType2HumanReadable.put("application/ogg", "OGG music file");
  68. }
  69. /**
  70. * Converts the file size in bytes to human readable output.
  71. * <ul>
  72. * <li>appends a size suffix, e.g. B, KB, MB etc.</li>
  73. * <li>rounds the size based on the suffix to 0,1 or 2 decimals</li>
  74. * </ul>
  75. *
  76. * @param bytes Input file size
  77. * @return Like something readable like "12 MB"
  78. */
  79. public static String bytesToHumanReadable(long bytes) {
  80. double result = bytes;
  81. int attachedSuff = 0;
  82. while (result > 1024 && attachedSuff < sizeSuffixes.length) {
  83. result /= 1024.;
  84. attachedSuff++;
  85. }
  86. return new BigDecimal(result).setScale(
  87. sizeScales[attachedSuff], BigDecimal.ROUND_HALF_UP) + " " + sizeSuffixes[attachedSuff];
  88. }
  89. /**
  90. * Converts MIME types like "image/jpg" to more end user friendly output
  91. * like "JPG image".
  92. *
  93. * @param mimetype MIME type to convert
  94. * @return A human friendly version of the MIME type
  95. */
  96. public static String convertMIMEtoPrettyPrint(String mimetype) {
  97. if (mimeType2HumanReadable.containsKey(mimetype)) {
  98. return mimeType2HumanReadable.get(mimetype);
  99. }
  100. if (mimetype.split("/").length >= 2)
  101. return mimetype.split("/")[1].toUpperCase() + " file";
  102. return "Unknown type";
  103. }
  104. /**
  105. * Converts Unix time to human readable format
  106. * @param milliseconds that have passed since 01/01/1970
  107. * @return The human readable time for the users locale
  108. */
  109. public static String unixTimeToHumanReadable(long milliseconds) {
  110. Date date = new Date(milliseconds);
  111. DateFormat df = DateFormat.getDateTimeInstance();
  112. return df.format(date);
  113. }
  114. public static int getSeasonalIconId() {
  115. if (Calendar.getInstance().get(Calendar.DAY_OF_YEAR) >= 354 &&
  116. MainApp.getAppContext().getString(R.string.app_name).equals(OWNCLOUD_APP_NAME)) {
  117. return R.drawable.winter_holidays_icon;
  118. } else {
  119. return R.drawable.icon;
  120. }
  121. }
  122. /**
  123. * Converts an internationalized domain name (IDN) in an URL to and from ASCII/Unicode.
  124. * @param url the URL where the domain name should be converted
  125. * @param toASCII if true converts from Unicode to ASCII, if false converts from ASCII to Unicode
  126. * @return the URL containing the converted domain name
  127. */
  128. @TargetApi(Build.VERSION_CODES.GINGERBREAD)
  129. public static String convertIdn(String url, boolean toASCII) {
  130. String urlNoDots = url;
  131. String dots="";
  132. while (urlNoDots.startsWith(".")) {
  133. urlNoDots = url.substring(1);
  134. dots = dots + ".";
  135. }
  136. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
  137. // Find host name after '//' or '@'
  138. int hostStart = 0;
  139. if (urlNoDots.indexOf("//") != -1) {
  140. hostStart = url.indexOf("//") + "//".length();
  141. } else if (url.indexOf("@") != -1) {
  142. hostStart = url.indexOf("@") + "@".length();
  143. }
  144. int hostEnd = url.substring(hostStart).indexOf("/");
  145. // Handle URL which doesn't have a path (path is implicitly '/')
  146. hostEnd = (hostEnd == -1 ? urlNoDots.length() : hostStart + hostEnd);
  147. String host = urlNoDots.substring(hostStart, hostEnd);
  148. host = (toASCII ? IDN.toASCII(host) : IDN.toUnicode(host));
  149. return dots + urlNoDots.substring(0, hostStart) + host + urlNoDots.substring(hostEnd);
  150. } else {
  151. return dots + url;
  152. }
  153. }
  154. /**
  155. * Get the file extension if it is on path as type "content://.../DocInfo.doc"
  156. * @param filepath: Content Uri converted to string format
  157. * @return String: fileExtension (type '.pdf'). Empty if no extension
  158. */
  159. public static String getFileExtension(String filepath) {
  160. String fileExtension = "";
  161. String fileNameInContentUri = filepath.substring(filepath.lastIndexOf("/"));
  162. // Check if extension is included in uri
  163. int pos = fileNameInContentUri.lastIndexOf('.');
  164. if (pos >= 0) {
  165. fileExtension = fileNameInContentUri.substring(pos);
  166. }
  167. return fileExtension;
  168. }
  169. @SuppressWarnings("deprecation")
  170. public static CharSequence getRelativeDateTimeString (
  171. Context c, long time, long minResolution, long transitionResolution, int flags
  172. ){
  173. CharSequence dateString = "";
  174. // in Future
  175. if (time > System.currentTimeMillis()){
  176. return DisplayUtils.unixTimeToHumanReadable(time);
  177. }
  178. // < 60 seconds -> seconds ago
  179. else if ((System.currentTimeMillis() - time) < 60 * 1000) {
  180. return c.getString(R.string.file_list_seconds_ago);
  181. } else {
  182. dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags);
  183. }
  184. String[] parts = dateString.toString().split(",");
  185. if (parts.length == 2) {
  186. if (parts[1].contains(":") && !parts[0].contains(":")) {
  187. return parts[0];
  188. } else if (parts[0].contains(":") && !parts[1].contains(":")) {
  189. return parts[1];
  190. }
  191. }
  192. //dateString contains unexpected format. fallback: use relative date time string from android api as is.
  193. return dateString.toString();
  194. }
  195. /**
  196. * Update the passed path removing the last "/" if it is not the root folder
  197. * @param path
  198. */
  199. public static String getPathWithoutLastSlash(String path) {
  200. // Remove last slash from path
  201. if (path.length() > 1 && path.charAt(path.length()-1) == OCFile.PATH_SEPARATOR.charAt(0)) {
  202. path = path.substring(0, path.length()-1);
  203. }
  204. return path;
  205. }
  206. /**
  207. * Gets the screen size in pixels in a backwards compatible way
  208. *
  209. * @param caller Activity calling; needed to get access to the {@link android.view.WindowManager}
  210. * @return Size in pixels of the screen, or default {@link Point} if caller is null
  211. */
  212. public static Point getScreenSize(Activity caller) {
  213. Point size = new Point();
  214. if (caller != null) {
  215. Display display = caller.getWindowManager().getDefaultDisplay();
  216. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
  217. display.getSize(size);
  218. } else {
  219. size.set(display.getWidth(), display.getHeight());
  220. }
  221. }
  222. return size;
  223. }
  224. /**
  225. * sets the coloring of the given progress bar to color_accent.
  226. *
  227. * @param progressBar the progress bar to be colored
  228. */
  229. public static void colorPreLollipopHorizontalProgressBar(ProgressBar progressBar) {
  230. if (progressBar != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  231. int color = progressBar.getResources().getColor(R.color.color_accent);
  232. progressBar.getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
  233. progressBar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
  234. }
  235. }
  236. /**
  237. * sets the coloring of the given seek bar to color_accent.
  238. *
  239. * @param seekBar the seek bar to be colored
  240. */
  241. public static void colorPreLollipopHorizontalSeekBar(SeekBar seekBar) {
  242. if (seekBar != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  243. colorPreLollipopHorizontalProgressBar(seekBar);
  244. if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
  245. int color = seekBar.getResources().getColor(R.color.color_accent);
  246. seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
  247. seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
  248. }
  249. }
  250. }
  251. /**
  252. * set the owncloud standard colors for the snackbar.
  253. *
  254. * @param context the context relevant for setting the color according to the context's theme
  255. * @param snackbar the snackbar to be colored
  256. */
  257. public static void colorSnackbar(Context context, Snackbar snackbar) {
  258. // Changing action button text color
  259. snackbar.setActionTextColor(ContextCompat.getColor(context, R.color.white));
  260. }
  261. }