Merge remote-tracking branch 'remotes/upstream/master' into switchListVsGridMaster
[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.graphics.PorterDuff;
42 import android.os.Build;
43 import android.text.format.DateUtils;
44 import android.view.Display;
45 import android.widget.ProgressBar;
46 import android.widget.SeekBar;
47
48 import com.owncloud.android.MainApp;
49 import com.owncloud.android.R;
50 import com.owncloud.android.datamodel.FileDataStorageManager;
51 import com.owncloud.android.datamodel.OCFile;
52
53 import java.net.IDN;
54 import java.text.DateFormat;
55 import java.util.Calendar;
56 import java.util.Date;
57 import java.util.HashMap;
58 import java.util.Map;
59
60 /**
61 * A helper class for some string operations.
62 */
63 public class DisplayUtils {
64
65 private static final String OWNCLOUD_APP_NAME = "ownCloud";
66
67 private static final String[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
68
69 private static Map<String, String> mimeType2HumanReadable;
70
71 static {
72 mimeType2HumanReadable = new HashMap<String, String>();
73 // images
74 mimeType2HumanReadable.put("image/jpeg", "JPEG image");
75 mimeType2HumanReadable.put("image/jpg", "JPEG image");
76 mimeType2HumanReadable.put("image/png", "PNG image");
77 mimeType2HumanReadable.put("image/bmp", "Bitmap image");
78 mimeType2HumanReadable.put("image/gif", "GIF image");
79 mimeType2HumanReadable.put("image/svg+xml", "JPEG image");
80 mimeType2HumanReadable.put("image/tiff", "TIFF image");
81 // music
82 mimeType2HumanReadable.put("audio/mpeg", "MP3 music file");
83 mimeType2HumanReadable.put("application/ogg", "OGG music file");
84 }
85
86 /**
87 * Converts the file size in bytes to human readable output.
88 *
89 * @param bytes Input file size
90 * @return Like something readable like "12 MB"
91 */
92 public static String bytesToHumanReadable(long bytes) {
93 double result = bytes;
94 int attachedsuff = 0;
95 while (result > 1024 && attachedsuff < sizeSuffixes.length) {
96 result /= 1024.;
97 attachedsuff++;
98 }
99 result = ((int) (result * 100)) / 100.;
100 return result + " " + sizeSuffixes[attachedsuff];
101 }
102
103 /**
104 * Converts MIME types like "image/jpg" to more end user friendly output
105 * like "JPG image".
106 *
107 * @param mimetype MIME type to convert
108 * @return A human friendly version of the MIME type
109 */
110 public static String convertMIMEtoPrettyPrint(String mimetype) {
111 if (mimeType2HumanReadable.containsKey(mimetype)) {
112 return mimeType2HumanReadable.get(mimetype);
113 }
114 if (mimetype.split("/").length >= 2)
115 return mimetype.split("/")[1].toUpperCase() + " file";
116 return "Unknown type";
117 }
118
119 /**
120 * Converts Unix time to human readable format
121 * @param milliseconds that have passed since 01/01/1970
122 * @return The human readable time for the users locale
123 */
124 public static String unixTimeToHumanReadable(long milliseconds) {
125 Date date = new Date(milliseconds);
126 DateFormat df = DateFormat.getDateTimeInstance();
127 return df.format(date);
128 }
129
130 public static int getSeasonalIconId() {
131 if (Calendar.getInstance().get(Calendar.DAY_OF_YEAR) >= 354 &&
132 MainApp.getAppContext().getString(R.string.app_name).equals(OWNCLOUD_APP_NAME)) {
133 return R.drawable.winter_holidays_icon;
134 } else {
135 return R.drawable.icon;
136 }
137 }
138
139 /**
140 * Converts an internationalized domain name (IDN) in an URL to and from ASCII/Unicode.
141 * @param url the URL where the domain name should be converted
142 * @param toASCII if true converts from Unicode to ASCII, if false converts from ASCII to Unicode
143 * @return the URL containing the converted domain name
144 */
145 @TargetApi(Build.VERSION_CODES.GINGERBREAD)
146 public static String convertIdn(String url, boolean toASCII) {
147
148 String urlNoDots = url;
149 String dots="";
150 while (urlNoDots.startsWith(".")) {
151 urlNoDots = url.substring(1);
152 dots = dots + ".";
153 }
154
155 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
156 // Find host name after '//' or '@'
157 int hostStart = 0;
158 if (urlNoDots.indexOf("//") != -1) {
159 hostStart = url.indexOf("//") + "//".length();
160 } else if (url.indexOf("@") != -1) {
161 hostStart = url.indexOf("@") + "@".length();
162 }
163
164 int hostEnd = url.substring(hostStart).indexOf("/");
165 // Handle URL which doesn't have a path (path is implicitly '/')
166 hostEnd = (hostEnd == -1 ? urlNoDots.length() : hostStart + hostEnd);
167
168 String host = urlNoDots.substring(hostStart, hostEnd);
169 host = (toASCII ? IDN.toASCII(host) : IDN.toUnicode(host));
170
171 return dots + urlNoDots.substring(0, hostStart) + host + urlNoDots.substring(hostEnd);
172 } else {
173 return dots + url;
174 }
175 }
176
177 /**
178 * Get the file extension if it is on path as type "content://.../DocInfo.doc"
179 * @param filepath: Content Uri converted to string format
180 * @return String: fileExtension (type '.pdf'). Empty if no extension
181 */
182 public static String getComposedFileExtension(String filepath) {
183 String fileExtension = "";
184 String fileNameInContentUri = filepath.substring(filepath.lastIndexOf("/"));
185
186 // Check if extension is included in uri
187 int pos = fileNameInContentUri.lastIndexOf('.');
188 if (pos >= 0) {
189 fileExtension = fileNameInContentUri.substring(pos);
190 }
191 return fileExtension;
192 }
193
194 @SuppressWarnings("deprecation")
195 public static CharSequence getRelativeDateTimeString (
196 Context c, long time, long minResolution, long transitionResolution, int flags
197 ){
198
199 CharSequence dateString = "";
200
201 // in Future
202 if (time > System.currentTimeMillis()){
203 return DisplayUtils.unixTimeToHumanReadable(time);
204 }
205 // < 60 seconds -> seconds ago
206 else if ((System.currentTimeMillis() - time) < 60 * 1000) {
207 return c.getString(R.string.file_list_seconds_ago);
208 } else {
209 // Workaround 2.x bug (see https://github.com/owncloud/android/issues/716)
210 if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB &&
211 (System.currentTimeMillis() - time) > 24 * 60 * 60 * 1000 ) {
212 Date date = new Date(time);
213 date.setHours(0);
214 date.setMinutes(0);
215 date.setSeconds(0);
216 dateString = DateUtils.getRelativeDateTimeString(
217 c, date.getTime(), minResolution, transitionResolution, flags
218 );
219 } else {
220 dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags);
221 }
222 }
223
224 return dateString.toString().split(",")[0];
225 }
226
227 /**
228 * Update the passed path removing the last "/" if it is not the root folder
229 * @param path
230 */
231 public static String getPathWithoutLastSlash(String path) {
232
233 // Remove last slash from path
234 if (path.length() > 1 && path.charAt(path.length()-1) == OCFile.PATH_SEPARATOR.charAt(0)) {
235 path = path.substring(0, path.length()-1);
236 }
237 return path;
238 }
239
240
241 /**
242 * Gets the screen size in pixels in a backwards compatible way
243 *
244 * @param caller Activity calling; needed to get access to the {@link android.view.WindowManager}
245 * @return Size in pixels of the screen, or default {@link Point} if caller is null
246 */
247 public static Point getScreenSize(Activity caller) {
248 Point size = new Point();
249 if (caller != null) {
250 Display display = caller.getWindowManager().getDefaultDisplay();
251 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
252 display.getSize(size);
253 } else {
254 size.set(display.getWidth(), display.getHeight());
255 }
256 }
257 return size;
258 }
259
260 /**
261 * Determines if user set folder to grid or list view. If folder is not set itself,
262 * it finds a parent that is set (at least root is set).
263 * @param file
264 * @param storageManager
265 * @return
266 */
267 public static boolean isGridView(OCFile file, FileDataStorageManager storageManager){
268 if (file != null) {
269 OCFile fileToTest = file;
270 OCFile parentDir = null;
271 String parentPath = null;
272
273 SharedPreferences setting = MainApp.getAppContext().getSharedPreferences(
274 "viewMode", Context.MODE_PRIVATE);
275
276 if (setting.contains(fileToTest.getRemoteId())) {
277 return setting.getBoolean(fileToTest.getRemoteId(), false);
278 } else {
279 do {
280 if (fileToTest.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
281 parentPath = new File(fileToTest.getRemotePath()).getParent();
282 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
283 parentPath + OCFile.PATH_SEPARATOR;
284 parentDir = storageManager.getFileByPath(parentPath);
285 } else {
286 parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
287 }
288
289 while (parentDir == null) {
290 parentPath = new File(parentPath).getParent();
291 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
292 parentPath + OCFile.PATH_SEPARATOR;
293 parentDir = storageManager.getFileByPath(parentPath);
294 }
295 fileToTest = parentDir;
296 } while (endWhile(parentDir, setting));
297 return setting.getBoolean(fileToTest.getRemoteId(), false);
298 }
299 } else {
300 return false;
301 }
302 }
303
304 private static boolean endWhile(OCFile parentDir, SharedPreferences setting) {
305 if (parentDir.getRemotePath().compareToIgnoreCase(OCFile.ROOT_PATH) == 0) {
306 return false;
307 } else {
308 return !setting.contains(parentDir.getRemoteId());
309 }
310 }
311
312 public static void setViewMode(OCFile file, boolean setGrid){
313 SharedPreferences setting = MainApp.getAppContext().getSharedPreferences(
314 "viewMode", Context.MODE_PRIVATE);
315
316 SharedPreferences.Editor editor = setting.edit();
317 editor.putBoolean(file.getRemoteId(), setGrid);
318 editor.commit();
319 }
320
321 /**
322 * sets the coloring of the given progress bar to color_accent.
323 *
324 * @param progressBar the progress bar to be colored
325 */
326 public static void colorPreLollipopHorizontalProgressBar(ProgressBar progressBar) {
327 if (progressBar != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
328 int color = progressBar.getResources().getColor(R.color.color_accent);
329 progressBar.getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
330 progressBar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
331 }
332 }
333
334 /**
335 * sets the coloring of the given seek bar to color_accent.
336 *
337 * @param seekBar the seek bar to be colored
338 */
339 public static void colorPreLollipopHorizontalSeekBar(SeekBar seekBar) {
340 if (seekBar != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
341 colorPreLollipopHorizontalProgressBar(seekBar);
342
343 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
344 int color = seekBar.getResources().getColor(R.color.color_accent);
345 seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
346 seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
347 }
348 }
349 }
350 }