• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.DecimalFormat;
25 import android.icu.text.MeasureFormat;
26 import android.icu.text.NumberFormat;
27 import android.icu.text.UnicodeSet;
28 import android.icu.text.UnicodeSetSpanner;
29 import android.icu.util.Measure;
30 import android.icu.util.MeasureUnit;
31 import android.text.BidiFormatter;
32 import android.text.TextUtils;
33 import android.view.View;
34 
35 import com.android.net.module.util.Inet4AddressUtils;
36 
37 import java.math.BigDecimal;
38 import java.util.Locale;
39 
40 /**
41  * Utility class to aid in formatting common values that are not covered
42  * by the {@link java.util.Formatter} class in {@link java.util}
43  */
44 @android.ravenwood.annotation.RavenwoodKeepWholeClass
45 public final class Formatter {
46 
47     /** {@hide} */
48     public static final int FLAG_SHORTER = 1 << 0;
49     /** {@hide} */
50     public static final int FLAG_CALCULATE_ROUNDED = 1 << 1;
51     /** {@hide} */
52     public static final int FLAG_SI_UNITS = 1 << 2;
53     /** {@hide} */
54     public static final int FLAG_IEC_UNITS = 1 << 3;
55 
56     /** {@hide} */
57     public static class BytesResult {
58         public final String value;
59         public final String units;
60         /**
61          * Content description of the {@link #units}.
62          * See {@link View#setContentDescription(CharSequence)}
63          */
64         public final String unitsContentDescription;
65         public final long roundedBytes;
66 
BytesResult(String value, String units, String unitsContentDescription, long roundedBytes)67         public BytesResult(String value, String units, String unitsContentDescription,
68                 long roundedBytes) {
69             this.value = value;
70             this.units = units;
71             this.unitsContentDescription = unitsContentDescription;
72             this.roundedBytes = roundedBytes;
73         }
74     }
75 
localeFromContext(@onNull Context context)76     private static Locale localeFromContext(@NonNull Context context) {
77         return context.getResources().getConfiguration().getLocales().get(0);
78     }
79 
80     /**
81      * Wraps the source string in bidi formatting characters in RTL locales.
82      */
bidiWrap(@onNull Context context, String source)83     private static String bidiWrap(@NonNull Context context, String source) {
84         final Locale locale = localeFromContext(context);
85         if (TextUtils.getLayoutDirectionFromLocale(locale) == View.LAYOUT_DIRECTION_RTL) {
86             return BidiFormatter.getInstance(true /* RTL*/).unicodeWrap(source);
87         } else {
88             return source;
89         }
90     }
91 
92     /**
93      * Formats a content size to be in the form of bytes, kilobytes, megabytes, etc.
94      *
95      * <p>As of O, the prefixes are used in their standard meanings in the SI system, so kB = 1000
96      * bytes, MB = 1,000,000 bytes, etc.</p>
97      *
98      * <p class="note">In {@link android.os.Build.VERSION_CODES#N} and earlier, powers of 1024 are
99      * used instead, with KB = 1024 bytes, MB = 1,048,576 bytes, etc.</p>
100      *
101      * <p>If the context has a right-to-left locale, the returned string is wrapped in bidi
102      * formatting characters to make sure it's displayed correctly if inserted inside a
103      * right-to-left string. (This is useful in cases where the unit strings, like "MB", are
104      * left-to-right, but the locale is right-to-left.)</p>
105      *
106      * @param context Context to use to load the localized units
107      * @param sizeBytes size value to be formatted, in bytes
108      * @return formatted string with the number
109      */
formatFileSize(@ullable Context context, long sizeBytes)110     public static String formatFileSize(@Nullable Context context, long sizeBytes) {
111         return formatFileSize(context, sizeBytes, FLAG_SI_UNITS);
112     }
113 
114     /** @hide */
formatFileSize(@ullable Context context, long sizeBytes, int flags)115     public static String formatFileSize(@Nullable Context context, long sizeBytes, int flags) {
116         if (context == null) {
117             return "";
118         }
119         final RoundedBytesResult res = RoundedBytesResult.roundBytes(sizeBytes, flags);
120         return bidiWrap(context, formatRoundedBytesResult(context, res));
121     }
122 
123     /**
124      * Like {@link #formatFileSize}, but trying to generate shorter numbers
125      * (showing fewer digits of precision).
126      */
formatShortFileSize(@ullable Context context, long sizeBytes)127     public static String formatShortFileSize(@Nullable Context context, long sizeBytes) {
128         return formatFileSize(context, sizeBytes, FLAG_SI_UNITS | FLAG_SHORTER);
129     }
130 
getByteSuffixOverride(@onNull Resources res)131     private static String getByteSuffixOverride(@NonNull Resources res) {
132         return res.getString(com.android.internal.R.string.byteShort);
133     }
134 
getNumberFormatter(Locale locale, int fractionDigits)135     private static NumberFormat getNumberFormatter(Locale locale, int fractionDigits) {
136         final NumberFormat numberFormatter = NumberFormat.getInstance(locale);
137         numberFormatter.setMinimumFractionDigits(fractionDigits);
138         numberFormatter.setMaximumFractionDigits(fractionDigits);
139         numberFormatter.setGroupingUsed(false);
140         if (numberFormatter instanceof DecimalFormat) {
141             // We do this only for DecimalFormat, since in the general NumberFormat case, calling
142             // setRoundingMode may throw an exception.
143             numberFormatter.setRoundingMode(BigDecimal.ROUND_HALF_UP);
144         }
145         return numberFormatter;
146     }
147 
deleteFirstFromString(String source, String toDelete)148     private static String deleteFirstFromString(String source, String toDelete) {
149         final int location = source.indexOf(toDelete);
150         if (location == -1) {
151             return source;
152         } else {
153             return source.substring(0, location)
154                     + source.substring(location + toDelete.length(), source.length());
155         }
156     }
157 
formatMeasureShort(Locale locale, NumberFormat numberFormatter, float value, MeasureUnit units)158     private static String formatMeasureShort(Locale locale, NumberFormat numberFormatter,
159             float value, MeasureUnit units) {
160         final MeasureFormat measureFormatter = MeasureFormat.getInstance(
161                 locale, MeasureFormat.FormatWidth.SHORT, numberFormatter);
162         return measureFormatter.format(new Measure(value, units));
163     }
164 
165     private static final UnicodeSetSpanner SPACES_AND_CONTROLS =
166             new UnicodeSetSpanner(new UnicodeSet("[[:Zs:][:Cf:]]").freeze());
167 
formatRoundedBytesResult( @onNull Context context, @NonNull RoundedBytesResult input)168     private static String formatRoundedBytesResult(
169             @NonNull Context context, @NonNull RoundedBytesResult input) {
170         final Locale locale = localeFromContext(context);
171         final NumberFormat numberFormatter = getNumberFormatter(locale, input.fractionDigits);
172         if (input.units == MeasureUnit.BYTE) {
173             // ICU spells out "byte" instead of "B".
174             final String formattedNumber = numberFormatter.format(input.value);
175             return context.getString(com.android.internal.R.string.fileSizeSuffix,
176                     formattedNumber, getByteSuffixOverride(context.getResources()));
177         } else {
178             return formatMeasureShort(locale, numberFormatter, input.value, input.units);
179         }
180     }
181 
182     /** {@hide} */
183     public static class RoundedBytesResult {
184         public final float value;
185         public final MeasureUnit units;
186         public final int fractionDigits;
187         public final long roundedBytes;
188 
RoundedBytesResult( float value, MeasureUnit units, int fractionDigits, long roundedBytes)189         private RoundedBytesResult(
190                 float value, MeasureUnit units, int fractionDigits, long roundedBytes) {
191             this.value = value;
192             this.units = units;
193             this.fractionDigits = fractionDigits;
194             this.roundedBytes = roundedBytes;
195         }
196 
197         /**
198          * Returns a RoundedBytesResult object based on the input size in bytes and the rounding
199          * flags. The result can be used for formatting.
200          */
roundBytes(long sizeBytes, int flags)201         public static RoundedBytesResult roundBytes(long sizeBytes, int flags) {
202             final int unit = ((flags & FLAG_IEC_UNITS) != 0) ? 1024 : 1000;
203             final boolean isNegative = (sizeBytes < 0);
204             float result = isNegative ? -sizeBytes : sizeBytes;
205             MeasureUnit units = MeasureUnit.BYTE;
206             long mult = 1;
207             if (result > 900) {
208                 units = MeasureUnit.KILOBYTE;
209                 mult = unit;
210                 result = result / unit;
211             }
212             if (result > 900) {
213                 units = MeasureUnit.MEGABYTE;
214                 mult *= unit;
215                 result = result / unit;
216             }
217             if (result > 900) {
218                 units = MeasureUnit.GIGABYTE;
219                 mult *= unit;
220                 result = result / unit;
221             }
222             if (result > 900) {
223                 units = MeasureUnit.TERABYTE;
224                 mult *= unit;
225                 result = result / unit;
226             }
227             if (result > 900) {
228                 units = MeasureUnit.PETABYTE;
229                 mult *= unit;
230                 result = result / unit;
231             }
232             // Note we calculate the rounded long by ourselves, but still let NumberFormat compute
233             // the rounded value. NumberFormat.format(0.1) might not return "0.1" due to floating
234             // point errors.
235             final int roundFactor;
236             final int roundDigits;
237             if (mult == 1 || result >= 100) {
238                 roundFactor = 1;
239                 roundDigits = 0;
240             } else if (result < 1) {
241                 roundFactor = 100;
242                 roundDigits = 2;
243             } else if (result < 10) {
244                 if ((flags & FLAG_SHORTER) != 0) {
245                     roundFactor = 10;
246                     roundDigits = 1;
247                 } else {
248                     roundFactor = 100;
249                     roundDigits = 2;
250                 }
251             } else { // 10 <= result < 100
252                 if ((flags & FLAG_SHORTER) != 0) {
253                     roundFactor = 1;
254                     roundDigits = 0;
255                 } else {
256                     roundFactor = 100;
257                     roundDigits = 2;
258                 }
259             }
260 
261             if (isNegative) {
262                 result = -result;
263             }
264 
265             // Note this might overflow if abs(result) >= Long.MAX_VALUE / 100, but that's like
266             // 80PB so it's okay (for now)...
267             final long roundedBytes =
268                     (flags & FLAG_CALCULATE_ROUNDED) == 0 ? 0
269                             : (((long) Math.round(result * roundFactor)) * mult / roundFactor);
270 
271             return new RoundedBytesResult(result, units, roundDigits, roundedBytes);
272         }
273     }
274 
275     /** {@hide} */
276     @UnsupportedAppUsage
formatBytes(Resources res, long sizeBytes, int flags)277     public static BytesResult formatBytes(Resources res, long sizeBytes, int flags) {
278         final RoundedBytesResult rounded = RoundedBytesResult.roundBytes(sizeBytes, flags);
279         final Locale locale = res.getConfiguration().getLocales().get(0);
280         final NumberFormat numberFormatter = getNumberFormatter(locale, rounded.fractionDigits);
281         final String formattedNumber = numberFormatter.format(rounded.value);
282         // Since ICU does not give us access to the pattern, we need to extract the unit string
283         // from ICU, which we do by taking out the formatted number out of the formatted string
284         // and trimming the result of spaces and controls.
285         final String formattedMeasure = formatMeasureShort(
286                 locale, numberFormatter, rounded.value, rounded.units);
287         final String numberRemoved = deleteFirstFromString(formattedMeasure, formattedNumber);
288         String units = SPACES_AND_CONTROLS.trim(numberRemoved).toString();
289         String unitsContentDescription = units;
290         if (rounded.units == MeasureUnit.BYTE) {
291             // ICU spells out "byte" instead of "B".
292             units = getByteSuffixOverride(res);
293         }
294         return new BytesResult(formattedNumber, units, unitsContentDescription,
295                 rounded.roundedBytes);
296     }
297 
298     /**
299      * Returns a string in the canonical IPv4 format ###.###.###.### from a packed integer
300      * containing the IP address. The IPv4 address is expected to be in little-endian
301      * format (LSB first). That is, 0x01020304 will return "4.3.2.1".
302      *
303      * @deprecated Use {@link java.net.InetAddress#getHostAddress()}, which supports both IPv4 and
304      *     IPv6 addresses. This method does not support IPv6 addresses.
305      */
306     @Deprecated
formatIpAddress(int ipv4Address)307     public static String formatIpAddress(int ipv4Address) {
308         return Inet4AddressUtils.intToInet4AddressHTL(ipv4Address).getHostAddress();
309     }
310 
311     private static final int SECONDS_PER_MINUTE = 60;
312     private static final int SECONDS_PER_HOUR = 60 * 60;
313     private static final int SECONDS_PER_DAY = 24 * 60 * 60;
314     private static final int MILLIS_PER_MINUTE = 1000 * 60;
315 
316     /**
317      * Returns elapsed time for the given millis, in the following format:
318      * 1 day, 5 hr; will include at most two units, can go down to seconds precision.
319      * @param context the application context
320      * @param millis the elapsed time in milli seconds
321      * @return the formatted elapsed time
322      * @hide
323      */
324     @UnsupportedAppUsage
formatShortElapsedTime(Context context, long millis)325     public static String formatShortElapsedTime(Context context, long millis) {
326         long secondsLong = millis / 1000;
327 
328         int days = 0, hours = 0, minutes = 0;
329         if (secondsLong >= SECONDS_PER_DAY) {
330             days = (int)(secondsLong / SECONDS_PER_DAY);
331             secondsLong -= days * SECONDS_PER_DAY;
332         }
333         if (secondsLong >= SECONDS_PER_HOUR) {
334             hours = (int)(secondsLong / SECONDS_PER_HOUR);
335             secondsLong -= hours * SECONDS_PER_HOUR;
336         }
337         if (secondsLong >= SECONDS_PER_MINUTE) {
338             minutes = (int)(secondsLong / SECONDS_PER_MINUTE);
339             secondsLong -= minutes * SECONDS_PER_MINUTE;
340         }
341         int seconds = (int)secondsLong;
342 
343         final Locale locale = localeFromContext(context);
344         final MeasureFormat measureFormat = MeasureFormat.getInstance(
345                 locale, MeasureFormat.FormatWidth.SHORT);
346         if (days >= 2 || (days > 0 && hours == 0)) {
347             days += (hours+12)/24;
348             return measureFormat.format(new Measure(days, MeasureUnit.DAY));
349         } else if (days > 0) {
350             return measureFormat.formatMeasures(
351                     new Measure(days, MeasureUnit.DAY),
352                     new Measure(hours, MeasureUnit.HOUR));
353         } else if (hours >= 2 || (hours > 0 && minutes == 0)) {
354             hours += (minutes+30)/60;
355             return measureFormat.format(new Measure(hours, MeasureUnit.HOUR));
356         } else if (hours > 0) {
357             return measureFormat.formatMeasures(
358                     new Measure(hours, MeasureUnit.HOUR),
359                     new Measure(minutes, MeasureUnit.MINUTE));
360         } else if (minutes >= 2 || (minutes > 0 && seconds == 0)) {
361             minutes += (seconds+30)/60;
362             return measureFormat.format(new Measure(minutes, MeasureUnit.MINUTE));
363         } else if (minutes > 0) {
364             return measureFormat.formatMeasures(
365                     new Measure(minutes, MeasureUnit.MINUTE),
366                     new Measure(seconds, MeasureUnit.SECOND));
367         } else {
368             return measureFormat.format(new Measure(seconds, MeasureUnit.SECOND));
369         }
370     }
371 
372     /**
373      * Returns elapsed time for the given millis, in the following format:
374      * 1 day, 5 hr; will include at most two units, can go down to minutes precision.
375      * @param context the application context
376      * @param millis the elapsed time in milli seconds
377      * @return the formatted elapsed time
378      * @hide
379      */
380     @UnsupportedAppUsage
formatShortElapsedTimeRoundingUpToMinutes(Context context, long millis)381     public static String formatShortElapsedTimeRoundingUpToMinutes(Context context, long millis) {
382         long minutesRoundedUp = (millis + MILLIS_PER_MINUTE - 1) / MILLIS_PER_MINUTE;
383 
384         if (minutesRoundedUp == 0 || minutesRoundedUp == 1) {
385             final Locale locale = localeFromContext(context);
386             final MeasureFormat measureFormat = MeasureFormat.getInstance(
387                     locale, MeasureFormat.FormatWidth.SHORT);
388             return measureFormat.format(new Measure(minutesRoundedUp, MeasureUnit.MINUTE));
389         }
390 
391         return formatShortElapsedTime(context, minutesRoundedUp * MILLIS_PER_MINUTE);
392     }
393 }
394