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