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