1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.text.format;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.compat.annotation.UnsupportedAppUsage;
22 import android.content.Context;
23 import android.content.res.Resources;
24 import android.icu.text.MeasureFormat;
25 import android.icu.util.Measure;
26 import android.icu.util.MeasureUnit;
27 import android.net.NetworkUtils;
28 import android.text.BidiFormatter;
29 import android.text.TextUtils;
30 import android.view.View;
31 
32 import java.util.Locale;
33 
34 /**
35  * Utility class to aid in formatting common values that are not covered
36  * by the {@link java.util.Formatter} class in {@link java.util}
37  */
38 public final class Formatter {
39 
40     /** {@hide} */
41     public static final int FLAG_SHORTER = 1 << 0;
42     /** {@hide} */
43     public static final int FLAG_CALCULATE_ROUNDED = 1 << 1;
44     /** {@hide} */
45     public static final int FLAG_SI_UNITS = 1 << 2;
46     /** {@hide} */
47     public static final int FLAG_IEC_UNITS = 1 << 3;
48 
49     /** {@hide} */
50     public static class BytesResult {
51         public final String value;
52         public final String units;
53         public final long roundedBytes;
54 
BytesResult(String value, String units, long roundedBytes)55         public BytesResult(String value, String units, long roundedBytes) {
56             this.value = value;
57             this.units = units;
58             this.roundedBytes = roundedBytes;
59         }
60     }
61 
localeFromContext(@onNull Context context)62     private static Locale localeFromContext(@NonNull Context context) {
63         return context.getResources().getConfiguration().getLocales().get(0);
64     }
65 
66     /* Wraps the source string in bidi formatting characters in RTL locales */
bidiWrap(@onNull Context context, String source)67     private static String bidiWrap(@NonNull Context context, String source) {
68         final Locale locale = localeFromContext(context);
69         if (TextUtils.getLayoutDirectionFromLocale(locale) == View.LAYOUT_DIRECTION_RTL) {
70             return BidiFormatter.getInstance(true /* RTL*/).unicodeWrap(source);
71         } else {
72             return source;
73         }
74     }
75 
76     /**
77      * Formats a content size to be in the form of bytes, kilobytes, megabytes, etc.
78      *
79      * <p>As of O, the prefixes are used in their standard meanings in the SI system, so kB = 1000
80      * bytes, MB = 1,000,000 bytes, etc.</p>
81      *
82      * <p class="note">In {@link android.os.Build.VERSION_CODES#N} and earlier, powers of 1024 are
83      * used instead, with KB = 1024 bytes, MB = 1,048,576 bytes, etc.</p>
84      *
85      * <p>If the context has a right-to-left locale, the returned string is wrapped in bidi
86      * formatting characters to make sure it's displayed correctly if inserted inside a
87      * right-to-left string. (This is useful in cases where the unit strings, like "MB", are
88      * left-to-right, but the locale is right-to-left.)</p>
89      *
90      * @param context Context to use to load the localized units
91      * @param sizeBytes size value to be formatted, in bytes
92      * @return formatted string with the number
93      */
formatFileSize(@ullable Context context, long sizeBytes)94     public static String formatFileSize(@Nullable Context context, long sizeBytes) {
95         return formatFileSize(context, sizeBytes, FLAG_SI_UNITS);
96     }
97 
98     /** @hide */
formatFileSize(@ullable Context context, long sizeBytes, int flags)99     public static String formatFileSize(@Nullable Context context, long sizeBytes, int flags) {
100         if (context == null) {
101             return "";
102         }
103         final BytesResult res = formatBytes(context.getResources(), sizeBytes, flags);
104         return bidiWrap(context, context.getString(com.android.internal.R.string.fileSizeSuffix,
105                 res.value, res.units));
106     }
107 
108     /**
109      * Like {@link #formatFileSize}, but trying to generate shorter numbers
110      * (showing fewer digits of precision).
111      */
formatShortFileSize(@ullable Context context, long sizeBytes)112     public static String formatShortFileSize(@Nullable Context context, long sizeBytes) {
113         if (context == null) {
114             return "";
115         }
116         final BytesResult res = formatBytes(context.getResources(), sizeBytes,
117                 FLAG_SI_UNITS | FLAG_SHORTER);
118         return bidiWrap(context, context.getString(com.android.internal.R.string.fileSizeSuffix,
119                 res.value, res.units));
120     }
121 
122     /** {@hide} */
123     @UnsupportedAppUsage
formatBytes(Resources res, long sizeBytes, int flags)124     public static BytesResult formatBytes(Resources res, long sizeBytes, int flags) {
125         final int unit = ((flags & FLAG_IEC_UNITS) != 0) ? 1024 : 1000;
126         final boolean isNegative = (sizeBytes < 0);
127         float result = isNegative ? -sizeBytes : sizeBytes;
128         int suffix = com.android.internal.R.string.byteShort;
129         long mult = 1;
130         if (result > 900) {
131             suffix = com.android.internal.R.string.kilobyteShort;
132             mult = unit;
133             result = result / unit;
134         }
135         if (result > 900) {
136             suffix = com.android.internal.R.string.megabyteShort;
137             mult *= unit;
138             result = result / unit;
139         }
140         if (result > 900) {
141             suffix = com.android.internal.R.string.gigabyteShort;
142             mult *= unit;
143             result = result / unit;
144         }
145         if (result > 900) {
146             suffix = com.android.internal.R.string.terabyteShort;
147             mult *= unit;
148             result = result / unit;
149         }
150         if (result > 900) {
151             suffix = com.android.internal.R.string.petabyteShort;
152             mult *= unit;
153             result = result / unit;
154         }
155         // Note we calculate the rounded long by ourselves, but still let String.format()
156         // compute the rounded value. String.format("%f", 0.1) might not return "0.1" due to
157         // floating point errors.
158         final int roundFactor;
159         final String roundFormat;
160         if (mult == 1 || result >= 100) {
161             roundFactor = 1;
162             roundFormat = "%.0f";
163         } else if (result < 1) {
164             roundFactor = 100;
165             roundFormat = "%.2f";
166         } else if (result < 10) {
167             if ((flags & FLAG_SHORTER) != 0) {
168                 roundFactor = 10;
169                 roundFormat = "%.1f";
170             } else {
171                 roundFactor = 100;
172                 roundFormat = "%.2f";
173             }
174         } else { // 10 <= result < 100
175             if ((flags & FLAG_SHORTER) != 0) {
176                 roundFactor = 1;
177                 roundFormat = "%.0f";
178             } else {
179                 roundFactor = 100;
180                 roundFormat = "%.2f";
181             }
182         }
183 
184         if (isNegative) {
185             result = -result;
186         }
187         final String roundedString = String.format(roundFormat, result);
188 
189         // Note this might overflow if abs(result) >= Long.MAX_VALUE / 100, but that's like 80PB so
190         // it's okay (for now)...
191         final long roundedBytes =
192                 (flags & FLAG_CALCULATE_ROUNDED) == 0 ? 0
193                 : (((long) Math.round(result * roundFactor)) * mult / roundFactor);
194 
195         final String units = res.getString(suffix);
196 
197         return new BytesResult(roundedString, units, roundedBytes);
198     }
199 
200     /**
201      * Returns a string in the canonical IPv4 format ###.###.###.### from a packed integer
202      * containing the IP address. The IPv4 address is expected to be in little-endian
203      * format (LSB first). That is, 0x01020304 will return "4.3.2.1".
204      *
205      * @deprecated Use {@link java.net.InetAddress#getHostAddress()}, which supports both IPv4 and
206      *     IPv6 addresses. This method does not support IPv6 addresses.
207      */
208     @Deprecated
formatIpAddress(int ipv4Address)209     public static String formatIpAddress(int ipv4Address) {
210         return NetworkUtils.intToInetAddress(ipv4Address).getHostAddress();
211     }
212 
213     private static final int SECONDS_PER_MINUTE = 60;
214     private static final int SECONDS_PER_HOUR = 60 * 60;
215     private static final int SECONDS_PER_DAY = 24 * 60 * 60;
216     private static final int MILLIS_PER_MINUTE = 1000 * 60;
217 
218     /**
219      * Returns elapsed time for the given millis, in the following format:
220      * 1 day, 5 hr; will include at most two units, can go down to seconds precision.
221      * @param context the application context
222      * @param millis the elapsed time in milli seconds
223      * @return the formatted elapsed time
224      * @hide
225      */
226     @UnsupportedAppUsage
formatShortElapsedTime(Context context, long millis)227     public static String formatShortElapsedTime(Context context, long millis) {
228         long secondsLong = millis / 1000;
229 
230         int days = 0, hours = 0, minutes = 0;
231         if (secondsLong >= SECONDS_PER_DAY) {
232             days = (int)(secondsLong / SECONDS_PER_DAY);
233             secondsLong -= days * SECONDS_PER_DAY;
234         }
235         if (secondsLong >= SECONDS_PER_HOUR) {
236             hours = (int)(secondsLong / SECONDS_PER_HOUR);
237             secondsLong -= hours * SECONDS_PER_HOUR;
238         }
239         if (secondsLong >= SECONDS_PER_MINUTE) {
240             minutes = (int)(secondsLong / SECONDS_PER_MINUTE);
241             secondsLong -= minutes * SECONDS_PER_MINUTE;
242         }
243         int seconds = (int)secondsLong;
244 
245         final Locale locale = localeFromContext(context);
246         final MeasureFormat measureFormat = MeasureFormat.getInstance(
247                 locale, MeasureFormat.FormatWidth.SHORT);
248         if (days >= 2 || (days > 0 && hours == 0)) {
249             days += (hours+12)/24;
250             return measureFormat.format(new Measure(days, MeasureUnit.DAY));
251         } else if (days > 0) {
252             return measureFormat.formatMeasures(
253                     new Measure(days, MeasureUnit.DAY),
254                     new Measure(hours, MeasureUnit.HOUR));
255         } else if (hours >= 2 || (hours > 0 && minutes == 0)) {
256             hours += (minutes+30)/60;
257             return measureFormat.format(new Measure(hours, MeasureUnit.HOUR));
258         } else if (hours > 0) {
259             return measureFormat.formatMeasures(
260                     new Measure(hours, MeasureUnit.HOUR),
261                     new Measure(minutes, MeasureUnit.MINUTE));
262         } else if (minutes >= 2 || (minutes > 0 && seconds == 0)) {
263             minutes += (seconds+30)/60;
264             return measureFormat.format(new Measure(minutes, MeasureUnit.MINUTE));
265         } else if (minutes > 0) {
266             return measureFormat.formatMeasures(
267                     new Measure(minutes, MeasureUnit.MINUTE),
268                     new Measure(seconds, MeasureUnit.SECOND));
269         } else {
270             return measureFormat.format(new Measure(seconds, MeasureUnit.SECOND));
271         }
272     }
273 
274     /**
275      * Returns elapsed time for the given millis, in the following format:
276      * 1 day, 5 hr; will include at most two units, can go down to minutes precision.
277      * @param context the application context
278      * @param millis the elapsed time in milli seconds
279      * @return the formatted elapsed time
280      * @hide
281      */
282     @UnsupportedAppUsage
formatShortElapsedTimeRoundingUpToMinutes(Context context, long millis)283     public static String formatShortElapsedTimeRoundingUpToMinutes(Context context, long millis) {
284         long minutesRoundedUp = (millis + MILLIS_PER_MINUTE - 1) / MILLIS_PER_MINUTE;
285 
286         if (minutesRoundedUp == 0 || minutesRoundedUp == 1) {
287             final Locale locale = localeFromContext(context);
288             final MeasureFormat measureFormat = MeasureFormat.getInstance(
289                     locale, MeasureFormat.FormatWidth.SHORT);
290             return measureFormat.format(new Measure(minutesRoundedUp, MeasureUnit.MINUTE));
291         }
292 
293         return formatShortElapsedTime(context, minutesRoundedUp * MILLIS_PER_MINUTE);
294     }
295 }
296