Add a power saving mode setting

Create a setting that tunes performance optimizations and improves the
power usage.
Automatically tune mode with the Power-saving mode of Android Lollipop+.
Also, when the phone drops below threshold for low battery, prompt user
to turn browser's power save mode on.

Change-Id: I64089a371de562f9a18c297eb09555733f020515
diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml
index d04560a..ad0b750 100644
--- a/res/values-zh-rCN/strings.xml
+++ b/res/values-zh-rCN/strings.xml
@@ -150,6 +150,8 @@
     <string name="pref_do_not_track">"不跟踪"</string>
     <string name="pref_do_not_track_summary">"随浏览流量发送"请勿跟踪"请求"</string>
     <string name="pref_sample_font_size">"拖动该滑块,将文字调整到适合您阅读的大小。点按两次某段落后,文字至少应该显示为这样的字体大小。"</string>
+    <string name="pref_powersave_enabled">"省电模式"</string>
+    <string name="pref_powersave_enabled_summary">"开启省电模式"</string>
 
   <string-array name="pref_content_plugins_choices">
     <item msgid="6745108155096660725">"始终启用(打开)"</item>
diff --git a/res/values-zh-rHK/strings.xml b/res/values-zh-rHK/strings.xml
index 57d9092..587921c 100644
--- a/res/values-zh-rHK/strings.xml
+++ b/res/values-zh-rHK/strings.xml
@@ -145,7 +145,8 @@
     <string name="ssl_certificate">安全性憑證</string>
     <string name="ssl_certificate_is_valid">此憑證有效。</string>
     <string name="pref_memory_monitor">啟用記憶體監察器</string>
-
+    <string name="pref_powersave_enabled">"省電模式"</string>
+    <string name="pref_powersave_enabled_summary">"開啟省電模式"</string>
 
   <string-array name="pref_content_plugins_choices">
     <item msgid="6745108155096660725">"永遠開啟"</item>
diff --git a/res/values-zh-rTW/strings.xml b/res/values-zh-rTW/strings.xml
index 2fa98a5..3ff6708 100644
--- a/res/values-zh-rTW/strings.xml
+++ b/res/values-zh-rTW/strings.xml
@@ -136,6 +136,11 @@
     <string name="pref_content_javascript" msgid="4570972030299516843">"啟用 JavaScript"</string>
     <string name="pref_content_open_in_background" msgid="824123779725118663">"在背景中開啟"</string>
     <string name="pref_content_plugins" msgid="7231944644794301582">"啟用外掛程式"</string>
+
+    <!-- Custom Translations -->
+    <string name="pref_powersave_enabled">"省電模式"</string>
+    <string name="pref_powersave_enabled_summary">"開啟省電模式"</string>
+
   <string-array name="pref_content_plugins_choices">
     <item msgid="6745108155096660725">"永遠開啟"</item>
     <item msgid="2484126708670016519">"隨選"</item>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index cc63a70..62b31d7 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -380,6 +380,11 @@
     <!-- Settings category for autofill under general. [CHAR-LIMIT=50] -->
     <string name="pref_general_autofill_title">Auto-fill</string>
 
+    <!-- Checkbox setting for enabling/disabling power save mode feature -->
+    <string name ="pref_powersave_enabled">Power save mode</string>
+    <!-- Settings summary for the powersave feature. -->
+    <string name ="pref_powersave_enabled_summary">Turn on power saving mode</string>
+
     <!-- Checkbox setting for enabling/disabling the form AutoFill feature [CHAR-LIMIT=32] -->
     <string name="pref_autofill_enabled">Form auto-fill</string>
     <!-- Settings summary for the form AutoFill feature. [CHAR-LIMIT=none] -->
diff --git a/res/xml/general_preferences.xml b/res/xml/general_preferences.xml
index a1f2d25..d0bf533 100644
--- a/res/xml/general_preferences.xml
+++ b/res/xml/general_preferences.xml
@@ -37,6 +37,12 @@
             android:title="@string/pref_lab_fullscreen" />
 
         <CheckBoxPreference
+            android:defaultValue="false"
+            android:key="powersave_enabled"
+            android:summary="@string/pref_powersave_enabled_summary"
+            android:title="@string/pref_powersave_enabled" />
+
+        <CheckBoxPreference
             android:key="autofill_enabled"
             android:title="@string/pref_autofill_enabled"
             android:summary="@string/pref_autofill_enabled_summary"
diff --git a/src/com/android/browser/BrowserSettings.java b/src/com/android/browser/BrowserSettings.java
index e3d1ee5..864315a 100644
--- a/src/com/android/browser/BrowserSettings.java
+++ b/src/com/android/browser/BrowserSettings.java
@@ -774,6 +774,14 @@
         mPrefs.edit().putBoolean(PREF_AUTOFILL_ENABLED, value).apply();
     }
 
+    public boolean isPowerSaveModeEnabled() {
+        return mPrefs.getBoolean(PREF_POWERSAVE_ENABLED, false);
+    }
+
+    public void setPowerSaveModeEnabled(boolean value) {
+        mPrefs.edit().putBoolean(PREF_POWERSAVE_ENABLED, value).apply();
+    }
+
     // -----------------------------
     // getter/setters for debug_preferences.xml
     // -----------------------------
diff --git a/src/com/android/browser/Controller.java b/src/com/android/browser/Controller.java
index 353fea9..07f2d12 100644
--- a/src/com/android/browser/Controller.java
+++ b/src/com/android/browser/Controller.java
@@ -1,6 +1,8 @@
 /*
  * Copyright (C) 2010 The Android Open Source Project
  *
+ * Copyright (C) 2015 The Linux Foundation
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
@@ -30,6 +32,7 @@
 import android.content.DialogInterface;
 import android.content.DialogInterface.OnCancelListener;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.res.Configuration;
@@ -255,6 +258,8 @@
     private float mLevel = 0.0f;
     private WebView.HitTestResult mResult;
     private static Bitmap mBookmarkBitmap;
+    private PowerConnectionReceiver mLowPowerReceiver;
+    private PowerConnectionReceiver mPowerChangeReceiver;
 
     public Controller(Activity browser) {
         mActivity = browser;
@@ -398,6 +403,19 @@
                 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
             bookmarksOrHistoryPicker(ComboViews.Bookmarks);
         }
+
+        mLowPowerReceiver = new PowerConnectionReceiver();
+        mPowerChangeReceiver = new PowerConnectionReceiver();
+
+        //always track the android framework's power save mode
+        IntentFilter filter = new IntentFilter();
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+            // Power save mode only exists in Lollipop and above
+            filter.addAction("android.os.action.POWER_SAVE_MODE_CHANGED");
+        }
+        filter.addAction(Intent.ACTION_BATTERY_OKAY);
+        mActivity.registerReceiver(mPowerChangeReceiver, filter);
+
     }
 
     private static class PruneThumbnails implements Runnable {
@@ -748,6 +766,8 @@
 
         WebView.disablePlatformNotifications();
         NfcHandler.unregister(mActivity);
+
+        mActivity.unregisterReceiver(mLowPowerReceiver);
     }
 
     @Override
@@ -797,6 +817,8 @@
         if (current != null && current.hasCrashed) {
             current.replaceCrashView(current.getWebView(), current.getViewContainer());
         }
+
+        mActivity.registerReceiver(mLowPowerReceiver, new IntentFilter(Intent.ACTION_BATTERY_LOW));
     }
 
     private void releaseWakeLock() {
@@ -852,6 +874,8 @@
         mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
         // Destroy all the tabs
         mTabControl.destroy();
+        // Unregister receiver
+        mActivity.unregisterReceiver(mPowerChangeReceiver);
     }
 
     protected boolean isActivityPaused() {
diff --git a/src/com/android/browser/PowerConnectionReceiver.java b/src/com/android/browser/PowerConnectionReceiver.java
new file mode 100644
index 0000000..f68d3fc
--- /dev/null
+++ b/src/com/android/browser/PowerConnectionReceiver.java
@@ -0,0 +1,60 @@
+/* Copyright (c) 2015, The Linux Foundation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *      * Redistributions of source code must retain the above copyright
+ *      notice, this list of conditions and the following disclaimer.
+ *      * Redistributions in binary form must reproduce the above
+ *      copyright notice, this list of conditions and the following
+ *      disclaimer in the documentation and/or other materials provided
+ *      with the distribution.
+ *      * Neither the name of The Linux Foundation nor the names of its
+ *      contributors may be used to endorse or promote products derived
+ *      from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package com.android.browser;
+
+import com.android.browser.preferences.GeneralPreferencesFragment;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.DownloadManager;
+import android.content.ActivityNotFoundException;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.PowerManager;
+
+public class PowerConnectionReceiver extends BroadcastReceiver {
+    static final String POWER_MODE_TOGGLE = "android.os.action.POWER_SAVE_MODE_CHANGED";
+    static final String POWER_OKAY = Intent.ACTION_BATTERY_OKAY;
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        BrowserSettings settings = BrowserSettings.getInstance();
+        String action = intent.getAction();
+        if (POWER_MODE_TOGGLE.equals(action)) {
+            // This feature is only on android L+
+            PowerManager pm = (PowerManager) context.getSystemService(context.POWER_SERVICE);
+            settings.setPowerSaveModeEnabled(pm.isPowerSaveMode());
+        } else if (POWER_OKAY.equals(action)) {
+            settings.setPowerSaveModeEnabled(false);
+        } else {
+            if (settings.isPowerSaveModeEnabled())
+                return;
+            Bundle bundle = new Bundle();
+            bundle.putBoolean("LowPower", true);
+            BrowserPreferencesPage.startPreferenceFragmentExtraForResult((Activity) context, GeneralPreferencesFragment.class.getName(), bundle, 0);
+        }
+    }
+}
diff --git a/src/com/android/browser/PreferenceKeys.java b/src/com/android/browser/PreferenceKeys.java
index f6b37f5..b0c384a 100644
--- a/src/com/android/browser/PreferenceKeys.java
+++ b/src/com/android/browser/PreferenceKeys.java
@@ -60,6 +60,7 @@
     static final String PREF_AUTOFILL_ENABLED = "autofill_enabled";
     static final String PREF_AUTOFILL_PROFILE = "autofill_profile";
     static final String PREF_HOMEPAGE = "homepage";
+    static final String PREF_POWERSAVE_ENABLED = "powersave_enabled";
     static final String PREF_SYNC_WITH_CHROME = "sync_with_chrome";
 
     // ----------------------
diff --git a/src/com/android/browser/preferences/GeneralPreferencesFragment.java b/src/com/android/browser/preferences/GeneralPreferencesFragment.java
index f481e73..8ab79a3 100644
--- a/src/com/android/browser/preferences/GeneralPreferencesFragment.java
+++ b/src/com/android/browser/preferences/GeneralPreferencesFragment.java
@@ -93,6 +93,12 @@
                 PreferenceKeys.PREF_AUTOFILL_PROFILE);
         autofill.setOnPreferenceClickListener(this);
 
+        final Bundle arguments = getArguments();
+        if (arguments != null && arguments.getBoolean("LowPower")) {
+            LowPowerDialogFragment fragment = LowPowerDialogFragment.newInstance();
+            fragment.show(getActivity().getFragmentManager(), "setPowersave dialog");
+        }
+
         //Disable set search engine preference if SEARCH_ENGINE restriction is enabled
         if (SearchEngineRestriction.getInstance().isEnabled()) {
             findPreference("search_engine").setEnabled(false);
@@ -301,4 +307,37 @@
             outState.putString(HOME_PAGE, editText.getText().toString().trim());
         }
     }
+    public static class LowPowerDialogFragment extends DialogFragment {
+        public static LowPowerDialogFragment newInstance() {
+            LowPowerDialogFragment frag = new LowPowerDialogFragment();
+            return frag;
+        }
+
+        @Override
+        public Dialog onCreateDialog(Bundle savedInstanceState) {
+            final BrowserSettings settings = BrowserSettings.getInstance();
+            final AlertDialog dialog = new AlertDialog.Builder(getActivity())
+                    .setPositiveButton(android.R.string.ok, new OnClickListener() {
+                        @Override
+                        public void onClick(DialogInterface dialog, int which) {
+                            settings.setPowerSaveModeEnabled(true);
+                            getActivity().finish();
+                        }
+                    })
+                    .setNegativeButton(android.R.string.cancel, new OnClickListener() {
+                        @Override
+                        public void onClick(DialogInterface dialog, int which) {
+                            dialog.cancel();
+                            getActivity().finish();
+                        }
+                    })
+                    .setTitle(R.string.pref_powersave_enabled_summary)
+                    .create();
+
+            dialog.getWindow().setSoftInputMode(
+                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
+
+            return dialog;
+        }
+    }
 }