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