blob: 33ef8cec72c8f750849d2b2ce2b1e2189da78155 [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 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
Bijan Amirzada41242f22014-03-21 12:12:18 -070017package com.android.browser;
Michael Kolb8233fac2010-10-26 16:08:53 -070018
Michael Kolb8233fac2010-10-26 16:08:53 -070019import android.app.Activity;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080020
luxiaolb40014b2013-07-19 10:01:43 +080021import android.app.AlertDialog;
John Reck68234a92012-04-19 15:27:12 -070022import android.app.Dialog;
Michael Kolb8233fac2010-10-26 16:08:53 -070023import android.app.DownloadManager;
John Reck68234a92012-04-19 15:27:12 -070024import android.app.ProgressDialog;
Vivek Sekharce2a4832014-03-26 13:26:53 -070025import android.content.Context;
Michael Kolb8233fac2010-10-26 16:08:53 -070026import android.content.ClipboardManager;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070028import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070029import android.content.ContentValues;
John Reck68234a92012-04-19 15:27:12 -070030import android.content.DialogInterface;
31import android.content.DialogInterface.OnCancelListener;
Michael Kolb8233fac2010-10-26 16:08:53 -070032import android.content.Intent;
33import android.content.pm.PackageManager;
34import android.content.pm.ResolveInfo;
35import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070036import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050037import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Mattias Nilsson561d1952011-10-04 10:18:50 +020040import android.database.sqlite.SQLiteException;
Michael Kolb8233fac2010-10-26 16:08:53 -070041import android.graphics.Bitmap;
kaiyiz6e5b3e02013-08-19 20:02:01 +080042import android.graphics.BitmapFactory;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080043import android.graphics.Rect;
kaiyiza016da12013-08-26 17:50:22 +080044import android.net.ConnectivityManager;
45import android.net.NetworkInfo;
Michael Kolb8233fac2010-10-26 16:08:53 -070046import android.net.Uri;
47import android.net.http.SslError;
kaiyiza016da12013-08-26 17:50:22 +080048import android.net.wifi.WifiManager;
kaiyizb7bf1f22013-10-02 11:42:23 +080049import android.net.wifi.ScanResult;
Michael Kolb8233fac2010-10-26 16:08:53 -070050import android.os.AsyncTask;
51import android.os.Bundle;
George Mount387d45d2011-10-07 15:57:53 -070052import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.os.Handler;
54import android.os.Message;
55import android.os.PowerManager;
56import android.os.PowerManager.WakeLock;
Michael Kolb8233fac2010-10-26 16:08:53 -070057import android.provider.ContactsContract;
58import android.provider.ContactsContract.Intents.Insert;
kaiyiza016da12013-08-26 17:50:22 +080059import android.provider.Settings;
Michael Kolb0b129122012-06-04 16:31:58 -070060import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070061import android.text.TextUtils;
62import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080063import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070064import android.view.ActionMode;
65import android.view.ContextMenu;
66import android.view.ContextMenu.ContextMenuInfo;
67import android.view.Gravity;
68import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070069import android.view.Menu;
70import android.view.MenuInflater;
71import android.view.MenuItem;
72import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070073import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070074import android.view.View;
Pankaj Garg7b279f62014-08-12 14:47:18 -070075import android.view.WindowManager;
George Mount387d45d2011-10-07 15:57:53 -070076import android.webkit.MimeTypeMap;
Michael Kolb8233fac2010-10-26 16:08:53 -070077import android.webkit.ValueCallback;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080078import android.webkit.WebChromeClient.CustomViewCallback;
Pankaj Garg49b79252014-11-07 17:33:41 -080079import android.widget.EditText;
Leon Scrogginsac993842011-02-02 12:54:07 -050080import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070081
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080082import org.codeaurora.swe.CookieManager;
83import org.codeaurora.swe.CookieSyncManager;
Pankaj Garg18902562014-12-05 16:18:51 -080084import org.codeaurora.swe.Engine;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080085import org.codeaurora.swe.HttpAuthHandler;
86import org.codeaurora.swe.SslErrorHandler;
87import org.codeaurora.swe.WebSettings;
88import org.codeaurora.swe.WebView;
Vivek Sekhar0e10a202014-09-12 19:13:23 -070089import org.codeaurora.swe.WebBackForwardList;
90import org.codeaurora.swe.WebHistoryItem;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080091
Axesh R. Ajmera34d3f142014-06-30 20:05:36 -070092import com.android.browser.AppAdapter;
Bijan Amirzada41242f22014-03-21 12:12:18 -070093import com.android.browser.R;
94import com.android.browser.IntentHandler.UrlData;
95import com.android.browser.UI.ComboViews;
96import com.android.browser.mynavigation.AddMyNavigationPage;
97import com.android.browser.mynavigation.MyNavigationUtil;
Bijan Amirzada3f04dc72014-06-25 11:48:36 -070098import com.android.browser.platformsupport.Browser;
Bijan Amirzada41242f22014-03-21 12:12:18 -070099import com.android.browser.platformsupport.BrowserContract;
100import com.android.browser.platformsupport.WebAddress;
101import com.android.browser.platformsupport.BrowserContract.Images;
Pankaj Garg18902562014-12-05 16:18:51 -0800102import com.android.browser.preferences.AboutPreferencesFragment;
Bijan Amirzada41242f22014-03-21 12:12:18 -0700103import com.android.browser.provider.BrowserProvider2.Thumbnails;
104import com.android.browser.provider.SnapshotProvider.Snapshots;
105import com.android.browser.reflect.ReflectHelper;
Pankaj Garg49b79252014-11-07 17:33:41 -0800106import com.android.browser.appmenu.AppMenuHandler;
107import com.android.browser.appmenu.AppMenuPropertiesDelegate;
Michael Kolb4bd767d2011-05-27 11:33:55 -0700108
Michael Kolb8233fac2010-10-26 16:08:53 -0700109import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -0700110import java.io.File;
111import java.io.FileOutputStream;
112import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -0700113import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -0700114import java.text.DateFormat;
115import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -0700116import java.util.ArrayList;
George Mount387d45d2011-10-07 15:57:53 -0700117import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -0700118import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800119import java.util.List;
Johan Redestigaa676182012-10-03 13:33:01 +0200120import java.util.Locale;
John Reck26b18322011-06-21 13:08:58 -0700121import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700122
123/**
124 * Controller for browser
125 */
126public class Controller
Pankaj Garg49b79252014-11-07 17:33:41 -0800127 implements WebViewController, UiController, ActivityController,
128 AppMenuPropertiesDelegate {
Michael Kolb8233fac2010-10-26 16:08:53 -0700129
130 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800131 private static final String SEND_APP_ID_EXTRA =
132 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700133 private static final String INCOGNITO_URI = "browser:incognito";
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800134
Vivek Sekharb54614f2014-05-01 19:03:37 -0700135 // Remind switch to data connection if wifi is unavailable
136 private static final int NETWORK_SWITCH_TYPE_OK = 1;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800137
Michael Kolb8233fac2010-10-26 16:08:53 -0700138 // public message ids
139 public final static int LOAD_URL = 1001;
140 public final static int STOP_LOAD = 1002;
141
142 // Message Ids
143 private static final int FOCUS_NODE_HREF = 102;
144 private static final int RELEASE_WAKELOCK = 107;
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -0800145 private static final int UNKNOWN_TYPE_MSG = 109;
Michael Kolb8233fac2010-10-26 16:08:53 -0700146
147 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
148
149 private static final int OPEN_BOOKMARKS = 201;
kaiyiz591110b2013-08-06 17:11:06 +0800150 private static final int OPEN_MENU = 202;
Michael Kolb8233fac2010-10-26 16:08:53 -0700151
152 private static final int EMPTY_MENU = -1;
153
Michael Kolb8233fac2010-10-26 16:08:53 -0700154 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700155 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 final static int PREFERENCES_PAGE = 3;
157 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000158 final static int AUTOFILL_SETUP = 5;
Michael Kolb0b129122012-06-04 16:31:58 -0700159 final static int VOICE_RESULT = 6;
kaiyiz6e5b3e02013-08-19 20:02:01 +0800160 final static int MY_NAVIGATION = 7;
Ben Murdoch8029a772010-11-16 11:58:21 +0000161
Michael Kolb8233fac2010-10-26 16:08:53 -0700162 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
163
164 // As the ids are dynamically created, we can't guarantee that they will
165 // be in sequence, so this static array maps ids to a window number.
166 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
167 { R.id.window_one_menu_id, R.id.window_two_menu_id,
168 R.id.window_three_menu_id, R.id.window_four_menu_id,
169 R.id.window_five_menu_id, R.id.window_six_menu_id,
170 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
171
172 // "source" parameter for Google search through search key
173 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
174 // "source" parameter for Google search through simplily type
175 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
176
George Mount387d45d2011-10-07 15:57:53 -0700177 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700178 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
179
John Reckd7dd9b22011-08-30 09:18:29 -0700180 // A bitmap that is re-used in createScreenshot as scratch space
181 private static Bitmap sThumbnailBitmap;
182
Michael Kolb8233fac2010-10-26 16:08:53 -0700183 private Activity mActivity;
184 private UI mUi;
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700185 private HomepageHandler mHomepageHandler;
186 protected TabControl mTabControl;
Michael Kolb8233fac2010-10-26 16:08:53 -0700187 private BrowserSettings mSettings;
188 private WebViewFactory mFactory;
189
190 private WakeLock mWakeLock;
191
192 private UrlHandler mUrlHandler;
193 private UploadHandler mUploadHandler;
194 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700195 private PageDialogsHandler mPageDialogsHandler;
196 private NetworkStateHandler mNetworkHandler;
197
Ben Murdoch8029a772010-11-16 11:58:21 +0000198 private Message mAutoFillSetupMessage;
199
kaiyiza016da12013-08-26 17:50:22 +0800200 private boolean mNetworkShouldNotify = true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700201
Michael Kolb8233fac2010-10-26 16:08:53 -0700202 // FIXME, temp address onPrepareMenu performance problem.
203 // When we move everything out of view, we should rewrite this.
204 private int mCurrentMenuState = 0;
Kulanthaivel Palanichamy77942682014-10-28 11:52:06 -0700205 private int mMenuState = EMPTY_MENU;
Michael Kolb8233fac2010-10-26 16:08:53 -0700206 private int mOldMenuState = EMPTY_MENU;
207 private Menu mCachedMenu;
208
Michael Kolb8233fac2010-10-26 16:08:53 -0700209 private boolean mMenuIsDown;
210
Pankaj Garg49b79252014-11-07 17:33:41 -0800211 private boolean mWasInPageLoad = false;
212 private AppMenuHandler mAppMenuHandler;
213
Michael Kolb8233fac2010-10-26 16:08:53 -0700214 // For select and find, we keep track of the ActionMode so that
215 // finish() can be called as desired.
216 private ActionMode mActionMode;
217
218 /**
219 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
220 * of whether the configuration has changed. The first onMenuOpened call
221 * after a configuration change is simply a reopening of the same menu
222 * (i.e. mIconView did not change).
223 */
224 private boolean mConfigChanged;
225
226 /**
227 * Keeps track of whether the options menu is open. This is important in
228 * determining whether to show or hide the title bar overlay
229 */
230 private boolean mOptionsMenuOpen;
231
232 /**
233 * Whether or not the options menu is in its bigger, popup menu form. When
234 * true, we want the title bar overlay to be gone. When false, we do not.
235 * Only meaningful if mOptionsMenuOpen is true.
236 */
237 private boolean mExtendedMenuOpen;
238
Michael Kolb8233fac2010-10-26 16:08:53 -0700239 private boolean mActivityPaused = true;
240 private boolean mLoadStopped;
241
242 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500243 // Checks to see when the bookmarks database has changed, and updates the
244 // Tabs' notion of whether they represent bookmarked sites.
245 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700246 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700247
Michael Kolbc3af0672011-08-09 10:24:41 -0700248 private boolean mBlockEvents;
249
Michael Kolb0b129122012-06-04 16:31:58 -0700250 private String mVoiceResult;
kaiyiz6e5b3e02013-08-19 20:02:01 +0800251 private boolean mUpdateMyNavThumbnail;
252 private String mUpdateMyNavThumbnailUrl;
Vivek Sekharb991edb2014-12-17 18:18:07 -0800253 private float mLevel = 0.0f;
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -0800254 private WebView.HitTestResult mResult;
Michael Kolb0b129122012-06-04 16:31:58 -0700255
George Mount3636d0a2011-11-21 09:08:21 -0800256 public Controller(Activity browser) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700257 mActivity = browser;
258 mSettings = BrowserSettings.getInstance();
259 mTabControl = new TabControl(this);
260 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700261 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
George Mount3636d0a2011-11-21 09:08:21 -0800262 mCrashRecoveryHandler.preloadCrashState();
Michael Kolb14612442011-06-24 13:06:29 -0700263 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700264
265 mUrlHandler = new UrlHandler(this);
266 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
268
Michael Kolb8233fac2010-10-26 16:08:53 -0700269 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500270 mBookmarksObserver = new ContentObserver(mHandler) {
271 @Override
272 public void onChange(boolean selfChange) {
273 int size = mTabControl.getTabCount();
274 for (int i = 0; i < size; i++) {
275 mTabControl.getTab(i).updateBookmarkedStatus();
276 }
277 }
278
279 };
280 browser.getContentResolver().registerContentObserver(
281 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700282
283 mNetworkHandler = new NetworkStateHandler(mActivity, this);
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700284 mHomepageHandler = new HomepageHandler(browser, this);
Pankaj Garg49b79252014-11-07 17:33:41 -0800285 mAppMenuHandler = new AppMenuHandler(browser, this, R.menu.browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700286 }
287
John Reck9c35b9c2012-05-30 10:08:50 -0700288 @Override
289 public void start(final Intent intent) {
Kulanthaivel Palanichamy77942682014-10-28 11:52:06 -0700290 mMenuState = R.id.MAIN_MENU;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800291 WebView.setShouldMonitorWebCoreThread();
George Mount3636d0a2011-11-21 09:08:21 -0800292 // mCrashRecoverHandler has any previously saved state.
293 mCrashRecoveryHandler.startRecovery(intent);
John Reck847b5322011-04-14 17:02:18 -0700294 }
295
George Mount3636d0a2011-11-21 09:08:21 -0800296 void doStart(final Bundle icicle, final Intent intent) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800297 // we dont want to ever recover incognito tabs
298 final boolean restoreIncognitoTabs = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700299
Patrick Scott7d50a932011-02-04 09:27:26 -0500300 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700301 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500302 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000303
Michael Kolbc831b632011-05-11 09:30:34 -0700304 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500305 // Not able to restore so we go ahead and clear session cookies. We
306 // must do this before trying to login the user as we don't want to
307 // clear any session cookies set during login.
308 CookieManager.getInstance().removeSessionCookie();
John Reck1cf4b792011-07-26 10:22:22 -0700309 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
George Mount3636d0a2011-11-21 09:08:21 -0800310 if (intent == null) {
311 // This won't happen under common scenarios. The icicle is
312 // not null, but there aren't any tabs to restore.
313 openTabToHomePage();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700314 } else {
George Mount3636d0a2011-11-21 09:08:21 -0800315 final Bundle extra = intent.getExtras();
316 // Create an initial tab.
317 // If the intent is ACTION_VIEW and data is not null, the Browser is
318 // invoked to view the content by another application. In this case,
319 // the tab will be close when exit.
kaiyiz6e5b3e02013-08-19 20:02:01 +0800320 UrlData urlData = null;
321 if (intent.getData() != null
322 && Intent.ACTION_VIEW.equals(intent.getAction())
323 && intent.getData().toString().startsWith("content://")) {
324 urlData = new UrlData(intent.getData().toString());
325 } else {
326 urlData = IntentHandler.getUrlDataFromIntent(intent);
327 }
George Mount3636d0a2011-11-21 09:08:21 -0800328 Tab t = null;
329 if (urlData.isEmpty()) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700330 String landingPage = mActivity.getResources().getString(
331 R.string.def_landing_page);
332 if (!landingPage.isEmpty()) {
333 t = openTab(landingPage, false, true, true);
kaiyiz6e5b3e02013-08-19 20:02:01 +0800334 } else {
335 t = openTabToHomePage();
336 }
George Mount3636d0a2011-11-21 09:08:21 -0800337 } else {
338 t = openTab(urlData);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700339 t.setDerivedFromIntent(true);
George Mount3636d0a2011-11-21 09:08:21 -0800340 }
341 if (t != null) {
342 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
343 }
344 WebView webView = t.getWebView();
345 if (extra != null) {
346 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
347 if (scale > 0 && scale <= 1000) {
348 webView.setInitialScale(scale);
349 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700350 }
351 }
John Reckd8c74522011-06-14 08:45:00 -0700352 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700353 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700354 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500355 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700356 List<Tab> tabs = mTabControl.getTabs();
357 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700358
John Reck1cf4b792011-07-26 10:22:22 -0700359 for (Tab t : tabs) {
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700360 //handle restored pages that may require a JS interface
361 if (t.getWebView() != null) {
362 WebBackForwardList backForwardList = t.getWebView().copyBackForwardList();
363 if (backForwardList != null) {
364 for (int i = 0; i < backForwardList.getSize(); i++) {
365 WebHistoryItem item = backForwardList.getItemAtIndex(i);
366 mHomepageHandler.registerJsInterface( t.getWebView(), item.getUrl());
367 }
368 }
369 }
John Reck1cf4b792011-07-26 10:22:22 -0700370 restoredTabs.add(t.getId());
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700371 if (t != mTabControl.getCurrentTab()) {
372 t.pause();
373 }
John Reck1cf4b792011-07-26 10:22:22 -0700374 }
375 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700376 if (tabs.size() == 0) {
377 openTabToHomePage();
378 }
John Reck1cf4b792011-07-26 10:22:22 -0700379 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700380 // TabControl.restoreState() will create a new tab even if
381 // restoring the state fails.
382 setActiveTab(mTabControl.getCurrentTab());
George Mount3636d0a2011-11-21 09:08:21 -0800383 // Intent is non-null when framework thinks the browser should be
384 // launching with a new intent (icicle is null).
385 if (intent != null) {
John Reck9dd4a412011-10-05 14:55:30 -0700386 mIntentHandler.onNewIntent(intent);
387 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700388 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700389 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700390 String jsFlags = getSettings().getJsEngineFlags();
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800391 if (jsFlags.trim().length() != 0) {
392 getCurrentWebView().setJsFlags(jsFlags);
Michael Kolb8233fac2010-10-26 16:08:53 -0700393 }
George Mount3636d0a2011-11-21 09:08:21 -0800394 if (intent != null
395 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700396 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800397 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700398 }
399
John Reck1cf4b792011-07-26 10:22:22 -0700400 private static class PruneThumbnails implements Runnable {
401 private Context mContext;
402 private List<Long> mIds;
403
404 PruneThumbnails(Context context, List<Long> preserveIds) {
405 mContext = context.getApplicationContext();
406 mIds = preserveIds;
407 }
408
409 @Override
410 public void run() {
411 ContentResolver cr = mContext.getContentResolver();
412 if (mIds == null || mIds.size() == 0) {
413 cr.delete(Thumbnails.CONTENT_URI, null, null);
414 } else {
415 int length = mIds.size();
416 StringBuilder where = new StringBuilder();
417 where.append(Thumbnails._ID);
418 where.append(" not in (");
419 for (int i = 0; i < length; i++) {
420 where.append(mIds.get(i));
421 if (i < (length - 1)) {
422 where.append(",");
423 }
424 }
425 where.append(")");
426 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
427 }
428 }
429
430 }
431
Michael Kolb1514bb72010-11-22 09:11:48 -0800432 @Override
433 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700434 return mFactory;
435 }
436
437 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800438 public void onSetWebView(Tab tab, WebView view) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800439 if (tab.hasCrashed)
440 tab.showCrashView();
441 else
442 mUi.onSetWebView(tab, view);
Michael Kolba713ec82010-11-29 17:27:06 -0800443 }
444
445 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800446 public void createSubWindow(Tab tab) {
447 endActionMode();
448 WebView mainView = tab.getWebView();
449 WebView subView = mFactory.createWebView((mainView == null)
450 ? false
451 : mainView.isPrivateBrowsingEnabled());
452 mUi.createSubWindow(tab, subView);
453 }
454
455 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700456 public Context getContext() {
457 return mActivity;
458 }
459
460 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700461 public Activity getActivity() {
462 return mActivity;
463 }
464
465 void setUi(UI ui) {
466 mUi = ui;
467 }
468
Michael Kolbaf63dba2012-05-16 12:58:05 -0700469 @Override
470 public BrowserSettings getSettings() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700471 return mSettings;
472 }
473
474 IntentHandler getIntentHandler() {
475 return mIntentHandler;
476 }
477
478 @Override
479 public UI getUi() {
480 return mUi;
481 }
482
483 int getMaxTabs() {
484 return mActivity.getResources().getInteger(R.integer.max_tabs);
485 }
486
487 @Override
488 public TabControl getTabControl() {
489 return mTabControl;
490 }
491
Michael Kolb1bf23132010-11-19 12:55:12 -0800492 @Override
493 public List<Tab> getTabs() {
494 return mTabControl.getTabs();
495 }
496
Michael Kolb8233fac2010-10-26 16:08:53 -0700497 private void startHandler() {
498 mHandler = new Handler() {
499
500 @Override
501 public void handleMessage(Message msg) {
502 switch (msg.what) {
503 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700504 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700505 break;
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -0800506 case UNKNOWN_TYPE_MSG:
507 HashMap unknownTypeMap = (HashMap) msg.obj;
508 WebView viewForUnknownType = (WebView) unknownTypeMap.get("webview");
509 /*
510 * When the context menu is shown to the user
511 * we need to assure that its happening on the current webview
512 * and its the current webview only which had sent the UNKNOWN_TYPE_MSG
513 */
514 if (getCurrentWebView() != viewForUnknownType)
515 break;
516
517 String unknown_type_src = (String)msg.getData().get("src");
518 WebView.HitTestResult result = new WebView.HitTestResult();
519
520 //setting the HitTestResult with new RESULT TYPE
521 if (!TextUtils.isEmpty(unknown_type_src)) {
522 result.setType(WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
523 result.setExtra(unknown_type_src);
524 } else {
525 result.setType(WebView.HitTestResult.SRC_ANCHOR_TYPE);
526 result.setExtra("about:blank");
527 }
528
529 mResult = result;
530 openContextMenu(viewForUnknownType);
531 mResult = null;
532
533 break;
534
Michael Kolb8233fac2010-10-26 16:08:53 -0700535 case FOCUS_NODE_HREF:
536 {
537 String url = (String) msg.getData().get("url");
538 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500539 String src = (String) msg.getData().get("src");
540 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700541 if (TextUtils.isEmpty(url)) {
542 break;
543 }
544 HashMap focusNodeMap = (HashMap) msg.obj;
545 WebView view = (WebView) focusNodeMap.get("webview");
546 // Only apply the action if the top window did not change.
547 if (getCurrentTopWebView() != view) {
548 break;
549 }
550 switch (msg.arg1) {
551 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700552 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700553 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500554 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700555 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500556 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500557 case R.id.open_newtab_context_menu_id:
558 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700559 openTab(url, parent,
560 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500561 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700562 case R.id.copy_link_context_menu_id:
563 copy(url);
564 break;
565 case R.id.save_link_context_menu_id:
566 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500567 DownloadHandler.onDownloadStartNoStream(
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800568 mActivity, url, view.getSettings().getUserAgentString(),
569 null, null, null, view.isPrivateBrowsingEnabled(), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -0700570 break;
Tarun Nainani700b69b2014-03-26 16:07:25 -0700571 case R.id.save_link_bookmark_context_menu_id:
Tarun Nainani9f27c612014-04-02 14:34:03 -0700572 if(title == null || title == "")
573 title = url;
574
575 Intent bookmarkIntent = new Intent(mActivity, AddBookmarkPage.class);
576 //SWE TODO: No thumbnail support for the url obtained via
577 //browser context menu as its not loaded in webview.
578 if (bookmarkIntent != null) {
579 bookmarkIntent.putExtra(BrowserContract.Bookmarks.URL, url);
580 bookmarkIntent.putExtra(BrowserContract.Bookmarks.TITLE, title);
581 mActivity.startActivity(bookmarkIntent);
582 }
Tarun Nainani700b69b2014-03-26 16:07:25 -0700583 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700584 }
585 break;
586 }
587
588 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700589 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700590 break;
591
592 case STOP_LOAD:
593 stopLoading();
594 break;
595
596 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700597 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700598 mWakeLock.release();
599 // if we reach here, Browser should be still in the
600 // background loading after WAKELOCK_TIMEOUT (5-min).
601 // To avoid burning the battery, stop loading.
602 mTabControl.stopAllLoading();
603 }
604 break;
605
606 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800607 Tab tab = (Tab) msg.obj;
608 if (tab != null) {
609 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700610 }
611 break;
kaiyiz591110b2013-08-06 17:11:06 +0800612 case OPEN_MENU:
613 if (!mOptionsMenuOpen && mActivity != null ) {
614 mActivity.openOptionsMenu();
615 }
616 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700617 }
618 }
619 };
620
621 }
622
John Reckef654f12011-07-12 16:42:08 -0700623 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200624 public Tab getCurrentTab() {
625 return mTabControl.getCurrentTab();
626 }
627
Michael Kolbba99c5d2010-11-29 14:57:41 -0800628 @Override
629 public void shareCurrentPage() {
630 shareCurrentPage(mTabControl.getCurrentTab());
631 }
632
633 private void shareCurrentPage(Tab tab) {
Tarun Nainaniea28dde2014-08-27 17:25:09 -0700634 if (tab == null || tab.getWebView() == null)
635 return;
636
637 final Tab mytab = tab;
638 final ValueCallback<Bitmap> onScreenshot = new ValueCallback<Bitmap>() {
639 @Override
640 public void onReceiveValue(Bitmap bitmap) {
641 sharePage(mActivity, mytab.getTitle(), mytab.getUrl(),
642 mytab.getFavicon(), bitmap);
643 }
644 };
645
646 createScreenshotAsync(
647 tab.getWebView(),
648 getDesiredThumbnailWidth(mActivity),
649 getDesiredThumbnailHeight(mActivity),
650 new ValueCallback<Bitmap>() {
651 @Override
652 public void onReceiveValue(Bitmap bitmap) {
653 sharePage(mActivity, mytab.getTitle(), mytab.getUrl(),
654 mytab.getFavicon(), bitmap);
655 }
656 });
Michael Kolbba99c5d2010-11-29 14:57:41 -0800657 }
658
Michael Kolb8233fac2010-10-26 16:08:53 -0700659 /**
660 * Share a page, providing the title, url, favicon, and a screenshot. Uses
661 * an {@link Intent} to launch the Activity chooser.
662 * @param c Context used to launch a new Activity.
663 * @param title Title of the page. Stored in the Intent with
664 * {@link Intent#EXTRA_SUBJECT}
665 * @param url URL of the page. Stored in the Intent with
666 * {@link Intent#EXTRA_TEXT}
667 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
668 * with {@link Browser#EXTRA_SHARE_FAVICON}
669 * @param screenshot Bitmap of a screenshot of the page. Stored in the
670 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
671 */
672 static final void sharePage(Context c, String title, String url,
673 Bitmap favicon, Bitmap screenshot) {
Axesh R. Ajmera34d3f142014-06-30 20:05:36 -0700674
675 ShareDialog sDialog = new ShareDialog((Activity)c, title, url, favicon, screenshot);
676 final AppAdapter adapter = new AppAdapter(c, c.getPackageManager(),
677 R.layout.app_row, sDialog.getApps());
678 sDialog.loadView(adapter);
Michael Kolb8233fac2010-10-26 16:08:53 -0700679 }
680
681 private void copy(CharSequence text) {
682 ClipboardManager cm = (ClipboardManager) mActivity
683 .getSystemService(Context.CLIPBOARD_SERVICE);
684 cm.setText(text);
685 }
686
687 // lifecycle
688
John Reck9c35b9c2012-05-30 10:08:50 -0700689 @Override
690 public void onConfgurationChanged(Configuration config) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700691 mConfigChanged = true;
Michael Kolb18f252f2012-03-06 13:36:20 -0800692 // update the menu in case of a locale change
693 mActivity.invalidateOptionsMenu();
Pankaj Garg49b79252014-11-07 17:33:41 -0800694 mAppMenuHandler.hideAppMenu();
kaiyiz591110b2013-08-06 17:11:06 +0800695 if (mOptionsMenuOpen) {
696 mActivity.closeOptionsMenu();
697 mHandler.sendMessageDelayed(mHandler.obtainMessage(OPEN_MENU), 100);
698 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700699 if (mPageDialogsHandler != null) {
700 mPageDialogsHandler.onConfigurationChanged(config);
701 }
702 mUi.onConfigurationChanged(config);
703 }
704
705 @Override
706 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700707 if (!mUi.isWebShowing()) {
708 mUi.showWeb(false);
709 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700710 mIntentHandler.onNewIntent(intent);
711 }
712
John Reck9c35b9c2012-05-30 10:08:50 -0700713 @Override
714 public void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800715 if (mUi.isCustomViewShowing()) {
716 hideCustomView();
717 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700718 if (mActivityPaused) {
719 Log.e(LOGTAG, "BrowserActivity is already paused.");
720 return;
721 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700722 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800723 Tab tab = mTabControl.getCurrentTab();
724 if (tab != null) {
725 tab.pause();
726 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700727 if (mWakeLock == null) {
728 PowerManager pm = (PowerManager) mActivity
729 .getSystemService(Context.POWER_SERVICE);
730 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
731 }
Michael Kolb70976932010-11-30 11:34:01 -0800732 mWakeLock.acquire();
733 mHandler.sendMessageDelayed(mHandler
734 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
735 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700736 }
737 mUi.onPause();
738 mNetworkHandler.onPause();
739
740 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100741 NfcHandler.unregister(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700742 }
743
John Reck9c35b9c2012-05-30 10:08:50 -0700744 @Override
745 public void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700746 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800747 Bundle saveState = createSaveState();
748
749 // crash recovery manages all save & restore state
750 mCrashRecoveryHandler.writeState(saveState);
751 mSettings.setLastRunPaused(true);
752 }
753
754 /**
755 * Save the current state to outState. Does not write the state to
756 * disk.
757 * @return Bundle containing the current state of all tabs.
758 */
759 /* package */ Bundle createSaveState() {
760 Bundle saveState = new Bundle();
761 mTabControl.saveState(saveState);
George Mount3636d0a2011-11-21 09:08:21 -0800762 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700763 }
764
John Reck9c35b9c2012-05-30 10:08:50 -0700765 @Override
766 public void onResume() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700767 if (!mActivityPaused) {
768 Log.e(LOGTAG, "BrowserActivity is already resumed.");
769 return;
770 }
George Mount3636d0a2011-11-21 09:08:21 -0800771 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700772 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800773 Tab current = mTabControl.getCurrentTab();
774 if (current != null) {
775 current.resume();
776 resumeWebViewTimers(current);
777 }
John Reckf57c0292011-07-21 18:15:39 -0700778 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200779
Michael Kolb8233fac2010-10-26 16:08:53 -0700780 mUi.onResume();
781 mNetworkHandler.onResume();
782 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100783 NfcHandler.register(mActivity, this);
Michael Kolb0b129122012-06-04 16:31:58 -0700784 if (mVoiceResult != null) {
785 mUi.onVoiceResult(mVoiceResult);
786 mVoiceResult = null;
787 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800788 if (current != null && current.hasCrashed) {
Vivek Sekhar2868b8d2014-12-03 17:22:50 -0800789 current.replaceCrashView(current.getWebView(), current.getViewContainer());
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800790 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700791 }
792
John Reckf57c0292011-07-21 18:15:39 -0700793 private void releaseWakeLock() {
794 if (mWakeLock != null && mWakeLock.isHeld()) {
795 mHandler.removeMessages(RELEASE_WAKELOCK);
796 mWakeLock.release();
797 }
798 }
799
Michael Kolb70976932010-11-30 11:34:01 -0800800 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800801 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800802 * @param tab guaranteed non-null
803 */
804 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700805 boolean inLoad = tab.inPageLoad();
806 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
807 CookieSyncManager.getInstance().startSync();
808 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100809 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700810 }
811 }
812
Michael Kolb70976932010-11-30 11:34:01 -0800813 /**
814 * Pause all WebView timers using the WebView of the given tab
815 * @param tab
816 * @return true if the timers are paused or tab is null
817 */
818 private boolean pauseWebViewTimers(Tab tab) {
819 if (tab == null) {
820 return true;
821 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700822 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100823 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700824 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700825 }
Michael Kolb70976932010-11-30 11:34:01 -0800826 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700827 }
828
John Reck9c35b9c2012-05-30 10:08:50 -0700829 @Override
830 public void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800831 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700832 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
833 mUploadHandler = null;
834 }
835 if (mTabControl == null) return;
836 mUi.onDestroy();
837 // Remove the current tab and sub window
838 Tab t = mTabControl.getCurrentTab();
839 if (t != null) {
840 dismissSubWindow(t);
841 removeTab(t);
842 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500843 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700844 // Destroy all the tabs
845 mTabControl.destroy();
Michael Kolb8233fac2010-10-26 16:08:53 -0700846 }
847
848 protected boolean isActivityPaused() {
849 return mActivityPaused;
850 }
851
John Reck9c35b9c2012-05-30 10:08:50 -0700852 @Override
853 public void onLowMemory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700854 mTabControl.freeMemory();
855 }
856
857 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700858 public void stopLoading() {
859 mLoadStopped = true;
860 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700861 WebView w = getCurrentTopWebView();
Michael Kolb778a4882012-04-12 15:27:28 -0700862 if (w != null) {
863 w.stopLoading();
864 mUi.onPageStopped(tab);
865 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700866 }
867
868 boolean didUserStopLoading() {
869 return mLoadStopped;
870 }
871
kaiyiza016da12013-08-26 17:50:22 +0800872 private void handleNetworkNotify(WebView view) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700873 final String reminderType = getContext().getResources().getString(
874 R.string.def_wifi_browser_interaction_remind_type);
875 final String selectionConnnection = getContext().getResources().getString(
876 R.string.def_action_wifi_selection_data_connections);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700877 final String wifiSelection = getContext().getResources().getString(
878 R.string.def_intent_pick_network);
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700879
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700880 if (reminderType.isEmpty() || selectionConnnection.isEmpty() ||
881 wifiSelection.isEmpty())
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700882 return;
883
kaiyiza016da12013-08-26 17:50:22 +0800884 ConnectivityManager conMgr = (ConnectivityManager) this.getContext().getSystemService(
Vivek Sekharb54614f2014-05-01 19:03:37 -0700885 Context.CONNECTIVITY_SERVICE);
886 NetworkInfo networkInfo = conMgr.getActiveNetworkInfo();
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700887 WifiManager wifiMgr = (WifiManager) this.getContext()
888 .getSystemService(Context.WIFI_SERVICE);
Vivek Sekharb54614f2014-05-01 19:03:37 -0700889 if (networkInfo == null
890 || (networkInfo != null && (networkInfo.getType() !=
891 ConnectivityManager.TYPE_WIFI))) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700892 int isReminder = Settings.System.getInt(mActivity.getContentResolver(),
893 reminderType, NETWORK_SWITCH_TYPE_OK);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700894 List<ScanResult> list = wifiMgr.getScanResults();
895 // Have no AP's for Wifi's fall back to data
896 if (list != null && list.size() == 0 && isReminder == NETWORK_SWITCH_TYPE_OK) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700897 Intent intent = new Intent(selectionConnnection);
Vivek Sekharb54614f2014-05-01 19:03:37 -0700898 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
899 this.getContext().startActivity(intent);
900 } else {
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700901 // Request to select Wifi AP
902 try {
903 Intent intent = new Intent(wifiSelection);
904 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
905 this.getContext().startActivity(intent);
906 } catch (Exception e) {
907 String err_msg = this.getContext().getString(
908 R.string.acivity_not_found, wifiSelection);
909 Toast.makeText(this.getContext(), err_msg, Toast.LENGTH_LONG).show();
910 }
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700911 }
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700912 mNetworkShouldNotify = false;
kaiyiza016da12013-08-26 17:50:22 +0800913 }
914 }
Vivek Sekharb54614f2014-05-01 19:03:37 -0700915
Michael Kolb8233fac2010-10-26 16:08:53 -0700916 // WebViewController
917
918 @Override
John Reck324d4402011-01-11 16:56:42 -0800919 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700920
921 // We've started to load a new page. If there was a pending message
922 // to save a screenshot then we will now take the new page and save
923 // an incorrect screenshot. Therefore, remove any pending thumbnail
924 // messages from the queue.
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700925 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700926
927 // reset sync timer to avoid sync starts during loading a page
928 CookieSyncManager.getInstance().resetSync();
Vivek Sekharb54614f2014-05-01 19:03:37 -0700929 WifiManager wifiMgr = (WifiManager) this.getContext()
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700930 .getSystemService(Context.WIFI_SERVICE);
Panos Thomas4bdb5252014-11-13 16:20:11 -0800931 boolean networkNotifier = BrowserConfig.getInstance(getContext())
932 .hasFeature(BrowserConfig.Feature.NETWORK_NOTIFIER);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700933 if (networkNotifier && mNetworkShouldNotify && wifiMgr.isWifiEnabled()){
Vivek Sekharb54614f2014-05-01 19:03:37 -0700934 handleNetworkNotify(view);
kaiyiza016da12013-08-26 17:50:22 +0800935 } else {
936 if (!mNetworkHandler.isNetworkUp()) {
937 view.setNetworkAvailable(false);
938 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700939 }
940
941 // when BrowserActivity just starts, onPageStarted may be called before
942 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
943 // to start the timer. As we won't switch tabs while an activity is in
944 // pause state, we can ensure calling resume and pause in pair.
945 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800946 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700947 }
948 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700949 endActionMode();
950
John Reck30c714c2010-12-16 17:30:34 -0800951 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700952
John Reck324d4402011-01-11 16:56:42 -0800953 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700954 // update the bookmark database for favicon
955 maybeUpdateFavicon(tab, null, url, favicon);
956
957 Performance.tracePageStart(url);
958
959 // Performance probe
960 if (false) {
961 Performance.onPageStarted();
962 }
963
964 }
965
966 @Override
John Reck324d4402011-01-11 16:56:42 -0800967 public void onPageFinished(Tab tab) {
Michael Kolb72864272012-05-03 15:42:15 -0700968 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800969 mUi.onTabDataChanged(tab);
Martijn Coenenb2f93552011-06-14 10:48:35 +0200970
Michael Kolb8233fac2010-10-26 16:08:53 -0700971 // Performance probe
972 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800973 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700974 }
975
Tarun Nainani8eb00912014-07-17 12:28:32 -0700976 tab.onPageFinished();
977
Michael Kolb8233fac2010-10-26 16:08:53 -0700978 Performance.tracePageFinished();
979 }
980
981 @Override
John Reck30c714c2010-12-16 17:30:34 -0800982 public void onProgressChanged(Tab tab) {
983 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700984
985 if (newProgress == 100) {
986 CookieSyncManager.getInstance().sync();
987 // onProgressChanged() may continue to be called after the main
988 // frame has finished loading, as any remaining sub frames continue
989 // to load. We'll only get called once though with newProgress as
990 // 100 when everything is loaded. (onPageFinished is called once
991 // when the main frame completes loading regardless of the state of
992 // any sub frames so calls to onProgressChanges may continue after
993 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800994 if (tab.inPageLoad()) {
Pankaj Garg49b79252014-11-07 17:33:41 -0800995 mWasInPageLoad = true;
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800996 updateInLoadMenuItems(mCachedMenu, tab);
Pankaj Garg49b79252014-11-07 17:33:41 -0800997 } else if (mWasInPageLoad) {
998 mWasInPageLoad = false;
999 updateInLoadMenuItems(mCachedMenu, tab);
1000 }
1001
1002 if (mActivityPaused && pauseWebViewTimers(tab)) {
Mattias Falk9cc2d032012-05-25 09:40:31 +02001003 // pause the WebView timer and release the wake lock if it is
1004 // finished while BrowserActivity is in pause state.
1005 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -07001006 }
John Reckd9862372012-02-21 15:04:50 -08001007 if (!tab.isPrivateBrowsingEnabled()
1008 && !TextUtils.isEmpty(tab.getUrl())
1009 && !tab.isSnapshot()) {
1010 // Only update the bookmark screenshot if the user did not
1011 // cancel the load early and there is not already
1012 // a pending update for the tab.
Michael Kolb72864272012-05-03 15:42:15 -07001013 if (tab.shouldUpdateThumbnail() &&
1014 (tab.inForeground() && !didUserStopLoading()
1015 || !tab.inForeground())) {
John Reckd9862372012-02-21 15:04:50 -08001016 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
1017 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1018 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001019 1500);
John Reckd9862372012-02-21 15:04:50 -08001020 }
1021 }
1022 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001023 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001024 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001025 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001026 // still loading
1027 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -07001028 // update the menu items.
Pankaj Garg49b79252014-11-07 17:33:41 -08001029 mWasInPageLoad = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001030 updateInLoadMenuItems(mCachedMenu, tab);
Pankaj Garg49b79252014-11-07 17:33:41 -08001031 } else {
1032 mWasInPageLoad = true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001033 }
1034 }
John Reck30c714c2010-12-16 17:30:34 -08001035 mUi.onProgressChanged(tab);
1036 }
1037
1038 @Override
Steve Block2466eff2011-10-03 15:33:09 +01001039 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08001040 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001041 }
1042
1043 @Override
1044 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -08001045 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -08001046 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -08001047 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -07001048 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
1049 return;
1050 }
1051 // Update the title in the history database if not in private browsing mode
1052 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -07001053 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -07001054 }
1055 }
1056
1057 @Override
1058 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -08001059 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001060 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
1061 }
1062
1063 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -08001064 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
1065 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07001066 }
1067
1068 @Override
1069 public boolean shouldOverrideKeyEvent(KeyEvent event) {
1070 if (mMenuIsDown) {
1071 // only check shortcut key when MENU is held
1072 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
1073 event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001074 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001075 int keyCode = event.getKeyCode();
1076 // We need to send almost every key to WebKit. However:
1077 // 1. We don't want to block the device on the renderer for
1078 // some keys like menu, home, call.
1079 // 2. There are no WebKit equivalents for some of these keys
1080 // (see app/keyboard_codes_win.h)
1081 // Note that these are not the same set as KeyEvent.isSystemKey:
1082 // for instance, AKEYCODE_MEDIA_* will be dispatched to webkit.
1083 if (keyCode == KeyEvent.KEYCODE_MENU ||
1084 keyCode == KeyEvent.KEYCODE_HOME ||
1085 keyCode == KeyEvent.KEYCODE_BACK ||
1086 keyCode == KeyEvent.KEYCODE_CALL ||
1087 keyCode == KeyEvent.KEYCODE_ENDCALL ||
1088 keyCode == KeyEvent.KEYCODE_POWER ||
1089 keyCode == KeyEvent.KEYCODE_HEADSETHOOK ||
1090 keyCode == KeyEvent.KEYCODE_CAMERA ||
1091 keyCode == KeyEvent.KEYCODE_FOCUS ||
1092 keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
1093 keyCode == KeyEvent.KEYCODE_VOLUME_MUTE ||
1094 keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
1095 return true;
1096 }
1097
1098 // We also have to intercept some shortcuts before we send them to the ContentView.
1099 if (event.isCtrlPressed() && (
1100 keyCode == KeyEvent.KEYCODE_TAB ||
1101 keyCode == KeyEvent.KEYCODE_W ||
1102 keyCode == KeyEvent.KEYCODE_F4)) {
1103 return true;
1104 }
1105
1106 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 }
1108
1109 @Override
John Reck997b1b72012-04-19 18:08:25 -07001110 public boolean onUnhandledKeyEvent(KeyEvent event) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001111 if (!isActivityPaused()) {
1112 if (event.getAction() == KeyEvent.ACTION_DOWN) {
John Reck997b1b72012-04-19 18:08:25 -07001113 return mActivity.onKeyDown(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001114 } else {
John Reck997b1b72012-04-19 18:08:25 -07001115 return mActivity.onKeyUp(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001116 }
1117 }
John Reck997b1b72012-04-19 18:08:25 -07001118 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07001119 }
1120
1121 @Override
John Reck324d4402011-01-11 16:56:42 -08001122 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Panos Thomas4bdb5252014-11-13 16:20:11 -08001123 // Don't save anything in private browsing mode or when disabling history
1124 // for regular tabs is enabled
1125 if (tab.isPrivateBrowsingEnabled() || BrowserConfig.getInstance(getContext())
1126 .hasFeature(BrowserConfig.Feature.DISABLE_HISTORY))
1127 return;
Bijan Amirzadae75909d2014-05-06 14:18:54 -07001128
John Reck49a603c2011-03-03 09:33:05 -08001129 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -07001130
John Reck324d4402011-01-11 16:56:42 -08001131 if (TextUtils.isEmpty(url)
1132 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001133 return;
1134 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001135
John Reckf57c0292011-07-21 18:15:39 -07001136 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -07001137 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07001138 }
1139
1140 @Override
1141 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1142 AsyncTask<Void, Void, String[]> task =
1143 new AsyncTask<Void, Void, String[]>() {
1144 @Override
1145 public String[] doInBackground(Void... unused) {
Bijan Amirzada3f04dc72014-06-25 11:48:36 -07001146 return (String[]) Browser.getVisitedHistory(mActivity.getContentResolver());
Michael Kolb8233fac2010-10-26 16:08:53 -07001147 }
1148 @Override
1149 public void onPostExecute(String[] result) {
1150 callback.onReceiveValue(result);
1151 }
1152 };
1153 task.execute();
1154 }
1155
1156 @Override
1157 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
1158 final HttpAuthHandler handler, final String host,
1159 final String realm) {
1160 String username = null;
1161 String password = null;
1162
1163 boolean reuseHttpAuthUsernamePassword
1164 = handler.useHttpAuthUsernamePassword();
1165
1166 if (reuseHttpAuthUsernamePassword && view != null) {
1167 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
1168 if (credentials != null && credentials.length == 2) {
1169 username = credentials[0];
1170 password = credentials[1];
1171 }
1172 }
1173
1174 if (username != null && password != null) {
1175 handler.proceed(username, password);
1176 } else {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001177 if (tab.inForeground() /*&& !handler.suppressDialog()*/) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001178 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1179 } else {
1180 handler.cancel();
1181 }
1182 }
1183 }
1184
1185 @Override
1186 public void onDownloadStart(Tab tab, String url, String userAgent,
Selim Gurun0b3d66f2012-08-29 13:08:13 -07001187 String contentDisposition, String mimetype, String referer,
1188 long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001189 WebView w = tab.getWebView();
Axesh R. Ajmera87c5aba2014-11-06 14:13:36 -08001190 if ( w == null) return;
qqzhoua95a2e22013-04-18 17:28:31 +08001191 boolean ret = DownloadHandler.onDownloadStart(mActivity, url, userAgent,
luxiaol62677b02013-07-22 07:54:49 +08001192 contentDisposition, mimetype, referer, w.isPrivateBrowsingEnabled(), contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +08001193 if (ret == false && w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001194 // This Tab was opened for the sole purpose of downloading a
1195 // file. Remove it.
1196 if (tab == mTabControl.getCurrentTab()) {
1197 // In this case, the Tab is still on top.
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07001198 if (tab.getDerivedFromIntent())
1199 closeTab(tab);
1200 else
1201 goBackOnePageOrQuit();
Michael Kolb8233fac2010-10-26 16:08:53 -07001202 } else {
1203 // In this case, it is not.
1204 closeTab(tab);
1205 }
1206 }
1207 }
1208
1209 @Override
1210 public Bitmap getDefaultVideoPoster() {
1211 return mUi.getDefaultVideoPoster();
1212 }
1213
1214 @Override
1215 public View getVideoLoadingProgressView() {
1216 return mUi.getVideoLoadingProgressView();
1217 }
1218
1219 @Override
1220 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1221 SslError error) {
1222 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1223 }
1224
1225 // helper method
1226
1227 /*
1228 * Update the favorites icon if the private browsing isn't enabled and the
1229 * icon is valid.
1230 */
1231 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1232 final String url, Bitmap favicon) {
1233 if (favicon == null) {
1234 return;
1235 }
1236 if (!tab.isPrivateBrowsingEnabled()) {
1237 Bookmarks.updateFavicon(mActivity
1238 .getContentResolver(), originalUrl, url, favicon);
1239 }
1240 }
1241
Leon Scroggins4cd97792010-12-03 15:31:56 -05001242 @Override
1243 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001244 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001245 mUi.bookmarkedStatusHasChanged(tab);
1246 }
1247
Michael Kolb8233fac2010-10-26 16:08:53 -07001248 // end WebViewController
1249
1250 protected void pageUp() {
1251 getCurrentTopWebView().pageUp(false);
1252 }
1253
1254 protected void pageDown() {
1255 getCurrentTopWebView().pageDown(false);
1256 }
1257
1258 // callback from phone title bar
John Reck9c35b9c2012-05-30 10:08:50 -07001259 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07001260 public void editUrl() {
1261 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolb1f9b3562012-04-24 14:38:34 -07001262 mUi.editUrl(false, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001263 }
1264
John Reck9c35b9c2012-05-30 10:08:50 -07001265 @Override
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001266 public void showCustomView(Tab tab, View view, int requestedOrientation,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001267 CustomViewCallback callback) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001268 if (tab.inForeground()) {
1269 if (mUi.isCustomViewShowing()) {
1270 callback.onCustomViewHidden();
1271 return;
1272 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001273 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001274 // Save the menu state and set it to empty while the custom
1275 // view is showing.
1276 mOldMenuState = mMenuState;
1277 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001278 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001279 }
1280 }
1281
1282 @Override
1283 public void hideCustomView() {
1284 if (mUi.isCustomViewShowing()) {
1285 mUi.onHideCustomView();
1286 // Reset the old menu state.
1287 mMenuState = mOldMenuState;
1288 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001289 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001290 }
1291 }
1292
John Reck9c35b9c2012-05-30 10:08:50 -07001293 @Override
1294 public void onActivityResult(int requestCode, int resultCode,
Michael Kolb8233fac2010-10-26 16:08:53 -07001295 Intent intent) {
1296 if (getCurrentTopWebView() == null) return;
1297 switch (requestCode) {
1298 case PREFERENCES_PAGE:
1299 if (resultCode == Activity.RESULT_OK && intent != null) {
1300 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001301 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001302 mTabControl.removeParentChildRelationShips();
1303 }
1304 }
1305 break;
1306 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001307 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001308 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001309 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001310 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001311 case AUTOFILL_SETUP:
1312 // Determine whether a profile was actually set up or not
1313 // and if so, send the message back to the WebTextView to
1314 // fill the form with the new profile.
1315 if (getSettings().getAutoFillProfile() != null) {
1316 mAutoFillSetupMessage.sendToTarget();
1317 mAutoFillSetupMessage = null;
1318 }
1319 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001320 case COMBO_VIEW:
1321 if (intent == null || resultCode != Activity.RESULT_OK) {
1322 break;
1323 }
John Reck3ba45532011-08-11 16:26:53 -07001324 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001325 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1326 Tab t = getCurrentTab();
1327 Uri uri = intent.getData();
kaiyiz6e5b3e02013-08-19 20:02:01 +08001328 mUpdateMyNavThumbnail = true;
1329 mUpdateMyNavThumbnailUrl = uri.toString();
John Reckd3e4d5b2011-07-13 15:48:43 -07001330 loadUrl(t, uri.toString());
1331 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1332 String[] urls = intent.getStringArrayExtra(
1333 ComboViewActivity.EXTRA_OPEN_ALL);
1334 Tab parent = getCurrentTab();
1335 for (String url : urls) {
kaiyiz47097d62013-08-09 09:30:28 +08001336 if (url != null) {
1337 parent = openTab(url, parent,
1338 !mSettings.openInBackground(), true);
1339 }
John Reckd3e4d5b2011-07-13 15:48:43 -07001340 }
1341 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1342 long id = intent.getLongExtra(
1343 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1344 if (id >= 0) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001345 createNewSnapshotTab(id, true);
John Reckd3e4d5b2011-07-13 15:48:43 -07001346 }
1347 }
1348 break;
Michael Kolb0b129122012-06-04 16:31:58 -07001349 case VOICE_RESULT:
1350 if (resultCode == Activity.RESULT_OK && intent != null) {
1351 ArrayList<String> results = intent.getStringArrayListExtra(
1352 RecognizerIntent.EXTRA_RESULTS);
1353 if (results.size() >= 1) {
1354 mVoiceResult = results.get(0);
1355 }
1356 }
1357 break;
kaiyiz6e5b3e02013-08-19 20:02:01 +08001358 case MY_NAVIGATION:
1359 if (intent == null || resultCode != Activity.RESULT_OK) {
1360 break;
1361 }
1362
1363 if (intent.getBooleanExtra("need_refresh", false) &&
1364 getCurrentTopWebView() != null) {
1365 getCurrentTopWebView().reload();
1366 }
1367 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001368 default:
1369 break;
1370 }
1371 getCurrentTopWebView().requestFocus();
1372 }
1373
1374 /**
1375 * Open the Go page.
1376 * @param startWithHistory If true, open starting on the history tab.
1377 * Otherwise, start with the bookmarks tab.
1378 */
1379 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001380 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001381 if (mTabControl.getCurrentWebView() == null) {
1382 return;
1383 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001384 // clear action mode
1385 if (isInCustomActionMode()) {
1386 endActionMode();
1387 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001388 Bundle extras = new Bundle();
1389 // Disable opening in a new window if we have maxed out the windows
1390 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1391 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001392 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001393 }
1394
1395 // combo view callbacks
1396
Michael Kolb8233fac2010-10-26 16:08:53 -07001397 // key handling
1398 protected void onBackKey() {
1399 if (!mUi.onBackKey()) {
1400 WebView subwindow = mTabControl.getCurrentSubWindow();
1401 if (subwindow != null) {
1402 if (subwindow.canGoBack()) {
1403 subwindow.goBack();
1404 } else {
1405 dismissSubWindow(mTabControl.getCurrentTab());
1406 }
1407 } else {
1408 goBackOnePageOrQuit();
1409 }
1410 }
1411 }
1412
Michael Kolb4bd767d2011-05-27 11:33:55 -07001413 protected boolean onMenuKey() {
1414 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001415 }
1416
Michael Kolb8233fac2010-10-26 16:08:53 -07001417 // menu handling and state
1418 // TODO: maybe put into separate handler
1419
John Reck9c35b9c2012-05-30 10:08:50 -07001420 @Override
1421 public boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001422 if (mMenuState == EMPTY_MENU) {
1423 return false;
1424 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001425 MenuInflater inflater = mActivity.getMenuInflater();
1426 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001427 return true;
1428 }
1429
John Reck9c35b9c2012-05-30 10:08:50 -07001430 @Override
1431 public void onCreateContextMenu(ContextMenu menu, View v,
Michael Kolb8233fac2010-10-26 16:08:53 -07001432 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001433 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001434 return;
1435 }
1436 if (!(v instanceof WebView)) {
1437 return;
1438 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001439 final WebView webview = (WebView) v;
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -08001440 WebView.HitTestResult result;
1441
1442 /* Determine whether the ContextMenu got triggered because
1443 * of user action of long click or because of the UNKNOWN_TYPE_MSG
1444 * received. The mResult acts as a flag to identify, how it got trigerred
1445 */
1446 if (mResult == null){
1447 result = webview.getHitTestResult();
1448 } else {
1449 result = mResult;
1450 }
1451
Michael Kolb8233fac2010-10-26 16:08:53 -07001452 if (result == null) {
1453 return;
1454 }
1455
1456 int type = result.getType();
1457 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -08001458
1459 HashMap<String, Object> unknownTypeMap = new HashMap<String, Object>();
1460 unknownTypeMap.put("webview", webview);
1461 final Message msg = mHandler.obtainMessage(
1462 UNKNOWN_TYPE_MSG, unknownTypeMap);
1463 /* As defined in android developers guide
1464 * when UNKNOWN_TYPE is received as a result of HitTest
1465 * you need to determing the type by invoking requestFocusNodeHref
1466 */
1467 webview.requestFocusNodeHref(msg);
1468
Michael Kolb8233fac2010-10-26 16:08:53 -07001469 Log.w(LOGTAG,
1470 "We should not show context menu when nothing is touched");
1471 return;
1472 }
1473 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1474 // let TextView handles context menu
1475 return;
1476 }
1477
1478 // Note, http://b/issue?id=1106666 is requesting that
1479 // an inflated menu can be used again. This is not available
1480 // yet, so inflate each time (yuk!)
1481 MenuInflater inflater = mActivity.getMenuInflater();
1482 inflater.inflate(R.menu.browsercontext, menu);
1483
1484 // Show the correct menu group
1485 final String extra = result.getExtra();
kaiyiz6e5b3e02013-08-19 20:02:01 +08001486 final String navigationUrl = MyNavigationUtil.getMyNavigationUrl(extra);
Michael Kolbc159c1a2011-12-15 16:06:38 -08001487 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001488 menu.setGroupVisible(R.id.PHONE_MENU,
1489 type == WebView.HitTestResult.PHONE_TYPE);
1490 menu.setGroupVisible(R.id.EMAIL_MENU,
1491 type == WebView.HitTestResult.EMAIL_TYPE);
1492 menu.setGroupVisible(R.id.GEO_MENU,
1493 type == WebView.HitTestResult.GEO_TYPE);
kaiyiz6e5b3e02013-08-19 20:02:01 +08001494 String itemUrl = null;
1495 String url = webview.getOriginalUrl();
1496 if (url != null && url.equalsIgnoreCase(MyNavigationUtil.MY_NAVIGATION)) {
1497 itemUrl = Uri.decode(navigationUrl);
1498 if (itemUrl != null && !MyNavigationUtil.isDefaultMyNavigation(itemUrl)) {
1499 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU,
1500 type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1501 } else {
1502 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU, false);
1503 }
1504 menu.setGroupVisible(R.id.IMAGE_MENU, false);
1505 menu.setGroupVisible(R.id.ANCHOR_MENU, false);
1506 } else {
1507 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU, false);
1508
1509 menu.setGroupVisible(R.id.IMAGE_MENU,
1510 type == WebView.HitTestResult.IMAGE_TYPE
1511 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1512 menu.setGroupVisible(R.id.ANCHOR_MENU,
1513 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1514 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Vivek Sekharcc4bc5e2014-05-13 12:46:37 -07001515 menu.findItem(R.id.save_link_context_menu_id).setEnabled(
1516 UrlUtils.isDownloadableScheme(extra));
kaiyiz6e5b3e02013-08-19 20:02:01 +08001517 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001518 // Setup custom handling depending on the type
1519 switch (type) {
1520 case WebView.HitTestResult.PHONE_TYPE:
1521 menu.setHeaderTitle(Uri.decode(extra));
1522 menu.findItem(R.id.dial_context_menu_id).setIntent(
1523 new Intent(Intent.ACTION_VIEW, Uri
1524 .parse(WebView.SCHEME_TEL + extra)));
1525 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1526 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1527 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1528 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1529 addIntent);
1530 menu.findItem(R.id.copy_phone_context_menu_id)
1531 .setOnMenuItemClickListener(
1532 new Copy(extra));
1533 break;
1534
1535 case WebView.HitTestResult.EMAIL_TYPE:
1536 menu.setHeaderTitle(extra);
1537 menu.findItem(R.id.email_context_menu_id).setIntent(
1538 new Intent(Intent.ACTION_VIEW, Uri
1539 .parse(WebView.SCHEME_MAILTO + extra)));
1540 menu.findItem(R.id.copy_mail_context_menu_id)
1541 .setOnMenuItemClickListener(
1542 new Copy(extra));
1543 break;
1544
1545 case WebView.HitTestResult.GEO_TYPE:
1546 menu.setHeaderTitle(extra);
1547 menu.findItem(R.id.map_context_menu_id).setIntent(
1548 new Intent(Intent.ACTION_VIEW, Uri
1549 .parse(WebView.SCHEME_GEO
1550 + URLEncoder.encode(extra))));
1551 menu.findItem(R.id.copy_geo_context_menu_id)
1552 .setOnMenuItemClickListener(
1553 new Copy(extra));
1554 break;
1555
1556 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1557 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001558 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001559 // decide whether to show the open link in new tab option
1560 boolean showNewTab = mTabControl.canCreateNewTab();
1561 MenuItem newTabItem
1562 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001563 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001564 ? R.string.contextmenu_openlink_newwindow_background
1565 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001566 newTabItem.setVisible(showNewTab);
1567 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001568 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1569 newTabItem.setOnMenuItemClickListener(
1570 new MenuItem.OnMenuItemClickListener() {
1571 @Override
1572 public boolean onMenuItemClick(MenuItem item) {
1573 final HashMap<String, WebView> hrefMap =
1574 new HashMap<String, WebView>();
1575 hrefMap.put("webview", webview);
1576 final Message msg = mHandler.obtainMessage(
1577 FOCUS_NODE_HREF,
1578 R.id.open_newtab_context_menu_id,
1579 0, hrefMap);
1580 webview.requestFocusNodeHref(msg);
1581 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001582 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001583 });
1584 } else {
1585 newTabItem.setOnMenuItemClickListener(
1586 new MenuItem.OnMenuItemClickListener() {
1587 @Override
1588 public boolean onMenuItemClick(MenuItem item) {
1589 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001590 openTab(extra, parent,
1591 !mSettings.openInBackground(),
1592 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001593 return true;
1594 }
1595 });
1596 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001597 }
kaiyiz6e5b3e02013-08-19 20:02:01 +08001598 if (url != null && url.equalsIgnoreCase(MyNavigationUtil.MY_NAVIGATION)) {
1599 menu.setHeaderTitle(navigationUrl);
1600 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(false);
1601
1602 if (itemUrl != null) {
1603 if (!MyNavigationUtil.isDefaultMyNavigation(itemUrl)) {
1604 menu.findItem(R.id.edit_my_navigation_context_menu_id)
1605 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1606 @Override
1607 public boolean onMenuItemClick(MenuItem item) {
1608 final Intent intent = new Intent(Controller.this
1609 .getContext(),
1610 AddMyNavigationPage.class);
1611 Bundle bundle = new Bundle();
1612 String url = Uri.decode(navigationUrl);
1613 bundle.putBoolean("isAdding", false);
1614 bundle.putString("url", url);
1615 bundle.putString("name", getNameFromUrl(url));
1616 intent.putExtra("websites", bundle);
1617 mActivity.startActivityForResult(intent, MY_NAVIGATION);
1618 return false;
1619 }
1620 });
1621 menu.findItem(R.id.delete_my_navigation_context_menu_id)
1622 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1623 @Override
1624 public boolean onMenuItemClick(MenuItem item) {
1625 showMyNavigationDeleteDialog(Uri.decode(navigationUrl));
1626 return false;
1627 }
1628 });
1629 }
1630 } else {
1631 Log.e(LOGTAG, "mynavigation onCreateContextMenu itemUrl is null!");
1632 }
1633 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001634 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1635 break;
1636 }
1637 // otherwise fall through to handle image part
1638 case WebView.HitTestResult.IMAGE_TYPE:
Victoria Lease5987b802012-03-12 13:05:23 -07001639 MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
1640 shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
Michael Kolb8233fac2010-10-26 16:08:53 -07001641 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1642 menu.setHeaderTitle(extra);
Victoria Lease5987b802012-03-12 13:05:23 -07001643 shareItem.setOnMenuItemClickListener(
1644 new MenuItem.OnMenuItemClickListener() {
1645 @Override
1646 public boolean onMenuItemClick(MenuItem item) {
1647 sharePage(mActivity, null, extra, null,
1648 null);
1649 return true;
1650 }
1651 }
1652 );
Michael Kolb8233fac2010-10-26 16:08:53 -07001653 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001654 menu.findItem(R.id.view_image_context_menu_id)
1655 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1656 @Override
1657 public boolean onMenuItemClick(MenuItem item) {
1658 openTab(extra, mTabControl.getCurrentTab(), true, true);
1659 return false;
1660 }
1661 });
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02001662 menu.findItem(R.id.download_context_menu_id).setOnMenuItemClickListener(
1663 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled(),
1664 webview.getSettings().getUserAgentString()));
John Reck3527dd12011-02-22 10:35:29 -08001665 menu.findItem(R.id.set_wallpaper_context_menu_id).
1666 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1667 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001668 break;
1669
1670 default:
1671 Log.w(LOGTAG, "We should not get here.");
1672 break;
1673 }
1674 //update the ui
1675 mUi.onContextMenuCreated(menu);
1676 }
1677
kaiyiz6e5b3e02013-08-19 20:02:01 +08001678 public void startAddMyNavigation(String url) {
1679 final Intent intent = new Intent(Controller.this.getContext(), AddMyNavigationPage.class);
1680 Bundle bundle = new Bundle();
1681 bundle.putBoolean("isAdding", true);
1682 bundle.putString("url", url);
1683 bundle.putString("name", getNameFromUrl(url));
1684 intent.putExtra("websites", bundle);
1685 mActivity.startActivityForResult(intent, MY_NAVIGATION);
1686 }
1687
1688 private void showMyNavigationDeleteDialog(final String itemUrl) {
1689 new AlertDialog.Builder(this.getContext())
1690 .setTitle(R.string.my_navigation_delete_label)
1691 .setIcon(android.R.drawable.ic_dialog_alert)
1692 .setMessage(R.string.my_navigation_delete_msg)
1693 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
1694 @Override
1695 public void onClick(DialogInterface dialog, int whichButton) {
1696 deleteMyNavigationItem(itemUrl);
1697 }
1698 })
1699 .setNegativeButton(R.string.cancel, null)
1700 .show();
1701 }
1702
1703 private void deleteMyNavigationItem(final String itemUrl) {
1704 ContentResolver cr = this.getContext().getContentResolver();
1705 Cursor cursor = null;
1706
1707 try {
1708 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1709 new String[] {
1710 MyNavigationUtil.ID
1711 }, "url = ?", new String[] {
1712 itemUrl
1713 }, null);
1714 if (null != cursor && cursor.moveToFirst()) {
1715 Uri uri = ContentUris.withAppendedId(MyNavigationUtil.MY_NAVIGATION_URI,
1716 cursor.getLong(0));
1717
1718 ContentValues values = new ContentValues();
1719 values.put(MyNavigationUtil.TITLE, "");
1720 values.put(MyNavigationUtil.URL, "ae://" + cursor.getLong(0) + "add-fav");
1721 values.put(MyNavigationUtil.WEBSITE, 0 + "");
1722 ByteArrayOutputStream os = new ByteArrayOutputStream();
1723 Bitmap bm = BitmapFactory.decodeResource(this.getContext().getResources(),
1724 R.raw.my_navigation_add);
1725 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1726 values.put(MyNavigationUtil.THUMBNAIL, os.toByteArray());
1727 Log.d(LOGTAG, "deleteMyNavigationItem uri is : " + uri);
1728 cr.update(uri, values, null, null);
1729 } else {
1730 Log.e(LOGTAG, "deleteMyNavigationItem the item does not exist!");
1731 }
1732 } catch (IllegalStateException e) {
1733 Log.e(LOGTAG, "deleteMyNavigationItem", e);
1734 } finally {
1735 if (null != cursor) {
1736 cursor.close();
1737 }
1738 }
1739
1740 if (getCurrentTopWebView() != null) {
1741 getCurrentTopWebView().reload();
1742 }
1743 }
1744
1745 private String getNameFromUrl(String itemUrl) {
1746 ContentResolver cr = this.getContext().getContentResolver();
1747 Cursor cursor = null;
1748 String name = null;
1749
1750 try {
1751 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1752 new String[] {
1753 MyNavigationUtil.TITLE
1754 }, "url = ?", new String[] {
1755 itemUrl
1756 }, null);
1757 if (null != cursor && cursor.moveToFirst()) {
1758 name = cursor.getString(0);
1759 } else {
1760 Log.e(LOGTAG, "this item does not exist!");
1761 }
1762 } catch (IllegalStateException e) {
1763 Log.e(LOGTAG, "getNameFromUrl", e);
1764 } finally {
1765 if (null != cursor) {
1766 cursor.close();
1767 }
1768 }
1769 return name;
1770 }
1771
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07001772 private void updateMyNavigationThumbnail(final String itemUrl, final Bitmap bitmap) {
kaiyiz6e5b3e02013-08-19 20:02:01 +08001773 final ContentResolver cr = mActivity.getContentResolver();
1774 new AsyncTask<Void, Void, Void>() {
1775 @Override
1776 protected Void doInBackground(Void... unused) {
Tarun Nainanicc8ac9e2015-01-08 14:45:21 -08001777 boolean isMyNavigationUrl = MyNavigationUtil.isMyNavigationUrl(mActivity, itemUrl);
1778 if(!isMyNavigationUrl)
1779 return null;
1780
kaiyiz6e5b3e02013-08-19 20:02:01 +08001781 ContentResolver cr = mActivity.getContentResolver();
1782 Cursor cursor = null;
1783 try {
1784 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1785 new String[] {
1786 MyNavigationUtil.ID
1787 }, "url = ?", new String[] {
1788 itemUrl
1789 }, null);
1790 if (null != cursor && cursor.moveToFirst()) {
1791 final ByteArrayOutputStream os = new ByteArrayOutputStream();
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07001792 bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
kaiyiz6e5b3e02013-08-19 20:02:01 +08001793
1794 ContentValues values = new ContentValues();
1795 values.put(MyNavigationUtil.THUMBNAIL, os.toByteArray());
1796 Uri uri = ContentUris.withAppendedId(MyNavigationUtil.MY_NAVIGATION_URI,
1797 cursor.getLong(0));
1798 Log.d(LOGTAG, "updateMyNavigationThumbnail uri is " + uri);
1799 cr.update(uri, values, null, null);
1800 os.close();
1801 }
1802 } catch (IllegalStateException e) {
1803 Log.e(LOGTAG, "updateMyNavigationThumbnail", e);
1804 } catch (IOException e) {
1805 Log.e(LOGTAG, "updateMyNavigationThumbnail", e);
1806 } finally {
1807 if (null != cursor) {
1808 cursor.close();
1809 }
1810 }
1811 return null;
1812 }
1813 }.execute();
1814 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001815 /**
1816 * As the menu can be open when loading state changes
1817 * we must manually update the state of the stop/reload menu
1818 * item
1819 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001820 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001821 if (menu == null) {
1822 return;
1823 }
1824 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001825 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001826 menu.findItem(R.id.stop_menu_id):
1827 menu.findItem(R.id.reload_menu_id);
1828 if (src != null) {
1829 dest.setIcon(src.getIcon());
1830 dest.setTitle(src.getTitle());
1831 }
Pankaj Garg49b79252014-11-07 17:33:41 -08001832 mActivity.invalidateOptionsMenu();
1833 }
1834
1835 public void invalidateOptionsMenu() {
1836 mAppMenuHandler.invalidateAppMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001837 }
1838
John Reck9c35b9c2012-05-30 10:08:50 -07001839 @Override
1840 public boolean onPrepareOptionsMenu(Menu menu) {
Pankaj Garg49b79252014-11-07 17:33:41 -08001841 // Software menu key (toolbar key)
1842 mAppMenuHandler.showAppMenu(mActivity.findViewById(R.id.more_browser_settings), false, false);
1843 return true;
1844 }
1845
1846 @Override
1847 public void prepareMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001848 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001849 // hold on to the menu reference here; it is used by the page callbacks
1850 // to update the menu based on loading state
1851 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001852 // Note: setVisible will decide whether an item is visible; while
1853 // setEnabled() will decide whether an item is enabled, which also means
1854 // whether the matching shortcut key will function.
1855 switch (mMenuState) {
1856 case EMPTY_MENU:
1857 if (mCurrentMenuState != mMenuState) {
1858 menu.setGroupVisible(R.id.MAIN_MENU, false);
1859 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1860 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1861 }
1862 break;
1863 default:
1864 if (mCurrentMenuState != mMenuState) {
1865 menu.setGroupVisible(R.id.MAIN_MENU, true);
1866 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1867 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1868 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001869 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001870 break;
1871 }
1872 mCurrentMenuState = mMenuState;
Pankaj Garg49b79252014-11-07 17:33:41 -08001873 mUi.onPrepareOptionsMenu(menu);
1874 }
1875
1876 private void setMenuItemVisibility(Menu menu, int id,
1877 boolean visibility) {
1878 MenuItem item = menu.findItem(id);
1879 if (item != null) {
1880 item.setVisible(visibility);
1881 }
1882 }
1883
1884 private int lookupBookmark(String title, String url) {
1885 final ContentResolver cr = getActivity().getContentResolver();
Tarun Nainanif7c4cfc2015-01-07 12:43:46 -08001886 int count = 0;
1887 Cursor cursor = null;
1888 try {
1889 cursor = cr.query(BrowserContract.Bookmarks.CONTENT_URI,
1890 BookmarksLoader.PROJECTION,
1891 "title = ? OR url = ?",
1892 new String[] {
Pankaj Garg49b79252014-11-07 17:33:41 -08001893 title, url
Tarun Nainanif7c4cfc2015-01-07 12:43:46 -08001894 },
1895 null);
Pankaj Garg49b79252014-11-07 17:33:41 -08001896
Tarun Nainanif7c4cfc2015-01-07 12:43:46 -08001897 if (cursor != null)
1898 count = cursor.getCount();
1899
1900 } catch (IllegalStateException e) {
1901 Log.e(LOGTAG, "lookupBookmark ", e);
1902 } finally {
1903 if (null != cursor) {
1904 cursor.close();
1905 }
Pankaj Garg49b79252014-11-07 17:33:41 -08001906 }
Tarun Nainanif7c4cfc2015-01-07 12:43:46 -08001907 return count;
Pankaj Garg49b79252014-11-07 17:33:41 -08001908 }
1909
1910 private void resetMenuItems(Menu menu) {
1911 setMenuItemVisibility(menu, R.id.history_menu_id, true);
1912 setMenuItemVisibility(menu, R.id.find_menu_id, true);
1913
1914 WebView w = getCurrentTopWebView();
1915 MenuItem bookmark_icon = menu.findItem(R.id.bookmark_this_page_id);
1916
1917 String title = w.getTitle();
1918 String url = w.getUrl();
1919 if (title != null && url != null && lookupBookmark(title, url) > 0) {
1920 bookmark_icon.setChecked(true);
1921 } else {
1922 bookmark_icon.setChecked(false);
1923 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001924 }
1925
Michael Kolb4bf79712011-07-14 14:18:12 -07001926 @Override
1927 public void updateMenuState(Tab tab, Menu menu) {
Michael Kolb4bf79712011-07-14 14:18:12 -07001928 boolean canGoForward = false;
John Reck42229bc2011-08-19 13:26:43 -07001929 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001930 boolean isLive = false;
Tarun Nainani8eb00912014-07-17 12:28:32 -07001931 // Following flag is used to identify schemes for which the LIVE_MENU
1932 // items defined in res/menu/browser.xml should be enabled
1933 boolean isLiveScheme = false;
1934 boolean isPageFinished = false;
Pankaj Garg49b79252014-11-07 17:33:41 -08001935
1936 resetMenuItems(menu);
1937
Michael Kolb4bf79712011-07-14 14:18:12 -07001938 if (tab != null) {
Michael Kolb4bf79712011-07-14 14:18:12 -07001939 canGoForward = tab.canGoForward();
John Reck42229bc2011-08-19 13:26:43 -07001940 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001941 isLive = !tab.isSnapshot();
Tarun Nainani8eb00912014-07-17 12:28:32 -07001942 isLiveScheme = UrlUtils.isLiveScheme(tab.getWebView().getUrl());
Pankaj Garg49b79252014-11-07 17:33:41 -08001943 isPageFinished = (tab.getPageFinishedStatus() || !tab.inPageLoad());
Michael Kolb4bf79712011-07-14 14:18:12 -07001944 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001945
1946 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1947 forward.setEnabled(canGoForward);
1948
Michael Kolb4bf79712011-07-14 14:18:12 -07001949 // decide whether to show the share link option
1950 PackageManager pm = mActivity.getPackageManager();
1951 Intent send = new Intent(Intent.ACTION_SEND);
1952 send.setType("text/plain");
1953 ResolveInfo ri = pm.resolveActivity(send,
1954 PackageManager.MATCH_DEFAULT_ONLY);
1955 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1956
1957 boolean isNavDump = mSettings.enableNavDump();
1958 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1959 nav.setVisible(isNavDump);
1960 nav.setEnabled(isNavDump);
1961
1962 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001963 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1964 uaSwitcher.setChecked(isDesktopUa);
Tarun Nainani8eb00912014-07-17 12:28:32 -07001965 menu.setGroupVisible(R.id.LIVE_MENU, isLive && isLiveScheme);
Pankaj Garg49b79252014-11-07 17:33:41 -08001966 menu.setGroupVisible(R.id.NAV_MENU, isLive && isLiveScheme);
1967 setMenuItemVisibility(menu, R.id.find_menu_id, isLive && isLiveScheme);
John Recke1a03a32011-09-14 17:04:16 -07001968 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Pankaj Garg49b79252014-11-07 17:33:41 -08001969 setMenuItemVisibility(menu, R.id.add_to_homescreen,
1970 isLive && isLiveScheme && isPageFinished);
1971 setMenuItemVisibility(menu, R.id.save_snapshot_menu_id,
1972 isLive && isLiveScheme && isPageFinished);
kaiyiza8b6dbb2013-07-29 18:11:22 +08001973 // history and snapshots item are the members of COMBO menu group,
1974 // so if show history item, only make snapshots item invisible.
1975 menu.findItem(R.id.snapshots_menu_id).setVisible(false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001976
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001977 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001978 }
1979
John Reck9c35b9c2012-05-30 10:08:50 -07001980 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07001981 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 if (null == getCurrentTopWebView()) {
1983 return false;
1984 }
1985 if (mMenuIsDown) {
1986 // The shortcut action consumes the MENU. Even if it is still down,
1987 // it won't trigger the next shortcut action. In the case of the
1988 // shortcut action triggering a new activity, like Bookmarks, we
1989 // won't get onKeyUp for MENU. So it is important to reset it here.
1990 mMenuIsDown = false;
1991 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001992 if (mUi.onOptionsItemSelected(item)) {
1993 // ui callback handled it
1994 return true;
1995 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001996 switch (item.getItemId()) {
1997 // -- Main menu
1998 case R.id.new_tab_menu_id:
1999 openTabToHomePage();
2000 break;
2001
2002 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07002003 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002004 break;
2005
2006 case R.id.goto_menu_id:
2007 editUrl();
2008 break;
2009
2010 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07002011 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
2012 break;
2013
2014 case R.id.history_menu_id:
2015 bookmarksOrHistoryPicker(ComboViews.History);
2016 break;
2017
2018 case R.id.snapshots_menu_id:
2019 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07002020 break;
2021
Pankaj Garg49b79252014-11-07 17:33:41 -08002022 case R.id.bookmark_this_page_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002023 bookmarkCurrentPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07002024 break;
2025
2026 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002027 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 stopLoading();
2029 } else {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002030 Tab currentTab = mTabControl.getCurrentTab();
2031 if (currentTab.hasCrashed) {
2032 currentTab.replaceCrashView(getCurrentTopWebView(),
2033 currentTab.getViewContainer());
2034 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002035 getCurrentTopWebView().reload();
2036 }
2037 break;
2038
Michael Kolb8233fac2010-10-26 16:08:53 -07002039 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07002040 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07002041 break;
2042
2043 case R.id.close_menu_id:
2044 // Close the subwindow if it exists.
2045 if (mTabControl.getCurrentSubWindow() != null) {
2046 dismissSubWindow(mTabControl.getCurrentTab());
2047 break;
2048 }
2049 closeCurrentTab();
2050 break;
2051
kaiyiza8b6dbb2013-07-29 18:11:22 +08002052 case R.id.exit_menu_id:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002053 Object[] params = { new String("persist.debug.browsermonkeytest")};
2054 Class[] type = new Class[] {String.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -07002055 String ret = (String)ReflectHelper.invokeMethod(
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002056 "android.os.SystemProperties","get", type, params);
kaiyiza8b6dbb2013-07-29 18:11:22 +08002057 if (ret != null && ret.equals("enable"))
2058 break;
Panos Thomas4bdb5252014-11-13 16:20:11 -08002059 if (BrowserConfig.getInstance(getContext())
2060 .hasFeature(BrowserConfig.Feature.EXIT_DIALOG))
2061 showExitDialog(mActivity);
luxiaolb40014b2013-07-19 10:01:43 +08002062 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002063 case R.id.homepage_menu_id:
2064 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002065 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07002066 break;
2067
2068 case R.id.preferences_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002069 openPreferences();
Michael Kolb8233fac2010-10-26 16:08:53 -07002070 break;
2071
2072 case R.id.find_menu_id:
Michael Kolbe11b9212012-04-13 13:39:54 -07002073 findOnPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07002074 break;
2075
John Reck2bc80422011-06-30 15:11:49 -07002076 case R.id.save_snapshot_menu_id:
2077 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07002078 if (source == null) break;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002079 createScreenshotAsync(
2080 source.getWebView(),
2081 getDesiredThumbnailWidth(mActivity),
2082 getDesiredThumbnailHeight(mActivity),
2083 new ValueCallback<Bitmap>() {
2084 @Override
2085 public void onReceiveValue(Bitmap bitmap) {
2086 new SaveSnapshotTask(source, bitmap).execute();
2087 }
2088 });
Leon Scrogginsac993842011-02-02 12:54:07 -05002089 break;
2090
Michael Kolb8233fac2010-10-26 16:08:53 -07002091 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07002092 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07002093 break;
2094
John Recke1a03a32011-09-14 17:04:16 -07002095 case R.id.snapshot_go_live:
2096 goLive();
2097 return true;
2098
Michael Kolb8233fac2010-10-26 16:08:53 -07002099 case R.id.share_page_menu_id:
2100 Tab currentTab = mTabControl.getCurrentTab();
2101 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002102 return false;
2103 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08002104 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002105 break;
2106
2107 case R.id.dump_nav_menu_id:
2108 getCurrentTopWebView().debugDump();
2109 break;
2110
Michael Kolb8233fac2010-10-26 16:08:53 -07002111 case R.id.zoom_in_menu_id:
2112 getCurrentTopWebView().zoomIn();
2113 break;
2114
2115 case R.id.zoom_out_menu_id:
2116 getCurrentTopWebView().zoomOut();
2117 break;
2118
2119 case R.id.view_downloads_menu_id:
2120 viewDownloads();
2121 break;
2122
John Reck42229bc2011-08-19 13:26:43 -07002123 case R.id.ua_desktop_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002124 toggleUserAgent();
John Reck42229bc2011-08-19 13:26:43 -07002125 break;
2126
Michael Kolb8233fac2010-10-26 16:08:53 -07002127 case R.id.window_one_menu_id:
2128 case R.id.window_two_menu_id:
2129 case R.id.window_three_menu_id:
2130 case R.id.window_four_menu_id:
2131 case R.id.window_five_menu_id:
2132 case R.id.window_six_menu_id:
2133 case R.id.window_seven_menu_id:
2134 case R.id.window_eight_menu_id:
2135 {
2136 int menuid = item.getItemId();
2137 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
2138 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
2139 Tab desiredTab = mTabControl.getTab(id);
2140 if (desiredTab != null &&
2141 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07002142 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002143 }
2144 break;
2145 }
2146 }
2147 }
2148 break;
2149
Axesh R. Ajmera652d08e2014-06-16 16:36:33 -07002150 case R.id.about_menu_id:
Pankaj Garg18902562014-12-05 16:18:51 -08002151 Bundle bundle = new Bundle();
2152 bundle.putCharSequence("UA", Engine.getDefaultUserAgent());
2153 bundle.putCharSequence("TabTitle", mTabControl.getCurrentTab().getTitle());
2154 bundle.putCharSequence("TabURL", mTabControl.getCurrentTab().getUrl());
2155 BrowserPreferencesPage.startPreferenceFragmentExtraForResult(mActivity,
2156 AboutPreferencesFragment.class.getName(), bundle, 0);
Axesh R. Ajmera652d08e2014-06-16 16:36:33 -07002157 break;
2158
Pankaj Garg49b79252014-11-07 17:33:41 -08002159 case R.id.add_to_homescreen:
2160 final WebView w = getCurrentTopWebView();
2161 final EditText input = new EditText(getContext());
2162 input.setText(w.getTitle());
2163 new AlertDialog.Builder(getContext())
2164 .setTitle("Add to homescreen")
2165 .setMessage("Title")
2166 .setView(input)
2167 .setPositiveButton("Add", new DialogInterface.OnClickListener() {
2168 public void onClick(DialogInterface dialog, int whichButton) {
2169 mActivity.sendBroadcast(BookmarkUtils.createAddToHomeIntent(
2170 getContext(),
2171 w.getUrl(),
2172 input.getText().toString(),
2173 w.getViewportBitmap(),
2174 w.getFavicon()));
2175
2176 mActivity.startActivity(new Intent(Intent.ACTION_MAIN)
2177 .addCategory(Intent.CATEGORY_HOME));
2178 }})
2179 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
2180 public void onClick(DialogInterface dialog, int whichButton) {
2181 // Do nothing.
2182 }
2183 })
2184 .show();
2185 break;
2186
Michael Kolb8233fac2010-10-26 16:08:53 -07002187 default:
2188 return false;
2189 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002190 return true;
2191 }
2192
John Reck68234a92012-04-19 15:27:12 -07002193 private class SaveSnapshotTask extends AsyncTask<Void, Void, Long>
2194 implements OnCancelListener {
2195
2196 private Tab mTab;
2197 private Dialog mProgressDialog;
2198 private ContentValues mValues;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002199 private Bitmap mBitmap;
John Reck68234a92012-04-19 15:27:12 -07002200
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002201 private SaveSnapshotTask(Tab tab, Bitmap bm) {
John Reck68234a92012-04-19 15:27:12 -07002202 mTab = tab;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002203 mBitmap = bm;
John Reck68234a92012-04-19 15:27:12 -07002204 }
2205
2206 @Override
2207 protected void onPreExecute() {
2208 CharSequence message = mActivity.getText(R.string.saving_snapshot);
2209 mProgressDialog = ProgressDialog.show(mActivity, null, message,
2210 true, true, this);
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002211 mValues = mTab.createSnapshotValues(mBitmap);
John Reck68234a92012-04-19 15:27:12 -07002212 }
2213
2214 @Override
2215 protected Long doInBackground(Void... params) {
2216 if (!mTab.saveViewState(mValues)) {
2217 return null;
2218 }
2219 if (isCancelled()) {
2220 String path = mValues.getAsString(Snapshots.VIEWSTATE_PATH);
2221 File file = mActivity.getFileStreamPath(path);
2222 if (!file.delete()) {
2223 file.deleteOnExit();
2224 }
2225 return null;
2226 }
2227 final ContentResolver cr = mActivity.getContentResolver();
2228 Uri result = cr.insert(Snapshots.CONTENT_URI, mValues);
2229 if (result == null) {
2230 return null;
2231 }
2232 long id = ContentUris.parseId(result);
2233 return id;
2234 }
2235
2236 @Override
2237 protected void onPostExecute(Long id) {
2238 if (isCancelled()) {
2239 return;
2240 }
2241 mProgressDialog.dismiss();
2242 if (id == null) {
2243 Toast.makeText(mActivity, R.string.snapshot_failed,
2244 Toast.LENGTH_SHORT).show();
2245 return;
2246 }
2247 Bundle b = new Bundle();
2248 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
2249 mUi.showComboView(ComboViews.Snapshots, b);
2250 }
2251
2252 @Override
2253 public void onCancel(DialogInterface dialog) {
2254 cancel(true);
2255 }
2256 }
2257
Michael Kolb80f75082012-04-10 10:50:06 -07002258 @Override
2259 public void toggleUserAgent() {
2260 WebView web = getCurrentWebView();
2261 mSettings.toggleDesktopUseragent(web);
Michael Kolb80f75082012-04-10 10:50:06 -07002262 }
2263
2264 @Override
2265 public void findOnPage() {
2266 getCurrentTopWebView().showFindDialog(null, true);
2267 }
2268
2269 @Override
2270 public void openPreferences() {
Enrico Rosd6efa972014-12-02 19:49:59 -08002271 BrowserPreferencesPage.startPreferencesForResult(mActivity, getCurrentTopWebView().getUrl(), PREFERENCES_PAGE);
Michael Kolb80f75082012-04-10 10:50:06 -07002272 }
2273
2274 @Override
2275 public void bookmarkCurrentPage() {
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002276 WebView w = getCurrentTopWebView();
2277 if (w == null)
2278 return;
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002279 final Intent i = createBookmarkCurrentPageIntent(false);
2280 createScreenshotAsync(
2281 w, getDesiredThumbnailWidth(mActivity),
2282 getDesiredThumbnailHeight(mActivity),
2283 new ValueCallback<Bitmap>() {
2284 @Override
2285 public void onReceiveValue(Bitmap bitmap) {
2286 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL, bitmap);
2287 mActivity.startActivity(i);
2288 }
2289 });
Michael Kolb80f75082012-04-10 10:50:06 -07002290 }
2291
John Recke1a03a32011-09-14 17:04:16 -07002292 private void goLive() {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002293 SnapshotTab t = (SnapshotTab) getCurrentTab();
Tarun Nainani8eb00912014-07-17 12:28:32 -07002294 String url = t.getLiveUrl();
Axesh R. Ajmera8b3ed5d2014-10-22 16:35:25 -07002295 boolean onlySingleTabRemaining = false;
2296 if (mTabControl.getTabCount() > 1) {
2297 // destroy the old snapshot tab
2298 closeCurrentTab();
2299 } else {
2300 onlySingleTabRemaining = true;
2301 }
Tarun Nainani8eb00912014-07-17 12:28:32 -07002302 Tab liveTab = createNewTab(false, true, false);
Axesh R. Ajmera8b3ed5d2014-10-22 16:35:25 -07002303 if (onlySingleTabRemaining) {
2304 closeTab(t);
2305 }
2306
Tarun Nainani8eb00912014-07-17 12:28:32 -07002307 loadUrl(liveTab, url);
John Recke1a03a32011-09-14 17:04:16 -07002308 }
2309
luxiaolb40014b2013-07-19 10:01:43 +08002310 private void showExitDialog(final Activity activity) {
2311 new AlertDialog.Builder(activity)
2312 .setTitle(R.string.exit_browser_title)
Enrico Ros1f5a0952014-11-18 20:15:48 -08002313 /* disabled, was worrying people: .setIcon(android.R.drawable.ic_dialog_alert) */
luxiaolb40014b2013-07-19 10:01:43 +08002314 .setMessage(R.string.exit_browser_msg)
2315 .setNegativeButton(R.string.exit_minimize, new DialogInterface.OnClickListener() {
2316 public void onClick(DialogInterface dialog, int which) {
2317 activity.moveTaskToBack(true);
2318 dialog.dismiss();
2319 }
2320 })
2321 .setPositiveButton(R.string.exit_quit, new DialogInterface.OnClickListener() {
2322 public void onClick(DialogInterface dialog, int which) {
2323 activity.finish();
2324 mHandler.postDelayed(new Runnable() {
2325 @Override
2326 public void run() {
luxiaolb40014b2013-07-19 10:01:43 +08002327 mCrashRecoveryHandler.clearState(true);
2328 int pid = android.os.Process.myPid();
2329 android.os.Process.killProcess(pid);
2330 }
2331 }, 300);
2332 dialog.dismiss();
2333 }
2334 })
2335 .show();
2336 }
Michael Kolb315d5022011-10-13 12:47:11 -07002337 @Override
2338 public void showPageInfo() {
2339 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
2340 }
2341
John Reck9c35b9c2012-05-30 10:08:50 -07002342 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002343 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08002344 // Let the History and Bookmark fragments handle menus they created.
2345 if (item.getGroupId() == R.id.CONTEXT_MENU) {
2346 return false;
2347 }
2348
Michael Kolb8233fac2010-10-26 16:08:53 -07002349 int id = item.getItemId();
2350 boolean result = true;
2351 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002352 // -- Browser context menu
2353 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07002354 case R.id.save_link_context_menu_id:
Tarun Nainani700b69b2014-03-26 16:07:25 -07002355 case R.id.save_link_bookmark_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07002356 case R.id.copy_link_context_menu_id:
2357 final WebView webView = getCurrentTopWebView();
2358 if (null == webView) {
2359 result = false;
2360 break;
2361 }
2362 final HashMap<String, WebView> hrefMap =
2363 new HashMap<String, WebView>();
2364 hrefMap.put("webview", webView);
2365 final Message msg = mHandler.obtainMessage(
2366 FOCUS_NODE_HREF, id, 0, hrefMap);
2367 webView.requestFocusNodeHref(msg);
2368 break;
2369
2370 default:
2371 // For other context menus
2372 result = onOptionsItemSelected(item);
2373 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002374 return result;
2375 }
2376
2377 /**
2378 * support programmatically opening the context menu
2379 */
2380 public void openContextMenu(View view) {
2381 mActivity.openContextMenu(view);
2382 }
2383
2384 /**
2385 * programmatically open the options menu
2386 */
2387 public void openOptionsMenu() {
2388 mActivity.openOptionsMenu();
2389 }
2390
John Reck9c35b9c2012-05-30 10:08:50 -07002391 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002392 public boolean onMenuOpened(int featureId, Menu menu) {
2393 if (mOptionsMenuOpen) {
2394 if (mConfigChanged) {
2395 // We do not need to make any changes to the state of the
2396 // title bar, since the only thing that happened was a
2397 // change in orientation
2398 mConfigChanged = false;
2399 } else {
2400 if (!mExtendedMenuOpen) {
2401 mExtendedMenuOpen = true;
2402 mUi.onExtendedMenuOpened();
2403 } else {
2404 // Switching the menu back to icon view, so show the
2405 // title bar once again.
2406 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002407 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002408 }
2409 }
2410 } else {
2411 // The options menu is closed, so open it, and show the title
2412 mOptionsMenuOpen = true;
2413 mConfigChanged = false;
2414 mExtendedMenuOpen = false;
2415 mUi.onOptionsMenuOpened();
2416 }
2417 return true;
2418 }
2419
John Reck9c35b9c2012-05-30 10:08:50 -07002420 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002421 public void onOptionsMenuClosed(Menu menu) {
2422 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002423 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002424 }
2425
John Reck9c35b9c2012-05-30 10:08:50 -07002426 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002427 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002428 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002429 }
2430
2431 // Helper method for getting the top window.
2432 @Override
2433 public WebView getCurrentTopWebView() {
2434 return mTabControl.getCurrentTopWebView();
2435 }
2436
2437 @Override
2438 public WebView getCurrentWebView() {
2439 return mTabControl.getCurrentWebView();
2440 }
2441
2442 /*
2443 * This method is called as a result of the user selecting the options
2444 * menu to see the download window. It shows the download window on top of
2445 * the current window.
2446 */
2447 void viewDownloads() {
2448 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2449 mActivity.startActivity(intent);
2450 }
2451
John Reck30b065e2011-07-19 10:58:05 -07002452 int getActionModeHeight() {
2453 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
2454 new int[] { android.R.attr.actionBarSize });
2455 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
2456 actionBarSizeTypedArray.recycle();
2457 return size;
2458 }
2459
Michael Kolb8233fac2010-10-26 16:08:53 -07002460 // action mode
2461
John Reck9c35b9c2012-05-30 10:08:50 -07002462 @Override
2463 public void onActionModeStarted(ActionMode mode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002464 mUi.onActionModeStarted(mode);
2465 mActionMode = mode;
2466 }
2467
2468 /*
2469 * True if a custom ActionMode (i.e. find or select) is in use.
2470 */
2471 @Override
2472 public boolean isInCustomActionMode() {
2473 return mActionMode != null;
2474 }
2475
2476 /*
2477 * End the current ActionMode.
2478 */
2479 @Override
2480 public void endActionMode() {
2481 if (mActionMode != null) {
2482 mActionMode.finish();
2483 }
2484 }
2485
2486 /*
2487 * Called by find and select when they are finished. Replace title bars
2488 * as necessary.
2489 */
John Reck9c35b9c2012-05-30 10:08:50 -07002490 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002491 public void onActionModeFinished(ActionMode mode) {
2492 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002493 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002494 mActionMode = null;
2495 }
2496
2497 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08002498 final Tab tab = getCurrentTab();
2499 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002500 }
2501
2502 // bookmark handling
2503
2504 /**
2505 * add the current page as a bookmark to the given folder id
2506 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07002507 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05002508 * bookmarked, and if it is, edit that bookmark. If false, and
2509 * the site is already bookmarked, do not attempt to edit the
2510 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07002511 */
2512 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07002513 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07002514 WebView w = getCurrentTopWebView();
2515 if (w == null) {
2516 return null;
2517 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002518 Intent i = new Intent(mActivity,
2519 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07002520 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
2521 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
2522 String touchIconUrl = w.getTouchIconUrl();
2523 if (touchIconUrl != null) {
2524 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
2525 WebSettings settings = w.getSettings();
2526 if (settings != null) {
2527 i.putExtra(AddBookmarkPage.USER_AGENT,
2528 settings.getUserAgentString());
2529 }
2530 }
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002531 //SWE: Thumbnail will need to be set asynchronously
Michael Kolb8233fac2010-10-26 16:08:53 -07002532 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07002533 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05002534 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
2535 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002536 // Put the dialog at the upper right of the screen, covering the
2537 // star on the title bar.
2538 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07002539 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07002540 }
2541
2542 // file chooser
John Reck9c35b9c2012-05-30 10:08:50 -07002543 @Override
Ben Murdoch8cad4132012-01-11 10:56:43 +00002544 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002545 mUploadHandler = new UploadHandler(this);
Ben Murdoch8cad4132012-01-11 10:56:43 +00002546 mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
Michael Kolb8233fac2010-10-26 16:08:53 -07002547 }
2548
Vivek Sekharb54614f2014-05-01 19:03:37 -07002549 @Override
2550 public void showFileChooser(ValueCallback<String[]> uploadFilePaths, String acceptTypes,
2551 boolean capture) {
2552 mUploadHandler = new UploadHandler(this);
2553 mUploadHandler.showFileChooser(uploadFilePaths, acceptTypes, capture);
2554 }
2555
Michael Kolb8233fac2010-10-26 16:08:53 -07002556 // thumbnails
2557
2558 /**
2559 * Return the desired width for thumbnail screenshots, which are stored in
2560 * the database, and used on the bookmarks screen.
2561 * @param context Context for finding out the density of the screen.
2562 * @return desired width for thumbnail screenshot.
2563 */
2564 static int getDesiredThumbnailWidth(Context context) {
2565 return context.getResources().getDimensionPixelOffset(
2566 R.dimen.bookmarkThumbnailWidth);
2567 }
2568
2569 /**
2570 * Return the desired height for thumbnail screenshots, which are stored in
2571 * the database, and used on the bookmarks screen.
2572 * @param context Context for finding out the density of the screen.
2573 * @return desired height for thumbnail screenshot.
2574 */
2575 static int getDesiredThumbnailHeight(Context context) {
2576 return context.getResources().getDimensionPixelOffset(
2577 R.dimen.bookmarkThumbnailHeight);
2578 }
2579
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002580 static void createScreenshotAsync(WebView view, int width, int height,
2581 final ValueCallback<Bitmap> cb) {
2582 if (view == null || width == 0 || height == 0) {
2583 return;
2584 }
2585
2586 view.getContentBitmapAsync(
2587 (float) width / view.getWidth(),
2588 new Rect(),
2589 new ValueCallback<Bitmap>() {
2590 @Override
2591 public void onReceiveValue(Bitmap bitmap) {
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002592 if (bitmap != null)
2593 bitmap = bitmap.copy(Bitmap.Config.RGB_565, false);
2594 cb.onReceiveValue(bitmap);
2595 }});
2596 }
2597
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002598 private void updateScreenshot(final Tab tab) {
2599 createScreenshotAsync(
2600 tab.getWebView(),
2601 getDesiredThumbnailWidth(mActivity),
2602 getDesiredThumbnailHeight(mActivity),
2603 new ValueCallback<Bitmap>() {
2604 @Override
2605 public void onReceiveValue(Bitmap bitmap) {
2606 updateScreenshot(tab, bitmap);
2607 }
2608 });
2609 }
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002610
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002611 private void updateScreenshot(Tab tab, final Bitmap bm) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002612 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002613 // FIXME: Would like to make sure there is actually something to
2614 // draw, but the API for that (WebViewCore.pictureReady()) is not
2615 // currently accessible here.
2616
John Reck34ef2672011-02-10 11:30:55 -08002617 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002618 if (view == null) {
2619 // Tab was destroyed
2620 return;
2621 }
John Reck34ef2672011-02-10 11:30:55 -08002622 final String url = tab.getUrl();
2623 final String originalUrl = view.getOriginalUrl();
kaiyiz6e5b3e02013-08-19 20:02:01 +08002624 final String thumbnailUrl = mUpdateMyNavThumbnailUrl;
John Reck34ef2672011-02-10 11:30:55 -08002625 if (TextUtils.isEmpty(url)) {
2626 return;
2627 }
2628
kaiyiz6e5b3e02013-08-19 20:02:01 +08002629 //update My Navigation Thumbnails
Tarun Nainanicc8ac9e2015-01-08 14:45:21 -08002630 if (bm != null) {
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002631 updateMyNavigationThumbnail(url, bm);
kaiyiz6e5b3e02013-08-19 20:02:01 +08002632 }
John Reck34ef2672011-02-10 11:30:55 -08002633 // Only update thumbnails for web urls (http(s)://), not for
2634 // about:, javascript:, data:, etc...
2635 // Unless it is a bookmarked site, then always update
2636 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2637 return;
2638 }
2639
kaiyiz6e5b3e02013-08-19 20:02:01 +08002640 if (url != null && mUpdateMyNavThumbnailUrl != null
2641 && Patterns.WEB_URL.matcher(url).matches()
2642 && Patterns.WEB_URL.matcher(mUpdateMyNavThumbnailUrl).matches()) {
2643 String urlHost = (new WebAddress(url)).getHost();
2644 String bookmarkHost = (new WebAddress(mUpdateMyNavThumbnailUrl)).getHost();
2645 if (urlHost == null || urlHost.length() == 0 || bookmarkHost == null
2646 || bookmarkHost.length() == 0) {
2647 return;
2648 }
2649 String urlDomain = urlHost.substring(urlHost.indexOf('.'), urlHost.length());
2650 String bookmarkDomain = bookmarkHost.substring(bookmarkHost.indexOf('.'),
2651 bookmarkHost.length());
2652 Log.d(LOGTAG, "addressUrl domain is " + urlDomain);
2653 Log.d(LOGTAG, "bookmarkUrl domain is " + bookmarkDomain);
2654 if (!bookmarkDomain.equals(urlDomain)) {
2655 return;
2656 }
2657 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002658 if (bm == null) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002659 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
2660 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2661 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
2662 500);
2663 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002664 return;
2665 }
2666
2667 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002668 new AsyncTask<Void, Void, Void>() {
2669 @Override
2670 protected Void doInBackground(Void... unused) {
2671 Cursor cursor = null;
2672 try {
2673 // TODO: Clean this up
kaiyiz6e5b3e02013-08-19 20:02:01 +08002674 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl,
2675 mUpdateMyNavThumbnail ? ((thumbnailUrl != null) ? thumbnailUrl : url)
2676 : url);
2677 if (mUpdateMyNavThumbnail) {
2678 mUpdateMyNavThumbnail = false;
2679 mUpdateMyNavThumbnailUrl = null;
2680 }
John Reck34ef2672011-02-10 11:30:55 -08002681 if (cursor != null && cursor.moveToFirst()) {
2682 final ByteArrayOutputStream os =
2683 new ByteArrayOutputStream();
2684 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002685
John Reck34ef2672011-02-10 11:30:55 -08002686 ContentValues values = new ContentValues();
2687 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002688
John Reck34ef2672011-02-10 11:30:55 -08002689 do {
John Reck617fd832011-02-16 14:35:59 -08002690 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002691 cr.update(Images.CONTENT_URI, values, null, null);
2692 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002693 }
John Reck34ef2672011-02-10 11:30:55 -08002694 } catch (IllegalStateException e) {
2695 // Ignore
Mattias Nilsson561d1952011-10-04 10:18:50 +02002696 } catch (SQLiteException s) {
2697 // Added for possible error when user tries to remove the same bookmark
2698 // that is being updated with a screen shot
2699 Log.w(LOGTAG, "Error when running updateScreenshot ", s);
John Reck34ef2672011-02-10 11:30:55 -08002700 } finally {
2701 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002702 }
John Reck34ef2672011-02-10 11:30:55 -08002703 return null;
2704 }
2705 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002706 }
2707
2708 private class Copy implements OnMenuItemClickListener {
2709 private CharSequence mText;
2710
John Reck9c35b9c2012-05-30 10:08:50 -07002711 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002712 public boolean onMenuItemClick(MenuItem item) {
2713 copy(mText);
2714 return true;
2715 }
2716
2717 public Copy(CharSequence toCopy) {
2718 mText = toCopy;
2719 }
2720 }
2721
Leon Scroggins63c02662010-11-18 15:16:27 -05002722 private static class Download implements OnMenuItemClickListener {
2723 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002724 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002725 private boolean mPrivateBrowsing;
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002726 private String mUserAgent;
George Mount387d45d2011-10-07 15:57:53 -07002727 private static final String FALLBACK_EXTENSION = "dat";
2728 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002729
John Reck9c35b9c2012-05-30 10:08:50 -07002730 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002731 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002732 if (DataUri.isDataUri(mText)) {
2733 saveDataUri();
2734 } else {
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002735 DownloadHandler.onDownloadStartNoStream(mActivity, mText, mUserAgent,
luxiaol62677b02013-07-22 07:54:49 +08002736 null, null, null, mPrivateBrowsing, 0);
George Mount387d45d2011-10-07 15:57:53 -07002737 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002738 return true;
2739 }
2740
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002741 public Download(Activity activity, String toDownload, boolean privateBrowsing,
2742 String userAgent) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002743 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002744 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002745 mPrivateBrowsing = privateBrowsing;
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002746 mUserAgent = userAgent;
Michael Kolb8233fac2010-10-26 16:08:53 -07002747 }
George Mount387d45d2011-10-07 15:57:53 -07002748
2749 /**
2750 * Treats mText as a data URI and writes its contents to a file
2751 * based on the current time.
2752 */
2753 private void saveDataUri() {
2754 FileOutputStream outputStream = null;
2755 try {
2756 DataUri uri = new DataUri(mText);
2757 File target = getTarget(uri);
2758 outputStream = new FileOutputStream(target);
2759 outputStream.write(uri.getData());
2760 final DownloadManager manager =
2761 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2762 manager.addCompletedDownload(target.getName(),
2763 mActivity.getTitle().toString(), false,
2764 uri.getMimeType(), target.getAbsolutePath(),
John Reck9c35b9c2012-05-30 10:08:50 -07002765 uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002766 } catch (IOException e) {
2767 Log.e(LOGTAG, "Could not save data URL");
2768 } finally {
2769 if (outputStream != null) {
2770 try {
2771 outputStream.close();
2772 } catch (IOException e) {
2773 // ignore close errors
2774 }
2775 }
2776 }
2777 }
2778
2779 /**
2780 * Creates a File based on the current time stamp and uses
2781 * the mime type of the DataUri to get the extension.
2782 */
2783 private File getTarget(DataUri uri) throws IOException {
2784 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
Johan Redestigaa676182012-10-03 13:33:01 +02002785 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT, Locale.US);
George Mount387d45d2011-10-07 15:57:53 -07002786 String nameBase = format.format(new Date());
2787 String mimeType = uri.getMimeType();
2788 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2789 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2790 if (extension == null) {
2791 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2792 extension = FALLBACK_EXTENSION;
2793 }
2794 extension = "." + extension; // createTempFile needs the '.'
2795 File targetFile = File.createTempFile(nameBase, extension, dir);
2796 return targetFile;
2797 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002798 }
2799
Cary Clark8974d282010-11-22 10:46:05 -05002800 private static class SelectText implements OnMenuItemClickListener {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002801 private WebView mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002802
John Reck9c35b9c2012-05-30 10:08:50 -07002803 @Override
Cary Clark8974d282010-11-22 10:46:05 -05002804 public boolean onMenuItemClick(MenuItem item) {
2805 if (mWebView != null) {
2806 return mWebView.selectText();
2807 }
2808 return false;
2809 }
2810
2811 public SelectText(WebView webView) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002812 mWebView = webView;
Cary Clark8974d282010-11-22 10:46:05 -05002813 }
2814
2815 }
2816
Michael Kolb8233fac2010-10-26 16:08:53 -07002817 /********************** TODO: UI stuff *****************************/
2818
2819 // these methods have been copied, they still need to be cleaned up
2820
2821 /****************** tabs ***************************************************/
2822
2823 // basic tab interactions:
2824
2825 // it is assumed that tabcontrol already knows about the tab
2826 protected void addTab(Tab tab) {
2827 mUi.addTab(tab);
2828 }
2829
2830 protected void removeTab(Tab tab) {
2831 mUi.removeTab(tab);
2832 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002833 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002834 }
2835
Michael Kolbf2055602011-04-09 17:20:03 -07002836 @Override
2837 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002838 // monkey protection against delayed start
2839 if (tab != null) {
2840 mTabControl.setCurrentTab(tab);
2841 // the tab is guaranteed to have a webview after setCurrentTab
2842 mUi.setActiveTab(tab);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002843 tab.setTimeStamp();
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07002844 //Purge active tabs
2845 MemoryMonitor.purgeActiveTabs(mActivity.getApplicationContext(), this, mSettings);
Michael Kolbcd424e92011-02-24 10:26:26 -08002846 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002847 }
2848
John Reck8bcafc12011-08-29 16:43:02 -07002849 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002850 Tab current = mTabControl.getCurrentTab();
2851 if (current != null
2852 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002853 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002854 }
2855 }
2856
John Reck26b18322011-06-21 13:08:58 -07002857 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002858 // Dismiss the subwindow if applicable.
2859 dismissSubWindow(appTab);
2860 // Since we might kill the WebView, remove it from the
2861 // content view first.
2862 mUi.detachTab(appTab);
2863 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002864 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002865 // TODO: analyze why the remove and add are necessary
2866 mUi.attachTab(appTab);
2867 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002868 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002869 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002870 } else {
2871 // If the tab was the current tab, we have to attach
2872 // it to the view system again.
2873 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002874 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002875 }
2876 }
2877
2878 // Remove the sub window if it exists. Also called by TabControl when the
2879 // user clicks the 'X' to dismiss a sub window.
John Reck9c35b9c2012-05-30 10:08:50 -07002880 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002881 public void dismissSubWindow(Tab tab) {
2882 removeSubWindow(tab);
2883 // dismiss the subwindow. This will destroy the WebView.
2884 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002885 WebView wv = getCurrentTopWebView();
2886 if (wv != null) {
2887 wv.requestFocus();
2888 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002889 }
2890
2891 @Override
2892 public void removeSubWindow(Tab t) {
2893 if (t.getSubWebView() != null) {
2894 mUi.removeSubWindow(t.getSubViewContainer());
2895 }
2896 }
2897
2898 @Override
2899 public void attachSubWindow(Tab tab) {
2900 if (tab.getSubWebView() != null) {
2901 mUi.attachSubWindow(tab.getSubViewContainer());
2902 getCurrentTopWebView().requestFocus();
2903 }
2904 }
2905
Mathew Inwood29721c22011-06-29 17:55:24 +01002906 private Tab showPreloadedTab(final UrlData urlData) {
2907 if (!urlData.isPreloaded()) {
2908 return null;
2909 }
2910 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2911 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2912 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002913 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002914 // Could not submit query. Fallback to regular tab creation
2915 tabControl.destroy();
2916 return null;
2917 }
2918 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002919 // check tab count and make room for new tab
2920 if (!mTabControl.canCreateNewTab()) {
2921 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2922 if (leastUsed != null) {
2923 closeTab(leastUsed);
2924 }
2925 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002926 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002927 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002928 mTabControl.addPreloadedTab(t);
2929 addTab(t);
2930 setActiveTab(t);
2931 return t;
2932 }
2933
Michael Kolb7bcafde2011-05-09 13:55:59 -07002934 // open a non inconito tab with the given url data
2935 // and set as active tab
2936 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002937 Tab tab = showPreloadedTab(urlData);
2938 if (tab == null) {
2939 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002940 if ((tab != null) && !urlData.isEmpty()) {
2941 loadUrlDataIn(tab, urlData);
2942 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002943 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002944 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002945 }
2946
Michael Kolb843510f2010-12-09 10:51:49 -08002947 @Override
2948 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002949 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002950 }
2951
Michael Kolb8233fac2010-10-26 16:08:53 -07002952 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002953 public Tab openIncognitoTab() {
2954 return openTab(INCOGNITO_URI, true, true, false);
2955 }
2956
2957 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002958 public Tab openTab(String url, boolean incognito, boolean setActive,
2959 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002960 return openTab(url, incognito, setActive, useCurrent, null);
2961 }
2962
2963 @Override
2964 public Tab openTab(String url, Tab parent, boolean setActive,
2965 boolean useCurrent) {
2966 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2967 setActive, useCurrent, parent);
2968 }
2969
2970 public Tab openTab(String url, boolean incognito, boolean setActive,
2971 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002972 Tab tab = createNewTab(incognito, setActive, useCurrent);
2973 if (tab != null) {
Vivek Sekhar871172e2014-07-23 12:16:54 -07002974 if (parent instanceof SnapshotTab) {
2975 addTab(tab);
2976 if (setActive)
2977 setActiveTab(tab);
2978 }else if (parent != null && parent != tab) {
John Reck5949c662011-05-27 09:52:29 -07002979 parent.addChildTab(tab);
2980 }
Michael Kolb519d2282011-05-09 17:03:19 -07002981 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002982 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002983 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002984 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002985 return tab;
2986 }
2987
2988 // this method will attempt to create a new tab
2989 // incognito: private browsing tab
2990 // setActive: ste tab as current tab
2991 // useCurrent: if no new tab can be created, return current tab
2992 private Tab createNewTab(boolean incognito, boolean setActive,
2993 boolean useCurrent) {
2994 Tab tab = null;
2995 if (mTabControl.canCreateNewTab()) {
Stewart Chaoe0e132e2014-12-01 18:28:22 -05002996 tab = mTabControl.createNewTab(incognito, !setActive);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002997 addTab(tab);
2998 if (setActive) {
2999 setActiveTab(tab);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07003000 } else {
3001 tab.pause();
Michael Kolb7bcafde2011-05-09 13:55:59 -07003002 }
3003 } else {
3004 if (useCurrent) {
3005 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07003006 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07003007 } else {
3008 mUi.showMaxTabsWarning();
3009 }
3010 }
3011 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07003012 }
3013
John Reck2bc80422011-06-30 15:11:49 -07003014 @Override
3015 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
3016 SnapshotTab tab = null;
3017 if (mTabControl.canCreateNewTab()) {
3018 tab = mTabControl.createSnapshotTab(snapshotId);
3019 addTab(tab);
3020 if (setActive) {
3021 setActiveTab(tab);
3022 }
3023 } else {
3024 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07003025 }
3026 return tab;
3027 }
3028
Michael Kolb8233fac2010-10-26 16:08:53 -07003029 /**
Michael Kolbc831b632011-05-11 09:30:34 -07003030 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07003031 * @return boolean True if we successfully switched to a different tab. If
3032 * the indexth tab is null, or if that tab is the same as
3033 * the current one, return false.
3034 */
3035 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07003036 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003037 Tab currentTab = mTabControl.getCurrentTab();
3038 if (tab == null || tab == currentTab) {
3039 return false;
3040 }
3041 setActiveTab(tab);
3042 return true;
3043 }
3044
3045 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07003046 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07003047 closeCurrentTab(false);
3048 }
3049
3050 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003051 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07003052 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07003053 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08003054 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07003055 return;
3056 }
Michael Kolbc831b632011-05-11 09:30:34 -07003057 final Tab current = mTabControl.getCurrentTab();
3058 final int pos = mTabControl.getCurrentPosition();
3059 Tab newTab = current.getParent();
3060 if (newTab == null) {
3061 newTab = mTabControl.getTab(pos + 1);
3062 if (newTab == null) {
3063 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07003064 }
3065 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07003066 if (andQuit) {
3067 mTabControl.setCurrentTab(newTab);
3068 closeTab(current);
3069 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003070 // Close window
3071 closeTab(current);
3072 }
3073 }
3074
3075 /**
3076 * Close the tab, remove its associated title bar, and adjust mTabControl's
3077 * current tab to a valid value.
3078 */
3079 @Override
3080 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07003081 if (tab == mTabControl.getCurrentTab()) {
3082 closeCurrentTab();
3083 } else {
3084 removeTab(tab);
3085 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003086 }
3087
Afzal Najamd4e33312012-04-26 01:54:01 -04003088 /**
3089 * Close all tabs except the current one
3090 */
3091 @Override
3092 public void closeOtherTabs() {
3093 int inactiveTabs = mTabControl.getTabCount() - 1;
3094 for (int i = inactiveTabs; i >= 0; i--) {
3095 Tab tab = mTabControl.getTab(i);
3096 if (tab != mTabControl.getCurrentTab()) {
3097 removeTab(tab);
3098 }
3099 }
3100 }
3101
Michael Kolb8233fac2010-10-26 16:08:53 -07003102 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07003103 protected void loadUrlFromContext(String url) {
3104 Tab tab = getCurrentTab();
3105 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07003106 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07003107 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003108 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixone1d6dfc2012-12-17 13:39:17 -08003109 if (!((BrowserWebView) view).getWebViewClient().
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00003110 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07003111 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07003112 }
3113 }
3114 }
3115
3116 /**
3117 * Load the URL into the given WebView and update the title bar
3118 * to reflect the new load. Call this instead of WebView.loadUrl
3119 * directly.
3120 * @param view The WebView used to load url.
3121 * @param url The URL to load.
3122 */
John Reck71e51422011-07-01 16:49:28 -07003123 @Override
3124 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07003125 loadUrl(tab, url, null);
3126 }
3127
3128 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
3129 if (tab != null) {
3130 dismissSubWindow(tab);
Vivek Sekhar0e10a202014-09-12 19:13:23 -07003131 mHomepageHandler.registerJsInterface(tab.getWebView(), url);
John Reck26b18322011-06-21 13:08:58 -07003132 tab.loadUrl(url, headers);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003133 if (tab.hasCrashed) {
3134 tab.replaceCrashView(tab.getWebView(), tab.getViewContainer());
3135 }
Michael Kolba53c9892011-10-05 13:31:40 -07003136 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07003137 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003138 }
3139
3140 /**
3141 * Load UrlData into a Tab and update the title bar to reflect the new
3142 * load. Call this instead of UrlData.loadIn directly.
3143 * @param t The Tab used to load.
3144 * @param data The UrlData being loaded.
3145 */
3146 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07003147 if (data != null) {
Michael Kolb5ff5c8b2012-05-03 11:37:58 -07003148 if (data.isPreloaded()) {
Michael Kolb14612442011-06-24 13:06:29 -07003149 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07003150 } else {
John Reck38b39652012-06-05 09:22:59 -07003151 if (t != null && data.mDisableUrlOverride) {
3152 t.disableUrlOverridingForLoad();
3153 }
John Reck26b18322011-06-21 13:08:58 -07003154 loadUrl(t, data.mUrl, data.mHeaders);
3155 }
3156 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003157 }
3158
John Reck30c714c2010-12-16 17:30:34 -08003159 @Override
3160 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08003161 // TODO: Figure out the "right" behavior
Tarun Nainani1f481922014-12-18 13:54:54 -08003162 //In case of tab can go back (aka tab has navigation entry) do nothing
3163 //else just load homepage in current tab.
3164 if (!tab.canGoBack()) {
John Reckef654f12011-07-12 16:42:08 -07003165 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08003166 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003167 }
3168
3169 void goBackOnePageOrQuit() {
3170 Tab current = mTabControl.getCurrentTab();
3171 if (current == null) {
Panos Thomas4bdb5252014-11-13 16:20:11 -08003172 if (BrowserConfig.getInstance(getContext()).hasFeature(BrowserConfig.Feature.EXIT_DIALOG)) {
3173 showExitDialog(mActivity);
3174 } else {
3175 /*
3176 * Instead of finishing the activity, simply push this to the back
3177 * of the stack and let ActivityManager to choose the foreground
3178 * activity. As BrowserActivity is singleTask, it will be always the
3179 * root of the task. So we can use either true or false for
3180 * moveTaskToBack().
3181 */
3182 mActivity.moveTaskToBack(true);
3183 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003184 return;
3185 }
John Reckef654f12011-07-12 16:42:08 -07003186 if (current.canGoBack()) {
3187 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07003188 } else {
3189 // Check to see if we are closing a window that was created by
3190 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07003191 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07003192 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07003193 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07003194 // Now we close the other tab
3195 closeTab(current);
Panos Thomas4bdb5252014-11-13 16:20:11 -08003196 } else if (BrowserConfig.getInstance(getContext())
3197 .hasFeature(BrowserConfig.Feature.EXIT_DIALOG)) {
3198 showExitDialog(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -07003199 } else {
Panos Thomas4bdb5252014-11-13 16:20:11 -08003200 if ((current.getAppId() != null) || current.closeOnBack()) {
3201 closeCurrentTab(true);
3202 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003203 /*
3204 * Instead of finishing the activity, simply push this to the back
3205 * of the stack and let ActivityManager to choose the foreground
3206 * activity. As BrowserActivity is singleTask, it will be always the
3207 * root of the task. So we can use either true or false for
3208 * moveTaskToBack().
3209 */
Panos Thomas4bdb5252014-11-13 16:20:11 -08003210 mActivity.moveTaskToBack(true);
Michael Kolb8233fac2010-10-26 16:08:53 -07003211 }
3212 }
3213 }
3214
3215 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07003216 * helper method for key handler
3217 * returns the current tab if it can't advance
3218 */
Michael Kolbc831b632011-05-11 09:30:34 -07003219 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08003220 int pos = mTabControl.getCurrentPosition() + 1;
3221 if (pos >= mTabControl.getTabCount()) {
3222 pos = 0;
3223 }
3224 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07003225 }
3226
3227 /**
3228 * helper method for key handler
3229 * returns the current tab if it can't advance
3230 */
Michael Kolbc831b632011-05-11 09:30:34 -07003231 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08003232 int pos = mTabControl.getCurrentPosition() - 1;
3233 if ( pos < 0) {
3234 pos = mTabControl.getTabCount() - 1;
3235 }
3236 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07003237 }
3238
John Reckbcef87f2012-02-03 14:58:34 -08003239 boolean isMenuOrCtrlKey(int keyCode) {
3240 return (KeyEvent.KEYCODE_MENU == keyCode)
3241 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
3242 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
3243 }
3244
Michael Kolb0035fad2011-03-14 13:25:28 -07003245 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07003246 * handle key events in browser
3247 *
3248 * @param keyCode
3249 * @param event
3250 * @return true if handled, false to pass to super
3251 */
John Reck9c35b9c2012-05-30 10:08:50 -07003252 @Override
3253 public boolean onKeyDown(int keyCode, KeyEvent event) {
Pankaj Garg49b79252014-11-07 17:33:41 -08003254 if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
3255 // Hardware menu key
Enrico Ros1f5a0952014-11-18 20:15:48 -08003256 mAppMenuHandler.showAppMenu(mActivity.findViewById(R.id.taburlbar),
Pankaj Garg49b79252014-11-07 17:33:41 -08003257 true, false);
3258 return true;
3259 }
3260
Cary Clark160bbb92011-01-10 11:17:07 -05003261 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07003262 // Even if MENU is already held down, we need to call to super to open
3263 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08003264 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003265 mMenuIsDown = true;
3266 return false;
3267 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003268
Cary Clark8ff8c662010-12-29 15:03:05 -05003269 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07003270 Tab tab = getCurrentTab();
3271 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05003272
Cary Clark160bbb92011-01-10 11:17:07 -05003273 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
3274 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05003275
Michael Kolb8233fac2010-10-26 16:08:53 -07003276 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07003277 case KeyEvent.KEYCODE_TAB:
3278 if (event.isCtrlPressed()) {
3279 if (event.isShiftPressed()) {
3280 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07003281 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07003282 } else {
3283 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07003284 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07003285 }
3286 return true;
3287 }
3288 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07003289 case KeyEvent.KEYCODE_SPACE:
3290 // WebView/WebTextView handle the keys in the KeyDown. As
3291 // the Activity's shortcut keys are only handled when WebView
3292 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05003293 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003294 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05003295 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003296 pageDown();
3297 }
3298 return true;
3299 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05003300 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08003301 event.startTracking();
3302 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07003303 case KeyEvent.KEYCODE_FORWARD:
3304 if (!noModifiers) break;
3305 tab.goForward();
3306 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05003307 case KeyEvent.KEYCODE_DPAD_LEFT:
3308 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07003309 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05003310 return true;
3311 }
3312 break;
3313 case KeyEvent.KEYCODE_DPAD_RIGHT:
3314 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07003315 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05003316 return true;
3317 }
3318 break;
3319 case KeyEvent.KEYCODE_A:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003320 if (ctrl) {
3321 webView.selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05003322 return true;
3323 }
3324 break;
Michael Kolba4183062011-01-16 10:43:21 -08003325// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003326 case KeyEvent.KEYCODE_C:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003327 if (ctrl ) {
3328 webView.copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05003329 return true;
3330 }
3331 break;
Michael Kolba4183062011-01-16 10:43:21 -08003332// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003333// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08003334// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003335// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08003336// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003337// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08003338// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003339// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08003340// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003341// case KeyEvent.KEYCODE_M: // unused
3342// case KeyEvent.KEYCODE_N: // in Chrome: new window
3343// case KeyEvent.KEYCODE_O: // in Chrome: open file
3344// case KeyEvent.KEYCODE_P: // in Chrome: print page
3345// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003346// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05003347// case KeyEvent.KEYCODE_S: // in Chrome: saves page
3348 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003349 // we can't use the ctrl/shift flags, they check for
3350 // exclusive use of a modifier
3351 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05003352 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07003353 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05003354 } else {
3355 openTabToHomePage();
3356 }
3357 return true;
3358 }
3359 break;
3360// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
3361// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07003362// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003363// case KeyEvent.KEYCODE_X: // text view intercepts to cut
3364// case KeyEvent.KEYCODE_Y: // unused
3365// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07003366 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003367 // it is a regular key and webview is not null
3368 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07003369 }
3370
John Reck9c35b9c2012-05-30 10:08:50 -07003371 @Override
3372 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
John Recke6bf4ab2011-02-24 15:48:05 -08003373 switch(keyCode) {
3374 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07003375 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07003376 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08003377 return true;
3378 }
3379 break;
3380 }
3381 return false;
3382 }
3383
John Reck9c35b9c2012-05-30 10:08:50 -07003384 @Override
3385 public boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08003386 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07003387 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08003388 if (KeyEvent.KEYCODE_MENU == keyCode
3389 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07003390 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07003391 }
3392 }
Cary Clark160bbb92011-01-10 11:17:07 -05003393 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07003394 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003395 case KeyEvent.KEYCODE_BACK:
3396 if (event.isTracking() && !event.isCanceled()) {
3397 onBackKey();
3398 return true;
3399 }
3400 break;
3401 }
3402 return false;
3403 }
3404
3405 public boolean isMenuDown() {
3406 return mMenuIsDown;
3407 }
3408
John Reck9c35b9c2012-05-30 10:08:50 -07003409 @Override
Ben Murdoch8029a772010-11-16 11:58:21 +00003410 public void setupAutoFill(Message message) {
3411 // Open the settings activity at the AutoFill profile fragment so that
3412 // the user can create a new profile. When they return, we will dispatch
3413 // the message so that we can autofill the form using their new profile.
Ben Murdoch8029a772010-11-16 11:58:21 +00003414 mAutoFillSetupMessage = message;
Enrico Rosd6efa972014-12-02 19:49:59 -08003415 BrowserPreferencesPage.startPreferenceFragmentForResult(mActivity,
3416 AutoFillSettingsFragment.class.getName(), AUTOFILL_SETUP);
Ben Murdoch8029a772010-11-16 11:58:21 +00003417 }
John Reckb3417f02011-01-14 11:01:05 -08003418
John Reck9c35b9c2012-05-30 10:08:50 -07003419 @Override
Michael Kolbfbc579a2011-07-07 15:59:33 -07003420 public boolean onSearchRequested() {
Michael Kolb1f9b3562012-04-24 14:38:34 -07003421 mUi.editUrl(false, true);
Michael Kolbfbc579a2011-07-07 15:59:33 -07003422 return true;
3423 }
3424
John Reck1cf4b792011-07-26 10:22:22 -07003425 @Override
3426 public boolean shouldCaptureThumbnails() {
3427 return mUi.shouldCaptureThumbnails();
3428 }
3429
Michael Kolbc3af0672011-08-09 10:24:41 -07003430 @Override
Michael Kolb0b129122012-06-04 16:31:58 -07003431 public boolean supportsVoice() {
3432 PackageManager pm = mActivity.getPackageManager();
3433 List activities = pm.queryIntentActivities(new Intent(
3434 RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
3435 return activities.size() != 0;
3436 }
3437
3438 @Override
3439 public void startVoiceRecognizer() {
3440 Intent voice = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003441 voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
Michael Kolb0b129122012-06-04 16:31:58 -07003442 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
3443 voice.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
3444 mActivity.startActivityForResult(voice, VOICE_RESULT);
3445 }
3446
Pankaj Garg7b279f62014-08-12 14:47:18 -07003447 public void setWindowDimming(float level) {
Vivek Sekharb991edb2014-12-17 18:18:07 -08003448 if (mLevel == level)
3449 return;
3450 mLevel = level;
3451 if (level != 0.0f) {
Pankaj Garg7b279f62014-08-12 14:47:18 -07003452 WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
3453 lp.dimAmount = level;
3454 mActivity.getWindow().setAttributes(lp);
3455 mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
3456 } else {
3457 mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
3458 }
3459 }
3460
Michael Kolb0b129122012-06-04 16:31:58 -07003461 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003462 public void setBlockEvents(boolean block) {
3463 mBlockEvents = block;
3464 }
3465
John Reck9c35b9c2012-05-30 10:08:50 -07003466 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003467 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07003468 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003469 }
3470
John Reck9c35b9c2012-05-30 10:08:50 -07003471 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003472 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07003473 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003474 }
3475
John Reck9c35b9c2012-05-30 10:08:50 -07003476 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003477 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003478 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003479 }
3480
John Reck9c35b9c2012-05-30 10:08:50 -07003481 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003482 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003483 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003484 }
3485
John Reck9c35b9c2012-05-30 10:08:50 -07003486 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003487 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003488 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003489 }
3490
Pankaj Garg49b79252014-11-07 17:33:41 -08003491 @Override
3492 public boolean shouldShowAppMenu() {
3493 return true;
3494 }
3495
3496 @Override
3497 public int getMenuThemeResourceId() {
3498 return R.style.OverflowMenuTheme;
3499 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003500}