Merge "Browser: add homepage and bookmark feature"
diff --git a/assets/qrd_homepage/en/default_page.html b/assets/qrd_homepage/en/default_page.html
new file mode 100644
index 0000000..1d75dba
--- /dev/null
+++ b/assets/qrd_homepage/en/default_page.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+    <head>
+        <meta name="viewport" content="width=device-width, user-scalable=no" />
+        <meta http-equiv="Content-Type" content="text/html; charset=GB2312">
+        <script type="text/javascript">
+        </script>
+        <style type="text/css">
+        .item{width:170px; height:70px; font-size:22px}
+        .img{width:18px; height:18px;}
+        </style>
+    </head>
+    <body topmargin=90>
+    <p>
+    <table align="center" CellPadding="5" width="10%" height="10%">
+        <tr>
+            <td><button class="item" onClick="default_homepage.loadBookmarks()"><img class="img" src="../images/bookmark.png">&nbsp&nbspBookmark</td>
+        </tr>
+        <tr>
+            <td><button class="item" onClick="default_homepage.loadHistory()"><img class="img" src="../images/history.png">&nbsp&nbspHistory&nbsp&nbsp&nbsp&nbsp</td>
+        </tr>
+    </table>
+    </p>
+    </body>
+</html>
\ No newline at end of file
diff --git a/assets/qrd_homepage/images/bookmark.png b/assets/qrd_homepage/images/bookmark.png
new file mode 100644
index 0000000..b2dab47
--- /dev/null
+++ b/assets/qrd_homepage/images/bookmark.png
Binary files differ
diff --git a/assets/qrd_homepage/images/history.png b/assets/qrd_homepage/images/history.png
new file mode 100644
index 0000000..beaacc7
--- /dev/null
+++ b/assets/qrd_homepage/images/history.png
Binary files differ
diff --git a/assets/qrd_homepage/zh_cn/default_page.html b/assets/qrd_homepage/zh_cn/default_page.html
new file mode 100644
index 0000000..78306e0
--- /dev/null
+++ b/assets/qrd_homepage/zh_cn/default_page.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+    <head>
+        <meta name="viewport" content="width=device-width, user-scalable=no" />
+        <meta http-equiv="Content-Type" content="text/html; charset=GB2312">
+        <script type="text/javascript">
+        </script>
+        <style type="text/css">
+        .item{width:170px; height:70px; font-size:22px}
+        .img{width:18px; height:18px;}
+        </style>
+    </head>
+    <body topmargin=90>
+    <p>
+    <table align="center" CellPadding="5" width="10%" height="10%">
+        <tr>
+            <td><button class="item" onClick="default_homepage.loadBookmarks()"><img class="img" src="../images/bookmark.png">&nbsp&nbspÊé&nbsp&nbsp&nbsp&nbsp&nbsp&nbspÇ©</td>
+        </tr>
+        <tr>
+            <td><button class="item" onClick="default_homepage.loadHistory()"><img class="img" src="../images/history.png">&nbsp&nbspÀúÊ·¼Ç¼</td>
+        </tr>
+    </table>
+    </p>
+    </body>
+</html>
\ No newline at end of file
diff --git a/proguard.flags b/proguard.flags
index 888c238..3a6daef 100644
--- a/proguard.flags
+++ b/proguard.flags
@@ -1,2 +1,6 @@
 # Most of the classes in this package are fragments only referenced from XML
 -keep class com.android.browser.preferences.*
+-keep class com.android.browser.BrowserActivity{
+    public void loadBookmarks();
+    public void loadHistory();
+}
diff --git a/src/com/android/browser/BrowserActivity.java b/src/com/android/browser/BrowserActivity.java
index 4166b11..3ecdcb4 100644
--- a/src/com/android/browser/BrowserActivity.java
+++ b/src/com/android/browser/BrowserActivity.java
@@ -22,6 +22,7 @@
 import android.content.Intent;
 import android.content.res.Configuration;
 import android.os.Bundle;
+import android.os.Handler;
 import android.os.PowerManager;
 import android.util.Log;
 import android.view.ActionMode;
@@ -33,8 +34,11 @@
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.Window;
+import android.webkit.JavascriptInterface;
 
+import com.android.browser.UI.ComboViews;
 import com.android.browser.stub.NullController;
+
 import com.google.common.annotations.VisibleForTesting;
 
 public class BrowserActivity extends Activity {
@@ -50,6 +54,7 @@
     private final static boolean LOGV_ENABLED = Browser.LOGV_ENABLED;
 
     private ActivityController mController = NullController.INSTANCE;
+    private Handler mHandler = new Handler();
 
     @Override
     public void onCreate(Bundle icicle) {
@@ -304,4 +309,29 @@
                 super.dispatchGenericMotionEvent(ev);
     }
 
+    // add for carrier homepage feature
+    @JavascriptInterface
+    public void loadBookmarks() {
+        mHandler.post(new Runnable() {
+            @Override
+            public void run() {
+                if (mController instanceof Controller) {
+                    ((Controller)mController).bookmarksOrHistoryPicker(ComboViews.Bookmarks);
+                }
+            }
+        });
+    }
+
+    // add for carrier homepage feature
+    @JavascriptInterface
+    public void loadHistory() {
+        mHandler.post(new Runnable() {
+            @Override
+            public void run() {
+                if (mController instanceof Controller) {
+                    ((Controller)mController).bookmarksOrHistoryPicker(ComboViews.History);
+                }
+            }
+        });
+    }
 }
diff --git a/src/com/android/browser/BrowserSettings.java b/src/com/android/browser/BrowserSettings.java
index 95afa71..c390ab6 100644
--- a/src/com/android/browser/BrowserSettings.java
+++ b/src/com/android/browser/BrowserSettings.java
@@ -22,14 +22,17 @@
 import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
+import android.content.res.AssetManager;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.os.Build;
 import android.os.Message;
+import android.os.SystemProperties;
 import android.preference.PreferenceManager;
 import android.provider.Browser;
 import android.provider.Settings;
 import android.util.DisplayMetrics;
+import android.util.Log;
 import android.webkit.CookieManager;
 import android.webkit.GeolocationPermissions;
 import android.webkit.WebIconDatabase;
@@ -49,9 +52,11 @@
 import com.android.browser.search.SearchEngine;
 import com.android.browser.search.SearchEngines;
 
+import java.io.InputStream;
 import java.lang.ref.WeakReference;
 import java.util.Iterator;
 import java.util.LinkedList;
+import java.util.Locale;
 import java.util.WeakHashMap;
 
 /**
@@ -129,6 +134,9 @@
 
     private static String sFactoryResetUrl;
 
+    // add for carrier feature
+    private static Context sResPackageCtx;
+
     public static void initialize(final Context context) {
         sInstance = new BrowserSettings(context);
     }
@@ -144,6 +152,16 @@
         mManagedSettings = new LinkedList<WeakReference<WebSettings>>();
         mCustomUserAgents = new WeakHashMap<WebSettings, String>();
         mAutofillHandler.asyncLoadFromDb();
+
+        // add for carrier feature
+        try {
+            sResPackageCtx = context.createPackageContext(
+                "com.android.browser.res",
+                Context.CONTEXT_IGNORE_SECURITY);
+        } catch (Exception e) {
+            Log.e("Res_Update", "Create Res Apk Failed");
+        }
+
         BackgroundHandler.execute(mSetup);
     }
 
@@ -225,7 +243,60 @@
                 mPrefs.edit().remove(PREF_TEXT_SIZE).apply();
             }
 
-            sFactoryResetUrl = mContext.getResources().getString(R.string.homepage_base);
+
+            // add for carrier homepage feature
+            String browserRes = SystemProperties.get("persist.env.c.browser.resource", "default");
+            if ("cu".equals(browserRes)) {
+                int resID = sResPackageCtx.getResources().getIdentifier(
+                        "homepage_base", "string", "com.android.browser.res");
+                sFactoryResetUrl = sResPackageCtx.getResources().getString(resID);
+            } else if ("ct".equals(browserRes)) {
+                int resID = sResPackageCtx.getResources().getIdentifier(
+                        "homepage_base", "string", "com.android.browser.res");
+                sFactoryResetUrl = sResPackageCtx.getResources().getString(resID);
+
+                int pathID = sResPackageCtx.getResources().getIdentifier(
+                        "homepage_path", "string", "com.android.browser.res");
+                String path = sResPackageCtx.getResources().getString(pathID);
+                Locale locale = Locale.getDefault();
+                path = path.replace("%y", locale.getLanguage().toLowerCase());
+                path = path.replace("%z", '_'+locale.getCountry().toLowerCase());
+                boolean useCountry = true;
+                boolean useLanguage = true;
+                InputStream is = null;
+                AssetManager am = mContext.getAssets();
+                try {
+                    is = am.open(path);
+                } catch (Exception ignored) {
+                    useCountry = false;
+                    path = sResPackageCtx.getResources().getString(pathID);
+                    path = path.replace("%y", locale.getLanguage().toLowerCase());
+                    path = path.replace("%z", "");
+                    try {
+                        is = am.open(path);
+                    } catch (Exception ignoredlanguage) {
+                        useLanguage = false;
+                    }
+                } finally {
+                    if (is != null) {
+                        try {
+                            is.close();
+                        } catch (Exception ignored) {}
+                    }
+                }
+
+                if (!useCountry && !useLanguage) {
+                    sFactoryResetUrl = sFactoryResetUrl.replace("%y%z", "en");
+                } else {
+                    sFactoryResetUrl = sFactoryResetUrl.replace("%y",
+                            locale.getLanguage().toLowerCase());
+                    sFactoryResetUrl = sFactoryResetUrl.replace("%z", useCountry ?
+                            '_' + locale.getCountry().toLowerCase() : "");
+                }
+            } else {
+                sFactoryResetUrl = mContext.getResources().getString(R.string.homepage_base);
+            }
+
             if (sFactoryResetUrl.indexOf("{CID}") != -1) {
                 sFactoryResetUrl = sFactoryResetUrl.replace("{CID}",
                     BrowserProvider.getClientId(mContext.getContentResolver()));
diff --git a/src/com/android/browser/BrowserWebViewFactory.java b/src/com/android/browser/BrowserWebViewFactory.java
index 66d9e78..441ac6a 100644
--- a/src/com/android/browser/BrowserWebViewFactory.java
+++ b/src/com/android/browser/BrowserWebViewFactory.java
@@ -17,6 +17,7 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.os.SystemProperties;
 import android.util.AttributeSet;
 import android.view.View;
 import android.webkit.WebView;
@@ -61,6 +62,15 @@
                 || pm.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT);
         w.getSettings().setDisplayZoomControls(!supportsMultiTouch);
 
+        // add for carrier homepage feature
+        String browserRes = SystemProperties.get("persist.env.c.browser.resource", "default");
+        if ("ct".equals(browserRes)) {
+            w.getSettings().setJavaScriptEnabled(true);
+            if (mContext instanceof BrowserActivity) {
+                w.addJavascriptInterface(mContext, "default_homepage");
+            }
+        }
+
         // Add this WebView to the settings observer list and update the
         // settings
         final BrowserSettings s = BrowserSettings.getInstance();
diff --git a/src/com/android/browser/TabControl.java b/src/com/android/browser/TabControl.java
index 150ece0..10de8a1 100644
--- a/src/com/android/browser/TabControl.java
+++ b/src/com/android/browser/TabControl.java
@@ -17,6 +17,7 @@
 package com.android.browser;
 
 import android.os.Bundle;
+import android.os.SystemProperties;
 import android.util.Log;
 import android.webkit.WebView;
 
@@ -408,6 +409,22 @@
                     // sNextId to be set correctly.
                     continue;
                 }
+
+                // add for carrier homepage feature
+                // If the webview restore successfully, add javascript interface again.
+                WebView view = t.getWebView();
+                if (view != null) {
+                    String browserRes = SystemProperties.get("persist.env.c.browser.resource",
+                            "default");
+                    if ("ct".equals(browserRes)) {
+                        view.getSettings().setJavaScriptEnabled(true);
+                        if (mController.getActivity() instanceof BrowserActivity) {
+                            view.addJavascriptInterface(mController.getActivity(),
+                                    "default_homepage");
+                        }
+                    }
+                }
+
                 tabMap.put(id, t);
                 // Me must set the current tab before restoring the state
                 // so that all the client classes are set.
diff --git a/src/com/android/browser/provider/BrowserProvider2.java b/src/com/android/browser/provider/BrowserProvider2.java
index 014a32d..9577af6 100644
--- a/src/com/android/browser/provider/BrowserProvider2.java
+++ b/src/com/android/browser/provider/BrowserProvider2.java
@@ -36,6 +36,7 @@
 import android.database.sqlite.SQLiteOpenHelper;
 import android.database.sqlite.SQLiteQueryBuilder;
 import android.net.Uri;
+import android.os.SystemProperties;
 import android.provider.BaseColumns;
 import android.provider.Browser;
 import android.provider.Browser.BookmarkColumns;
@@ -52,6 +53,7 @@
 import android.provider.ContactsContract.RawContacts;
 import android.provider.SyncStateContract;
 import android.text.TextUtils;
+import android.util.Log;
 
 import com.android.browser.R;
 import com.android.browser.UrlUtils;
@@ -68,6 +70,8 @@
 
 public class BrowserProvider2 extends SQLiteContentProvider {
 
+    private static final String TAG = "BrowserProvider2";
+
     public static final String PARAM_GROUP_BY = "groupBy";
     public static final String PARAM_ALLOW_EMPTY_ACCOUNTS = "allowEmptyAccounts";
 
@@ -651,6 +655,11 @@
             db.insertOrThrow(TABLE_BOOKMARKS, null, values);
 
             addDefaultBookmarks(db, FIXED_ID_ROOT);
+            // add for carrier bookmark feature
+            String browserRes = SystemProperties.get("persist.env.c.browser.resource", "default");
+            if ("ct".equals(browserRes)) {
+                addDefaultCarrierBookmarks(db, FIXED_ID_ROOT);
+            }
         }
 
         private void addDefaultBookmarks(SQLiteDatabase db, long parentId) {
@@ -710,6 +719,91 @@
             }
         }
 
+        // add for carrier bookmark feature
+        private void addDefaultCarrierBookmarks(SQLiteDatabase db, long parentId) {
+            Context mResPackageCtx = null;
+            try {
+                mResPackageCtx = getContext().createPackageContext(
+                    "com.android.browser.res",
+                    Context.CONTEXT_IGNORE_SECURITY);
+            } catch (Exception e) {
+                Log.e(TAG, "Create Res Apk Failed");
+            }
+            if (mResPackageCtx == null)
+                return;
+
+            CharSequence[] bookmarks = null;
+            TypedArray preloads = null;
+            Resources res = mResPackageCtx.getResources();
+            int resBookmarksID = res.getIdentifier("bookmarks", "array", "com.android.browser.res");
+            int resPreloadsID = res.getIdentifier("bookmark_preloads", "array",
+                    "com.android.browser.res");
+            if (resBookmarksID != 0 && resPreloadsID != 0) {
+                bookmarks = res.getTextArray(resBookmarksID);
+                preloads = res.obtainTypedArray(resPreloadsID);
+            } else {
+                return;
+            }
+
+            // The Default Carrier bookmarks size
+            int size = bookmarks.length;
+
+            // googleSize the Default Google bookmarks size.
+            // The Default Carrier Bookmarks original position need move to googleSize index.
+            final CharSequence[] googleBookmarks = getContext().getResources().getTextArray(
+                    R.array.bookmarks);
+            int googleSize = googleBookmarks.length;
+            try {
+                String parent = Long.toString(parentId);
+                String now = Long.toString(System.currentTimeMillis());
+                for (int i = 0; i < size; i = i + 2) {
+                    CharSequence bookmarkDestination = replaceSystemPropertyInString(getContext(),
+                            bookmarks[i + 1]);
+                    db.execSQL("INSERT INTO bookmarks (" +
+                            Bookmarks.TITLE + ", " +
+                            Bookmarks.URL + ", " +
+                            Bookmarks.IS_FOLDER + "," +
+                            Bookmarks.PARENT + "," +
+                            Bookmarks.POSITION + "," +
+                            Bookmarks.DATE_CREATED +
+                        ") VALUES (" +
+                            "'" + bookmarks[i] + "', " +
+                            "'" + bookmarkDestination + "', " +
+                            "0," +
+                            parent + "," +
+                            Integer.toString(googleSize + i) + "," +
+                            now +
+                            ");");
+
+                    int faviconId = preloads.getResourceId(i, 0);
+                    int thumbId = preloads.getResourceId(i + 1, 0);
+                    byte[] thumb = null, favicon = null;
+                    try {
+                        thumb = readRaw(res, thumbId);
+                    } catch (IOException e) {
+                    }
+                    try {
+                        favicon = readRaw(res, faviconId);
+                    } catch (IOException e) {
+                    }
+                    if (thumb != null || favicon != null) {
+                        ContentValues imageValues = new ContentValues();
+                        imageValues.put(Images.URL, bookmarkDestination.toString());
+                        if (favicon != null) {
+                            imageValues.put(Images.FAVICON, favicon);
+                        }
+                        if (thumb != null) {
+                            imageValues.put(Images.THUMBNAIL, thumb);
+                        }
+                        db.insert(TABLE_IMAGES, Images.FAVICON, imageValues);
+                    }
+                }
+            } catch (ArrayIndexOutOfBoundsException e) {
+            } finally {
+                preloads.recycle();
+            }
+        }
+
         private byte[] readRaw(Resources res, int id) throws IOException {
             if (id == 0) {
                 return null;