Merge branch 'material_toolbar' of https://github.com/owncloud/android into material_...
[pub/Android/ownCloud.git] / src / com / owncloud / android / utils / DisplayUtils.java
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
23 package com.owncloud.android.utils;
24
25 import java.math.BigDecimal;
26 import java.net.IDN;
27 import java.text.DateFormat;
28 import java.util.Arrays;
29 import java.util.Calendar;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Set;
34 import java.util.Vector;
35
36 import android.annotation.TargetApi;
37 import android.app.Activity;
38 import android.content.Context;
39 import android.graphics.Point;
40 import android.os.Build;
41 import android.text.format.DateUtils;
42 import android.view.Display;
43 import android.webkit.MimeTypeMap;
44
45 import com.owncloud.android.MainApp;
46 import com.owncloud.android.R;
47 import com.owncloud.android.datamodel.OCFile;
48
49 /**
50 * A helper class for some string operations.
51 */
52 public class DisplayUtils {
53
54 private static final String OWNCLOUD_APP_NAME = "ownCloud";
55
56 //private static String TAG = DisplayUtils.class.getSimpleName();
57
58 private static final String[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
59 private static final int[] sizeScales = { 0, 0, 0, 1, 1, 2, 2, 2, 2 };
60
61 private static HashMap<String, String> mimeType2HUmanReadable;
62 static {
63 mimeType2HUmanReadable = new HashMap<String, String>();
64 // images
65 mimeType2HUmanReadable.put("image/jpeg", "JPEG image");
66 mimeType2HUmanReadable.put("image/jpg", "JPEG image");
67 mimeType2HUmanReadable.put("image/png", "PNG image");
68 mimeType2HUmanReadable.put("image/bmp", "Bitmap image");
69 mimeType2HUmanReadable.put("image/gif", "GIF image");
70 mimeType2HUmanReadable.put("image/svg+xml", "JPEG image");
71 mimeType2HUmanReadable.put("image/tiff", "TIFF image");
72 // music
73 mimeType2HUmanReadable.put("audio/mpeg", "MP3 music file");
74 mimeType2HUmanReadable.put("application/ogg", "OGG music file");
75
76 }
77
78 private static final String TYPE_APPLICATION = "application";
79 private static final String TYPE_AUDIO = "audio";
80 private static final String TYPE_IMAGE = "image";
81 private static final String TYPE_TXT = "text";
82 private static final String TYPE_VIDEO = "video";
83
84 private static final String SUBTYPE_PDF = "pdf";
85 private static final String SUBTYPE_XML = "xml";
86 private static final String[] SUBTYPES_DOCUMENT = {
87 "msword",
88 "vnd.openxmlformats-officedocument.wordprocessingml.document",
89 "vnd.oasis.opendocument.text",
90 "rtf",
91 "javascript"
92 };
93 private static Set<String> SUBTYPES_DOCUMENT_SET = new HashSet<String>(Arrays.asList(SUBTYPES_DOCUMENT));
94 private static final String[] SUBTYPES_SPREADSHEET = {
95 "msexcel",
96 "vnd.ms-excel",
97 "vnd.openxmlformats-officedocument.spreadsheetml.sheet",
98 "vnd.oasis.opendocument.spreadsheet"
99 };
100 private static Set<String> SUBTYPES_SPREADSHEET_SET = new HashSet<String>(Arrays.asList(SUBTYPES_SPREADSHEET));
101 private static final String[] SUBTYPES_PRESENTATION = {
102 "mspowerpoint",
103 "vnd.ms-powerpoint",
104 "vnd.openxmlformats-officedocument.presentationml.presentation",
105 "vnd.oasis.opendocument.presentation"
106 };
107 private static Set<String> SUBTYPES_PRESENTATION_SET = new HashSet<String>(Arrays.asList(SUBTYPES_PRESENTATION));
108 private static final String[] SUBTYPES_COMPRESSED = {"x-tar", "x-gzip", "zip"};
109 private static final Set<String> SUBTYPES_COMPRESSED_SET = new HashSet<String>(Arrays.asList(SUBTYPES_COMPRESSED));
110 private static final String SUBTYPE_OCTET_STREAM = "octet-stream";
111 private static final String EXTENSION_RAR = "rar";
112 private static final String EXTENSION_RTF = "rtf";
113 private static final String EXTENSION_3GP = "3gp";
114 private static final String EXTENSION_PY = "py";
115 private static final String EXTENSION_JS = "js";
116
117 /**
118 * Converts the file size in bytes to human readable output.
119 * <ul>
120 * <li>appends a size suffix, e.g. B, KB, MB etc.</li>
121 * <li>rounds the size based on the suffix to 0,1 or 2 decimals</li>
122 * </ul>
123 *
124 * @param bytes Input file size
125 * @return Like something readable like "12 MB"
126 */
127 public static String bytesToHumanReadable(long bytes) {
128 double result = bytes;
129 int attachedsuff = 0;
130 while (result > 1024 && attachedsuff < sizeSuffixes.length) {
131 result /= 1024.;
132 attachedsuff++;
133 }
134
135 return new BigDecimal(result).setScale(
136 sizeScales[attachedsuff], BigDecimal.ROUND_HALF_UP) + " " + sizeSuffixes[attachedsuff];
137 }
138
139 /**
140 * Converts MIME types like "image/jpg" to more end user friendly output
141 * like "JPG image".
142 *
143 * @param mimetype MIME type to convert
144 * @return A human friendly version of the MIME type
145 */
146 public static String convertMIMEtoPrettyPrint(String mimetype) {
147 if (mimeType2HUmanReadable.containsKey(mimetype)) {
148 return mimeType2HUmanReadable.get(mimetype);
149 }
150 if (mimetype.split("/").length >= 2)
151 return mimetype.split("/")[1].toUpperCase() + " file";
152 return "Unknown type";
153 }
154
155
156 /**
157 * Returns the resource identifier of an image to use as icon associated to a known MIME type.
158 *
159 * @param mimetype MIME type string; if NULL, the method tries to guess it from the extension in filename
160 * @param filename Name, with extension.
161 * @return Identifier of an image resource.
162 */
163 public static int getFileTypeIconId(String mimetype, String filename) {
164
165 if (mimetype == null) {
166 String fileExtension = getExtension(filename);
167 mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
168 if (mimetype == null) {
169 mimetype = TYPE_APPLICATION + "/" + SUBTYPE_OCTET_STREAM;
170 }
171 }
172
173 if ("DIR".equals(mimetype)) {
174 return R.drawable.ic_menu_archive;
175
176 } else {
177 String [] parts = mimetype.split("/");
178 String type = parts[0];
179 String subtype = (parts.length > 1) ? parts[1] : "";
180
181 if(TYPE_TXT.equals(type)) {
182 return R.drawable.file_doc;
183
184 } else if(TYPE_IMAGE.equals(type)) {
185 return R.drawable.file_image;
186
187 } else if(TYPE_VIDEO.equals(type)) {
188 return R.drawable.file_movie;
189
190 } else if(TYPE_AUDIO.equals(type)) {
191 return R.drawable.file_sound;
192
193 } else if(TYPE_APPLICATION.equals(type)) {
194
195 if (SUBTYPE_PDF.equals(subtype)) {
196 return R.drawable.file_pdf;
197
198 } else if (SUBTYPE_XML.equals(subtype)) {
199 return R.drawable.file_doc;
200
201 } else if (SUBTYPES_DOCUMENT_SET.contains(subtype)) {
202 return R.drawable.file_doc;
203
204 } else if (SUBTYPES_SPREADSHEET_SET.contains(subtype)) {
205 return R.drawable.file_xls;
206
207 } else if (SUBTYPES_PRESENTATION_SET.contains(subtype)) {
208 return R.drawable.file_ppt;
209
210 } else if (SUBTYPES_COMPRESSED_SET.contains(subtype)) {
211 return R.drawable.file_zip;
212
213 } else if (SUBTYPE_OCTET_STREAM.equals(subtype) ) {
214 if (getExtension(filename).equalsIgnoreCase(EXTENSION_RAR)) {
215 return R.drawable.file_zip;
216
217 } else if (getExtension(filename).equalsIgnoreCase(EXTENSION_RTF)) {
218 return R.drawable.file_doc;
219
220 } else if (getExtension(filename).equalsIgnoreCase(EXTENSION_3GP)) {
221 return R.drawable.file_movie;
222
223 } else if ( getExtension(filename).equalsIgnoreCase(EXTENSION_PY) ||
224 getExtension(filename).equalsIgnoreCase(EXTENSION_JS)) {
225 return R.drawable.file_doc;
226 }
227 }
228 }
229 }
230
231 // default icon
232 return R.drawable.file;
233 }
234
235
236 private static String getExtension(String filename) {
237 String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
238 return extension;
239 }
240
241 /**
242 * Converts Unix time to human readable format
243 * @param milliseconds that have passed since 01/01/1970
244 * @return The human readable time for the users locale
245 */
246 public static String unixTimeToHumanReadable(long milliseconds) {
247 Date date = new Date(milliseconds);
248 DateFormat df = DateFormat.getDateTimeInstance();
249 return df.format(date);
250 }
251
252
253 public static int getSeasonalIconId() {
254 if (Calendar.getInstance().get(Calendar.DAY_OF_YEAR) >= 354 &&
255 MainApp.getAppContext().getString(R.string.app_name).equals(OWNCLOUD_APP_NAME)) {
256 return R.drawable.winter_holidays_icon;
257 } else {
258 return R.drawable.icon;
259 }
260 }
261
262 /**
263 * Converts an internationalized domain name (IDN) in an URL to and from ASCII/Unicode.
264 * @param url the URL where the domain name should be converted
265 * @param toASCII if true converts from Unicode to ASCII, if false converts from ASCII to Unicode
266 * @return the URL containing the converted domain name
267 */
268 @TargetApi(Build.VERSION_CODES.GINGERBREAD)
269 public static String convertIdn(String url, boolean toASCII) {
270
271 String urlNoDots = url;
272 String dots="";
273 while (urlNoDots.startsWith(".")) {
274 urlNoDots = url.substring(1);
275 dots = dots + ".";
276 }
277
278 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
279 // Find host name after '//' or '@'
280 int hostStart = 0;
281 if (urlNoDots.indexOf("//") != -1) {
282 hostStart = url.indexOf("//") + "//".length();
283 } else if (url.indexOf("@") != -1) {
284 hostStart = url.indexOf("@") + "@".length();
285 }
286
287 int hostEnd = url.substring(hostStart).indexOf("/");
288 // Handle URL which doesn't have a path (path is implicitly '/')
289 hostEnd = (hostEnd == -1 ? urlNoDots.length() : hostStart + hostEnd);
290
291 String host = urlNoDots.substring(hostStart, hostEnd);
292 host = (toASCII ? IDN.toASCII(host) : IDN.toUnicode(host));
293
294 return dots + urlNoDots.substring(0, hostStart) + host + urlNoDots.substring(hostEnd);
295 } else {
296 return dots + url;
297 }
298 }
299
300 /**
301 * Get the file extension if it is on path as type "content://.../DocInfo.doc"
302 * @param filepath: Content Uri converted to string format
303 * @return String: fileExtension (type '.pdf'). Empty if no extension
304 */
305 public static String getComposedFileExtension(String filepath) {
306 String fileExtension = "";
307 String fileNameInContentUri = filepath.substring(filepath.lastIndexOf("/"));
308
309 // Check if extension is included in uri
310 int pos = fileNameInContentUri.lastIndexOf('.');
311 if (pos >= 0) {
312 fileExtension = fileNameInContentUri.substring(pos);
313 }
314 return fileExtension;
315 }
316
317 @SuppressWarnings("deprecation")
318 public static CharSequence getRelativeDateTimeString (
319 Context c, long time, long minResolution, long transitionResolution, int flags
320 ){
321
322 CharSequence dateString = "";
323
324 // in Future
325 if (time > System.currentTimeMillis()){
326 return DisplayUtils.unixTimeToHumanReadable(time);
327 }
328 // < 60 seconds -> seconds ago
329 else if ((System.currentTimeMillis() - time) < 60 * 1000) {
330 return c.getString(R.string.file_list_seconds_ago);
331 } else {
332 // Workaround 2.x bug (see https://github.com/owncloud/android/issues/716)
333 if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB &&
334 (System.currentTimeMillis() - time) > 24 * 60 * 60 * 1000 ) {
335 Date date = new Date(time);
336 date.setHours(0);
337 date.setMinutes(0);
338 date.setSeconds(0);
339 dateString = DateUtils.getRelativeDateTimeString(
340 c, date.getTime(), minResolution, transitionResolution, flags
341 );
342 } else {
343 dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags);
344 }
345 }
346
347 return dateString.toString().split(",")[0];
348 }
349
350 /**
351 * Update the passed path removing the last "/" if it is not the root folder
352 * @param path
353 */
354 public static String getPathWithoutLastSlash(String path) {
355
356 // Remove last slash from path
357 if (path.length() > 1 && path.charAt(path.length()-1) == OCFile.PATH_SEPARATOR.charAt(0)) {
358 path = path.substring(0, path.length()-1);
359 }
360 return path;
361 }
362
363
364 /**
365 * Gets the screen size in pixels in a backwards compatible way
366 *
367 * @param caller Activity calling; needed to get access to the {@link android.view.WindowManager}
368 * @return Size in pixels of the screen, or default {@link Point} if caller is null
369 */
370 public static Point getScreenSize(Activity caller) {
371 Point size = new Point();
372 if (caller != null) {
373 Display display = caller.getWindowManager().getDefaultDisplay();
374 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
375 display.getSize(size);
376 } else {
377 size.set(display.getWidth(), display.getHeight());
378 }
379 }
380 return size;
381 }
382
383 }