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