blob: 1cb255bf89731919668d230791ba004887645aed [file] [log] [blame]
Tony Mantlerb3543e02015-05-28 14:48:00 -07001/*
2 * Copyright (C) 2015 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
17package com.android.settingslib.datetime;
18
19import android.content.Context;
20import android.content.res.XmlResourceParser;
Roozbeh Pournader5b810312017-07-17 15:07:41 -070021import android.icu.text.TimeZoneFormat;
Neil Fuller4a180122015-12-16 18:50:07 +000022import android.icu.text.TimeZoneNames;
Maurice Lamebc050f2016-10-31 16:17:53 -070023import android.support.v4.text.BidiFormatter;
24import android.support.v4.text.TextDirectionHeuristicsCompat;
25import android.text.SpannableString;
26import android.text.SpannableStringBuilder;
Tony Mantlerb3543e02015-05-28 14:48:00 -070027import android.text.TextUtils;
Maurice Lamebc050f2016-10-31 16:17:53 -070028import android.text.format.DateUtils;
29import android.text.style.TtsSpan;
Tony Mantlerb3543e02015-05-28 14:48:00 -070030import android.util.Log;
31import android.view.View;
32
33import com.android.settingslib.R;
34
Tony Mantlerb3543e02015-05-28 14:48:00 -070035import org.xmlpull.v1.XmlPullParserException;
36
Tony Mantlerb3543e02015-05-28 14:48:00 -070037import java.util.ArrayList;
Tony Mantlerb3543e02015-05-28 14:48:00 -070038import java.util.Date;
39import java.util.HashMap;
Neil Fuller4a180122015-12-16 18:50:07 +000040import java.util.HashSet;
Tony Mantlerb3543e02015-05-28 14:48:00 -070041import java.util.List;
42import java.util.Locale;
Neil Fuller6394a392015-06-09 10:04:43 +010043import java.util.Map;
44import java.util.Set;
Tony Mantlerb3543e02015-05-28 14:48:00 -070045import java.util.TimeZone;
Neil Fuller1cc722b2017-10-25 20:26:02 +010046import libcore.util.TimeZoneFinder;
Tony Mantlerb3543e02015-05-28 14:48:00 -070047
jackqdyuleic6a32742016-09-27 15:58:51 -070048/**
49 * ZoneGetter is the utility class to get time zone and zone list, and both of them have display
50 * name in time zone. In this class, we will keep consistency about display names for all
51 * the methods.
52 *
53 * The display name chosen for each zone entry depends on whether the zone is one associated
54 * with the country of the user's chosen locale. For "local" zones we prefer the "long name"
55 * (e.g. "Europe/London" -> "British Summer Time" for people in the UK). For "non-local"
56 * zones we prefer the exemplar location (e.g. "Europe/London" -> "London" for English
57 * speakers from outside the UK). This heuristic is based on the fact that people are
58 * typically familiar with their local timezones and exemplar locations don't always match
59 * modern-day expectations for people living in the country covered. Large countries like
60 * China that mostly use a single timezone (olson id: "Asia/Shanghai") may not live near
61 * "Shanghai" and prefer the long name over the exemplar location. The only time we don't
62 * follow this policy for local zones is when Android supplies multiple olson IDs to choose
63 * from and the use of a zone's long name leads to ambiguity. For example, at the time of
64 * writing Android lists 5 olson ids for Australia which collapse to 2 different zone names
65 * in winter but 4 different zone names in summer. The ambiguity leads to the users
66 * selecting the wrong olson ids.
67 *
68 */
Tony Mantlerb3543e02015-05-28 14:48:00 -070069public class ZoneGetter {
70 private static final String TAG = "ZoneGetter";
71
Tony Mantlerb3543e02015-05-28 14:48:00 -070072 public static final String KEY_ID = "id"; // value: String
Maurice Lamebc050f2016-10-31 16:17:53 -070073
74 /**
75 * @deprecated Use {@link #KEY_DISPLAY_LABEL} instead.
76 */
77 @Deprecated
Tony Mantlerb3543e02015-05-28 14:48:00 -070078 public static final String KEY_DISPLAYNAME = "name"; // value: String
Maurice Lamebc050f2016-10-31 16:17:53 -070079
80 public static final String KEY_DISPLAY_LABEL = "display_label"; // value: CharSequence
81
82 /**
83 * @deprecated Use {@link #KEY_OFFSET_LABEL} instead.
84 */
85 @Deprecated
Tony Mantlerb3543e02015-05-28 14:48:00 -070086 public static final String KEY_GMT = "gmt"; // value: String
87 public static final String KEY_OFFSET = "offset"; // value: int (Integer)
Maurice Lamebc050f2016-10-31 16:17:53 -070088 public static final String KEY_OFFSET_LABEL = "offset_label"; // value: CharSequence
Tony Mantlerb3543e02015-05-28 14:48:00 -070089
jackqdyuleic6a32742016-09-27 15:58:51 -070090 private static final String XMLTAG_TIMEZONE = "timezone";
Tony Mantlerb3543e02015-05-28 14:48:00 -070091
Maurice Lamebc050f2016-10-31 16:17:53 -070092 public static CharSequence getTimeZoneOffsetAndName(Context context, TimeZone tz, Date now) {
Roozbeh Pournader5b810312017-07-17 15:07:41 -070093 Locale locale = context.getResources().getConfiguration().locale;
94 TimeZoneFormat tzFormatter = TimeZoneFormat.getInstance(locale);
95 CharSequence gmtText = getGmtOffsetText(tzFormatter, locale, tz, now);
jackqdyulei476a9ad2017-06-12 13:58:26 -070096 TimeZoneNames timeZoneNames = TimeZoneNames.getInstance(locale);
97 String zoneNameString = getZoneLongName(timeZoneNames, tz, now);
98 if (zoneNameString == null) {
Maurice Lamebc050f2016-10-31 16:17:53 -070099 return gmtText;
Tony Mantlerb3543e02015-05-28 14:48:00 -0700100 }
Neil Fuller6394a392015-06-09 10:04:43 +0100101
102 // We don't use punctuation here to avoid having to worry about localizing that too!
jackqdyulei476a9ad2017-06-12 13:58:26 -0700103 return TextUtils.concat(gmtText, " ", zoneNameString);
Neil Fuller6394a392015-06-09 10:04:43 +0100104 }
105
106 public static List<Map<String, Object>> getZonesList(Context context) {
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700107 final Locale locale = context.getResources().getConfiguration().locale;
Neil Fuller6394a392015-06-09 10:04:43 +0100108 final Date now = new Date();
Neil Fuller4a180122015-12-16 18:50:07 +0000109 final TimeZoneNames timeZoneNames = TimeZoneNames.getInstance(locale);
jackqdyuleic6a32742016-09-27 15:58:51 -0700110 final ZoneGetterData data = new ZoneGetterData(context);
Neil Fuller6394a392015-06-09 10:04:43 +0100111
Neil Fuller4a180122015-12-16 18:50:07 +0000112 // Work out whether the display names we would show by default would be ambiguous.
jackqdyuleic6a32742016-09-27 15:58:51 -0700113 final boolean useExemplarLocationForLocalNames =
114 shouldUseExemplarLocationForLocalNames(data, timeZoneNames);
Neil Fuller6394a392015-06-09 10:04:43 +0100115
116 // Generate the list of zone entries to return.
117 List<Map<String, Object>> zones = new ArrayList<Map<String, Object>>();
jackqdyuleic6a32742016-09-27 15:58:51 -0700118 for (int i = 0; i < data.zoneCount; i++) {
119 TimeZone tz = data.timeZones[i];
Maurice Lamebc050f2016-10-31 16:17:53 -0700120 CharSequence gmtOffsetText = data.gmtOffsetTexts[i];
Neil Fuller6394a392015-06-09 10:04:43 +0100121
Maurice Lamebc050f2016-10-31 16:17:53 -0700122 CharSequence displayName = getTimeZoneDisplayName(data, timeZoneNames,
jackqdyuleic6a32742016-09-27 15:58:51 -0700123 useExemplarLocationForLocalNames, tz, data.olsonIdsToDisplay[i]);
Maurice Lamebc050f2016-10-31 16:17:53 -0700124 if (TextUtils.isEmpty(displayName)) {
125 displayName = gmtOffsetText;
Neil Fuller4a180122015-12-16 18:50:07 +0000126 }
127
Neil Fuller6394a392015-06-09 10:04:43 +0100128 int offsetMillis = tz.getOffset(now.getTime());
129 Map<String, Object> displayEntry =
Maurice Lamebc050f2016-10-31 16:17:53 -0700130 createDisplayEntry(tz, gmtOffsetText, displayName, offsetMillis);
Neil Fuller6394a392015-06-09 10:04:43 +0100131 zones.add(displayEntry);
132 }
133 return zones;
134 }
135
136 private static Map<String, Object> createDisplayEntry(
Maurice Lamebc050f2016-10-31 16:17:53 -0700137 TimeZone tz, CharSequence gmtOffsetText, CharSequence displayName, int offsetMillis) {
138 Map<String, Object> map = new HashMap<>();
Neil Fuller6394a392015-06-09 10:04:43 +0100139 map.put(KEY_ID, tz.getID());
Maurice Lamebc050f2016-10-31 16:17:53 -0700140 map.put(KEY_DISPLAYNAME, displayName.toString());
141 map.put(KEY_DISPLAY_LABEL, displayName);
142 map.put(KEY_GMT, gmtOffsetText.toString());
143 map.put(KEY_OFFSET_LABEL, gmtOffsetText);
Neil Fuller6394a392015-06-09 10:04:43 +0100144 map.put(KEY_OFFSET, offsetMillis);
145 return map;
146 }
147
Neil Fuller6394a392015-06-09 10:04:43 +0100148 private static List<String> readTimezonesToDisplay(Context context) {
149 List<String> olsonIds = new ArrayList<String>();
150 try (XmlResourceParser xrp = context.getResources().getXml(R.xml.timezones)) {
Tony Mantlerb3543e02015-05-28 14:48:00 -0700151 while (xrp.next() != XmlResourceParser.START_TAG) {
152 continue;
153 }
154 xrp.next();
155 while (xrp.getEventType() != XmlResourceParser.END_TAG) {
156 while (xrp.getEventType() != XmlResourceParser.START_TAG) {
157 if (xrp.getEventType() == XmlResourceParser.END_DOCUMENT) {
Neil Fuller6394a392015-06-09 10:04:43 +0100158 return olsonIds;
Tony Mantlerb3543e02015-05-28 14:48:00 -0700159 }
160 xrp.next();
161 }
162 if (xrp.getName().equals(XMLTAG_TIMEZONE)) {
163 String olsonId = xrp.getAttributeValue(0);
Neil Fuller6394a392015-06-09 10:04:43 +0100164 olsonIds.add(olsonId);
Tony Mantlerb3543e02015-05-28 14:48:00 -0700165 }
166 while (xrp.getEventType() != XmlResourceParser.END_TAG) {
167 xrp.next();
168 }
169 xrp.next();
170 }
Tony Mantlerb3543e02015-05-28 14:48:00 -0700171 } catch (XmlPullParserException xppe) {
172 Log.e(TAG, "Ill-formatted timezones.xml file");
173 } catch (java.io.IOException ioe) {
174 Log.e(TAG, "Unable to read timezones.xml file");
175 }
Neil Fuller6394a392015-06-09 10:04:43 +0100176 return olsonIds;
Tony Mantlerb3543e02015-05-28 14:48:00 -0700177 }
178
jackqdyuleic6a32742016-09-27 15:58:51 -0700179 private static boolean shouldUseExemplarLocationForLocalNames(ZoneGetterData data,
180 TimeZoneNames timeZoneNames) {
Maurice Lamebc050f2016-10-31 16:17:53 -0700181 final Set<CharSequence> localZoneNames = new HashSet<>();
jackqdyuleic6a32742016-09-27 15:58:51 -0700182 final Date now = new Date();
183 for (int i = 0; i < data.zoneCount; i++) {
184 final String olsonId = data.olsonIdsToDisplay[i];
185 if (data.localZoneIds.contains(olsonId)) {
186 final TimeZone tz = data.timeZones[i];
Maurice Lamebc050f2016-10-31 16:17:53 -0700187 CharSequence displayName = getZoneLongName(timeZoneNames, tz, now);
jackqdyuleic6a32742016-09-27 15:58:51 -0700188 if (displayName == null) {
Maurice Lamebc050f2016-10-31 16:17:53 -0700189 displayName = data.gmtOffsetTexts[i];
jackqdyuleic6a32742016-09-27 15:58:51 -0700190 }
191 final boolean nameIsUnique = localZoneNames.add(displayName);
192 if (!nameIsUnique) {
193 return true;
194 }
195 }
196 }
197
198 return false;
199 }
200
Maurice Lamebc050f2016-10-31 16:17:53 -0700201 private static CharSequence getTimeZoneDisplayName(ZoneGetterData data,
202 TimeZoneNames timeZoneNames, boolean useExemplarLocationForLocalNames, TimeZone tz,
203 String olsonId) {
jackqdyuleic6a32742016-09-27 15:58:51 -0700204 final Date now = new Date();
205 final boolean isLocalZoneId = data.localZoneIds.contains(olsonId);
206 final boolean preferLongName = isLocalZoneId && !useExemplarLocationForLocalNames;
207 String displayName;
208
209 if (preferLongName) {
210 displayName = getZoneLongName(timeZoneNames, tz, now);
211 } else {
Neil Fuller2242ff72017-04-05 13:58:26 +0100212 // Canonicalize the zone ID for ICU. It will only return valid strings for zone IDs
213 // that match ICUs zone IDs (which are similar but not guaranteed the same as those
214 // in timezones.xml). timezones.xml and related files uses the IANA IDs. ICU IDs are
215 // stable and IANA IDs have changed over time so they have drifted.
216 // See http://bugs.icu-project.org/trac/ticket/13070 / http://b/36469833.
217 String canonicalZoneId = android.icu.util.TimeZone.getCanonicalID(tz.getID());
218 if (canonicalZoneId == null) {
219 canonicalZoneId = tz.getID();
220 }
221 displayName = timeZoneNames.getExemplarLocationName(canonicalZoneId);
jackqdyuleic6a32742016-09-27 15:58:51 -0700222 if (displayName == null || displayName.isEmpty()) {
223 // getZoneExemplarLocation can return null. Fall back to the long name.
224 displayName = getZoneLongName(timeZoneNames, tz, now);
225 }
226 }
227
228 return displayName;
229 }
230
Neil Fuller4a180122015-12-16 18:50:07 +0000231 /**
232 * Returns the long name for the timezone for the given locale at the time specified.
233 * Can return {@code null}.
234 */
235 private static String getZoneLongName(TimeZoneNames names, TimeZone tz, Date now) {
jackqdyuleic6a32742016-09-27 15:58:51 -0700236 final TimeZoneNames.NameType nameType =
Neil Fuller4a180122015-12-16 18:50:07 +0000237 tz.inDaylightTime(now) ? TimeZoneNames.NameType.LONG_DAYLIGHT
jackqdyuleic6a32742016-09-27 15:58:51 -0700238 : TimeZoneNames.NameType.LONG_STANDARD;
Neil Fuller4a180122015-12-16 18:50:07 +0000239 return names.getDisplayName(tz.getID(), nameType, now.getTime());
Tony Mantlerb3543e02015-05-28 14:48:00 -0700240 }
241
Maurice Lamebc050f2016-10-31 16:17:53 -0700242 private static void appendWithTtsSpan(SpannableStringBuilder builder, CharSequence content,
243 TtsSpan span) {
244 int start = builder.length();
245 builder.append(content);
246 builder.setSpan(span, start, builder.length(), 0);
247 }
248
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700249 // Input must be positive. minDigits must be 1 or 2.
250 private static String formatDigits(int input, int minDigits, String localizedDigits) {
251 final int tens = input / 10;
252 final int units = input % 10;
253 StringBuilder builder = new StringBuilder(minDigits);
254 if (input >= 10 || minDigits == 2) {
255 builder.append(localizedDigits.charAt(tens));
256 }
257 builder.append(localizedDigits.charAt(units));
Maurice Lamebc050f2016-10-31 16:17:53 -0700258 return builder.toString();
259 }
260
261 /**
262 * Get the GMT offset text label for the given time zone, in the format "GMT-08:00". This will
263 * also add TTS spans to give hints to the text-to-speech engine for the type of data it is.
264 *
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700265 * @param tzFormatter The timezone formatter to use.
Maurice Lamebc050f2016-10-31 16:17:53 -0700266 * @param locale The locale which the string is displayed in. This should be the same as the
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700267 * locale of the time zone formatter.
Maurice Lamebc050f2016-10-31 16:17:53 -0700268 * @param tz Time zone to get the GMT offset from.
269 * @param now The current time, used to tell whether daylight savings is active.
270 * @return A CharSequence suitable for display as the offset label of {@code tz}.
271 */
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700272 private static CharSequence getGmtOffsetText(TimeZoneFormat tzFormatter, Locale locale,
273 TimeZone tz, Date now) {
274 final SpannableStringBuilder builder = new SpannableStringBuilder();
Maurice Lamebc050f2016-10-31 16:17:53 -0700275
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700276 final String gmtPattern = tzFormatter.getGMTPattern();
277 final int placeholderIndex = gmtPattern.indexOf("{0}");
278 final String gmtPatternPrefix, gmtPatternSuffix;
279 if (placeholderIndex == -1) {
280 // Bad pattern. Replace with defaults.
281 gmtPatternPrefix = "GMT";
282 gmtPatternSuffix = "";
283 } else {
284 gmtPatternPrefix = gmtPattern.substring(0, placeholderIndex);
285 gmtPatternSuffix = gmtPattern.substring(placeholderIndex + 3); // After the "{0}".
Maurice Lamebc050f2016-10-31 16:17:53 -0700286 }
287
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700288 if (!gmtPatternPrefix.isEmpty()) {
289 appendWithTtsSpan(builder, gmtPatternPrefix,
290 new TtsSpan.TextBuilder(gmtPatternPrefix).build());
291 }
292
293 int offsetMillis = tz.getOffset(now.getTime());
294 final boolean negative = offsetMillis < 0;
295 final TimeZoneFormat.GMTOffsetPatternType patternType;
296 if (negative) {
297 offsetMillis = -offsetMillis;
298 patternType = TimeZoneFormat.GMTOffsetPatternType.NEGATIVE_HM;
299 } else {
300 patternType = TimeZoneFormat.GMTOffsetPatternType.POSITIVE_HM;
301 }
302 final String gmtOffsetPattern = tzFormatter.getGMTOffsetPattern(patternType);
303 final String localizedDigits = tzFormatter.getGMTOffsetDigits();
304
Maurice Lamebc050f2016-10-31 16:17:53 -0700305 final int offsetHours = (int) (offsetMillis / DateUtils.HOUR_IN_MILLIS);
Maurice Lamebc050f2016-10-31 16:17:53 -0700306 final int offsetMinutes = (int) (offsetMillis / DateUtils.MINUTE_IN_MILLIS);
307 final int offsetMinutesRemaining = Math.abs(offsetMinutes) % 60;
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700308
309 for (int i = 0; i < gmtOffsetPattern.length(); i++) {
310 char c = gmtOffsetPattern.charAt(i);
311 if (c == '+' || c == '-' || c == '\u2212' /* MINUS SIGN */) {
312 final String sign = String.valueOf(c);
313 appendWithTtsSpan(builder, sign, new TtsSpan.VerbatimBuilder(sign).build());
314 } else if (c == 'H' || c == 'm') {
315 final int numDigits;
316 if (i + 1 < gmtOffsetPattern.length() && gmtOffsetPattern.charAt(i + 1) == c) {
317 numDigits = 2;
318 i++; // Skip the next formatting character.
319 } else {
320 numDigits = 1;
321 }
322 final int number;
323 final String unit;
324 if (c == 'H') {
325 number = offsetHours;
326 unit = "hour";
327 } else { // c == 'm'
328 number = offsetMinutesRemaining;
329 unit = "minute";
330 }
331 appendWithTtsSpan(builder, formatDigits(number, numDigits, localizedDigits),
332 new TtsSpan.MeasureBuilder().setNumber(number).setUnit(unit).build());
333 } else {
334 builder.append(c);
335 }
336 }
337
338 if (!gmtPatternSuffix.isEmpty()) {
339 appendWithTtsSpan(builder, gmtPatternSuffix,
340 new TtsSpan.TextBuilder(gmtPatternSuffix).build());
341 }
Maurice Lamebc050f2016-10-31 16:17:53 -0700342
343 CharSequence gmtText = new SpannableString(builder);
Tony Mantlerb3543e02015-05-28 14:48:00 -0700344
345 // Ensure that the "GMT+" stays with the "00:00" even if the digits are RTL.
jackqdyuleic6a32742016-09-27 15:58:51 -0700346 final BidiFormatter bidiFormatter = BidiFormatter.getInstance();
Neil Fuller6394a392015-06-09 10:04:43 +0100347 boolean isRtl = TextUtils.getLayoutDirectionFromLocale(locale) == View.LAYOUT_DIRECTION_RTL;
Maurice Lamebc050f2016-10-31 16:17:53 -0700348 gmtText = bidiFormatter.unicodeWrap(gmtText,
349 isRtl ? TextDirectionHeuristicsCompat.RTL : TextDirectionHeuristicsCompat.LTR);
350 return gmtText;
Tony Mantlerb3543e02015-05-28 14:48:00 -0700351 }
jackqdyuleic6a32742016-09-27 15:58:51 -0700352
353 private static final class ZoneGetterData {
354 public final String[] olsonIdsToDisplay;
Maurice Lamebc050f2016-10-31 16:17:53 -0700355 public final CharSequence[] gmtOffsetTexts;
jackqdyuleic6a32742016-09-27 15:58:51 -0700356 public final TimeZone[] timeZones;
357 public final Set<String> localZoneIds;
358 public final int zoneCount;
359
360 public ZoneGetterData(Context context) {
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700361 final Locale locale = context.getResources().getConfiguration().locale;
362 final TimeZoneFormat tzFormatter = TimeZoneFormat.getInstance(locale);
jackqdyuleic6a32742016-09-27 15:58:51 -0700363 final Date now = new Date();
364 final List<String> olsonIdsToDisplayList = readTimezonesToDisplay(context);
365
366 // Load all the data needed to display time zones
367 zoneCount = olsonIdsToDisplayList.size();
368 olsonIdsToDisplay = new String[zoneCount];
369 timeZones = new TimeZone[zoneCount];
Maurice Lamebc050f2016-10-31 16:17:53 -0700370 gmtOffsetTexts = new CharSequence[zoneCount];
jackqdyuleic6a32742016-09-27 15:58:51 -0700371 for (int i = 0; i < zoneCount; i++) {
372 final String olsonId = olsonIdsToDisplayList.get(i);
373 olsonIdsToDisplay[i] = olsonId;
374 final TimeZone tz = TimeZone.getTimeZone(olsonId);
375 timeZones[i] = tz;
Roozbeh Pournader5b810312017-07-17 15:07:41 -0700376 gmtOffsetTexts[i] = getGmtOffsetText(tzFormatter, locale, tz, now);
jackqdyuleic6a32742016-09-27 15:58:51 -0700377 }
378
379 // Create a lookup of local zone IDs.
Neil Fuller1cc722b2017-10-25 20:26:02 +0100380 List<String> zoneIds =
381 TimeZoneFinder.getInstance().lookupTimeZoneIdsByCountry(locale.getCountry());
382 localZoneIds = new HashSet<>(zoneIds);
jackqdyuleic6a32742016-09-27 15:58:51 -0700383 }
384 }
Neil Fuller2242ff72017-04-05 13:58:26 +0100385}