Debian Codegraph @

core/java/com/android/internal/app/SuggestedLocaleAdapter.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2016 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 com.android.internal.app;
18
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.content.Context;
22 import android.content.res.Configuration;
23 import android.text.TextUtils;
24 import android.view.LayoutInflater;
25 import android.view.View;
26 import android.view.ViewGroup;
27 import android.widget.BaseAdapter;
28 import android.widget.Filter;
29 import android.widget.Filterable;
30 import android.widget.LinearLayout;
31 import android.widget.TextView;
32
33 import com.android.internal.R;
34
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.Locale;
38 import java.util.Set;
39
40
41 /**
42 * This adapter wraps around a regular ListAdapter for LocaleInfo, and creates 2 sections.
43 *
44 * <p>The first section contains "suggested" languages (usually including a region),
45 * the second section contains all the languages within the original adapter.
46 * The "others" might still include languages that appear in the "suggested" section.</p>
47 *
48 * <p>Example: if we show "German Switzerland" as "suggested" (based on SIM, let's say),
49 * then "German" will still show in the "others" section, clicking on it will only show the
50 * countries for all the other German locales, but not Switzerland
51 * (Austria, Belgium, Germany, Liechtenstein, Luxembourg)</p>
52 */
53 public class SuggestedLocaleAdapter extends BaseAdapter implements Filterable {
54 private static final int TYPE_HEADER_SUGGESTED = 0;
55 private static final int TYPE_HEADER_ALL_OTHERS = 1;
56 private static final int TYPE_LOCALE = 2;
57 private static final int TYPE_SYSTEM_LANGUAGE_FOR_APP_LANGUAGE_PICKER = 3;
58 private static final int TYPE_CURRENT_LOCALE = 4;
59 private static final int MIN_REGIONS_FOR_SUGGESTIONS = 6;
60 private static final int APP_LANGUAGE_PICKER_TYPE_COUNT = 5;
61 private static final int SYSTEM_LANGUAGE_TYPE_COUNT = 3;
62 private static final int SYSTEM_LANGUAGE_WITHOUT_HEADER_TYPE_COUNT = 1;
63
64 private ArrayList<LocaleStore.LocaleInfo> mLocaleOptions;
65 private ArrayList<LocaleStore.LocaleInfo> mOriginalLocaleOptions;
66 private int mSuggestionCount;
67 private final boolean mCountryMode;
68 private LayoutInflater mInflater;
69
70 private Locale mDisplayLocale = null;
71 // used to potentially cache a modified Context that uses mDisplayLocale
72 private Context mContextOverride = null;
73 private boolean mHasSpecificAppPackageName;
74
75 public SuggestedLocaleAdapter(Set<LocaleStore.LocaleInfo> localeOptions, boolean countryMode) {
76 this(localeOptions, countryMode, false);
77 }
78
79 public SuggestedLocaleAdapter(Set<LocaleStore.LocaleInfo> localeOptions, boolean countryMode,
80 boolean hasSpecificAppPackageName) {
81 mCountryMode = countryMode;
82 mLocaleOptions = new ArrayList<>(localeOptions.size());
83 mHasSpecificAppPackageName = hasSpecificAppPackageName;
84
85 for (LocaleStore.LocaleInfo li : localeOptions) {
86 if (li.isSuggested()) {
87 mSuggestionCount++;
88 }
89 mLocaleOptions.add(li);
90 }
91 }
92
93 @Override
94 public boolean areAllItemsEnabled() {
95 return false;
96 }
97
98 @Override
99 public boolean isEnabled(int position) {
100 return getItemViewType(position) == TYPE_LOCALE
101 || getItemViewType(position) == TYPE_SYSTEM_LANGUAGE_FOR_APP_LANGUAGE_PICKER
102 || getItemViewType(position) == TYPE_CURRENT_LOCALE;
103 }
104
105 @Override
106 public int getItemViewType(int position) {
107 if (!showHeaders()) {
108 LocaleStore.LocaleInfo item = (LocaleStore.LocaleInfo) getItem(position);
109 if (item.isSystemLocale()) {
110 return TYPE_SYSTEM_LANGUAGE_FOR_APP_LANGUAGE_PICKER;
111 }
112 if (item.isAppCurrentLocale()) {
113 return TYPE_CURRENT_LOCALE;
114 }
115 return TYPE_LOCALE;
116 } else {
117 if (position == 0) {
118 return TYPE_HEADER_SUGGESTED;
119 }
120 if (position == mSuggestionCount + 1) {
121 return TYPE_HEADER_ALL_OTHERS;
122 }
123
124 LocaleStore.LocaleInfo item = (LocaleStore.LocaleInfo) getItem(position);
125 if (item.isSystemLocale()) {
126 return TYPE_SYSTEM_LANGUAGE_FOR_APP_LANGUAGE_PICKER;
127 }
128 if (item.isAppCurrentLocale()) {
129 return TYPE_CURRENT_LOCALE;
130 }
131 return TYPE_LOCALE;
132 }
133 }
134
135 @Override
136 public int getViewTypeCount() {
137 if (mHasSpecificAppPackageName && showHeaders()) {
138 // Two headers, 1 "System language", 1 current locale
139 return APP_LANGUAGE_PICKER_TYPE_COUNT;
140 } else if (showHeaders()) {
141 // Two headers in addition to the locales
142 return SYSTEM_LANGUAGE_TYPE_COUNT;
143 } else {
144 return SYSTEM_LANGUAGE_WITHOUT_HEADER_TYPE_COUNT; // Locales items only
145 }
146 }
147
148 @Override
149 public int getCount() {
150 if (showHeaders()) {
151 return mLocaleOptions.size() + 2; // 2 extra for the headers
152 } else {
153 return mLocaleOptions.size();
154 }
155 }
156
157 @Override
158 public Object getItem(int position) {
159 int offset = 0;
160 if (showHeaders()) {
161 offset = position > mSuggestionCount ? -2 : -1;
162 }
163
164 return mLocaleOptions.get(position + offset);
165 }
166
167 @Override
168 public long getItemId(int position) {
169 return position;
170 }
171
172 /**
173 * Overrides the locale used to display localized labels. Setting the locale to null will reset
174 * the Adapter to use the default locale for the labels.
175 */
176 public void setDisplayLocale(@NonNull Context context, @Nullable Locale locale) {
177 if (locale == null) {
178 mDisplayLocale = null;
179 mContextOverride = null;
180 } else if (!locale.equals(mDisplayLocale)) {
181 mDisplayLocale = locale;
182 final Configuration configOverride = new Configuration();
183 configOverride.setLocale(locale);
184 mContextOverride = context.createConfigurationContext(configOverride);
185 }
186 }
187
188 private void setTextTo(@NonNull TextView textView, int resId) {
189 if (mContextOverride == null) {
190 textView.setText(resId);
191 } else {
192 textView.setText(mContextOverride.getText(resId));
193 // If mContextOverride is not null, mDisplayLocale can't be null either.
194 }
195 }
196
197 @Override
198 public View getView(int position, View convertView, ViewGroup parent) {
199 if (convertView == null && mInflater == null) {
200 mInflater = LayoutInflater.from(parent.getContext());
201 }
202
203 int itemType = getItemViewType(position);
204 View itemView = getNewViewIfNeeded(convertView, parent, itemType, position);
205 switch (itemType) {
206 case TYPE_HEADER_SUGGESTED: // intentional fallthrough
207 case TYPE_HEADER_ALL_OTHERS:
208 TextView textView = (TextView) itemView;
209 if (itemType == TYPE_HEADER_SUGGESTED) {
210 if (mCountryMode) {
211 setTextTo(textView, R.string.language_picker_regions_section_suggested);
212 } else {
213 setTextTo(textView, R.string.language_picker_section_suggested);
214 }
215 } else {
216 if (mCountryMode) {
217 setTextTo(textView, R.string.region_picker_section_all);
218 } else {
219 setTextTo(textView, R.string.language_picker_section_all);
220 }
221 }
222 textView.setTextLocale(
223 mDisplayLocale != null ? mDisplayLocale : Locale.getDefault());
224 break;
225 case TYPE_SYSTEM_LANGUAGE_FOR_APP_LANGUAGE_PICKER:
226 TextView title;
227 if (((LocaleStore.LocaleInfo)getItem(position)).isAppCurrentLocale()) {
228 title = itemView.findViewById(R.id.language_picker_item);
229 } else {
230 title = itemView.findViewById(R.id.locale);
231 }
232 title.setText(R.string.system_locale_title);
233 break;
234 case TYPE_CURRENT_LOCALE:
235 updateTextView(itemView,
236 itemView.findViewById(R.id.language_picker_item), position);
237 break;
238 default:
239 updateTextView(itemView, itemView.findViewById(R.id.locale), position);
240 break;
241 }
242 return itemView;
243 }
244
245 /** Check if the old view can be reused, otherwise create a new one. */
246 private View getNewViewIfNeeded(
247 View convertView, ViewGroup parent, int itemType, int position) {
248 View updatedView = convertView;
249 boolean shouldReuseView;
250 switch (itemType) {
251 case TYPE_HEADER_SUGGESTED: // intentional fallthrough
252 case TYPE_HEADER_ALL_OTHERS:
253 shouldReuseView = convertView instanceof TextView
254 && convertView.findViewById(R.id.language_picker_header) != null;
255 if (!shouldReuseView) {
256 updatedView = mInflater.inflate(
257 R.layout.language_picker_section_header, parent, false);
258 }
259 break;
260 case TYPE_SYSTEM_LANGUAGE_FOR_APP_LANGUAGE_PICKER:
261 if (((LocaleStore.LocaleInfo) getItem(position)).isAppCurrentLocale()) {
262 shouldReuseView = convertView instanceof LinearLayout
263 && convertView.findViewById(R.id.language_picker_item) != null;
264 if (!shouldReuseView) {
265 updatedView = mInflater.inflate(
266 R.layout.app_language_picker_current_locale_item,
267 parent, false);
268 addStateDescriptionIntoCurrentLocaleItem(updatedView);
269 }
270 } else {
271 shouldReuseView = convertView instanceof TextView
272 && convertView.findViewById(R.id.locale) != null;
273 if (!shouldReuseView) {
274 updatedView = mInflater.inflate(
275 R.layout.language_picker_item, parent, false);
276 }
277 }
278 break;
279 case TYPE_CURRENT_LOCALE:
280 shouldReuseView = convertView instanceof LinearLayout
281 && convertView.findViewById(R.id.language_picker_item) != null;
282 if (!shouldReuseView) {
283 updatedView = mInflater.inflate(
284 R.layout.app_language_picker_current_locale_item, parent, false);
285 addStateDescriptionIntoCurrentLocaleItem(updatedView);
286 }
287 break;
288 default:
289 shouldReuseView = convertView instanceof TextView
290 && convertView.findViewById(R.id.locale) != null;
291 if (!shouldReuseView) {
292 updatedView = mInflater.inflate(R.layout.language_picker_item, parent, false);
293 }
294 break;
295 }
296 return updatedView;
297 }
298
299 private boolean showHeaders() {
300 // We don't want to show suggestions for locales with very few regions
301 // (e.g. Romanian, with 2 regions)
302 // So we put a (somewhat) arbitrary limit.
303 //
304 // The initial idea was to make that limit dependent on the screen height.
305 // But that would mean rotating the screen could make the suggestions disappear,
306 // as the number of countries that fits on the screen would be different in portrait
307 // and landscape mode.
308 if (mCountryMode && mLocaleOptions.size() < MIN_REGIONS_FOR_SUGGESTIONS) {
309 return false;
310 }
311 return mSuggestionCount != 0 && mSuggestionCount != mLocaleOptions.size();
312 }
313
314 /**
315 * Sorts the items in the adapter using a locale-aware comparator.
316 * @param comp The locale-aware comparator to use.
317 */
318 public void sort(LocaleHelper.LocaleInfoComparator comp) {
319 Collections.sort(mLocaleOptions, comp);
320 }
321
322 class FilterByNativeAndUiNames extends Filter {
323
324 @Override
325 protected FilterResults performFiltering(CharSequence prefix) {
326 FilterResults results = new FilterResults();
327
328 if (mOriginalLocaleOptions == null) {
329 mOriginalLocaleOptions = new ArrayList<>(mLocaleOptions);
330 }
331
332 ArrayList<LocaleStore.LocaleInfo> values;
333 values = new ArrayList<>(mOriginalLocaleOptions);
334 if (prefix == null || prefix.length() == 0) {
335 results.values = values;
336 results.count = values.size();
337 } else {
338 // TODO: decide if we should use the string's locale
339 Locale locale = Locale.getDefault();
340 String prefixString = LocaleHelper.normalizeForSearch(prefix.toString(), locale);
341
342 final int count = values.size();
343 final ArrayList<LocaleStore.LocaleInfo> newValues = new ArrayList<>();
344
345 for (int i = 0; i < count; i++) {
346 final LocaleStore.LocaleInfo value = values.get(i);
347 final String nameToCheck = LocaleHelper.normalizeForSearch(
348 value.getFullNameInUiLanguage(), locale);
349 final String nativeNameToCheck = LocaleHelper.normalizeForSearch(
350 value.getFullNameNative(), locale);
351 if (wordMatches(nativeNameToCheck, prefixString)
352 || wordMatches(nameToCheck, prefixString)) {
353 newValues.add(value);
354 }
355 }
356
357 results.values = newValues;
358 results.count = newValues.size();
359 }
360
361 return results;
362 }
363
364 // TODO: decide if this is enough, or we want to use a BreakIterator...
365 boolean wordMatches(String valueText, String prefixString) {
366 // First match against the whole, non-split value
367 if (valueText.startsWith(prefixString)) {
368 return true;
369 }
370
371 final String[] words = valueText.split(" ");
372 // Start at index 0, in case valueText starts with space(s)
373 for (String word : words) {
374 if (word.startsWith(prefixString)) {
375 return true;
376 }
377 }
378
379 return false;
380 }
381
382 @Override
383 protected void publishResults(CharSequence constraint, FilterResults results) {
384 mLocaleOptions = (ArrayList<LocaleStore.LocaleInfo>) results.values;
385
386 mSuggestionCount = 0;
387 for (LocaleStore.LocaleInfo li : mLocaleOptions) {
388 if (li.isSuggested()) {
389 mSuggestionCount++;
390 }
391 }
392
393 if (results.count > 0) {
394 notifyDataSetChanged();
395 } else {
396 notifyDataSetInvalidated();
397 }
398 }
399 }
400
401 @Override
402 public Filter getFilter() {
403 return new FilterByNativeAndUiNames();
404 }
405
406 private void updateTextView(View convertView, TextView text, int position) {
407 LocaleStore.LocaleInfo item = (LocaleStore.LocaleInfo) getItem(position);
408 text.setText(item.getLabel(mCountryMode));
409 text.setTextLocale(item.getLocale());
410 text.setContentDescription(item.getContentDescription(mCountryMode));
411 if (mCountryMode) {
412 int layoutDir = TextUtils.getLayoutDirectionFromLocale(item.getParent());
413 //noinspection ResourceType
414 convertView.setLayoutDirection(layoutDir);
415 text.setTextDirection(layoutDir == View.LAYOUT_DIRECTION_RTL
416 ? View.TEXT_DIRECTION_RTL
417 : View.TEXT_DIRECTION_LTR);
418 }
419 }
420
421 private void addStateDescriptionIntoCurrentLocaleItem(View root) {
422 String description = root.getContext().getResources().getString(R.string.checked);
423 root.setStateDescription(description);
424 }
425 }