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