Niedzielski has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/209656

Change subject: Add system language support
......................................................................

Add system language support

- Add UI support for using system language and update the WebView when
  the system language changes out of app.
- Don't rely on Site domain to derive language. This will not always be
  possible. Update Site.equals(), hashCode(), and toString().
- Light refactoring in Site and WikipediaApp.
- Rename lang and primaryLanguage to language in several places.

Change-Id: I3903bdf6b70da560487206f35484af2ce2c677da
---
M wikipedia-it/src/main/java/org/wikipedia/test/GetDescriptionsTaskTests.java
M wikipedia-it/src/main/java/org/wikipedia/test/LanguageVariantTests.java
M wikipedia/res/values/languages_list.xml
M wikipedia/src/main/java/org/wikipedia/Site.java
M wikipedia/src/main/java/org/wikipedia/WikipediaApp.java
M wikipedia/src/main/java/org/wikipedia/editing/EditPreviewFragment.java
M wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksActivity.java
M wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksFetchTask.java
M wikipedia/src/main/java/org/wikipedia/migration/ArticleImporter.java
M wikipedia/src/main/java/org/wikipedia/page/PageActivity.java
M wikipedia/src/main/java/org/wikipedia/search/SearchResultsFragment.java
M wikipedia/src/main/java/org/wikipedia/settings/LanguagePreference.java
M wikipedia/src/main/java/org/wikipedia/widgets/WidgetProviderFeaturedPage.java
13 files changed, 221 insertions(+), 119 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/apps/android/wikipedia 
refs/changes/56/209656/1

diff --git 
a/wikipedia-it/src/main/java/org/wikipedia/test/GetDescriptionsTaskTests.java 
b/wikipedia-it/src/main/java/org/wikipedia/test/GetDescriptionsTaskTests.java
index 1972d11..b61a1a0 100644
--- 
a/wikipedia-it/src/main/java/org/wikipedia/test/GetDescriptionsTaskTests.java
+++ 
b/wikipedia-it/src/main/java/org/wikipedia/test/GetDescriptionsTaskTests.java
@@ -17,7 +17,7 @@
  */
 public class GetDescriptionsTaskTests extends 
ActivityUnitTestCase<TestDummyActivity> {
     private static final int TASK_COMPLETION_TIMEOUT = 200000;
-    private static final Site SITE = Site.forLang("en");
+    private static final Site SITE = Site.forLanguage("en");
 
     public GetDescriptionsTaskTests() {
         super(TestDummyActivity.class);
diff --git 
a/wikipedia-it/src/main/java/org/wikipedia/test/LanguageVariantTests.java 
b/wikipedia-it/src/main/java/org/wikipedia/test/LanguageVariantTests.java
index 050d7e7..54526d7 100644
--- a/wikipedia-it/src/main/java/org/wikipedia/test/LanguageVariantTests.java
+++ b/wikipedia-it/src/main/java/org/wikipedia/test/LanguageVariantTests.java
@@ -38,7 +38,7 @@
             }
 
             private void cover(String expected, String primaryLanguage, Locale 
locale) {
-                app.setPrimaryLanguage(primaryLanguage);
+                app.setLanguage(primaryLanguage);
                 Locale.setDefault(locale);
                 assertEquals(expected, app.getAcceptLanguage());
             }
diff --git a/wikipedia/res/values/languages_list.xml 
b/wikipedia/res/values/languages_list.xml
index 8ee16e1..2875d29 100644
--- a/wikipedia/res/values/languages_list.xml
+++ b/wikipedia/res/values/languages_list.xml
@@ -1,6 +1,7 @@
 <?xml version='1.0' encoding='utf-8'?>
 <resources xmlns:tools="http://schemas.android.com/tools"; 
tools:ignore="MissingTranslation">
   <string-array name="preference_language_keys">
+    <item>@null</item>
     <item>en</item>
     <item>nl</item>
     <item>de</item>
@@ -290,6 +291,7 @@
     <item>test</item>
   </string-array>
   <string-array name="preference_language_local_names">
+    <item>System Language</item>
     <item>English</item>
     <item>Nederlands</item>
     <item>Deutsch</item>
@@ -579,6 +581,7 @@
     <item>Test</item>
   </string-array>
   <string-array name="preference_language_canonical_names">
+    <item>System Language</item>
     <item>English</item>
     <item>Dutch</item>
     <item>German</item>
diff --git a/wikipedia/src/main/java/org/wikipedia/Site.java 
b/wikipedia/src/main/java/org/wikipedia/Site.java
index df0ddfb..dffac1f 100644
--- a/wikipedia/src/main/java/org/wikipedia/Site.java
+++ b/wikipedia/src/main/java/org/wikipedia/Site.java
@@ -10,18 +10,26 @@
  */
 public class Site implements Parcelable {
     private final String domain;
+
     private final String language;
 
     public Site(String domain) {
-        this(domain, domain.split("\\.")[0]);
+        this(domain, urlToLanguage(domain));
     }
+
     public Site(String domain, String language) {
-        this.domain = domain.replaceFirst("\\.m\\.", ".");
+        this.domain = urlToDesktopSite(domain);
         this.language = language;
     }
 
     public Site(Parcel in) {
-        this(in.readString());
+        this(in.readString(), in.readString());
+    }
+
+    @Override
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeString(domain);
+        dest.writeString(language);
     }
 
     public String getScriptPath(String script) {
@@ -29,11 +37,11 @@
     }
 
     public String getResourceLoaderPath() {
-        return "https://bits.wikimedia.org/"; + language + 
".wikipedia.org/load.php";
+        return "https://bits.wikimedia.org/"; + getLanguage() + 
".wikipedia.org/load.php";
     }
 
     public String getApiDomain() {
-        return WikipediaApp.getInstance().getSslFallback() ? domain : 
domain.replaceFirst("\\.", ".m.");
+        return WikipediaApp.getInstance().getSslFallback() ? domain : 
urlToMobileSite(domain);
     }
 
     public boolean getUseSecure() {
@@ -49,11 +57,6 @@
         return 0;
     }
 
-    @Override
-    public void writeToParcel(Parcel dest, int flags) {
-        dest.writeString(domain);
-    }
-
     public static final Parcelable.Creator<Site> CREATOR
             = new Parcelable.Creator<Site>() {
         public Site createFromParcel(Parcel in) {
@@ -65,24 +68,39 @@
         }
     };
 
+    // Auto-generated
     @Override
     public boolean equals(Object o) {
-        if (!(o instanceof Site)) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
             return false;
         }
 
-        return ((Site)o).getDomain().equals(domain);
+        Site site = (Site) o;
+
+        if (domain != null ? !domain.equals(site.domain) : site.domain != 
null) {
+            return false;
+        }
+        return !(language != null ? !language.equals(site.language) : 
site.language != null);
+
     }
 
+    // Auto-generated
     @Override
     public int hashCode() {
-        return domain.hashCode();
+        int result = domain != null ? domain.hashCode() : 0;
+        result = 31 * result + (language != null ? language.hashCode() : 0);
+        return result;
     }
 
+    // Auto-generated
     @Override
     public String toString() {
         return "Site{"
                 + "domain='" + domain + '\''
+                + ", language='" + language + '\''
                 + '}';
     }
 
@@ -120,8 +138,8 @@
         return language;
     }
 
-    public static Site forLang(String lang) {
-        return new Site(lang + ".wikipedia.org", lang);
+    public static Site forLanguage(String language) {
+        return new Site(languageToWikiSubdomain(language) + ".wikipedia.org", 
language);
     }
 
     /**
@@ -132,4 +150,26 @@
     public static boolean isSupportedSite(String domain) {
         return domain.matches("[a-z\\-]+\\.(m\\.)?wikipedia\\.org");
     }
+
+    private static String urlToLanguage(String url) {
+        return url.split("\\.")[0];
+    }
+
+    private String urlToDesktopSite(String url) {
+        return url.replaceFirst("\\.m\\.", ".");
+    }
+
+    private String urlToMobileSite(String url) {
+        return url.replaceFirst("\\.", ".m.");
+    }
+
+    private static String languageToWikiSubdomain(String language) {
+        switch (language) {
+            case "zh-hans":
+            case "zh-hant":
+                return "zh";
+            default:
+                return language;
+        }
+    }
 }
diff --git a/wikipedia/src/main/java/org/wikipedia/WikipediaApp.java 
b/wikipedia/src/main/java/org/wikipedia/WikipediaApp.java
index 4fd6d5a..7494b63 100644
--- a/wikipedia/src/main/java/org/wikipedia/WikipediaApp.java
+++ b/wikipedia/src/main/java/org/wikipedia/WikipediaApp.java
@@ -8,6 +8,7 @@
 import android.graphics.drawable.Drawable;
 import android.os.Build;
 import android.preference.PreferenceManager;
+import android.support.annotation.Nullable;
 import android.text.TextUtils;
 import android.view.Window;
 import android.webkit.WebView;
@@ -43,6 +44,7 @@
 import org.wikipedia.zero.WikipediaZeroHandler;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
@@ -56,7 +58,7 @@
         resDialogCommentPrompt = R.string.acra_report_dialog_comment,
         mailTo = "mobile-android-wikipedia-cras...@wikimedia.org")
 public class WikipediaApp extends Application {
-    private static final String FALLBACK_WIKI_LANG_CODE = "en"; // Must exist 
in preference_language_keys.
+    private static final String FALLBACK_LANGUAGE = "en"; // Must exist in 
preference_language_keys.
     private static final String HTTPS_PROTOCOL = "https";
 
     private float screenDensity;
@@ -109,9 +111,26 @@
         return releaseType;
     }
 
-    private List<String> wikiCodes;
+    // Language codes for all supported languages in fixed order.
+    @Nullable
+    private List<String> supportedLanguages;
 
-    private List<String> languageMruList;
+    // English names for all supported languages in fixed order.
+    @Nullable
+    private String[] supportedLanguageCanonicalNames;
+
+    // Native names for all supported languages in fixed order.
+    @Nullable
+    private String[] supportedLanguageLocalNames;
+
+    // Language codes that have been explicitly chosen by the user in most 
recently used order.
+    @Nullable
+    private List<String> mruLanguages;
+
+    // The primary language code used by the app when the page language is 
unspecified. Null is a
+    // special value that indicates the system language should used.
+    @Nullable
+    private String language;
 
     private SessionFunnel sessionFunnel;
     public SessionFunnel getSessionFunnel() {
@@ -200,7 +219,6 @@
         return bus;
     }
 
-
     private String userAgent;
     public String getUserAgent() {
         if (userAgent == null) {
@@ -221,7 +239,7 @@
      */
     public String getAcceptLanguage() {
         // https://lists.wikimedia.org/pipermail/mobile-l/2014-July/007514.html
-        String primaryAppLanguage = getPrimaryLanguage();
+        String primaryAppLanguage = getLanguage();
         String acceptLanguage = primaryAppLanguage;
         Locale defaultLocale = Locale.getDefault();
         String wikiLanguage = 
Utils.langCodeToWikiLang(defaultLocale.getLanguage());
@@ -285,7 +303,7 @@
         // that with *this* platform, which does not do this for some reason 
(possibly on side effect free
         // method invocation theory. But given that up until now we haven't 
been adding the Accept-Language
         // header manually on this platform, we don't want to just arbitrarily 
start doing so for *all* requests.
-        if (!acceptLanguage.equals(getPrimaryLanguage())) {
+        if (!acceptLanguage.equals(getLanguage())) {
             customHeaders.put("Accept-Language", acceptLanguage);
         }
 
@@ -313,7 +331,7 @@
      */
     public Site getPrimarySite() {
         if (primarySite == null) {
-            primarySite = Site.forLang(getPrimaryLanguage());
+            primarySite = Site.forLanguage(getLanguage());
         }
 
         return primarySite;
@@ -328,28 +346,31 @@
         return getAPIForSite(getPrimarySite());
     }
 
-    private String primaryLanguage;
-    public String getPrimaryLanguage() {
-        if (primaryLanguage == null) {
-            primaryLanguage = 
prefs.getString(PrefKeys.getContentLanguageKey(), null);
-            if (primaryLanguage == null) {
-                // No preference set!
-                String wikiCode = 
Utils.langCodeToWikiLang(Locale.getDefault().getLanguage());
-                if (!isWikiLanguage(wikiCode)) {
-                    wikiCode = FALLBACK_WIKI_LANG_CODE; // fallback, see 
comments in #findWikiIndex
-                }
-                return wikiCode;
-            }
+    public Locale getLocale() {
+        return new Locale(getLanguage());
+    }
+
+    /** In general, this value should not be cached as it may change outside 
the app. */
+    public String getLanguage() {
+        return isSystemLanguage() ? getSystemOrFallbackLanguage() : language;
+    }
+
+    public String getLanguageKey() {
+        if (language == null) {
+            language = prefs.getString(PrefKeys.getContentLanguageKey(), null);
         }
-        return primaryLanguage;
+        return language;
     }
 
-    public void setPrimaryLanguage(String language) {
-        primaryLanguage = language;
+    public void setLanguage(String language) {
+        this.language = language;
         prefs.edit().putString(PrefKeys.getContentLanguageKey(), 
language).apply();
-        primarySite = null;
+        resetSite();
     }
 
+    public boolean isSystemLanguage() {
+        return getLanguageKey() == null;
+    }
 
     private DBOpenHelper dbOpenHelper;
     public DBOpenHelper getDbOpenHelper() {
@@ -381,25 +402,30 @@
         return persisters.get(cls.getCanonicalName());
     }
 
-    public int findWikiIndex(String wikiCode) {
-        int index = getWikiCodes().indexOf(wikiCode);
+    public int findSupportedLanguageIndex() {
+        return findSupportedLanguageIndex(getLanguageKey());
+    }
+
+    public int findSupportedLanguageIndex(String language) {
+        int index = getSupportedLanguages().indexOf(language);
         if (index == -1) {
             // FIXME: Instrument this with EL to find out what is happening on 
places where there is a lang we can't find
             // In the meantime, just fall back to en. See 
https://bugzilla.wikimedia.org/show_bug.cgi?id=66140
-            return findWikiIndex(FALLBACK_WIKI_LANG_CODE);
+            return findSupportedLanguageIndex(FALLBACK_LANGUAGE);
         }
         return index;
     }
 
-    private boolean isWikiLanguage(String lang) {
-        return getWikiCodes().contains(lang);
+    private boolean isSupportedLanguage(String language) {
+       return getSupportedLanguages().contains(language);
     }
 
-    private List<String> getWikiCodes() {
-        if (wikiCodes == null) {
-            wikiCodes = 
Arrays.asList(getResources().getStringArray(R.array.preference_language_keys));
+    /** @return Immutable list. */
+    public List<String> getSupportedLanguages() {
+        if (supportedLanguages == null) {
+            supportedLanguages = 
Arrays.asList(getResources().getStringArray(R.array.preference_language_keys));
         }
-        return wikiCodes;
+        return supportedLanguages;
     }
 
     private RemoteConfig remoteConfig;
@@ -410,20 +436,18 @@
         return remoteConfig;
     }
 
-    private String[] canonicalNames;
-    public String canonicalNameFor(int index) {
-        if (canonicalNames == null) {
-            canonicalNames = 
getResources().getStringArray(R.array.preference_language_canonical_names);
+    public String getCanonicalNameForSupportedLanguage(int index) {
+        if (supportedLanguageCanonicalNames == null) {
+            supportedLanguageCanonicalNames = 
getResources().getStringArray(R.array.preference_language_canonical_names);
         }
-        return canonicalNames[index];
+        return supportedLanguageCanonicalNames[index];
     }
 
-    private String[] localNames;
-    public String localNameFor(int index) {
-        if (localNames == null) {
-            localNames = 
getResources().getStringArray(R.array.preference_language_local_names);
+    public String getLocalNameForSupportedLanguage(int index) {
+        if (supportedLanguageLocalNames == null) {
+            supportedLanguageLocalNames = 
getResources().getStringArray(R.array.preference_language_local_names);
         }
-        return localNames[index];
+        return supportedLanguageLocalNames[index];
     }
 
     private EditTokenStorage editTokenStorage;
@@ -600,31 +624,58 @@
         return prefs.getBoolean(PrefKeys.getEventLoggingEnabled(), true);
     }
 
-    public List<String> getLanguageMruList() {
-        lazyInitLanguageMruList();
-        return languageMruList;
+    public List<String> getMruLanguages() {
+        if (mruLanguages == null) {
+            mruLanguages = unmarshalMruLanguages();
+        }
+        return mruLanguages;
     }
 
-    public void addLanguageToMruList(String langCode) {
-        lazyInitLanguageMruList();
-        languageMruList.remove(langCode);
-        languageMruList.add(0, langCode);
-        prefs.edit().putString(PrefKeys.getLanguageMru(), TextUtils.join(",", 
languageMruList)).apply();
+    public void setMruLanguage(String language) {
+        List<String> languages = getMruLanguages();
+        languages.remove(language);
+        languages.add(0, language);
+        prefs.edit().putString(PrefKeys.getLanguageMru(), 
listToCsv(languages)).apply();
     }
 
     public boolean showImages() {
         return prefs.getBoolean(PrefKeys.getShowImages(), true);
     }
 
-    private void lazyInitLanguageMruList() {
-        if (languageMruList == null) {
-            languageMruList = new ArrayList<>();
-            String mruString = prefs.getString(PrefKeys.getLanguageMru(), 
getPrimaryLanguage());
-            languageMruList.addAll(csvToList(mruString));
-        }
+    private List<String> unmarshalMruLanguages() {
+        String nullString = String.valueOf((Object) null);
+        String csv = prefs.getString(PrefKeys.getLanguageMru(), nullString);
+
+        List<String> list = new ArrayList<>(csvToList(csv));
+
+        // Null value is used to indicate that system language should be used.
+        Collections.replaceAll(list, nullString, null);
+
+        return list;
     }
 
-    private List<String> csvToList(String commaDelimitedString) {
-        return Arrays.asList(commaDelimitedString.split(","));
+    private String listToCsv(List<String> list) {
+        return TextUtils.join(",", list);
+    }
+
+    /** @return Immutable list. */
+    private List<String> csvToList(String csv) {
+        return Arrays.asList(csv.split(","));
+    }
+
+    public void resetSite() {
+        primarySite = null;
+    }
+
+    private String getSystemOrFallbackLanguage() {
+        String lang = Utils.langCodeToWikiLang(getSystemLanguage());
+        if (!isSupportedLanguage(lang)) {
+            lang = FALLBACK_LANGUAGE; // See comments in 
#findSupportedLanguageIndex().
+        }
+        return lang;
+    }
+
+    private String getSystemLanguage() {
+        return Locale.getDefault().getLanguage();
     }
 }
diff --git 
a/wikipedia/src/main/java/org/wikipedia/editing/EditPreviewFragment.java 
b/wikipedia/src/main/java/org/wikipedia/editing/EditPreviewFragment.java
index 7dce655..c8646ae 100644
--- a/wikipedia/src/main/java/org/wikipedia/editing/EditPreviewFragment.java
+++ b/wikipedia/src/main/java/org/wikipedia/editing/EditPreviewFragment.java
@@ -80,7 +80,7 @@
         AssetManager assets = oldResources.getAssets();
         DisplayMetrics metrics = oldResources.getDisplayMetrics();
         Locale oldLocale = oldResources.getConfiguration().locale;
-        Locale newLocale = new 
Locale(WikipediaApp.getInstance().getPrimaryLanguage());
+        Locale newLocale = WikipediaApp.getInstance().getLocale();
         Configuration config = new 
Configuration(oldResources.getConfiguration());
         Resources tempResources = getResources();
         if (!oldLocale.getLanguage().equals(newLocale.getLanguage())) {
diff --git 
a/wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksActivity.java 
b/wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksActivity.java
index a40fee2..3f95e74 100644
--- a/wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksActivity.java
+++ b/wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksActivity.java
@@ -20,7 +20,6 @@
 import org.wikipedia.page.PageActivity;
 
 import java.util.ArrayList;
-import java.util.List;
 
 public class LangLinksActivity extends ThemedActionBarActivity {
     public static final int ACTIVITY_RESULT_LANGLINK_SELECT = 1;
@@ -79,7 +78,7 @@
             @Override
             public void onItemClick(AdapterView<?> parent, View view, int 
position, long id) {
                 PageTitle langLink = (PageTitle) 
parent.getAdapter().getItem(position);
-                app.addLanguageToMruList(langLink.getSite().getLanguage());
+                app.setMruLanguage(langLink.getSite().getLanguage());
                 HistoryEntry historyEntry = new HistoryEntry(langLink, 
HistoryEntry.SOURCE_LANGUAGE_LINK);
                 Intent intent = new Intent();
                 intent.setClass(LangLinksActivity.this, PageActivity.class);
@@ -155,12 +154,11 @@
                 public void onFinish(ArrayList<PageTitle> result) {
                     langLinks = result;
 
-                    List<String> mru = app.getLanguageMruList();
                     // Rearrange language list based on the mru list
                     int addIndex = 0;
-                    for (String langCode : mru) {
+                    for (String language : app.getMruLanguages()) {
                         for (int i = 0; i < result.size(); i++) {
-                            if 
(langLinks.get(i).getSite().getLanguage().equals(langCode)) {
+                            if 
(langLinks.get(i).getSite().getLanguage().equals(language)) {
                                 PageTitle preferredLink = langLinks.remove(i);
                                 langLinks.add(addIndex++, preferredLink);
                                 break;
@@ -207,9 +205,9 @@
             this.langLinks.clear();
             filter = filter.toLowerCase();
             for (PageTitle l: origLangLinks) {
-                int langIndex = app.findWikiIndex(l.getSite().getLanguage());
-                String canonicalLang = app.canonicalNameFor(langIndex);
-                String localLang = app.localNameFor(langIndex);
+                int langIndex = 
app.findSupportedLanguageIndex(l.getSite().getLanguage());
+                String canonicalLang = 
app.getCanonicalNameForSupportedLanguage(langIndex);
+                String localLang = 
app.getLocalNameForSupportedLanguage(langIndex);
                 if (canonicalLang.toLowerCase().contains(filter)
                         || localLang.toLowerCase().contains(filter)) {
                     this.langLinks.add(l);
@@ -239,9 +237,9 @@
             }
 
             PageTitle langLink = (PageTitle) getItem(position);
-            String wikiCode = langLink.getSite().getLanguage();
-            int langIndex = app.findWikiIndex(wikiCode);
-            String localName = app.localNameFor(langIndex);
+            String language = langLink.getSite().getLanguage();
+            int langIndex = app.findSupportedLanguageIndex(language);
+            String localName = app.getLocalNameForSupportedLanguage(langIndex);
 
             TextView langLocalNameText = (TextView) 
convertView.findViewById(R.id.language_local_name);
             TextView articleLocalNameText = (TextView) 
convertView.findViewById(R.id.article_local_name);
@@ -252,4 +250,4 @@
             return convertView;
         }
     }
-}
\ No newline at end of file
+}
diff --git 
a/wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksFetchTask.java 
b/wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksFetchTask.java
index 8a6c94e..252aaae 100644
--- 
a/wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksFetchTask.java
+++ 
b/wikipedia/src/main/java/org/wikipedia/interlanguage/LangLinksFetchTask.java
@@ -50,7 +50,7 @@
             JSONObject langlinkJSON = langlinksJSON.optJSONObject(i);
             PageTitle linkTitle = new PageTitle(
                     langlinkJSON.optString("*"),
-                    Site.forLang(langlinkJSON.optString("lang")));
+                    Site.forLanguage(langlinkJSON.optString("lang")));
             linkTitles.add(linkTitle);
         }
 
diff --git 
a/wikipedia/src/main/java/org/wikipedia/migration/ArticleImporter.java 
b/wikipedia/src/main/java/org/wikipedia/migration/ArticleImporter.java
index a0b553a..df3075c 100644
--- a/wikipedia/src/main/java/org/wikipedia/migration/ArticleImporter.java
+++ b/wikipedia/src/main/java/org/wikipedia/migration/ArticleImporter.java
@@ -31,6 +31,6 @@
     }
 
     private PageTitle titleForItem(JSONObject item) {
-        return new PageTitle(null, item.optString("title"), 
Site.forLang(item.optString("lang")));
+        return new PageTitle(null, item.optString("title"), 
Site.forLanguage(item.optString("lang")));
     }
 }
diff --git a/wikipedia/src/main/java/org/wikipedia/page/PageActivity.java 
b/wikipedia/src/main/java/org/wikipedia/page/PageActivity.java
index 664bf7d..df86b85 100644
--- a/wikipedia/src/main/java/org/wikipedia/page/PageActivity.java
+++ b/wikipedia/src/main/java/org/wikipedia/page/PageActivity.java
@@ -67,6 +67,7 @@
     public static final String EXTRA_SEARCH_FROM_WIDGET = "searchFromWidget";
     public static final String EXTRA_FEATURED_ARTICLE_FROM_WIDGET = 
"featuredArticleFromWidget";
     private static final String ZERO_ON_NOTICE_PRESENTED = 
"org.wikipedia.zero.zeroOnNoticePresented";
+    private static final String LANGUAGE_BUNDLE_KEY = "language";
 
     private static final String KEY_LAST_FRAGMENT = "lastFragment";
     private static final String KEY_LAST_FRAGMENT_ARGS = "lastFragmentArgs";
@@ -203,6 +204,7 @@
             Log.w("PageActivity", "Received an unknown parcelable in intent:", 
e);
         }
 
+        boolean languageChanged = false;
         if (savedInstanceState != null) {
             pausedStateOfZero = 
savedInstanceState.getBoolean("pausedStateOfZero");
             pausedMessageOfZero = 
savedInstanceState.getParcelable("pausedMessageOfZero");
@@ -214,6 +216,8 @@
             if (savedInstanceState.getBoolean("isSearching")) {
                 searchFragment.openSearch();
             }
+            String language = 
savedInstanceState.getString(LANGUAGE_BUNDLE_KEY);
+            languageChanged = 
!emptyIfNull(language).equals(emptyIfNull(app.getLanguage()));
         } else if (themeChanged) {
             // we've changed themes!
             pausedStateOfZero = 
getIntent().getExtras().getBoolean("pausedStateOfZero");
@@ -228,6 +232,11 @@
             }
         }
         searchHintText.setText(getString(pausedStateOfZero ? 
R.string.zero_search_hint : R.string.search_hint));
+
+        if (languageChanged) {
+            app.resetSite();
+            displayMainPage();
+        }
 
         // If we're coming back from a Theme change, we'll need to "restore" 
our state based on
         // what's given in our Intent (since there's no way to relaunch the 
Activity in a way that
@@ -590,7 +599,7 @@
      * @param allowStateLoss Whether to allow state loss.
      */
     public void displayMainPage(boolean allowStateLoss) {
-        PageTitle title = new 
PageTitle(MainPageNameData.valueFor(app.getPrimaryLanguage()), 
app.getPrimarySite());
+        PageTitle title = new 
PageTitle(MainPageNameData.valueFor(app.getLanguage()), app.getPrimarySite());
         HistoryEntry historyEntry = new HistoryEntry(title, 
HistoryEntry.SOURCE_MAIN_PAGE);
         displayNewPage(title, historyEntry, allowStateLoss);
     }
@@ -791,6 +800,7 @@
             outState.putBoolean("themeChooserShowing", 
themeChooser.isShowing());
         }
         outState.putBoolean("isSearching", isSearching());
+        outState.putString(LANGUAGE_BUNDLE_KEY, app.getLanguage());
     }
 
     @Override
@@ -878,4 +888,8 @@
         // setTag().
         return mode.getTag() != null;
     }
+
+    private String emptyIfNull(String value) {
+        return value == null ? "" : value;
+    }
 }
diff --git 
a/wikipedia/src/main/java/org/wikipedia/search/SearchResultsFragment.java 
b/wikipedia/src/main/java/org/wikipedia/search/SearchResultsFragment.java
index fa06f7a..2aa97a4 100644
--- a/wikipedia/src/main/java/org/wikipedia/search/SearchResultsFragment.java
+++ b/wikipedia/src/main/java/org/wikipedia/search/SearchResultsFragment.java
@@ -163,7 +163,7 @@
             return;
         }
 
-        List<PageTitle> cacheResult = 
searchResultsCache.get(app.getPrimaryLanguage() + "-" + term);
+        List<PageTitle> cacheResult = searchResultsCache.get(app.getLanguage() 
+ "-" + term);
         if (cacheResult != null) {
             displayResults(cacheResult);
             return;
@@ -220,7 +220,7 @@
                 displayResults(pageTitles);
 
                 // title search special:
-                searchResultsCache.put(app.getPrimaryLanguage() + "-" + 
searchTerm, pageTitles);
+                searchResultsCache.put(app.getLanguage() + "-" + searchTerm, 
pageTitles);
                 curSearchTask = null;
 
                 final String suggestion = results.getSuggestion();
diff --git 
a/wikipedia/src/main/java/org/wikipedia/settings/LanguagePreference.java 
b/wikipedia/src/main/java/org/wikipedia/settings/LanguagePreference.java
index 0a45c59..bc6388e 100644
--- a/wikipedia/src/main/java/org/wikipedia/settings/LanguagePreference.java
+++ b/wikipedia/src/main/java/org/wikipedia/settings/LanguagePreference.java
@@ -18,9 +18,7 @@
 import org.wikipedia.WikipediaApp;
 
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.List;
-import java.util.Locale;
 
 public class LanguagePreference extends DialogPreference {
     private ListView languagesList;
@@ -32,11 +30,10 @@
         super(context, attrs);
         setPersistent(false);
         setDialogLayoutResource(R.layout.dialog_preference_languages);
-        languages = new ArrayList<>();
-        
languages.addAll(Arrays.asList(context.getResources().getStringArray(R.array.preference_language_keys)));
         app = (WikipediaApp) context.getApplicationContext();
+        languages = new ArrayList<>(app.getSupportedLanguages());
 
-        List<String> mru = app.getLanguageMruList();
+        List<String> mru = app.getMruLanguages();
         int addIndex = 0;
         for (String langCode : mru) {
             if (languages.contains(langCode)) {
@@ -45,8 +42,8 @@
             }
         }
 
-        int langIndex = app.findWikiIndex(app.getPrimaryLanguage());
-        setSummary(app.localNameFor(langIndex));
+        int index = app.findSupportedLanguageIndex();
+        setSummary(app.getLocalNameForSupportedLanguage(index));
         setPositiveButtonText(null);
         setNegativeButtonText(null);
     }
@@ -70,18 +67,18 @@
             @Override
             public void onItemClick(AdapterView<?> adapterView, View view, int 
i, long l) {
                 String lang = (String) languagesList.getAdapter().getItem(i);
-                app.setPrimaryLanguage(lang);
-                app.addLanguageToMruList(lang);
-                int langIndex = app.findWikiIndex(app.getPrimaryLanguage());
-                setSummary(app.localNameFor(langIndex));
-                LanguagePreference.this.getDialog().dismiss();
+                app.setLanguage(lang);
+                app.setMruLanguage(lang);
+                int index = app.findSupportedLanguageIndex();
+                setSummary(app.getLocalNameForSupportedLanguage(index));
+                getDialog().dismiss();
             }
         });
 
         languagesList.setAdapter(new LanguagesAdapter(languages, app));
 
-        int selectedLangIndex = languages.indexOf(app.getPrimaryLanguage());
-        languagesList.setItemChecked(selectedLangIndex, true);
+        int selectedLanguageIndex = languages.indexOf(app.getLanguageKey());
+        languagesList.setItemChecked(selectedLanguageIndex, true);
 
         languagesFilter.addTextChangedListener(new TextWatcher() {
             @Override
@@ -101,8 +98,7 @@
     }
 
     public String getCurrentLanguageDisplayString() {
-        Locale locale = new Locale(app.getPrimaryLanguage());
-        return locale.getDisplayLanguage(locale);
+        return app.getLocale().getDisplayLanguage();
     }
 
     private static final class LanguagesAdapter extends BaseAdapter {
@@ -120,14 +116,14 @@
         public void setFilterText(String filter) {
             this.languages.clear();
             filter = filter.toLowerCase();
-            for (String s: originalLanguages) {
-                int langIndex = app.findWikiIndex(s);
-                String canonicalLang = app.canonicalNameFor(langIndex);
-                String localLang = app.localNameFor(langIndex);
-                if (s.contains(filter)
+            for (String language: originalLanguages) {
+                int index = app.findSupportedLanguageIndex(language);
+                String canonicalLang = 
app.getCanonicalNameForSupportedLanguage(index);
+                String localLang = app.getLocalNameForSupportedLanguage(index);
+                if (language != null && language.contains(filter)
                         || canonicalLang.toLowerCase().contains(filter)
                         || localLang.toLowerCase().contains(filter)) {
-                    this.languages.add(s);
+                    this.languages.add(language);
                 }
             }
             notifyDataSetInvalidated();
@@ -159,10 +155,10 @@
 
             String wikiCode = (String) getItem(position);
 
-            int langIndex = app.findWikiIndex(wikiCode);
+            int langIndex = app.findSupportedLanguageIndex(wikiCode);
 
-            localNameText.setText(app.localNameFor(langIndex));
-            nameText.setText(app.canonicalNameFor(langIndex));
+            
localNameText.setText(app.getLocalNameForSupportedLanguage(langIndex));
+            
nameText.setText(app.getCanonicalNameForSupportedLanguage(langIndex));
 
             return convertView;
         }
diff --git 
a/wikipedia/src/main/java/org/wikipedia/widgets/WidgetProviderFeaturedPage.java 
b/wikipedia/src/main/java/org/wikipedia/widgets/WidgetProviderFeaturedPage.java
index 27baa74..723654c 100644
--- 
a/wikipedia/src/main/java/org/wikipedia/widgets/WidgetProviderFeaturedPage.java
+++ 
b/wikipedia/src/main/java/org/wikipedia/widgets/WidgetProviderFeaturedPage.java
@@ -94,7 +94,7 @@
 
     private class FetchMainPageTask extends SectionsFetchTask {
         public FetchMainPageTask(Context context) {
-            super(context, new 
PageTitle(MainPageNameData.valueFor(WikipediaApp.getInstance().getPrimaryLanguage()),
+            super(context, new 
PageTitle(MainPageNameData.valueFor(WikipediaApp.getInstance().getLanguage()),
                     WikipediaApp.getInstance().getPrimarySite()), "all");
         }
 

-- 
To view, visit https://gerrit.wikimedia.org/r/209656
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I3903bdf6b70da560487206f35484af2ce2c677da
Gerrit-PatchSet: 1
Gerrit-Project: apps/android/wikipedia
Gerrit-Branch: master
Gerrit-Owner: Niedzielski <sniedziel...@wikimedia.org>

_______________________________________________
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to