blob: 474de9074062cb9319b028524f4cebc14d795642 [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;
Neil Fuller4a180122015-12-16 18:50:07 +000021import android.icu.text.TimeZoneNames;
Maurice Lamebc050f2016-10-31 16:17:53 -070022import android.support.v4.text.BidiFormatter;
23import android.support.v4.text.TextDirectionHeuristicsCompat;
24import android.text.SpannableString;
25import android.text.SpannableStringBuilder;
Tony Mantlerb3543e02015-05-28 14:48:00 -070026import android.text.TextUtils;
Maurice Lamebc050f2016-10-31 16:17:53 -070027import android.text.format.DateUtils;
28import android.text.style.TtsSpan;
Tony Mantlerb3543e02015-05-28 14:48:00 -070029import android.util.Log;
30import android.view.View;
31
32import com.android.settingslib.R;
33
Tony Mantlerb3543e02015-05-28 14:48:00 -070034import org.xmlpull.v1.XmlPullParserException;
35
Tony Mantlerb3543e02015-05-28 14:48:00 -070036import java.util.ArrayList;
Tony Mantlerb3543e02015-05-28 14:48:00 -070037import java.util.Date;
38import java.util.HashMap;
Neil Fuller4a180122015-12-16 18:50:07 +000039import java.util.HashSet;
Tony Mantlerb3543e02015-05-28 14:48:00 -070040import java.util.List;
41import java.util.Locale;
Neil Fuller6394a392015-06-09 10:04:43 +010042import java.util.Map;
43import java.util.Set;
Tony Mantlerb3543e02015-05-28 14:48:00 -070044import java.util.TimeZone;
45
jackqdyuleic6a32742016-09-27 15:58:51 -070046/**
47 * ZoneGetter is the utility class to get time zone and zone list, and both of them have display
48 * name in time zone. In this class, we will keep consistency about display names for all
49 * the methods.
50 *
51 * The display name chosen for each zone entry depends on whether the zone is one associated
52 * with the country of the user's chosen locale. For "local" zones we prefer the "long name"
53 * (e.g. "Europe/London" -> "British Summer Time" for people in the UK). For "non-local"
54 * zones we prefer the exemplar location (e.g. "Europe/London" -> "London" for English
55 * speakers from outside the UK). This heuristic is based on the fact that people are
56 * typically familiar with their local timezones and exemplar locations don't always match
57 * modern-day expectations for people living in the country covered. Large countries like
58 * China that mostly use a single timezone (olson id: "Asia/Shanghai") may not live near
59 * "Shanghai" and prefer the long name over the exemplar location. The only time we don't
60 * follow this policy for local zones is when Android supplies multiple olson IDs to choose
61 * from and the use of a zone's long name leads to ambiguity. For example, at the time of
62 * writing Android lists 5 olson ids for Australia which collapse to 2 different zone names
63 * in winter but 4 different zone names in summer. The ambiguity leads to the users
64 * selecting the wrong olson ids.
65 *
66 */
Tony Mantlerb3543e02015-05-28 14:48:00 -070067public class ZoneGetter {
68 private static final String TAG = "ZoneGetter";
69
Tony Mantlerb3543e02015-05-28 14:48:00 -070070 public static final String KEY_ID = "id"; // value: String
Maurice Lamebc050f2016-10-31 16:17:53 -070071
72 /**
73 * @deprecated Use {@link #KEY_DISPLAY_LABEL} instead.
74 */
75 @Deprecated
Tony Mantlerb3543e02015-05-28 14:48:00 -070076 public static final String KEY_DISPLAYNAME = "name"; // value: String
Maurice Lamebc050f2016-10-31 16:17:53 -070077
78 public static final String KEY_DISPLAY_LABEL = "display_label"; // value: CharSequence
79
80 /**
81 * @deprecated Use {@link #KEY_OFFSET_LABEL} instead.
82 */
83 @Deprecated
Tony Mantlerb3543e02015-05-28 14:48:00 -070084 public static final String KEY_GMT = "gmt"; // value: String
85 public static final String KEY_OFFSET = "offset"; // value: int (Integer)
Maurice Lamebc050f2016-10-31 16:17:53 -070086 public static final String KEY_OFFSET_LABEL = "offset_label"; // value: CharSequence
Tony Mantlerb3543e02015-05-28 14:48:00 -070087
jackqdyuleic6a32742016-09-27 15:58:51 -070088 private static final String XMLTAG_TIMEZONE = "timezone";
Tony Mantlerb3543e02015-05-28 14:48:00 -070089
Maurice Lamebc050f2016-10-31 16:17:53 -070090 public static CharSequence getTimeZoneOffsetAndName(Context context, TimeZone tz, Date now) {
jackqdyuleic6a32742016-09-27 15:58:51 -070091 final Locale locale = Locale.getDefault();
Maurice Lamebc050f2016-10-31 16:17:53 -070092 final CharSequence gmtText = getGmtOffsetText(context, locale, tz, now);
jackqdyuleic6a32742016-09-27 15:58:51 -070093 final TimeZoneNames timeZoneNames = TimeZoneNames.getInstance(locale);
94 final ZoneGetterData data = new ZoneGetterData(context);
95
96 final boolean useExemplarLocationForLocalNames =
97 shouldUseExemplarLocationForLocalNames(data, timeZoneNames);
Maurice Lamebc050f2016-10-31 16:17:53 -070098 final CharSequence zoneName = getTimeZoneDisplayName(data, timeZoneNames,
jackqdyuleic6a32742016-09-27 15:58:51 -070099 useExemplarLocationForLocalNames, tz, tz.getID());
Maurice Lamebc050f2016-10-31 16:17:53 -0700100 if (zoneName == null) {
101 return gmtText;
Tony Mantlerb3543e02015-05-28 14:48:00 -0700102 }
Neil Fuller6394a392015-06-09 10:04:43 +0100103
104 // We don't use punctuation here to avoid having to worry about localizing that too!
Maurice Lamebc050f2016-10-31 16:17:53 -0700105 return TextUtils.concat(gmtText, " ", zoneName);
Neil Fuller6394a392015-06-09 10:04:43 +0100106 }
107
108 public static List<Map<String, Object>> getZonesList(Context context) {
109 final Locale locale = Locale.getDefault();
110 final Date now = new Date();
Neil Fuller4a180122015-12-16 18:50:07 +0000111 final TimeZoneNames timeZoneNames = TimeZoneNames.getInstance(locale);
jackqdyuleic6a32742016-09-27 15:58:51 -0700112 final ZoneGetterData data = new ZoneGetterData(context);
Neil Fuller6394a392015-06-09 10:04:43 +0100113
Neil Fuller4a180122015-12-16 18:50:07 +0000114 // Work out whether the display names we would show by default would be ambiguous.
jackqdyuleic6a32742016-09-27 15:58:51 -0700115 final boolean useExemplarLocationForLocalNames =
116 shouldUseExemplarLocationForLocalNames(data, timeZoneNames);
Neil Fuller6394a392015-06-09 10:04:43 +0100117
118 // Generate the list of zone entries to return.
119 List<Map<String, Object>> zones = new ArrayList<Map<String, Object>>();
jackqdyuleic6a32742016-09-27 15:58:51 -0700120 for (int i = 0; i < data.zoneCount; i++) {
121 TimeZone tz = data.timeZones[i];
Maurice Lamebc050f2016-10-31 16:17:53 -0700122 CharSequence gmtOffsetText = data.gmtOffsetTexts[i];
Neil Fuller6394a392015-06-09 10:04:43 +0100123
Maurice Lamebc050f2016-10-31 16:17:53 -0700124 CharSequence displayName = getTimeZoneDisplayName(data, timeZoneNames,
jackqdyuleic6a32742016-09-27 15:58:51 -0700125 useExemplarLocationForLocalNames, tz, data.olsonIdsToDisplay[i]);
Maurice Lamebc050f2016-10-31 16:17:53 -0700126 if (TextUtils.isEmpty(displayName)) {
127 displayName = gmtOffsetText;
Neil Fuller4a180122015-12-16 18:50:07 +0000128 }
129
Neil Fuller6394a392015-06-09 10:04:43 +0100130 int offsetMillis = tz.getOffset(now.getTime());
131 Map<String, Object> displayEntry =
Maurice Lamebc050f2016-10-31 16:17:53 -0700132 createDisplayEntry(tz, gmtOffsetText, displayName, offsetMillis);
Neil Fuller6394a392015-06-09 10:04:43 +0100133 zones.add(displayEntry);
134 }
135 return zones;
136 }
137
138 private static Map<String, Object> createDisplayEntry(
Maurice Lamebc050f2016-10-31 16:17:53 -0700139 TimeZone tz, CharSequence gmtOffsetText, CharSequence displayName, int offsetMillis) {
140 Map<String, Object> map = new HashMap<>();
Neil Fuller6394a392015-06-09 10:04:43 +0100141 map.put(KEY_ID, tz.getID());
Maurice Lamebc050f2016-10-31 16:17:53 -0700142 map.put(KEY_DISPLAYNAME, displayName.toString());
143 map.put(KEY_DISPLAY_LABEL, displayName);
144 map.put(KEY_GMT, gmtOffsetText.toString());
145 map.put(KEY_OFFSET_LABEL, gmtOffsetText);
Neil Fuller6394a392015-06-09 10:04:43 +0100146 map.put(KEY_OFFSET, offsetMillis);
147 return map;
148 }
149
Neil Fuller6394a392015-06-09 10:04:43 +0100150 private static List<String> readTimezonesToDisplay(Context context) {
151 List<String> olsonIds = new ArrayList<String>();
152 try (XmlResourceParser xrp = context.getResources().getXml(R.xml.timezones)) {
Tony Mantlerb3543e02015-05-28 14:48:00 -0700153 while (xrp.next() != XmlResourceParser.START_TAG) {
154 continue;
155 }
156 xrp.next();
157 while (xrp.getEventType() != XmlResourceParser.END_TAG) {
158 while (xrp.getEventType() != XmlResourceParser.START_TAG) {
159 if (xrp.getEventType() == XmlResourceParser.END_DOCUMENT) {
Neil Fuller6394a392015-06-09 10:04:43 +0100160 return olsonIds;
Tony Mantlerb3543e02015-05-28 14:48:00 -0700161 }
162 xrp.next();
163 }
164 if (xrp.getName().equals(XMLTAG_TIMEZONE)) {
165 String olsonId = xrp.getAttributeValue(0);
Neil Fuller6394a392015-06-09 10:04:43 +0100166 olsonIds.add(olsonId);
Tony Mantlerb3543e02015-05-28 14:48:00 -0700167 }
168 while (xrp.getEventType() != XmlResourceParser.END_TAG) {
169 xrp.next();
170 }
171 xrp.next();
172 }
Tony Mantlerb3543e02015-05-28 14:48:00 -0700173 } catch (XmlPullParserException xppe) {
174 Log.e(TAG, "Ill-formatted timezones.xml file");
175 } catch (java.io.IOException ioe) {
176 Log.e(TAG, "Unable to read timezones.xml file");
177 }
Neil Fuller6394a392015-06-09 10:04:43 +0100178 return olsonIds;
Tony Mantlerb3543e02015-05-28 14:48:00 -0700179 }
180
jackqdyuleic6a32742016-09-27 15:58:51 -0700181 private static boolean shouldUseExemplarLocationForLocalNames(ZoneGetterData data,
182 TimeZoneNames timeZoneNames) {
Maurice Lamebc050f2016-10-31 16:17:53 -0700183 final Set<CharSequence> localZoneNames = new HashSet<>();
jackqdyuleic6a32742016-09-27 15:58:51 -0700184 final Date now = new Date();
185 for (int i = 0; i < data.zoneCount; i++) {
186 final String olsonId = data.olsonIdsToDisplay[i];
187 if (data.localZoneIds.contains(olsonId)) {
188 final TimeZone tz = data.timeZones[i];
Maurice Lamebc050f2016-10-31 16:17:53 -0700189 CharSequence displayName = getZoneLongName(timeZoneNames, tz, now);
jackqdyuleic6a32742016-09-27 15:58:51 -0700190 if (displayName == null) {
Maurice Lamebc050f2016-10-31 16:17:53 -0700191 displayName = data.gmtOffsetTexts[i];
jackqdyuleic6a32742016-09-27 15:58:51 -0700192 }
193 final boolean nameIsUnique = localZoneNames.add(displayName);
194 if (!nameIsUnique) {
195 return true;
196 }
197 }
198 }
199
200 return false;
201 }
202
Maurice Lamebc050f2016-10-31 16:17:53 -0700203 private static CharSequence getTimeZoneDisplayName(ZoneGetterData data,
204 TimeZoneNames timeZoneNames, boolean useExemplarLocationForLocalNames, TimeZone tz,
205 String olsonId) {
jackqdyuleic6a32742016-09-27 15:58:51 -0700206 final Date now = new Date();
207 final boolean isLocalZoneId = data.localZoneIds.contains(olsonId);
208 final boolean preferLongName = isLocalZoneId && !useExemplarLocationForLocalNames;
209 String displayName;
210
211 if (preferLongName) {
212 displayName = getZoneLongName(timeZoneNames, tz, now);
213 } else {
Neil Fuller2242ff72017-04-05 13:58:26 +0100214 // Canonicalize the zone ID for ICU. It will only return valid strings for zone IDs
215 // that match ICUs zone IDs (which are similar but not guaranteed the same as those
216 // in timezones.xml). timezones.xml and related files uses the IANA IDs. ICU IDs are
217 // stable and IANA IDs have changed over time so they have drifted.
218 // See http://bugs.icu-project.org/trac/ticket/13070 / http://b/36469833.
219 String canonicalZoneId = android.icu.util.TimeZone.getCanonicalID(tz.getID());
220 if (canonicalZoneId == null) {
221 canonicalZoneId = tz.getID();
222 }
223 displayName = timeZoneNames.getExemplarLocationName(canonicalZoneId);
jackqdyuleic6a32742016-09-27 15:58:51 -0700224 if (displayName == null || displayName.isEmpty()) {
225 // getZoneExemplarLocation can return null. Fall back to the long name.
226 displayName = getZoneLongName(timeZoneNames, tz, now);
227 }
228 }
229
230 return displayName;
231 }
232
Neil Fuller4a180122015-12-16 18:50:07 +0000233 /**
234 * Returns the long name for the timezone for the given locale at the time specified.
235 * Can return {@code null}.
236 */
237 private static String getZoneLongName(TimeZoneNames names, TimeZone tz, Date now) {
jackqdyuleic6a32742016-09-27 15:58:51 -0700238 final TimeZoneNames.NameType nameType =
Neil Fuller4a180122015-12-16 18:50:07 +0000239 tz.inDaylightTime(now) ? TimeZoneNames.NameType.LONG_DAYLIGHT
jackqdyuleic6a32742016-09-27 15:58:51 -0700240 : TimeZoneNames.NameType.LONG_STANDARD;
Neil Fuller4a180122015-12-16 18:50:07 +0000241 return names.getDisplayName(tz.getID(), nameType, now.getTime());
Tony Mantlerb3543e02015-05-28 14:48:00 -0700242 }
243
Maurice Lamebc050f2016-10-31 16:17:53 -0700244 private static void appendWithTtsSpan(SpannableStringBuilder builder, CharSequence content,
245 TtsSpan span) {
246 int start = builder.length();
247 builder.append(content);
248 builder.setSpan(span, start, builder.length(), 0);
249 }
250
251 private static String twoDigits(int input) {
252 StringBuilder builder = new StringBuilder(3);
253 if (input < 0) builder.append('-');
254 String string = Integer.toString(Math.abs(input));
255 if (string.length() == 1) builder.append("0");
256 builder.append(string);
257 return builder.toString();
258 }
259
260 /**
261 * Get the GMT offset text label for the given time zone, in the format "GMT-08:00". This will
262 * also add TTS spans to give hints to the text-to-speech engine for the type of data it is.
263 *
264 * @param context The context which the string is displayed in.
265 * @param locale The locale which the string is displayed in. This should be the same as the
266 * locale of the context.
267 * @param tz Time zone to get the GMT offset from.
268 * @param now The current time, used to tell whether daylight savings is active.
269 * @return A CharSequence suitable for display as the offset label of {@code tz}.
270 */
271 private static CharSequence getGmtOffsetText(Context context, Locale locale, TimeZone tz,
272 Date now) {
273 SpannableStringBuilder builder = new SpannableStringBuilder();
274
275 appendWithTtsSpan(builder, "GMT",
276 new TtsSpan.TextBuilder(context.getString(R.string.time_zone_gmt)).build());
277
278 int offsetMillis = tz.getOffset(now.getTime());
279 if (offsetMillis >= 0) {
280 appendWithTtsSpan(builder, "+", new TtsSpan.VerbatimBuilder("+").build());
281 }
282
283 final int offsetHours = (int) (offsetMillis / DateUtils.HOUR_IN_MILLIS);
284 appendWithTtsSpan(builder, twoDigits(offsetHours),
285 new TtsSpan.MeasureBuilder().setNumber(offsetHours).setUnit("hour").build());
286
287 builder.append(":");
288
289 final int offsetMinutes = (int) (offsetMillis / DateUtils.MINUTE_IN_MILLIS);
290 final int offsetMinutesRemaining = Math.abs(offsetMinutes) % 60;
291 appendWithTtsSpan(builder, twoDigits(offsetMinutesRemaining),
292 new TtsSpan.MeasureBuilder().setNumber(offsetMinutesRemaining)
293 .setUnit("minute").build());
294
295 CharSequence gmtText = new SpannableString(builder);
Tony Mantlerb3543e02015-05-28 14:48:00 -0700296
297 // Ensure that the "GMT+" stays with the "00:00" even if the digits are RTL.
jackqdyuleic6a32742016-09-27 15:58:51 -0700298 final BidiFormatter bidiFormatter = BidiFormatter.getInstance();
Neil Fuller6394a392015-06-09 10:04:43 +0100299 boolean isRtl = TextUtils.getLayoutDirectionFromLocale(locale) == View.LAYOUT_DIRECTION_RTL;
Maurice Lamebc050f2016-10-31 16:17:53 -0700300 gmtText = bidiFormatter.unicodeWrap(gmtText,
301 isRtl ? TextDirectionHeuristicsCompat.RTL : TextDirectionHeuristicsCompat.LTR);
302 return gmtText;
Tony Mantlerb3543e02015-05-28 14:48:00 -0700303 }
jackqdyuleic6a32742016-09-27 15:58:51 -0700304
305 private static final class ZoneGetterData {
306 public final String[] olsonIdsToDisplay;
Maurice Lamebc050f2016-10-31 16:17:53 -0700307 public final CharSequence[] gmtOffsetTexts;
jackqdyuleic6a32742016-09-27 15:58:51 -0700308 public final TimeZone[] timeZones;
309 public final Set<String> localZoneIds;
310 public final int zoneCount;
311
312 public ZoneGetterData(Context context) {
313 final Locale locale = Locale.getDefault();
314 final Date now = new Date();
315 final List<String> olsonIdsToDisplayList = readTimezonesToDisplay(context);
316
317 // Load all the data needed to display time zones
318 zoneCount = olsonIdsToDisplayList.size();
319 olsonIdsToDisplay = new String[zoneCount];
320 timeZones = new TimeZone[zoneCount];
Maurice Lamebc050f2016-10-31 16:17:53 -0700321 gmtOffsetTexts = new CharSequence[zoneCount];
jackqdyuleic6a32742016-09-27 15:58:51 -0700322 for (int i = 0; i < zoneCount; i++) {
323 final String olsonId = olsonIdsToDisplayList.get(i);
324 olsonIdsToDisplay[i] = olsonId;
325 final TimeZone tz = TimeZone.getTimeZone(olsonId);
326 timeZones[i] = tz;
Maurice Lamebc050f2016-10-31 16:17:53 -0700327 gmtOffsetTexts[i] = getGmtOffsetText(context, locale, tz, now);
jackqdyuleic6a32742016-09-27 15:58:51 -0700328 }
329
330 // Create a lookup of local zone IDs.
331 localZoneIds = new HashSet<String>();
332 for (String olsonId : libcore.icu.TimeZoneNames.forLocale(locale)) {
333 localZoneIds.add(olsonId);
334 }
335 }
336 }
Neil Fuller2242ff72017-04-05 13:58:26 +0100337}