blob: f0aa5572f8a9da90608bb1a2e3cbbcb932614bcf [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;
145
146 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
147
148 private static final int OPEN_BOOKMARKS = 201;
kaiyiz591110b2013-08-06 17:11:06 +0800149 private static final int OPEN_MENU = 202;
Michael Kolb8233fac2010-10-26 16:08:53 -0700150
151 private static final int EMPTY_MENU = -1;
152
Michael Kolb8233fac2010-10-26 16:08:53 -0700153 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700154 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700155 final static int PREFERENCES_PAGE = 3;
156 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000157 final static int AUTOFILL_SETUP = 5;
Michael Kolb0b129122012-06-04 16:31:58 -0700158 final static int VOICE_RESULT = 6;
kaiyiz6e5b3e02013-08-19 20:02:01 +0800159 final static int MY_NAVIGATION = 7;
Ben Murdoch8029a772010-11-16 11:58:21 +0000160
Michael Kolb8233fac2010-10-26 16:08:53 -0700161 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
162
163 // As the ids are dynamically created, we can't guarantee that they will
164 // be in sequence, so this static array maps ids to a window number.
165 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
166 { R.id.window_one_menu_id, R.id.window_two_menu_id,
167 R.id.window_three_menu_id, R.id.window_four_menu_id,
168 R.id.window_five_menu_id, R.id.window_six_menu_id,
169 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
170
171 // "source" parameter for Google search through search key
172 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
173 // "source" parameter for Google search through simplily type
174 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
175
George Mount387d45d2011-10-07 15:57:53 -0700176 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700177 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
178
John Reckd7dd9b22011-08-30 09:18:29 -0700179 // A bitmap that is re-used in createScreenshot as scratch space
180 private static Bitmap sThumbnailBitmap;
181
Michael Kolb8233fac2010-10-26 16:08:53 -0700182 private Activity mActivity;
183 private UI mUi;
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700184 private HomepageHandler mHomepageHandler;
185 protected TabControl mTabControl;
Michael Kolb8233fac2010-10-26 16:08:53 -0700186 private BrowserSettings mSettings;
187 private WebViewFactory mFactory;
188
189 private WakeLock mWakeLock;
190
191 private UrlHandler mUrlHandler;
192 private UploadHandler mUploadHandler;
193 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700194 private PageDialogsHandler mPageDialogsHandler;
195 private NetworkStateHandler mNetworkHandler;
196
Ben Murdoch8029a772010-11-16 11:58:21 +0000197 private Message mAutoFillSetupMessage;
198
Michael Kolb8233fac2010-10-26 16:08:53 -0700199 private boolean mShouldShowErrorConsole;
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;
Michael Kolb0b129122012-06-04 16:31:58 -0700253
George Mount3636d0a2011-11-21 09:08:21 -0800254 public Controller(Activity browser) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700255 mActivity = browser;
256 mSettings = BrowserSettings.getInstance();
257 mTabControl = new TabControl(this);
258 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700259 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
George Mount3636d0a2011-11-21 09:08:21 -0800260 mCrashRecoveryHandler.preloadCrashState();
Michael Kolb14612442011-06-24 13:06:29 -0700261 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700262
263 mUrlHandler = new UrlHandler(this);
264 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700265 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
266
Michael Kolb8233fac2010-10-26 16:08:53 -0700267 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500268 mBookmarksObserver = new ContentObserver(mHandler) {
269 @Override
270 public void onChange(boolean selfChange) {
271 int size = mTabControl.getTabCount();
272 for (int i = 0; i < size; i++) {
273 mTabControl.getTab(i).updateBookmarkedStatus();
274 }
275 }
276
277 };
278 browser.getContentResolver().registerContentObserver(
279 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700280
281 mNetworkHandler = new NetworkStateHandler(mActivity, this);
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700282 mHomepageHandler = new HomepageHandler(browser, this);
Pankaj Garg49b79252014-11-07 17:33:41 -0800283 mAppMenuHandler = new AppMenuHandler(browser, this, R.menu.browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700284 }
285
John Reck9c35b9c2012-05-30 10:08:50 -0700286 @Override
287 public void start(final Intent intent) {
Kulanthaivel Palanichamy77942682014-10-28 11:52:06 -0700288 mMenuState = R.id.MAIN_MENU;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800289 WebView.setShouldMonitorWebCoreThread();
George Mount3636d0a2011-11-21 09:08:21 -0800290 // mCrashRecoverHandler has any previously saved state.
291 mCrashRecoveryHandler.startRecovery(intent);
John Reck847b5322011-04-14 17:02:18 -0700292 }
293
George Mount3636d0a2011-11-21 09:08:21 -0800294 void doStart(final Bundle icicle, final Intent intent) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800295 // we dont want to ever recover incognito tabs
296 final boolean restoreIncognitoTabs = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700297
Patrick Scott7d50a932011-02-04 09:27:26 -0500298 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700299 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500300 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000301
Michael Kolbc831b632011-05-11 09:30:34 -0700302 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500303 // Not able to restore so we go ahead and clear session cookies. We
304 // must do this before trying to login the user as we don't want to
305 // clear any session cookies set during login.
306 CookieManager.getInstance().removeSessionCookie();
John Reck1cf4b792011-07-26 10:22:22 -0700307 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
George Mount3636d0a2011-11-21 09:08:21 -0800308 if (intent == null) {
309 // This won't happen under common scenarios. The icicle is
310 // not null, but there aren't any tabs to restore.
311 openTabToHomePage();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700312 } else {
George Mount3636d0a2011-11-21 09:08:21 -0800313 final Bundle extra = intent.getExtras();
314 // Create an initial tab.
315 // If the intent is ACTION_VIEW and data is not null, the Browser is
316 // invoked to view the content by another application. In this case,
317 // the tab will be close when exit.
kaiyiz6e5b3e02013-08-19 20:02:01 +0800318 UrlData urlData = null;
319 if (intent.getData() != null
320 && Intent.ACTION_VIEW.equals(intent.getAction())
321 && intent.getData().toString().startsWith("content://")) {
322 urlData = new UrlData(intent.getData().toString());
323 } else {
324 urlData = IntentHandler.getUrlDataFromIntent(intent);
325 }
George Mount3636d0a2011-11-21 09:08:21 -0800326 Tab t = null;
327 if (urlData.isEmpty()) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700328 String landingPage = mActivity.getResources().getString(
329 R.string.def_landing_page);
330 if (!landingPage.isEmpty()) {
331 t = openTab(landingPage, false, true, true);
kaiyiz6e5b3e02013-08-19 20:02:01 +0800332 } else {
333 t = openTabToHomePage();
334 }
George Mount3636d0a2011-11-21 09:08:21 -0800335 } else {
336 t = openTab(urlData);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700337 t.setDerivedFromIntent(true);
George Mount3636d0a2011-11-21 09:08:21 -0800338 }
339 if (t != null) {
340 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
341 }
342 WebView webView = t.getWebView();
343 if (extra != null) {
344 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
345 if (scale > 0 && scale <= 1000) {
346 webView.setInitialScale(scale);
347 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700348 }
349 }
John Reckd8c74522011-06-14 08:45:00 -0700350 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700351 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700352 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500353 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700354 List<Tab> tabs = mTabControl.getTabs();
355 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700356
John Reck1cf4b792011-07-26 10:22:22 -0700357 for (Tab t : tabs) {
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700358 //handle restored pages that may require a JS interface
359 if (t.getWebView() != null) {
360 WebBackForwardList backForwardList = t.getWebView().copyBackForwardList();
361 if (backForwardList != null) {
362 for (int i = 0; i < backForwardList.getSize(); i++) {
363 WebHistoryItem item = backForwardList.getItemAtIndex(i);
364 mHomepageHandler.registerJsInterface( t.getWebView(), item.getUrl());
365 }
366 }
367 }
John Reck1cf4b792011-07-26 10:22:22 -0700368 restoredTabs.add(t.getId());
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700369 if (t != mTabControl.getCurrentTab()) {
370 t.pause();
371 }
John Reck1cf4b792011-07-26 10:22:22 -0700372 }
373 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700374 if (tabs.size() == 0) {
375 openTabToHomePage();
376 }
John Reck1cf4b792011-07-26 10:22:22 -0700377 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700378 // TabControl.restoreState() will create a new tab even if
379 // restoring the state fails.
380 setActiveTab(mTabControl.getCurrentTab());
George Mount3636d0a2011-11-21 09:08:21 -0800381 // Intent is non-null when framework thinks the browser should be
382 // launching with a new intent (icicle is null).
383 if (intent != null) {
John Reck9dd4a412011-10-05 14:55:30 -0700384 mIntentHandler.onNewIntent(intent);
385 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700386 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700387 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700388 String jsFlags = getSettings().getJsEngineFlags();
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800389 if (jsFlags.trim().length() != 0) {
390 getCurrentWebView().setJsFlags(jsFlags);
Michael Kolb8233fac2010-10-26 16:08:53 -0700391 }
George Mount3636d0a2011-11-21 09:08:21 -0800392 if (intent != null
393 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700394 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800395 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700396 }
397
John Reck1cf4b792011-07-26 10:22:22 -0700398 private static class PruneThumbnails implements Runnable {
399 private Context mContext;
400 private List<Long> mIds;
401
402 PruneThumbnails(Context context, List<Long> preserveIds) {
403 mContext = context.getApplicationContext();
404 mIds = preserveIds;
405 }
406
407 @Override
408 public void run() {
409 ContentResolver cr = mContext.getContentResolver();
410 if (mIds == null || mIds.size() == 0) {
411 cr.delete(Thumbnails.CONTENT_URI, null, null);
412 } else {
413 int length = mIds.size();
414 StringBuilder where = new StringBuilder();
415 where.append(Thumbnails._ID);
416 where.append(" not in (");
417 for (int i = 0; i < length; i++) {
418 where.append(mIds.get(i));
419 if (i < (length - 1)) {
420 where.append(",");
421 }
422 }
423 where.append(")");
424 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
425 }
426 }
427
428 }
429
Michael Kolb1514bb72010-11-22 09:11:48 -0800430 @Override
431 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700432 return mFactory;
433 }
434
435 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800436 public void onSetWebView(Tab tab, WebView view) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800437 if (tab.hasCrashed)
438 tab.showCrashView();
439 else
440 mUi.onSetWebView(tab, view);
Michael Kolba713ec82010-11-29 17:27:06 -0800441 }
442
443 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800444 public void createSubWindow(Tab tab) {
445 endActionMode();
446 WebView mainView = tab.getWebView();
447 WebView subView = mFactory.createWebView((mainView == null)
448 ? false
449 : mainView.isPrivateBrowsingEnabled());
450 mUi.createSubWindow(tab, subView);
451 }
452
453 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700454 public Context getContext() {
455 return mActivity;
456 }
457
458 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700459 public Activity getActivity() {
460 return mActivity;
461 }
462
463 void setUi(UI ui) {
464 mUi = ui;
465 }
466
Michael Kolbaf63dba2012-05-16 12:58:05 -0700467 @Override
468 public BrowserSettings getSettings() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700469 return mSettings;
470 }
471
472 IntentHandler getIntentHandler() {
473 return mIntentHandler;
474 }
475
476 @Override
477 public UI getUi() {
478 return mUi;
479 }
480
481 int getMaxTabs() {
482 return mActivity.getResources().getInteger(R.integer.max_tabs);
483 }
484
485 @Override
486 public TabControl getTabControl() {
487 return mTabControl;
488 }
489
Michael Kolb1bf23132010-11-19 12:55:12 -0800490 @Override
491 public List<Tab> getTabs() {
492 return mTabControl.getTabs();
493 }
494
Michael Kolb8233fac2010-10-26 16:08:53 -0700495 private void startHandler() {
496 mHandler = new Handler() {
497
498 @Override
499 public void handleMessage(Message msg) {
500 switch (msg.what) {
501 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700502 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700503 break;
504 case FOCUS_NODE_HREF:
505 {
506 String url = (String) msg.getData().get("url");
507 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500508 String src = (String) msg.getData().get("src");
509 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700510 if (TextUtils.isEmpty(url)) {
511 break;
512 }
513 HashMap focusNodeMap = (HashMap) msg.obj;
514 WebView view = (WebView) focusNodeMap.get("webview");
515 // Only apply the action if the top window did not change.
516 if (getCurrentTopWebView() != view) {
517 break;
518 }
519 switch (msg.arg1) {
520 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700521 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700522 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500523 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700524 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500525 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500526 case R.id.open_newtab_context_menu_id:
527 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700528 openTab(url, parent,
529 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500530 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700531 case R.id.copy_link_context_menu_id:
532 copy(url);
533 break;
534 case R.id.save_link_context_menu_id:
535 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500536 DownloadHandler.onDownloadStartNoStream(
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800537 mActivity, url, view.getSettings().getUserAgentString(),
538 null, null, null, view.isPrivateBrowsingEnabled(), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -0700539 break;
Tarun Nainani700b69b2014-03-26 16:07:25 -0700540 case R.id.save_link_bookmark_context_menu_id:
Tarun Nainani9f27c612014-04-02 14:34:03 -0700541 if(title == null || title == "")
542 title = url;
543
544 Intent bookmarkIntent = new Intent(mActivity, AddBookmarkPage.class);
545 //SWE TODO: No thumbnail support for the url obtained via
546 //browser context menu as its not loaded in webview.
547 if (bookmarkIntent != null) {
548 bookmarkIntent.putExtra(BrowserContract.Bookmarks.URL, url);
549 bookmarkIntent.putExtra(BrowserContract.Bookmarks.TITLE, title);
550 mActivity.startActivity(bookmarkIntent);
551 }
Tarun Nainani700b69b2014-03-26 16:07:25 -0700552 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700553 }
554 break;
555 }
556
557 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700558 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700559 break;
560
561 case STOP_LOAD:
562 stopLoading();
563 break;
564
565 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700566 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700567 mWakeLock.release();
568 // if we reach here, Browser should be still in the
569 // background loading after WAKELOCK_TIMEOUT (5-min).
570 // To avoid burning the battery, stop loading.
571 mTabControl.stopAllLoading();
572 }
573 break;
574
575 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800576 Tab tab = (Tab) msg.obj;
577 if (tab != null) {
578 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700579 }
580 break;
kaiyiz591110b2013-08-06 17:11:06 +0800581 case OPEN_MENU:
582 if (!mOptionsMenuOpen && mActivity != null ) {
583 mActivity.openOptionsMenu();
584 }
585 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700586 }
587 }
588 };
589
590 }
591
John Reckef654f12011-07-12 16:42:08 -0700592 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200593 public Tab getCurrentTab() {
594 return mTabControl.getCurrentTab();
595 }
596
Michael Kolbba99c5d2010-11-29 14:57:41 -0800597 @Override
598 public void shareCurrentPage() {
599 shareCurrentPage(mTabControl.getCurrentTab());
600 }
601
602 private void shareCurrentPage(Tab tab) {
Tarun Nainaniea28dde2014-08-27 17:25:09 -0700603 if (tab == null || tab.getWebView() == null)
604 return;
605
606 final Tab mytab = tab;
607 final ValueCallback<Bitmap> onScreenshot = new ValueCallback<Bitmap>() {
608 @Override
609 public void onReceiveValue(Bitmap bitmap) {
610 sharePage(mActivity, mytab.getTitle(), mytab.getUrl(),
611 mytab.getFavicon(), bitmap);
612 }
613 };
614
615 createScreenshotAsync(
616 tab.getWebView(),
617 getDesiredThumbnailWidth(mActivity),
618 getDesiredThumbnailHeight(mActivity),
619 new ValueCallback<Bitmap>() {
620 @Override
621 public void onReceiveValue(Bitmap bitmap) {
622 sharePage(mActivity, mytab.getTitle(), mytab.getUrl(),
623 mytab.getFavicon(), bitmap);
624 }
625 });
Michael Kolbba99c5d2010-11-29 14:57:41 -0800626 }
627
Michael Kolb8233fac2010-10-26 16:08:53 -0700628 /**
629 * Share a page, providing the title, url, favicon, and a screenshot. Uses
630 * an {@link Intent} to launch the Activity chooser.
631 * @param c Context used to launch a new Activity.
632 * @param title Title of the page. Stored in the Intent with
633 * {@link Intent#EXTRA_SUBJECT}
634 * @param url URL of the page. Stored in the Intent with
635 * {@link Intent#EXTRA_TEXT}
636 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
637 * with {@link Browser#EXTRA_SHARE_FAVICON}
638 * @param screenshot Bitmap of a screenshot of the page. Stored in the
639 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
640 */
641 static final void sharePage(Context c, String title, String url,
642 Bitmap favicon, Bitmap screenshot) {
Axesh R. Ajmera34d3f142014-06-30 20:05:36 -0700643
644 ShareDialog sDialog = new ShareDialog((Activity)c, title, url, favicon, screenshot);
645 final AppAdapter adapter = new AppAdapter(c, c.getPackageManager(),
646 R.layout.app_row, sDialog.getApps());
647 sDialog.loadView(adapter);
Michael Kolb8233fac2010-10-26 16:08:53 -0700648 }
649
650 private void copy(CharSequence text) {
651 ClipboardManager cm = (ClipboardManager) mActivity
652 .getSystemService(Context.CLIPBOARD_SERVICE);
653 cm.setText(text);
654 }
655
656 // lifecycle
657
John Reck9c35b9c2012-05-30 10:08:50 -0700658 @Override
659 public void onConfgurationChanged(Configuration config) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700660 mConfigChanged = true;
Michael Kolb18f252f2012-03-06 13:36:20 -0800661 // update the menu in case of a locale change
662 mActivity.invalidateOptionsMenu();
Pankaj Garg49b79252014-11-07 17:33:41 -0800663 mAppMenuHandler.hideAppMenu();
kaiyiz591110b2013-08-06 17:11:06 +0800664 if (mOptionsMenuOpen) {
665 mActivity.closeOptionsMenu();
666 mHandler.sendMessageDelayed(mHandler.obtainMessage(OPEN_MENU), 100);
667 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700668 if (mPageDialogsHandler != null) {
669 mPageDialogsHandler.onConfigurationChanged(config);
670 }
671 mUi.onConfigurationChanged(config);
672 }
673
674 @Override
675 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700676 if (!mUi.isWebShowing()) {
677 mUi.showWeb(false);
678 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700679 mIntentHandler.onNewIntent(intent);
680 }
681
John Reck9c35b9c2012-05-30 10:08:50 -0700682 @Override
683 public void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800684 if (mUi.isCustomViewShowing()) {
685 hideCustomView();
686 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700687 if (mActivityPaused) {
688 Log.e(LOGTAG, "BrowserActivity is already paused.");
689 return;
690 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700691 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800692 Tab tab = mTabControl.getCurrentTab();
693 if (tab != null) {
694 tab.pause();
695 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700696 if (mWakeLock == null) {
697 PowerManager pm = (PowerManager) mActivity
698 .getSystemService(Context.POWER_SERVICE);
699 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
700 }
Michael Kolb70976932010-11-30 11:34:01 -0800701 mWakeLock.acquire();
702 mHandler.sendMessageDelayed(mHandler
703 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
704 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700705 }
706 mUi.onPause();
707 mNetworkHandler.onPause();
708
709 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100710 NfcHandler.unregister(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700711 }
712
John Reck9c35b9c2012-05-30 10:08:50 -0700713 @Override
714 public void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700715 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800716 Bundle saveState = createSaveState();
717
718 // crash recovery manages all save & restore state
719 mCrashRecoveryHandler.writeState(saveState);
720 mSettings.setLastRunPaused(true);
721 }
722
723 /**
724 * Save the current state to outState. Does not write the state to
725 * disk.
726 * @return Bundle containing the current state of all tabs.
727 */
728 /* package */ Bundle createSaveState() {
729 Bundle saveState = new Bundle();
730 mTabControl.saveState(saveState);
George Mount3636d0a2011-11-21 09:08:21 -0800731 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700732 }
733
John Reck9c35b9c2012-05-30 10:08:50 -0700734 @Override
735 public void onResume() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700736 if (!mActivityPaused) {
737 Log.e(LOGTAG, "BrowserActivity is already resumed.");
738 return;
739 }
George Mount3636d0a2011-11-21 09:08:21 -0800740 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700741 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800742 Tab current = mTabControl.getCurrentTab();
743 if (current != null) {
744 current.resume();
745 resumeWebViewTimers(current);
746 }
John Reckf57c0292011-07-21 18:15:39 -0700747 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200748
Michael Kolb8233fac2010-10-26 16:08:53 -0700749 mUi.onResume();
750 mNetworkHandler.onResume();
751 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100752 NfcHandler.register(mActivity, this);
Michael Kolb0b129122012-06-04 16:31:58 -0700753 if (mVoiceResult != null) {
754 mUi.onVoiceResult(mVoiceResult);
755 mVoiceResult = null;
756 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800757 if (current != null && current.hasCrashed) {
Vivek Sekhar2868b8d2014-12-03 17:22:50 -0800758 current.replaceCrashView(current.getWebView(), current.getViewContainer());
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800759 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700760 }
761
John Reckf57c0292011-07-21 18:15:39 -0700762 private void releaseWakeLock() {
763 if (mWakeLock != null && mWakeLock.isHeld()) {
764 mHandler.removeMessages(RELEASE_WAKELOCK);
765 mWakeLock.release();
766 }
767 }
768
Michael Kolb70976932010-11-30 11:34:01 -0800769 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800770 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800771 * @param tab guaranteed non-null
772 */
773 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700774 boolean inLoad = tab.inPageLoad();
775 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
776 CookieSyncManager.getInstance().startSync();
777 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100778 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700779 }
780 }
781
Michael Kolb70976932010-11-30 11:34:01 -0800782 /**
783 * Pause all WebView timers using the WebView of the given tab
784 * @param tab
785 * @return true if the timers are paused or tab is null
786 */
787 private boolean pauseWebViewTimers(Tab tab) {
788 if (tab == null) {
789 return true;
790 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700791 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100792 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700793 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700794 }
Michael Kolb70976932010-11-30 11:34:01 -0800795 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700796 }
797
John Reck9c35b9c2012-05-30 10:08:50 -0700798 @Override
799 public void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800800 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700801 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
802 mUploadHandler = null;
803 }
804 if (mTabControl == null) return;
805 mUi.onDestroy();
806 // Remove the current tab and sub window
807 Tab t = mTabControl.getCurrentTab();
808 if (t != null) {
809 dismissSubWindow(t);
810 removeTab(t);
811 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500812 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700813 // Destroy all the tabs
814 mTabControl.destroy();
Michael Kolb8233fac2010-10-26 16:08:53 -0700815 }
816
817 protected boolean isActivityPaused() {
818 return mActivityPaused;
819 }
820
John Reck9c35b9c2012-05-30 10:08:50 -0700821 @Override
822 public void onLowMemory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700823 mTabControl.freeMemory();
824 }
825
826 @Override
827 public boolean shouldShowErrorConsole() {
828 return mShouldShowErrorConsole;
829 }
830
831 protected void setShouldShowErrorConsole(boolean show) {
832 if (show == mShouldShowErrorConsole) {
833 // Nothing to do.
834 return;
835 }
836 mShouldShowErrorConsole = show;
837 Tab t = mTabControl.getCurrentTab();
838 if (t == null) {
839 // There is no current tab so we cannot toggle the error console
840 return;
841 }
842 mUi.setShouldShowErrorConsole(t, show);
843 }
844
845 @Override
846 public void stopLoading() {
847 mLoadStopped = true;
848 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700849 WebView w = getCurrentTopWebView();
Michael Kolb778a4882012-04-12 15:27:28 -0700850 if (w != null) {
851 w.stopLoading();
852 mUi.onPageStopped(tab);
853 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700854 }
855
856 boolean didUserStopLoading() {
857 return mLoadStopped;
858 }
859
kaiyiza016da12013-08-26 17:50:22 +0800860 private void handleNetworkNotify(WebView view) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700861 final String reminderType = getContext().getResources().getString(
862 R.string.def_wifi_browser_interaction_remind_type);
863 final String selectionConnnection = getContext().getResources().getString(
864 R.string.def_action_wifi_selection_data_connections);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700865 final String wifiSelection = getContext().getResources().getString(
866 R.string.def_intent_pick_network);
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700867
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700868 if (reminderType.isEmpty() || selectionConnnection.isEmpty() ||
869 wifiSelection.isEmpty())
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700870 return;
871
kaiyiza016da12013-08-26 17:50:22 +0800872 ConnectivityManager conMgr = (ConnectivityManager) this.getContext().getSystemService(
Vivek Sekharb54614f2014-05-01 19:03:37 -0700873 Context.CONNECTIVITY_SERVICE);
874 NetworkInfo networkInfo = conMgr.getActiveNetworkInfo();
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700875 WifiManager wifiMgr = (WifiManager) this.getContext()
876 .getSystemService(Context.WIFI_SERVICE);
Vivek Sekharb54614f2014-05-01 19:03:37 -0700877 if (networkInfo == null
878 || (networkInfo != null && (networkInfo.getType() !=
879 ConnectivityManager.TYPE_WIFI))) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700880 int isReminder = Settings.System.getInt(mActivity.getContentResolver(),
881 reminderType, NETWORK_SWITCH_TYPE_OK);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700882 List<ScanResult> list = wifiMgr.getScanResults();
883 // Have no AP's for Wifi's fall back to data
884 if (list != null && list.size() == 0 && isReminder == NETWORK_SWITCH_TYPE_OK) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700885 Intent intent = new Intent(selectionConnnection);
Vivek Sekharb54614f2014-05-01 19:03:37 -0700886 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
887 this.getContext().startActivity(intent);
888 } else {
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700889 // Request to select Wifi AP
890 try {
891 Intent intent = new Intent(wifiSelection);
892 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
893 this.getContext().startActivity(intent);
894 } catch (Exception e) {
895 String err_msg = this.getContext().getString(
896 R.string.acivity_not_found, wifiSelection);
897 Toast.makeText(this.getContext(), err_msg, Toast.LENGTH_LONG).show();
898 }
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700899 }
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700900 mNetworkShouldNotify = false;
kaiyiza016da12013-08-26 17:50:22 +0800901 }
902 }
Vivek Sekharb54614f2014-05-01 19:03:37 -0700903
Michael Kolb8233fac2010-10-26 16:08:53 -0700904 // WebViewController
905
906 @Override
John Reck324d4402011-01-11 16:56:42 -0800907 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700908
909 // We've started to load a new page. If there was a pending message
910 // to save a screenshot then we will now take the new page and save
911 // an incorrect screenshot. Therefore, remove any pending thumbnail
912 // messages from the queue.
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700913 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700914
915 // reset sync timer to avoid sync starts during loading a page
916 CookieSyncManager.getInstance().resetSync();
Vivek Sekharb54614f2014-05-01 19:03:37 -0700917 WifiManager wifiMgr = (WifiManager) this.getContext()
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700918 .getSystemService(Context.WIFI_SERVICE);
Panos Thomas4bdb5252014-11-13 16:20:11 -0800919 boolean networkNotifier = BrowserConfig.getInstance(getContext())
920 .hasFeature(BrowserConfig.Feature.NETWORK_NOTIFIER);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700921 if (networkNotifier && mNetworkShouldNotify && wifiMgr.isWifiEnabled()){
Vivek Sekharb54614f2014-05-01 19:03:37 -0700922 handleNetworkNotify(view);
kaiyiza016da12013-08-26 17:50:22 +0800923 } else {
924 if (!mNetworkHandler.isNetworkUp()) {
925 view.setNetworkAvailable(false);
926 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700927 }
928
929 // when BrowserActivity just starts, onPageStarted may be called before
930 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
931 // to start the timer. As we won't switch tabs while an activity is in
932 // pause state, we can ensure calling resume and pause in pair.
933 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800934 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700935 }
936 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700937 endActionMode();
938
John Reck30c714c2010-12-16 17:30:34 -0800939 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700940
John Reck324d4402011-01-11 16:56:42 -0800941 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700942 // update the bookmark database for favicon
943 maybeUpdateFavicon(tab, null, url, favicon);
944
945 Performance.tracePageStart(url);
946
947 // Performance probe
948 if (false) {
949 Performance.onPageStarted();
950 }
951
952 }
953
954 @Override
John Reck324d4402011-01-11 16:56:42 -0800955 public void onPageFinished(Tab tab) {
Michael Kolb72864272012-05-03 15:42:15 -0700956 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800957 mUi.onTabDataChanged(tab);
Martijn Coenenb2f93552011-06-14 10:48:35 +0200958
Michael Kolb8233fac2010-10-26 16:08:53 -0700959 // Performance probe
960 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800961 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700962 }
963
Tarun Nainani8eb00912014-07-17 12:28:32 -0700964 tab.onPageFinished();
965
Michael Kolb8233fac2010-10-26 16:08:53 -0700966 Performance.tracePageFinished();
967 }
968
969 @Override
John Reck30c714c2010-12-16 17:30:34 -0800970 public void onProgressChanged(Tab tab) {
971 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700972
973 if (newProgress == 100) {
974 CookieSyncManager.getInstance().sync();
975 // onProgressChanged() may continue to be called after the main
976 // frame has finished loading, as any remaining sub frames continue
977 // to load. We'll only get called once though with newProgress as
978 // 100 when everything is loaded. (onPageFinished is called once
979 // when the main frame completes loading regardless of the state of
980 // any sub frames so calls to onProgressChanges may continue after
981 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800982 if (tab.inPageLoad()) {
Pankaj Garg49b79252014-11-07 17:33:41 -0800983 mWasInPageLoad = true;
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800984 updateInLoadMenuItems(mCachedMenu, tab);
Pankaj Garg49b79252014-11-07 17:33:41 -0800985 } else if (mWasInPageLoad) {
986 mWasInPageLoad = false;
987 updateInLoadMenuItems(mCachedMenu, tab);
988 }
989
990 if (mActivityPaused && pauseWebViewTimers(tab)) {
Mattias Falk9cc2d032012-05-25 09:40:31 +0200991 // pause the WebView timer and release the wake lock if it is
992 // finished while BrowserActivity is in pause state.
993 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700994 }
John Reckd9862372012-02-21 15:04:50 -0800995 if (!tab.isPrivateBrowsingEnabled()
996 && !TextUtils.isEmpty(tab.getUrl())
997 && !tab.isSnapshot()) {
998 // Only update the bookmark screenshot if the user did not
999 // cancel the load early and there is not already
1000 // a pending update for the tab.
Michael Kolb72864272012-05-03 15:42:15 -07001001 if (tab.shouldUpdateThumbnail() &&
1002 (tab.inForeground() && !didUserStopLoading()
1003 || !tab.inForeground())) {
John Reckd9862372012-02-21 15:04:50 -08001004 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
1005 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1006 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001007 1500);
John Reckd9862372012-02-21 15:04:50 -08001008 }
1009 }
1010 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001011 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001012 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001013 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001014 // still loading
1015 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -07001016 // update the menu items.
Pankaj Garg49b79252014-11-07 17:33:41 -08001017 mWasInPageLoad = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001018 updateInLoadMenuItems(mCachedMenu, tab);
Pankaj Garg49b79252014-11-07 17:33:41 -08001019 } else {
1020 mWasInPageLoad = true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001021 }
1022 }
John Reck30c714c2010-12-16 17:30:34 -08001023 mUi.onProgressChanged(tab);
1024 }
1025
1026 @Override
Steve Block2466eff2011-10-03 15:33:09 +01001027 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08001028 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001029 }
1030
1031 @Override
1032 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -08001033 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -08001034 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -08001035 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -07001036 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
1037 return;
1038 }
1039 // Update the title in the history database if not in private browsing mode
1040 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -07001041 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -07001042 }
1043 }
1044
1045 @Override
1046 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -08001047 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001048 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
1049 }
1050
1051 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -08001052 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
1053 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07001054 }
1055
1056 @Override
1057 public boolean shouldOverrideKeyEvent(KeyEvent event) {
1058 if (mMenuIsDown) {
1059 // only check shortcut key when MENU is held
1060 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
1061 event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001062 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001063 int keyCode = event.getKeyCode();
1064 // We need to send almost every key to WebKit. However:
1065 // 1. We don't want to block the device on the renderer for
1066 // some keys like menu, home, call.
1067 // 2. There are no WebKit equivalents for some of these keys
1068 // (see app/keyboard_codes_win.h)
1069 // Note that these are not the same set as KeyEvent.isSystemKey:
1070 // for instance, AKEYCODE_MEDIA_* will be dispatched to webkit.
1071 if (keyCode == KeyEvent.KEYCODE_MENU ||
1072 keyCode == KeyEvent.KEYCODE_HOME ||
1073 keyCode == KeyEvent.KEYCODE_BACK ||
1074 keyCode == KeyEvent.KEYCODE_CALL ||
1075 keyCode == KeyEvent.KEYCODE_ENDCALL ||
1076 keyCode == KeyEvent.KEYCODE_POWER ||
1077 keyCode == KeyEvent.KEYCODE_HEADSETHOOK ||
1078 keyCode == KeyEvent.KEYCODE_CAMERA ||
1079 keyCode == KeyEvent.KEYCODE_FOCUS ||
1080 keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
1081 keyCode == KeyEvent.KEYCODE_VOLUME_MUTE ||
1082 keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
1083 return true;
1084 }
1085
1086 // We also have to intercept some shortcuts before we send them to the ContentView.
1087 if (event.isCtrlPressed() && (
1088 keyCode == KeyEvent.KEYCODE_TAB ||
1089 keyCode == KeyEvent.KEYCODE_W ||
1090 keyCode == KeyEvent.KEYCODE_F4)) {
1091 return true;
1092 }
1093
1094 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07001095 }
1096
1097 @Override
John Reck997b1b72012-04-19 18:08:25 -07001098 public boolean onUnhandledKeyEvent(KeyEvent event) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001099 if (!isActivityPaused()) {
1100 if (event.getAction() == KeyEvent.ACTION_DOWN) {
John Reck997b1b72012-04-19 18:08:25 -07001101 return mActivity.onKeyDown(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001102 } else {
John Reck997b1b72012-04-19 18:08:25 -07001103 return mActivity.onKeyUp(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001104 }
1105 }
John Reck997b1b72012-04-19 18:08:25 -07001106 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 }
1108
1109 @Override
John Reck324d4402011-01-11 16:56:42 -08001110 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Panos Thomas4bdb5252014-11-13 16:20:11 -08001111 // Don't save anything in private browsing mode or when disabling history
1112 // for regular tabs is enabled
1113 if (tab.isPrivateBrowsingEnabled() || BrowserConfig.getInstance(getContext())
1114 .hasFeature(BrowserConfig.Feature.DISABLE_HISTORY))
1115 return;
Bijan Amirzadae75909d2014-05-06 14:18:54 -07001116
John Reck49a603c2011-03-03 09:33:05 -08001117 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -07001118
John Reck324d4402011-01-11 16:56:42 -08001119 if (TextUtils.isEmpty(url)
1120 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001121 return;
1122 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001123
John Reckf57c0292011-07-21 18:15:39 -07001124 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -07001125 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07001126 }
1127
1128 @Override
1129 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1130 AsyncTask<Void, Void, String[]> task =
1131 new AsyncTask<Void, Void, String[]>() {
1132 @Override
1133 public String[] doInBackground(Void... unused) {
Bijan Amirzada3f04dc72014-06-25 11:48:36 -07001134 return (String[]) Browser.getVisitedHistory(mActivity.getContentResolver());
Michael Kolb8233fac2010-10-26 16:08:53 -07001135 }
1136 @Override
1137 public void onPostExecute(String[] result) {
1138 callback.onReceiveValue(result);
1139 }
1140 };
1141 task.execute();
1142 }
1143
1144 @Override
1145 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
1146 final HttpAuthHandler handler, final String host,
1147 final String realm) {
1148 String username = null;
1149 String password = null;
1150
1151 boolean reuseHttpAuthUsernamePassword
1152 = handler.useHttpAuthUsernamePassword();
1153
1154 if (reuseHttpAuthUsernamePassword && view != null) {
1155 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
1156 if (credentials != null && credentials.length == 2) {
1157 username = credentials[0];
1158 password = credentials[1];
1159 }
1160 }
1161
1162 if (username != null && password != null) {
1163 handler.proceed(username, password);
1164 } else {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001165 if (tab.inForeground() /*&& !handler.suppressDialog()*/) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001166 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1167 } else {
1168 handler.cancel();
1169 }
1170 }
1171 }
1172
1173 @Override
1174 public void onDownloadStart(Tab tab, String url, String userAgent,
Selim Gurun0b3d66f2012-08-29 13:08:13 -07001175 String contentDisposition, String mimetype, String referer,
1176 long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001177 WebView w = tab.getWebView();
Axesh R. Ajmera87c5aba2014-11-06 14:13:36 -08001178 if ( w == null) return;
qqzhoua95a2e22013-04-18 17:28:31 +08001179 boolean ret = DownloadHandler.onDownloadStart(mActivity, url, userAgent,
luxiaol62677b02013-07-22 07:54:49 +08001180 contentDisposition, mimetype, referer, w.isPrivateBrowsingEnabled(), contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +08001181 if (ret == false && w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001182 // This Tab was opened for the sole purpose of downloading a
1183 // file. Remove it.
1184 if (tab == mTabControl.getCurrentTab()) {
1185 // In this case, the Tab is still on top.
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07001186 if (tab.getDerivedFromIntent())
1187 closeTab(tab);
1188 else
1189 goBackOnePageOrQuit();
Michael Kolb8233fac2010-10-26 16:08:53 -07001190 } else {
1191 // In this case, it is not.
1192 closeTab(tab);
1193 }
1194 }
1195 }
1196
1197 @Override
1198 public Bitmap getDefaultVideoPoster() {
1199 return mUi.getDefaultVideoPoster();
1200 }
1201
1202 @Override
1203 public View getVideoLoadingProgressView() {
1204 return mUi.getVideoLoadingProgressView();
1205 }
1206
1207 @Override
1208 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1209 SslError error) {
1210 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1211 }
1212
1213 // helper method
1214
1215 /*
1216 * Update the favorites icon if the private browsing isn't enabled and the
1217 * icon is valid.
1218 */
1219 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1220 final String url, Bitmap favicon) {
1221 if (favicon == null) {
1222 return;
1223 }
1224 if (!tab.isPrivateBrowsingEnabled()) {
1225 Bookmarks.updateFavicon(mActivity
1226 .getContentResolver(), originalUrl, url, favicon);
1227 }
1228 }
1229
Leon Scroggins4cd97792010-12-03 15:31:56 -05001230 @Override
1231 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001232 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001233 mUi.bookmarkedStatusHasChanged(tab);
1234 }
1235
Michael Kolb8233fac2010-10-26 16:08:53 -07001236 // end WebViewController
1237
1238 protected void pageUp() {
1239 getCurrentTopWebView().pageUp(false);
1240 }
1241
1242 protected void pageDown() {
1243 getCurrentTopWebView().pageDown(false);
1244 }
1245
1246 // callback from phone title bar
John Reck9c35b9c2012-05-30 10:08:50 -07001247 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07001248 public void editUrl() {
1249 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolb1f9b3562012-04-24 14:38:34 -07001250 mUi.editUrl(false, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001251 }
1252
John Reck9c35b9c2012-05-30 10:08:50 -07001253 @Override
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001254 public void showCustomView(Tab tab, View view, int requestedOrientation,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001255 CustomViewCallback callback) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001256 if (tab.inForeground()) {
1257 if (mUi.isCustomViewShowing()) {
1258 callback.onCustomViewHidden();
1259 return;
1260 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001261 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001262 // Save the menu state and set it to empty while the custom
1263 // view is showing.
1264 mOldMenuState = mMenuState;
1265 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001266 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001267 }
1268 }
1269
1270 @Override
1271 public void hideCustomView() {
1272 if (mUi.isCustomViewShowing()) {
1273 mUi.onHideCustomView();
1274 // Reset the old menu state.
1275 mMenuState = mOldMenuState;
1276 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001277 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001278 }
1279 }
1280
John Reck9c35b9c2012-05-30 10:08:50 -07001281 @Override
1282 public void onActivityResult(int requestCode, int resultCode,
Michael Kolb8233fac2010-10-26 16:08:53 -07001283 Intent intent) {
1284 if (getCurrentTopWebView() == null) return;
1285 switch (requestCode) {
1286 case PREFERENCES_PAGE:
1287 if (resultCode == Activity.RESULT_OK && intent != null) {
1288 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001289 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001290 mTabControl.removeParentChildRelationShips();
1291 }
1292 }
1293 break;
1294 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001295 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001296 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001297 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001298 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001299 case AUTOFILL_SETUP:
1300 // Determine whether a profile was actually set up or not
1301 // and if so, send the message back to the WebTextView to
1302 // fill the form with the new profile.
1303 if (getSettings().getAutoFillProfile() != null) {
1304 mAutoFillSetupMessage.sendToTarget();
1305 mAutoFillSetupMessage = null;
1306 }
1307 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001308 case COMBO_VIEW:
1309 if (intent == null || resultCode != Activity.RESULT_OK) {
1310 break;
1311 }
John Reck3ba45532011-08-11 16:26:53 -07001312 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001313 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1314 Tab t = getCurrentTab();
1315 Uri uri = intent.getData();
kaiyiz6e5b3e02013-08-19 20:02:01 +08001316 mUpdateMyNavThumbnail = true;
1317 mUpdateMyNavThumbnailUrl = uri.toString();
John Reckd3e4d5b2011-07-13 15:48:43 -07001318 loadUrl(t, uri.toString());
1319 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1320 String[] urls = intent.getStringArrayExtra(
1321 ComboViewActivity.EXTRA_OPEN_ALL);
1322 Tab parent = getCurrentTab();
1323 for (String url : urls) {
kaiyiz47097d62013-08-09 09:30:28 +08001324 if (url != null) {
1325 parent = openTab(url, parent,
1326 !mSettings.openInBackground(), true);
1327 }
John Reckd3e4d5b2011-07-13 15:48:43 -07001328 }
1329 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1330 long id = intent.getLongExtra(
1331 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1332 if (id >= 0) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001333 createNewSnapshotTab(id, true);
John Reckd3e4d5b2011-07-13 15:48:43 -07001334 }
1335 }
1336 break;
Michael Kolb0b129122012-06-04 16:31:58 -07001337 case VOICE_RESULT:
1338 if (resultCode == Activity.RESULT_OK && intent != null) {
1339 ArrayList<String> results = intent.getStringArrayListExtra(
1340 RecognizerIntent.EXTRA_RESULTS);
1341 if (results.size() >= 1) {
1342 mVoiceResult = results.get(0);
1343 }
1344 }
1345 break;
kaiyiz6e5b3e02013-08-19 20:02:01 +08001346 case MY_NAVIGATION:
1347 if (intent == null || resultCode != Activity.RESULT_OK) {
1348 break;
1349 }
1350
1351 if (intent.getBooleanExtra("need_refresh", false) &&
1352 getCurrentTopWebView() != null) {
1353 getCurrentTopWebView().reload();
1354 }
1355 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001356 default:
1357 break;
1358 }
1359 getCurrentTopWebView().requestFocus();
1360 }
1361
1362 /**
1363 * Open the Go page.
1364 * @param startWithHistory If true, open starting on the history tab.
1365 * Otherwise, start with the bookmarks tab.
1366 */
1367 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001368 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001369 if (mTabControl.getCurrentWebView() == null) {
1370 return;
1371 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001372 // clear action mode
1373 if (isInCustomActionMode()) {
1374 endActionMode();
1375 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001376 Bundle extras = new Bundle();
1377 // Disable opening in a new window if we have maxed out the windows
1378 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1379 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001380 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001381 }
1382
1383 // combo view callbacks
1384
Michael Kolb8233fac2010-10-26 16:08:53 -07001385 // key handling
1386 protected void onBackKey() {
1387 if (!mUi.onBackKey()) {
1388 WebView subwindow = mTabControl.getCurrentSubWindow();
1389 if (subwindow != null) {
1390 if (subwindow.canGoBack()) {
1391 subwindow.goBack();
1392 } else {
1393 dismissSubWindow(mTabControl.getCurrentTab());
1394 }
1395 } else {
1396 goBackOnePageOrQuit();
1397 }
1398 }
1399 }
1400
Michael Kolb4bd767d2011-05-27 11:33:55 -07001401 protected boolean onMenuKey() {
1402 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001403 }
1404
Michael Kolb8233fac2010-10-26 16:08:53 -07001405 // menu handling and state
1406 // TODO: maybe put into separate handler
1407
John Reck9c35b9c2012-05-30 10:08:50 -07001408 @Override
1409 public boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001410 if (mMenuState == EMPTY_MENU) {
1411 return false;
1412 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001413 MenuInflater inflater = mActivity.getMenuInflater();
1414 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001415 return true;
1416 }
1417
John Reck9c35b9c2012-05-30 10:08:50 -07001418 @Override
1419 public void onCreateContextMenu(ContextMenu menu, View v,
Michael Kolb8233fac2010-10-26 16:08:53 -07001420 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001421 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001422 return;
1423 }
1424 if (!(v instanceof WebView)) {
1425 return;
1426 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001427 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001428 WebView.HitTestResult result = webview.getHitTestResult();
1429 if (result == null) {
1430 return;
1431 }
1432
1433 int type = result.getType();
1434 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1435 Log.w(LOGTAG,
1436 "We should not show context menu when nothing is touched");
1437 return;
1438 }
1439 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1440 // let TextView handles context menu
1441 return;
1442 }
1443
1444 // Note, http://b/issue?id=1106666 is requesting that
1445 // an inflated menu can be used again. This is not available
1446 // yet, so inflate each time (yuk!)
1447 MenuInflater inflater = mActivity.getMenuInflater();
1448 inflater.inflate(R.menu.browsercontext, menu);
1449
1450 // Show the correct menu group
1451 final String extra = result.getExtra();
kaiyiz6e5b3e02013-08-19 20:02:01 +08001452 final String navigationUrl = MyNavigationUtil.getMyNavigationUrl(extra);
Michael Kolbc159c1a2011-12-15 16:06:38 -08001453 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001454 menu.setGroupVisible(R.id.PHONE_MENU,
1455 type == WebView.HitTestResult.PHONE_TYPE);
1456 menu.setGroupVisible(R.id.EMAIL_MENU,
1457 type == WebView.HitTestResult.EMAIL_TYPE);
1458 menu.setGroupVisible(R.id.GEO_MENU,
1459 type == WebView.HitTestResult.GEO_TYPE);
kaiyiz6e5b3e02013-08-19 20:02:01 +08001460 String itemUrl = null;
1461 String url = webview.getOriginalUrl();
1462 if (url != null && url.equalsIgnoreCase(MyNavigationUtil.MY_NAVIGATION)) {
1463 itemUrl = Uri.decode(navigationUrl);
1464 if (itemUrl != null && !MyNavigationUtil.isDefaultMyNavigation(itemUrl)) {
1465 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU,
1466 type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1467 } else {
1468 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU, false);
1469 }
1470 menu.setGroupVisible(R.id.IMAGE_MENU, false);
1471 menu.setGroupVisible(R.id.ANCHOR_MENU, false);
1472 } else {
1473 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU, false);
1474
1475 menu.setGroupVisible(R.id.IMAGE_MENU,
1476 type == WebView.HitTestResult.IMAGE_TYPE
1477 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1478 menu.setGroupVisible(R.id.ANCHOR_MENU,
1479 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1480 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Vivek Sekharcc4bc5e2014-05-13 12:46:37 -07001481 menu.findItem(R.id.save_link_context_menu_id).setEnabled(
1482 UrlUtils.isDownloadableScheme(extra));
kaiyiz6e5b3e02013-08-19 20:02:01 +08001483 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001484 // Setup custom handling depending on the type
1485 switch (type) {
1486 case WebView.HitTestResult.PHONE_TYPE:
1487 menu.setHeaderTitle(Uri.decode(extra));
1488 menu.findItem(R.id.dial_context_menu_id).setIntent(
1489 new Intent(Intent.ACTION_VIEW, Uri
1490 .parse(WebView.SCHEME_TEL + extra)));
1491 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1492 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1493 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1494 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1495 addIntent);
1496 menu.findItem(R.id.copy_phone_context_menu_id)
1497 .setOnMenuItemClickListener(
1498 new Copy(extra));
1499 break;
1500
1501 case WebView.HitTestResult.EMAIL_TYPE:
1502 menu.setHeaderTitle(extra);
1503 menu.findItem(R.id.email_context_menu_id).setIntent(
1504 new Intent(Intent.ACTION_VIEW, Uri
1505 .parse(WebView.SCHEME_MAILTO + extra)));
1506 menu.findItem(R.id.copy_mail_context_menu_id)
1507 .setOnMenuItemClickListener(
1508 new Copy(extra));
1509 break;
1510
1511 case WebView.HitTestResult.GEO_TYPE:
1512 menu.setHeaderTitle(extra);
1513 menu.findItem(R.id.map_context_menu_id).setIntent(
1514 new Intent(Intent.ACTION_VIEW, Uri
1515 .parse(WebView.SCHEME_GEO
1516 + URLEncoder.encode(extra))));
1517 menu.findItem(R.id.copy_geo_context_menu_id)
1518 .setOnMenuItemClickListener(
1519 new Copy(extra));
1520 break;
1521
1522 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1523 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001524 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001525 // decide whether to show the open link in new tab option
1526 boolean showNewTab = mTabControl.canCreateNewTab();
1527 MenuItem newTabItem
1528 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001529 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001530 ? R.string.contextmenu_openlink_newwindow_background
1531 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001532 newTabItem.setVisible(showNewTab);
1533 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001534 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1535 newTabItem.setOnMenuItemClickListener(
1536 new MenuItem.OnMenuItemClickListener() {
1537 @Override
1538 public boolean onMenuItemClick(MenuItem item) {
1539 final HashMap<String, WebView> hrefMap =
1540 new HashMap<String, WebView>();
1541 hrefMap.put("webview", webview);
1542 final Message msg = mHandler.obtainMessage(
1543 FOCUS_NODE_HREF,
1544 R.id.open_newtab_context_menu_id,
1545 0, hrefMap);
1546 webview.requestFocusNodeHref(msg);
1547 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001548 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001549 });
1550 } else {
1551 newTabItem.setOnMenuItemClickListener(
1552 new MenuItem.OnMenuItemClickListener() {
1553 @Override
1554 public boolean onMenuItemClick(MenuItem item) {
1555 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001556 openTab(extra, parent,
1557 !mSettings.openInBackground(),
1558 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001559 return true;
1560 }
1561 });
1562 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001563 }
kaiyiz6e5b3e02013-08-19 20:02:01 +08001564 if (url != null && url.equalsIgnoreCase(MyNavigationUtil.MY_NAVIGATION)) {
1565 menu.setHeaderTitle(navigationUrl);
1566 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(false);
1567
1568 if (itemUrl != null) {
1569 if (!MyNavigationUtil.isDefaultMyNavigation(itemUrl)) {
1570 menu.findItem(R.id.edit_my_navigation_context_menu_id)
1571 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1572 @Override
1573 public boolean onMenuItemClick(MenuItem item) {
1574 final Intent intent = new Intent(Controller.this
1575 .getContext(),
1576 AddMyNavigationPage.class);
1577 Bundle bundle = new Bundle();
1578 String url = Uri.decode(navigationUrl);
1579 bundle.putBoolean("isAdding", false);
1580 bundle.putString("url", url);
1581 bundle.putString("name", getNameFromUrl(url));
1582 intent.putExtra("websites", bundle);
1583 mActivity.startActivityForResult(intent, MY_NAVIGATION);
1584 return false;
1585 }
1586 });
1587 menu.findItem(R.id.delete_my_navigation_context_menu_id)
1588 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1589 @Override
1590 public boolean onMenuItemClick(MenuItem item) {
1591 showMyNavigationDeleteDialog(Uri.decode(navigationUrl));
1592 return false;
1593 }
1594 });
1595 }
1596 } else {
1597 Log.e(LOGTAG, "mynavigation onCreateContextMenu itemUrl is null!");
1598 }
1599 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001600 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1601 break;
1602 }
1603 // otherwise fall through to handle image part
1604 case WebView.HitTestResult.IMAGE_TYPE:
Victoria Lease5987b802012-03-12 13:05:23 -07001605 MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
1606 shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
Michael Kolb8233fac2010-10-26 16:08:53 -07001607 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1608 menu.setHeaderTitle(extra);
Victoria Lease5987b802012-03-12 13:05:23 -07001609 shareItem.setOnMenuItemClickListener(
1610 new MenuItem.OnMenuItemClickListener() {
1611 @Override
1612 public boolean onMenuItemClick(MenuItem item) {
1613 sharePage(mActivity, null, extra, null,
1614 null);
1615 return true;
1616 }
1617 }
1618 );
Michael Kolb8233fac2010-10-26 16:08:53 -07001619 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001620 menu.findItem(R.id.view_image_context_menu_id)
1621 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1622 @Override
1623 public boolean onMenuItemClick(MenuItem item) {
1624 openTab(extra, mTabControl.getCurrentTab(), true, true);
1625 return false;
1626 }
1627 });
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02001628 menu.findItem(R.id.download_context_menu_id).setOnMenuItemClickListener(
1629 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled(),
1630 webview.getSettings().getUserAgentString()));
John Reck3527dd12011-02-22 10:35:29 -08001631 menu.findItem(R.id.set_wallpaper_context_menu_id).
1632 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1633 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001634 break;
1635
1636 default:
1637 Log.w(LOGTAG, "We should not get here.");
1638 break;
1639 }
1640 //update the ui
1641 mUi.onContextMenuCreated(menu);
1642 }
1643
kaiyiz6e5b3e02013-08-19 20:02:01 +08001644 public void startAddMyNavigation(String url) {
1645 final Intent intent = new Intent(Controller.this.getContext(), AddMyNavigationPage.class);
1646 Bundle bundle = new Bundle();
1647 bundle.putBoolean("isAdding", true);
1648 bundle.putString("url", url);
1649 bundle.putString("name", getNameFromUrl(url));
1650 intent.putExtra("websites", bundle);
1651 mActivity.startActivityForResult(intent, MY_NAVIGATION);
1652 }
1653
1654 private void showMyNavigationDeleteDialog(final String itemUrl) {
1655 new AlertDialog.Builder(this.getContext())
1656 .setTitle(R.string.my_navigation_delete_label)
1657 .setIcon(android.R.drawable.ic_dialog_alert)
1658 .setMessage(R.string.my_navigation_delete_msg)
1659 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
1660 @Override
1661 public void onClick(DialogInterface dialog, int whichButton) {
1662 deleteMyNavigationItem(itemUrl);
1663 }
1664 })
1665 .setNegativeButton(R.string.cancel, null)
1666 .show();
1667 }
1668
1669 private void deleteMyNavigationItem(final String itemUrl) {
1670 ContentResolver cr = this.getContext().getContentResolver();
1671 Cursor cursor = null;
1672
1673 try {
1674 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1675 new String[] {
1676 MyNavigationUtil.ID
1677 }, "url = ?", new String[] {
1678 itemUrl
1679 }, null);
1680 if (null != cursor && cursor.moveToFirst()) {
1681 Uri uri = ContentUris.withAppendedId(MyNavigationUtil.MY_NAVIGATION_URI,
1682 cursor.getLong(0));
1683
1684 ContentValues values = new ContentValues();
1685 values.put(MyNavigationUtil.TITLE, "");
1686 values.put(MyNavigationUtil.URL, "ae://" + cursor.getLong(0) + "add-fav");
1687 values.put(MyNavigationUtil.WEBSITE, 0 + "");
1688 ByteArrayOutputStream os = new ByteArrayOutputStream();
1689 Bitmap bm = BitmapFactory.decodeResource(this.getContext().getResources(),
1690 R.raw.my_navigation_add);
1691 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1692 values.put(MyNavigationUtil.THUMBNAIL, os.toByteArray());
1693 Log.d(LOGTAG, "deleteMyNavigationItem uri is : " + uri);
1694 cr.update(uri, values, null, null);
1695 } else {
1696 Log.e(LOGTAG, "deleteMyNavigationItem the item does not exist!");
1697 }
1698 } catch (IllegalStateException e) {
1699 Log.e(LOGTAG, "deleteMyNavigationItem", e);
1700 } finally {
1701 if (null != cursor) {
1702 cursor.close();
1703 }
1704 }
1705
1706 if (getCurrentTopWebView() != null) {
1707 getCurrentTopWebView().reload();
1708 }
1709 }
1710
1711 private String getNameFromUrl(String itemUrl) {
1712 ContentResolver cr = this.getContext().getContentResolver();
1713 Cursor cursor = null;
1714 String name = null;
1715
1716 try {
1717 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1718 new String[] {
1719 MyNavigationUtil.TITLE
1720 }, "url = ?", new String[] {
1721 itemUrl
1722 }, null);
1723 if (null != cursor && cursor.moveToFirst()) {
1724 name = cursor.getString(0);
1725 } else {
1726 Log.e(LOGTAG, "this item does not exist!");
1727 }
1728 } catch (IllegalStateException e) {
1729 Log.e(LOGTAG, "getNameFromUrl", e);
1730 } finally {
1731 if (null != cursor) {
1732 cursor.close();
1733 }
1734 }
1735 return name;
1736 }
1737
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07001738 private void updateMyNavigationThumbnail(final String itemUrl, final Bitmap bitmap) {
1739 if (bitmap == null) {
kaiyiz6e5b3e02013-08-19 20:02:01 +08001740 Log.e(LOGTAG, "updateMyNavigationThumbnail bm is null!");
1741 return;
1742 }
1743
1744 final ContentResolver cr = mActivity.getContentResolver();
1745 new AsyncTask<Void, Void, Void>() {
1746 @Override
1747 protected Void doInBackground(Void... unused) {
1748 ContentResolver cr = mActivity.getContentResolver();
1749 Cursor cursor = null;
1750 try {
1751 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1752 new String[] {
1753 MyNavigationUtil.ID
1754 }, "url = ?", new String[] {
1755 itemUrl
1756 }, null);
1757 if (null != cursor && cursor.moveToFirst()) {
1758 final ByteArrayOutputStream os = new ByteArrayOutputStream();
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07001759 bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
kaiyiz6e5b3e02013-08-19 20:02:01 +08001760
1761 ContentValues values = new ContentValues();
1762 values.put(MyNavigationUtil.THUMBNAIL, os.toByteArray());
1763 Uri uri = ContentUris.withAppendedId(MyNavigationUtil.MY_NAVIGATION_URI,
1764 cursor.getLong(0));
1765 Log.d(LOGTAG, "updateMyNavigationThumbnail uri is " + uri);
1766 cr.update(uri, values, null, null);
1767 os.close();
1768 }
1769 } catch (IllegalStateException e) {
1770 Log.e(LOGTAG, "updateMyNavigationThumbnail", e);
1771 } catch (IOException e) {
1772 Log.e(LOGTAG, "updateMyNavigationThumbnail", e);
1773 } finally {
1774 if (null != cursor) {
1775 cursor.close();
1776 }
1777 }
1778 return null;
1779 }
1780 }.execute();
1781 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001782 /**
1783 * As the menu can be open when loading state changes
1784 * we must manually update the state of the stop/reload menu
1785 * item
1786 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001787 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001788 if (menu == null) {
1789 return;
1790 }
1791 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001792 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001793 menu.findItem(R.id.stop_menu_id):
1794 menu.findItem(R.id.reload_menu_id);
1795 if (src != null) {
1796 dest.setIcon(src.getIcon());
1797 dest.setTitle(src.getTitle());
1798 }
Pankaj Garg49b79252014-11-07 17:33:41 -08001799 mActivity.invalidateOptionsMenu();
1800 }
1801
1802 public void invalidateOptionsMenu() {
1803 mAppMenuHandler.invalidateAppMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001804 }
1805
John Reck9c35b9c2012-05-30 10:08:50 -07001806 @Override
1807 public boolean onPrepareOptionsMenu(Menu menu) {
Pankaj Garg49b79252014-11-07 17:33:41 -08001808 // Software menu key (toolbar key)
1809 mAppMenuHandler.showAppMenu(mActivity.findViewById(R.id.more_browser_settings), false, false);
1810 return true;
1811 }
1812
1813 @Override
1814 public void prepareMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001815 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001816 // hold on to the menu reference here; it is used by the page callbacks
1817 // to update the menu based on loading state
1818 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001819 // Note: setVisible will decide whether an item is visible; while
1820 // setEnabled() will decide whether an item is enabled, which also means
1821 // whether the matching shortcut key will function.
1822 switch (mMenuState) {
1823 case EMPTY_MENU:
1824 if (mCurrentMenuState != mMenuState) {
1825 menu.setGroupVisible(R.id.MAIN_MENU, false);
1826 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1827 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1828 }
1829 break;
1830 default:
1831 if (mCurrentMenuState != mMenuState) {
1832 menu.setGroupVisible(R.id.MAIN_MENU, true);
1833 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1834 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1835 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001836 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001837 break;
1838 }
1839 mCurrentMenuState = mMenuState;
Pankaj Garg49b79252014-11-07 17:33:41 -08001840 mUi.onPrepareOptionsMenu(menu);
1841 }
1842
1843 private void setMenuItemVisibility(Menu menu, int id,
1844 boolean visibility) {
1845 MenuItem item = menu.findItem(id);
1846 if (item != null) {
1847 item.setVisible(visibility);
1848 }
1849 }
1850
1851 private int lookupBookmark(String title, String url) {
1852 final ContentResolver cr = getActivity().getContentResolver();
1853
1854 Cursor cursor = cr.query(BrowserContract.Bookmarks.CONTENT_URI,
1855 BookmarksLoader.PROJECTION,
1856 "title = ? OR url = ?",
1857 new String[] {
1858 title, url
1859 },
1860 null);
1861
1862 if (cursor == null) {
1863 return 0;
1864 }
1865
1866 return cursor.getCount();
1867 }
1868
1869 private void resetMenuItems(Menu menu) {
1870 setMenuItemVisibility(menu, R.id.history_menu_id, true);
1871 setMenuItemVisibility(menu, R.id.find_menu_id, true);
1872
1873 WebView w = getCurrentTopWebView();
1874 MenuItem bookmark_icon = menu.findItem(R.id.bookmark_this_page_id);
1875
1876 String title = w.getTitle();
1877 String url = w.getUrl();
1878 if (title != null && url != null && lookupBookmark(title, url) > 0) {
1879 bookmark_icon.setChecked(true);
1880 } else {
1881 bookmark_icon.setChecked(false);
1882 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001883 }
1884
Michael Kolb4bf79712011-07-14 14:18:12 -07001885 @Override
1886 public void updateMenuState(Tab tab, Menu menu) {
Michael Kolb4bf79712011-07-14 14:18:12 -07001887 boolean canGoForward = false;
John Reck42229bc2011-08-19 13:26:43 -07001888 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001889 boolean isLive = false;
Tarun Nainani8eb00912014-07-17 12:28:32 -07001890 // Following flag is used to identify schemes for which the LIVE_MENU
1891 // items defined in res/menu/browser.xml should be enabled
1892 boolean isLiveScheme = false;
1893 boolean isPageFinished = false;
Pankaj Garg49b79252014-11-07 17:33:41 -08001894
1895 resetMenuItems(menu);
1896
Michael Kolb4bf79712011-07-14 14:18:12 -07001897 if (tab != null) {
Michael Kolb4bf79712011-07-14 14:18:12 -07001898 canGoForward = tab.canGoForward();
John Reck42229bc2011-08-19 13:26:43 -07001899 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001900 isLive = !tab.isSnapshot();
Tarun Nainani8eb00912014-07-17 12:28:32 -07001901 isLiveScheme = UrlUtils.isLiveScheme(tab.getWebView().getUrl());
Pankaj Garg49b79252014-11-07 17:33:41 -08001902 isPageFinished = (tab.getPageFinishedStatus() || !tab.inPageLoad());
Michael Kolb4bf79712011-07-14 14:18:12 -07001903 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001904
1905 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1906 forward.setEnabled(canGoForward);
1907
Michael Kolb4bf79712011-07-14 14:18:12 -07001908 // decide whether to show the share link option
1909 PackageManager pm = mActivity.getPackageManager();
1910 Intent send = new Intent(Intent.ACTION_SEND);
1911 send.setType("text/plain");
1912 ResolveInfo ri = pm.resolveActivity(send,
1913 PackageManager.MATCH_DEFAULT_ONLY);
1914 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1915
1916 boolean isNavDump = mSettings.enableNavDump();
1917 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1918 nav.setVisible(isNavDump);
1919 nav.setEnabled(isNavDump);
1920
1921 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001922 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1923 uaSwitcher.setChecked(isDesktopUa);
Tarun Nainani8eb00912014-07-17 12:28:32 -07001924 menu.setGroupVisible(R.id.LIVE_MENU, isLive && isLiveScheme);
Pankaj Garg49b79252014-11-07 17:33:41 -08001925 menu.setGroupVisible(R.id.NAV_MENU, isLive && isLiveScheme);
1926 setMenuItemVisibility(menu, R.id.find_menu_id, isLive && isLiveScheme);
John Recke1a03a32011-09-14 17:04:16 -07001927 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Pankaj Garg49b79252014-11-07 17:33:41 -08001928 setMenuItemVisibility(menu, R.id.add_to_homescreen,
1929 isLive && isLiveScheme && isPageFinished);
1930 setMenuItemVisibility(menu, R.id.save_snapshot_menu_id,
1931 isLive && isLiveScheme && isPageFinished);
kaiyiza8b6dbb2013-07-29 18:11:22 +08001932 // history and snapshots item are the members of COMBO menu group,
1933 // so if show history item, only make snapshots item invisible.
1934 menu.findItem(R.id.snapshots_menu_id).setVisible(false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001935
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001936 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001937 }
1938
John Reck9c35b9c2012-05-30 10:08:50 -07001939 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07001940 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001941 if (null == getCurrentTopWebView()) {
1942 return false;
1943 }
1944 if (mMenuIsDown) {
1945 // The shortcut action consumes the MENU. Even if it is still down,
1946 // it won't trigger the next shortcut action. In the case of the
1947 // shortcut action triggering a new activity, like Bookmarks, we
1948 // won't get onKeyUp for MENU. So it is important to reset it here.
1949 mMenuIsDown = false;
1950 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001951 if (mUi.onOptionsItemSelected(item)) {
1952 // ui callback handled it
1953 return true;
1954 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001955 switch (item.getItemId()) {
1956 // -- Main menu
1957 case R.id.new_tab_menu_id:
1958 openTabToHomePage();
1959 break;
1960
1961 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001962 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001963 break;
1964
1965 case R.id.goto_menu_id:
1966 editUrl();
1967 break;
1968
1969 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001970 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1971 break;
1972
1973 case R.id.history_menu_id:
1974 bookmarksOrHistoryPicker(ComboViews.History);
1975 break;
1976
1977 case R.id.snapshots_menu_id:
1978 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001979 break;
1980
Pankaj Garg49b79252014-11-07 17:33:41 -08001981 case R.id.bookmark_this_page_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001982 bookmarkCurrentPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001983 break;
1984
1985 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001986 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001987 stopLoading();
1988 } else {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001989 Tab currentTab = mTabControl.getCurrentTab();
1990 if (currentTab.hasCrashed) {
1991 currentTab.replaceCrashView(getCurrentTopWebView(),
1992 currentTab.getViewContainer());
1993 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001994 getCurrentTopWebView().reload();
1995 }
1996 break;
1997
Michael Kolb8233fac2010-10-26 16:08:53 -07001998 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07001999 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07002000 break;
2001
2002 case R.id.close_menu_id:
2003 // Close the subwindow if it exists.
2004 if (mTabControl.getCurrentSubWindow() != null) {
2005 dismissSubWindow(mTabControl.getCurrentTab());
2006 break;
2007 }
2008 closeCurrentTab();
2009 break;
2010
kaiyiza8b6dbb2013-07-29 18:11:22 +08002011 case R.id.exit_menu_id:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002012 Object[] params = { new String("persist.debug.browsermonkeytest")};
2013 Class[] type = new Class[] {String.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -07002014 String ret = (String)ReflectHelper.invokeMethod(
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002015 "android.os.SystemProperties","get", type, params);
kaiyiza8b6dbb2013-07-29 18:11:22 +08002016 if (ret != null && ret.equals("enable"))
2017 break;
Panos Thomas4bdb5252014-11-13 16:20:11 -08002018 if (BrowserConfig.getInstance(getContext())
2019 .hasFeature(BrowserConfig.Feature.EXIT_DIALOG))
2020 showExitDialog(mActivity);
luxiaolb40014b2013-07-19 10:01:43 +08002021 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002022 case R.id.homepage_menu_id:
2023 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002024 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07002025 break;
2026
2027 case R.id.preferences_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002028 openPreferences();
Michael Kolb8233fac2010-10-26 16:08:53 -07002029 break;
2030
2031 case R.id.find_menu_id:
Michael Kolbe11b9212012-04-13 13:39:54 -07002032 findOnPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07002033 break;
2034
John Reck2bc80422011-06-30 15:11:49 -07002035 case R.id.save_snapshot_menu_id:
2036 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07002037 if (source == null) break;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002038 createScreenshotAsync(
2039 source.getWebView(),
2040 getDesiredThumbnailWidth(mActivity),
2041 getDesiredThumbnailHeight(mActivity),
2042 new ValueCallback<Bitmap>() {
2043 @Override
2044 public void onReceiveValue(Bitmap bitmap) {
2045 new SaveSnapshotTask(source, bitmap).execute();
2046 }
2047 });
Leon Scrogginsac993842011-02-02 12:54:07 -05002048 break;
2049
Michael Kolb8233fac2010-10-26 16:08:53 -07002050 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07002051 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07002052 break;
2053
John Recke1a03a32011-09-14 17:04:16 -07002054 case R.id.snapshot_go_live:
2055 goLive();
2056 return true;
2057
Michael Kolb8233fac2010-10-26 16:08:53 -07002058 case R.id.share_page_menu_id:
2059 Tab currentTab = mTabControl.getCurrentTab();
2060 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002061 return false;
2062 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08002063 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002064 break;
2065
2066 case R.id.dump_nav_menu_id:
2067 getCurrentTopWebView().debugDump();
2068 break;
2069
Michael Kolb8233fac2010-10-26 16:08:53 -07002070 case R.id.zoom_in_menu_id:
2071 getCurrentTopWebView().zoomIn();
2072 break;
2073
2074 case R.id.zoom_out_menu_id:
2075 getCurrentTopWebView().zoomOut();
2076 break;
2077
2078 case R.id.view_downloads_menu_id:
2079 viewDownloads();
2080 break;
2081
John Reck42229bc2011-08-19 13:26:43 -07002082 case R.id.ua_desktop_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002083 toggleUserAgent();
John Reck42229bc2011-08-19 13:26:43 -07002084 break;
2085
Michael Kolb8233fac2010-10-26 16:08:53 -07002086 case R.id.window_one_menu_id:
2087 case R.id.window_two_menu_id:
2088 case R.id.window_three_menu_id:
2089 case R.id.window_four_menu_id:
2090 case R.id.window_five_menu_id:
2091 case R.id.window_six_menu_id:
2092 case R.id.window_seven_menu_id:
2093 case R.id.window_eight_menu_id:
2094 {
2095 int menuid = item.getItemId();
2096 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
2097 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
2098 Tab desiredTab = mTabControl.getTab(id);
2099 if (desiredTab != null &&
2100 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07002101 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002102 }
2103 break;
2104 }
2105 }
2106 }
2107 break;
2108
Axesh R. Ajmera652d08e2014-06-16 16:36:33 -07002109 case R.id.about_menu_id:
Pankaj Garg18902562014-12-05 16:18:51 -08002110 Bundle bundle = new Bundle();
2111 bundle.putCharSequence("UA", Engine.getDefaultUserAgent());
2112 bundle.putCharSequence("TabTitle", mTabControl.getCurrentTab().getTitle());
2113 bundle.putCharSequence("TabURL", mTabControl.getCurrentTab().getUrl());
2114 BrowserPreferencesPage.startPreferenceFragmentExtraForResult(mActivity,
2115 AboutPreferencesFragment.class.getName(), bundle, 0);
Axesh R. Ajmera652d08e2014-06-16 16:36:33 -07002116 break;
2117
Pankaj Garg49b79252014-11-07 17:33:41 -08002118 case R.id.add_to_homescreen:
2119 final WebView w = getCurrentTopWebView();
2120 final EditText input = new EditText(getContext());
2121 input.setText(w.getTitle());
2122 new AlertDialog.Builder(getContext())
2123 .setTitle("Add to homescreen")
2124 .setMessage("Title")
2125 .setView(input)
2126 .setPositiveButton("Add", new DialogInterface.OnClickListener() {
2127 public void onClick(DialogInterface dialog, int whichButton) {
2128 mActivity.sendBroadcast(BookmarkUtils.createAddToHomeIntent(
2129 getContext(),
2130 w.getUrl(),
2131 input.getText().toString(),
2132 w.getViewportBitmap(),
2133 w.getFavicon()));
2134
2135 mActivity.startActivity(new Intent(Intent.ACTION_MAIN)
2136 .addCategory(Intent.CATEGORY_HOME));
2137 }})
2138 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
2139 public void onClick(DialogInterface dialog, int whichButton) {
2140 // Do nothing.
2141 }
2142 })
2143 .show();
2144 break;
2145
Michael Kolb8233fac2010-10-26 16:08:53 -07002146 default:
2147 return false;
2148 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002149 return true;
2150 }
2151
John Reck68234a92012-04-19 15:27:12 -07002152 private class SaveSnapshotTask extends AsyncTask<Void, Void, Long>
2153 implements OnCancelListener {
2154
2155 private Tab mTab;
2156 private Dialog mProgressDialog;
2157 private ContentValues mValues;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002158 private Bitmap mBitmap;
John Reck68234a92012-04-19 15:27:12 -07002159
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002160 private SaveSnapshotTask(Tab tab, Bitmap bm) {
John Reck68234a92012-04-19 15:27:12 -07002161 mTab = tab;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002162 mBitmap = bm;
John Reck68234a92012-04-19 15:27:12 -07002163 }
2164
2165 @Override
2166 protected void onPreExecute() {
2167 CharSequence message = mActivity.getText(R.string.saving_snapshot);
2168 mProgressDialog = ProgressDialog.show(mActivity, null, message,
2169 true, true, this);
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002170 mValues = mTab.createSnapshotValues(mBitmap);
John Reck68234a92012-04-19 15:27:12 -07002171 }
2172
2173 @Override
2174 protected Long doInBackground(Void... params) {
2175 if (!mTab.saveViewState(mValues)) {
2176 return null;
2177 }
2178 if (isCancelled()) {
2179 String path = mValues.getAsString(Snapshots.VIEWSTATE_PATH);
2180 File file = mActivity.getFileStreamPath(path);
2181 if (!file.delete()) {
2182 file.deleteOnExit();
2183 }
2184 return null;
2185 }
2186 final ContentResolver cr = mActivity.getContentResolver();
2187 Uri result = cr.insert(Snapshots.CONTENT_URI, mValues);
2188 if (result == null) {
2189 return null;
2190 }
2191 long id = ContentUris.parseId(result);
2192 return id;
2193 }
2194
2195 @Override
2196 protected void onPostExecute(Long id) {
2197 if (isCancelled()) {
2198 return;
2199 }
2200 mProgressDialog.dismiss();
2201 if (id == null) {
2202 Toast.makeText(mActivity, R.string.snapshot_failed,
2203 Toast.LENGTH_SHORT).show();
2204 return;
2205 }
2206 Bundle b = new Bundle();
2207 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
2208 mUi.showComboView(ComboViews.Snapshots, b);
2209 }
2210
2211 @Override
2212 public void onCancel(DialogInterface dialog) {
2213 cancel(true);
2214 }
2215 }
2216
Michael Kolb80f75082012-04-10 10:50:06 -07002217 @Override
2218 public void toggleUserAgent() {
2219 WebView web = getCurrentWebView();
2220 mSettings.toggleDesktopUseragent(web);
Michael Kolb80f75082012-04-10 10:50:06 -07002221 }
2222
2223 @Override
2224 public void findOnPage() {
2225 getCurrentTopWebView().showFindDialog(null, true);
2226 }
2227
2228 @Override
2229 public void openPreferences() {
Enrico Rosd6efa972014-12-02 19:49:59 -08002230 BrowserPreferencesPage.startPreferencesForResult(mActivity, getCurrentTopWebView().getUrl(), PREFERENCES_PAGE);
Michael Kolb80f75082012-04-10 10:50:06 -07002231 }
2232
2233 @Override
2234 public void bookmarkCurrentPage() {
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002235 WebView w = getCurrentTopWebView();
2236 if (w == null)
2237 return;
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002238 final Intent i = createBookmarkCurrentPageIntent(false);
2239 createScreenshotAsync(
2240 w, getDesiredThumbnailWidth(mActivity),
2241 getDesiredThumbnailHeight(mActivity),
2242 new ValueCallback<Bitmap>() {
2243 @Override
2244 public void onReceiveValue(Bitmap bitmap) {
2245 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL, bitmap);
2246 mActivity.startActivity(i);
2247 }
2248 });
Michael Kolb80f75082012-04-10 10:50:06 -07002249 }
2250
John Recke1a03a32011-09-14 17:04:16 -07002251 private void goLive() {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002252 SnapshotTab t = (SnapshotTab) getCurrentTab();
Tarun Nainani8eb00912014-07-17 12:28:32 -07002253 String url = t.getLiveUrl();
Axesh R. Ajmera8b3ed5d2014-10-22 16:35:25 -07002254 boolean onlySingleTabRemaining = false;
2255 if (mTabControl.getTabCount() > 1) {
2256 // destroy the old snapshot tab
2257 closeCurrentTab();
2258 } else {
2259 onlySingleTabRemaining = true;
2260 }
Tarun Nainani8eb00912014-07-17 12:28:32 -07002261 Tab liveTab = createNewTab(false, true, false);
Axesh R. Ajmera8b3ed5d2014-10-22 16:35:25 -07002262 if (onlySingleTabRemaining) {
2263 closeTab(t);
2264 }
2265
Tarun Nainani8eb00912014-07-17 12:28:32 -07002266 loadUrl(liveTab, url);
John Recke1a03a32011-09-14 17:04:16 -07002267 }
2268
luxiaolb40014b2013-07-19 10:01:43 +08002269 private void showExitDialog(final Activity activity) {
2270 new AlertDialog.Builder(activity)
2271 .setTitle(R.string.exit_browser_title)
Enrico Ros1f5a0952014-11-18 20:15:48 -08002272 /* disabled, was worrying people: .setIcon(android.R.drawable.ic_dialog_alert) */
luxiaolb40014b2013-07-19 10:01:43 +08002273 .setMessage(R.string.exit_browser_msg)
2274 .setNegativeButton(R.string.exit_minimize, new DialogInterface.OnClickListener() {
2275 public void onClick(DialogInterface dialog, int which) {
2276 activity.moveTaskToBack(true);
2277 dialog.dismiss();
2278 }
2279 })
2280 .setPositiveButton(R.string.exit_quit, new DialogInterface.OnClickListener() {
2281 public void onClick(DialogInterface dialog, int which) {
2282 activity.finish();
2283 mHandler.postDelayed(new Runnable() {
2284 @Override
2285 public void run() {
luxiaolb40014b2013-07-19 10:01:43 +08002286 mCrashRecoveryHandler.clearState(true);
2287 int pid = android.os.Process.myPid();
2288 android.os.Process.killProcess(pid);
2289 }
2290 }, 300);
2291 dialog.dismiss();
2292 }
2293 })
2294 .show();
2295 }
Michael Kolb315d5022011-10-13 12:47:11 -07002296 @Override
2297 public void showPageInfo() {
2298 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
2299 }
2300
John Reck9c35b9c2012-05-30 10:08:50 -07002301 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002302 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08002303 // Let the History and Bookmark fragments handle menus they created.
2304 if (item.getGroupId() == R.id.CONTEXT_MENU) {
2305 return false;
2306 }
2307
Michael Kolb8233fac2010-10-26 16:08:53 -07002308 int id = item.getItemId();
2309 boolean result = true;
2310 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002311 // -- Browser context menu
2312 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07002313 case R.id.save_link_context_menu_id:
Tarun Nainani700b69b2014-03-26 16:07:25 -07002314 case R.id.save_link_bookmark_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07002315 case R.id.copy_link_context_menu_id:
2316 final WebView webView = getCurrentTopWebView();
2317 if (null == webView) {
2318 result = false;
2319 break;
2320 }
2321 final HashMap<String, WebView> hrefMap =
2322 new HashMap<String, WebView>();
2323 hrefMap.put("webview", webView);
2324 final Message msg = mHandler.obtainMessage(
2325 FOCUS_NODE_HREF, id, 0, hrefMap);
2326 webView.requestFocusNodeHref(msg);
2327 break;
2328
2329 default:
2330 // For other context menus
2331 result = onOptionsItemSelected(item);
2332 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002333 return result;
2334 }
2335
2336 /**
2337 * support programmatically opening the context menu
2338 */
2339 public void openContextMenu(View view) {
2340 mActivity.openContextMenu(view);
2341 }
2342
2343 /**
2344 * programmatically open the options menu
2345 */
2346 public void openOptionsMenu() {
2347 mActivity.openOptionsMenu();
2348 }
2349
John Reck9c35b9c2012-05-30 10:08:50 -07002350 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002351 public boolean onMenuOpened(int featureId, Menu menu) {
2352 if (mOptionsMenuOpen) {
2353 if (mConfigChanged) {
2354 // We do not need to make any changes to the state of the
2355 // title bar, since the only thing that happened was a
2356 // change in orientation
2357 mConfigChanged = false;
2358 } else {
2359 if (!mExtendedMenuOpen) {
2360 mExtendedMenuOpen = true;
2361 mUi.onExtendedMenuOpened();
2362 } else {
2363 // Switching the menu back to icon view, so show the
2364 // title bar once again.
2365 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002366 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002367 }
2368 }
2369 } else {
2370 // The options menu is closed, so open it, and show the title
2371 mOptionsMenuOpen = true;
2372 mConfigChanged = false;
2373 mExtendedMenuOpen = false;
2374 mUi.onOptionsMenuOpened();
2375 }
2376 return true;
2377 }
2378
John Reck9c35b9c2012-05-30 10:08:50 -07002379 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002380 public void onOptionsMenuClosed(Menu menu) {
2381 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002382 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002383 }
2384
John Reck9c35b9c2012-05-30 10:08:50 -07002385 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002386 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002387 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002388 }
2389
2390 // Helper method for getting the top window.
2391 @Override
2392 public WebView getCurrentTopWebView() {
2393 return mTabControl.getCurrentTopWebView();
2394 }
2395
2396 @Override
2397 public WebView getCurrentWebView() {
2398 return mTabControl.getCurrentWebView();
2399 }
2400
2401 /*
2402 * This method is called as a result of the user selecting the options
2403 * menu to see the download window. It shows the download window on top of
2404 * the current window.
2405 */
2406 void viewDownloads() {
2407 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2408 mActivity.startActivity(intent);
2409 }
2410
John Reck30b065e2011-07-19 10:58:05 -07002411 int getActionModeHeight() {
2412 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
2413 new int[] { android.R.attr.actionBarSize });
2414 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
2415 actionBarSizeTypedArray.recycle();
2416 return size;
2417 }
2418
Michael Kolb8233fac2010-10-26 16:08:53 -07002419 // action mode
2420
John Reck9c35b9c2012-05-30 10:08:50 -07002421 @Override
2422 public void onActionModeStarted(ActionMode mode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002423 mUi.onActionModeStarted(mode);
2424 mActionMode = mode;
2425 }
2426
2427 /*
2428 * True if a custom ActionMode (i.e. find or select) is in use.
2429 */
2430 @Override
2431 public boolean isInCustomActionMode() {
2432 return mActionMode != null;
2433 }
2434
2435 /*
2436 * End the current ActionMode.
2437 */
2438 @Override
2439 public void endActionMode() {
2440 if (mActionMode != null) {
2441 mActionMode.finish();
2442 }
2443 }
2444
2445 /*
2446 * Called by find and select when they are finished. Replace title bars
2447 * as necessary.
2448 */
John Reck9c35b9c2012-05-30 10:08:50 -07002449 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002450 public void onActionModeFinished(ActionMode mode) {
2451 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002452 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002453 mActionMode = null;
2454 }
2455
2456 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08002457 final Tab tab = getCurrentTab();
2458 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002459 }
2460
2461 // bookmark handling
2462
2463 /**
2464 * add the current page as a bookmark to the given folder id
2465 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07002466 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05002467 * bookmarked, and if it is, edit that bookmark. If false, and
2468 * the site is already bookmarked, do not attempt to edit the
2469 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07002470 */
2471 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07002472 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07002473 WebView w = getCurrentTopWebView();
2474 if (w == null) {
2475 return null;
2476 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002477 Intent i = new Intent(mActivity,
2478 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07002479 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
2480 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
2481 String touchIconUrl = w.getTouchIconUrl();
2482 if (touchIconUrl != null) {
2483 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
2484 WebSettings settings = w.getSettings();
2485 if (settings != null) {
2486 i.putExtra(AddBookmarkPage.USER_AGENT,
2487 settings.getUserAgentString());
2488 }
2489 }
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002490 //SWE: Thumbnail will need to be set asynchronously
Michael Kolb8233fac2010-10-26 16:08:53 -07002491 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07002492 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05002493 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
2494 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002495 // Put the dialog at the upper right of the screen, covering the
2496 // star on the title bar.
2497 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07002498 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07002499 }
2500
2501 // file chooser
John Reck9c35b9c2012-05-30 10:08:50 -07002502 @Override
Ben Murdoch8cad4132012-01-11 10:56:43 +00002503 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002504 mUploadHandler = new UploadHandler(this);
Ben Murdoch8cad4132012-01-11 10:56:43 +00002505 mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
Michael Kolb8233fac2010-10-26 16:08:53 -07002506 }
2507
Vivek Sekharb54614f2014-05-01 19:03:37 -07002508 @Override
2509 public void showFileChooser(ValueCallback<String[]> uploadFilePaths, String acceptTypes,
2510 boolean capture) {
2511 mUploadHandler = new UploadHandler(this);
2512 mUploadHandler.showFileChooser(uploadFilePaths, acceptTypes, capture);
2513 }
2514
Michael Kolb8233fac2010-10-26 16:08:53 -07002515 // thumbnails
2516
2517 /**
2518 * Return the desired width for thumbnail screenshots, which are stored in
2519 * the database, and used on the bookmarks screen.
2520 * @param context Context for finding out the density of the screen.
2521 * @return desired width for thumbnail screenshot.
2522 */
2523 static int getDesiredThumbnailWidth(Context context) {
2524 return context.getResources().getDimensionPixelOffset(
2525 R.dimen.bookmarkThumbnailWidth);
2526 }
2527
2528 /**
2529 * Return the desired height for thumbnail screenshots, which are stored in
2530 * the database, and used on the bookmarks screen.
2531 * @param context Context for finding out the density of the screen.
2532 * @return desired height for thumbnail screenshot.
2533 */
2534 static int getDesiredThumbnailHeight(Context context) {
2535 return context.getResources().getDimensionPixelOffset(
2536 R.dimen.bookmarkThumbnailHeight);
2537 }
2538
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002539 static void createScreenshotAsync(WebView view, int width, int height,
2540 final ValueCallback<Bitmap> cb) {
2541 if (view == null || width == 0 || height == 0) {
2542 return;
2543 }
2544
2545 view.getContentBitmapAsync(
2546 (float) width / view.getWidth(),
2547 new Rect(),
2548 new ValueCallback<Bitmap>() {
2549 @Override
2550 public void onReceiveValue(Bitmap bitmap) {
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002551 if (bitmap != null)
2552 bitmap = bitmap.copy(Bitmap.Config.RGB_565, false);
2553 cb.onReceiveValue(bitmap);
2554 }});
2555 }
2556
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002557 private void updateScreenshot(final Tab tab) {
2558 createScreenshotAsync(
2559 tab.getWebView(),
2560 getDesiredThumbnailWidth(mActivity),
2561 getDesiredThumbnailHeight(mActivity),
2562 new ValueCallback<Bitmap>() {
2563 @Override
2564 public void onReceiveValue(Bitmap bitmap) {
2565 updateScreenshot(tab, bitmap);
2566 }
2567 });
2568 }
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002569
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002570 private void updateScreenshot(Tab tab, final Bitmap bm) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002571 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002572 // FIXME: Would like to make sure there is actually something to
2573 // draw, but the API for that (WebViewCore.pictureReady()) is not
2574 // currently accessible here.
2575
John Reck34ef2672011-02-10 11:30:55 -08002576 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002577 if (view == null) {
2578 // Tab was destroyed
2579 return;
2580 }
John Reck34ef2672011-02-10 11:30:55 -08002581 final String url = tab.getUrl();
2582 final String originalUrl = view.getOriginalUrl();
kaiyiz6e5b3e02013-08-19 20:02:01 +08002583 final String thumbnailUrl = mUpdateMyNavThumbnailUrl;
John Reck34ef2672011-02-10 11:30:55 -08002584 if (TextUtils.isEmpty(url)) {
2585 return;
2586 }
2587
kaiyiz6e5b3e02013-08-19 20:02:01 +08002588 //update My Navigation Thumbnails
2589 boolean isMyNavigationUrl = MyNavigationUtil.isMyNavigationUrl(mActivity, url);
2590 if (isMyNavigationUrl) {
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002591 updateMyNavigationThumbnail(url, bm);
kaiyiz6e5b3e02013-08-19 20:02:01 +08002592 }
John Reck34ef2672011-02-10 11:30:55 -08002593 // Only update thumbnails for web urls (http(s)://), not for
2594 // about:, javascript:, data:, etc...
2595 // Unless it is a bookmarked site, then always update
2596 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2597 return;
2598 }
2599
kaiyiz6e5b3e02013-08-19 20:02:01 +08002600 if (url != null && mUpdateMyNavThumbnailUrl != null
2601 && Patterns.WEB_URL.matcher(url).matches()
2602 && Patterns.WEB_URL.matcher(mUpdateMyNavThumbnailUrl).matches()) {
2603 String urlHost = (new WebAddress(url)).getHost();
2604 String bookmarkHost = (new WebAddress(mUpdateMyNavThumbnailUrl)).getHost();
2605 if (urlHost == null || urlHost.length() == 0 || bookmarkHost == null
2606 || bookmarkHost.length() == 0) {
2607 return;
2608 }
2609 String urlDomain = urlHost.substring(urlHost.indexOf('.'), urlHost.length());
2610 String bookmarkDomain = bookmarkHost.substring(bookmarkHost.indexOf('.'),
2611 bookmarkHost.length());
2612 Log.d(LOGTAG, "addressUrl domain is " + urlDomain);
2613 Log.d(LOGTAG, "bookmarkUrl domain is " + bookmarkDomain);
2614 if (!bookmarkDomain.equals(urlDomain)) {
2615 return;
2616 }
2617 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002618 if (bm == null) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002619 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
2620 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2621 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
2622 500);
2623 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002624 return;
2625 }
2626
2627 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002628 new AsyncTask<Void, Void, Void>() {
2629 @Override
2630 protected Void doInBackground(Void... unused) {
2631 Cursor cursor = null;
2632 try {
2633 // TODO: Clean this up
kaiyiz6e5b3e02013-08-19 20:02:01 +08002634 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl,
2635 mUpdateMyNavThumbnail ? ((thumbnailUrl != null) ? thumbnailUrl : url)
2636 : url);
2637 if (mUpdateMyNavThumbnail) {
2638 mUpdateMyNavThumbnail = false;
2639 mUpdateMyNavThumbnailUrl = null;
2640 }
John Reck34ef2672011-02-10 11:30:55 -08002641 if (cursor != null && cursor.moveToFirst()) {
2642 final ByteArrayOutputStream os =
2643 new ByteArrayOutputStream();
2644 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002645
John Reck34ef2672011-02-10 11:30:55 -08002646 ContentValues values = new ContentValues();
2647 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002648
John Reck34ef2672011-02-10 11:30:55 -08002649 do {
John Reck617fd832011-02-16 14:35:59 -08002650 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002651 cr.update(Images.CONTENT_URI, values, null, null);
2652 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002653 }
John Reck34ef2672011-02-10 11:30:55 -08002654 } catch (IllegalStateException e) {
2655 // Ignore
Mattias Nilsson561d1952011-10-04 10:18:50 +02002656 } catch (SQLiteException s) {
2657 // Added for possible error when user tries to remove the same bookmark
2658 // that is being updated with a screen shot
2659 Log.w(LOGTAG, "Error when running updateScreenshot ", s);
John Reck34ef2672011-02-10 11:30:55 -08002660 } finally {
2661 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002662 }
John Reck34ef2672011-02-10 11:30:55 -08002663 return null;
2664 }
2665 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002666 }
2667
2668 private class Copy implements OnMenuItemClickListener {
2669 private CharSequence mText;
2670
John Reck9c35b9c2012-05-30 10:08:50 -07002671 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002672 public boolean onMenuItemClick(MenuItem item) {
2673 copy(mText);
2674 return true;
2675 }
2676
2677 public Copy(CharSequence toCopy) {
2678 mText = toCopy;
2679 }
2680 }
2681
Leon Scroggins63c02662010-11-18 15:16:27 -05002682 private static class Download implements OnMenuItemClickListener {
2683 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002684 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002685 private boolean mPrivateBrowsing;
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002686 private String mUserAgent;
George Mount387d45d2011-10-07 15:57:53 -07002687 private static final String FALLBACK_EXTENSION = "dat";
2688 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002689
John Reck9c35b9c2012-05-30 10:08:50 -07002690 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002691 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002692 if (DataUri.isDataUri(mText)) {
2693 saveDataUri();
2694 } else {
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002695 DownloadHandler.onDownloadStartNoStream(mActivity, mText, mUserAgent,
luxiaol62677b02013-07-22 07:54:49 +08002696 null, null, null, mPrivateBrowsing, 0);
George Mount387d45d2011-10-07 15:57:53 -07002697 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002698 return true;
2699 }
2700
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002701 public Download(Activity activity, String toDownload, boolean privateBrowsing,
2702 String userAgent) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002703 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002704 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002705 mPrivateBrowsing = privateBrowsing;
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002706 mUserAgent = userAgent;
Michael Kolb8233fac2010-10-26 16:08:53 -07002707 }
George Mount387d45d2011-10-07 15:57:53 -07002708
2709 /**
2710 * Treats mText as a data URI and writes its contents to a file
2711 * based on the current time.
2712 */
2713 private void saveDataUri() {
2714 FileOutputStream outputStream = null;
2715 try {
2716 DataUri uri = new DataUri(mText);
2717 File target = getTarget(uri);
2718 outputStream = new FileOutputStream(target);
2719 outputStream.write(uri.getData());
2720 final DownloadManager manager =
2721 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2722 manager.addCompletedDownload(target.getName(),
2723 mActivity.getTitle().toString(), false,
2724 uri.getMimeType(), target.getAbsolutePath(),
John Reck9c35b9c2012-05-30 10:08:50 -07002725 uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002726 } catch (IOException e) {
2727 Log.e(LOGTAG, "Could not save data URL");
2728 } finally {
2729 if (outputStream != null) {
2730 try {
2731 outputStream.close();
2732 } catch (IOException e) {
2733 // ignore close errors
2734 }
2735 }
2736 }
2737 }
2738
2739 /**
2740 * Creates a File based on the current time stamp and uses
2741 * the mime type of the DataUri to get the extension.
2742 */
2743 private File getTarget(DataUri uri) throws IOException {
2744 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
Johan Redestigaa676182012-10-03 13:33:01 +02002745 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT, Locale.US);
George Mount387d45d2011-10-07 15:57:53 -07002746 String nameBase = format.format(new Date());
2747 String mimeType = uri.getMimeType();
2748 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2749 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2750 if (extension == null) {
2751 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2752 extension = FALLBACK_EXTENSION;
2753 }
2754 extension = "." + extension; // createTempFile needs the '.'
2755 File targetFile = File.createTempFile(nameBase, extension, dir);
2756 return targetFile;
2757 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002758 }
2759
Cary Clark8974d282010-11-22 10:46:05 -05002760 private static class SelectText implements OnMenuItemClickListener {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002761 private WebView mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002762
John Reck9c35b9c2012-05-30 10:08:50 -07002763 @Override
Cary Clark8974d282010-11-22 10:46:05 -05002764 public boolean onMenuItemClick(MenuItem item) {
2765 if (mWebView != null) {
2766 return mWebView.selectText();
2767 }
2768 return false;
2769 }
2770
2771 public SelectText(WebView webView) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002772 mWebView = webView;
Cary Clark8974d282010-11-22 10:46:05 -05002773 }
2774
2775 }
2776
Michael Kolb8233fac2010-10-26 16:08:53 -07002777 /********************** TODO: UI stuff *****************************/
2778
2779 // these methods have been copied, they still need to be cleaned up
2780
2781 /****************** tabs ***************************************************/
2782
2783 // basic tab interactions:
2784
2785 // it is assumed that tabcontrol already knows about the tab
2786 protected void addTab(Tab tab) {
2787 mUi.addTab(tab);
2788 }
2789
2790 protected void removeTab(Tab tab) {
2791 mUi.removeTab(tab);
2792 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002793 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002794 }
2795
Michael Kolbf2055602011-04-09 17:20:03 -07002796 @Override
2797 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002798 // monkey protection against delayed start
2799 if (tab != null) {
2800 mTabControl.setCurrentTab(tab);
2801 // the tab is guaranteed to have a webview after setCurrentTab
2802 mUi.setActiveTab(tab);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002803 tab.setTimeStamp();
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07002804 //Purge active tabs
2805 MemoryMonitor.purgeActiveTabs(mActivity.getApplicationContext(), this, mSettings);
Michael Kolbcd424e92011-02-24 10:26:26 -08002806 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002807 }
2808
John Reck8bcafc12011-08-29 16:43:02 -07002809 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002810 Tab current = mTabControl.getCurrentTab();
2811 if (current != null
2812 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002813 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002814 }
2815 }
2816
John Reck26b18322011-06-21 13:08:58 -07002817 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002818 // Dismiss the subwindow if applicable.
2819 dismissSubWindow(appTab);
2820 // Since we might kill the WebView, remove it from the
2821 // content view first.
2822 mUi.detachTab(appTab);
2823 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002824 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002825 // TODO: analyze why the remove and add are necessary
2826 mUi.attachTab(appTab);
2827 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002828 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002829 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002830 } else {
2831 // If the tab was the current tab, we have to attach
2832 // it to the view system again.
2833 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002834 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002835 }
2836 }
2837
2838 // Remove the sub window if it exists. Also called by TabControl when the
2839 // user clicks the 'X' to dismiss a sub window.
John Reck9c35b9c2012-05-30 10:08:50 -07002840 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002841 public void dismissSubWindow(Tab tab) {
2842 removeSubWindow(tab);
2843 // dismiss the subwindow. This will destroy the WebView.
2844 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002845 WebView wv = getCurrentTopWebView();
2846 if (wv != null) {
2847 wv.requestFocus();
2848 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002849 }
2850
2851 @Override
2852 public void removeSubWindow(Tab t) {
2853 if (t.getSubWebView() != null) {
2854 mUi.removeSubWindow(t.getSubViewContainer());
2855 }
2856 }
2857
2858 @Override
2859 public void attachSubWindow(Tab tab) {
2860 if (tab.getSubWebView() != null) {
2861 mUi.attachSubWindow(tab.getSubViewContainer());
2862 getCurrentTopWebView().requestFocus();
2863 }
2864 }
2865
Mathew Inwood29721c22011-06-29 17:55:24 +01002866 private Tab showPreloadedTab(final UrlData urlData) {
2867 if (!urlData.isPreloaded()) {
2868 return null;
2869 }
2870 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2871 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2872 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002873 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002874 // Could not submit query. Fallback to regular tab creation
2875 tabControl.destroy();
2876 return null;
2877 }
2878 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002879 // check tab count and make room for new tab
2880 if (!mTabControl.canCreateNewTab()) {
2881 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2882 if (leastUsed != null) {
2883 closeTab(leastUsed);
2884 }
2885 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002886 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002887 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002888 mTabControl.addPreloadedTab(t);
2889 addTab(t);
2890 setActiveTab(t);
2891 return t;
2892 }
2893
Michael Kolb7bcafde2011-05-09 13:55:59 -07002894 // open a non inconito tab with the given url data
2895 // and set as active tab
2896 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002897 Tab tab = showPreloadedTab(urlData);
2898 if (tab == null) {
2899 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002900 if ((tab != null) && !urlData.isEmpty()) {
2901 loadUrlDataIn(tab, urlData);
2902 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002903 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002904 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002905 }
2906
Michael Kolb843510f2010-12-09 10:51:49 -08002907 @Override
2908 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002909 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002910 }
2911
Michael Kolb8233fac2010-10-26 16:08:53 -07002912 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002913 public Tab openIncognitoTab() {
2914 return openTab(INCOGNITO_URI, true, true, false);
2915 }
2916
2917 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002918 public Tab openTab(String url, boolean incognito, boolean setActive,
2919 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002920 return openTab(url, incognito, setActive, useCurrent, null);
2921 }
2922
2923 @Override
2924 public Tab openTab(String url, Tab parent, boolean setActive,
2925 boolean useCurrent) {
2926 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2927 setActive, useCurrent, parent);
2928 }
2929
2930 public Tab openTab(String url, boolean incognito, boolean setActive,
2931 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002932 Tab tab = createNewTab(incognito, setActive, useCurrent);
2933 if (tab != null) {
Vivek Sekhar871172e2014-07-23 12:16:54 -07002934 if (parent instanceof SnapshotTab) {
2935 addTab(tab);
2936 if (setActive)
2937 setActiveTab(tab);
2938 }else if (parent != null && parent != tab) {
John Reck5949c662011-05-27 09:52:29 -07002939 parent.addChildTab(tab);
2940 }
Michael Kolb519d2282011-05-09 17:03:19 -07002941 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002942 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002943 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002944 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002945 return tab;
2946 }
2947
2948 // this method will attempt to create a new tab
2949 // incognito: private browsing tab
2950 // setActive: ste tab as current tab
2951 // useCurrent: if no new tab can be created, return current tab
2952 private Tab createNewTab(boolean incognito, boolean setActive,
2953 boolean useCurrent) {
2954 Tab tab = null;
2955 if (mTabControl.canCreateNewTab()) {
Stewart Chaoe0e132e2014-12-01 18:28:22 -05002956 tab = mTabControl.createNewTab(incognito, !setActive);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002957 addTab(tab);
2958 if (setActive) {
2959 setActiveTab(tab);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07002960 } else {
2961 tab.pause();
Michael Kolb7bcafde2011-05-09 13:55:59 -07002962 }
2963 } else {
2964 if (useCurrent) {
2965 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002966 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002967 } else {
2968 mUi.showMaxTabsWarning();
2969 }
2970 }
2971 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002972 }
2973
John Reck2bc80422011-06-30 15:11:49 -07002974 @Override
2975 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2976 SnapshotTab tab = null;
2977 if (mTabControl.canCreateNewTab()) {
2978 tab = mTabControl.createSnapshotTab(snapshotId);
2979 addTab(tab);
2980 if (setActive) {
2981 setActiveTab(tab);
2982 }
2983 } else {
2984 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002985 }
2986 return tab;
2987 }
2988
Michael Kolb8233fac2010-10-26 16:08:53 -07002989 /**
Michael Kolbc831b632011-05-11 09:30:34 -07002990 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07002991 * @return boolean True if we successfully switched to a different tab. If
2992 * the indexth tab is null, or if that tab is the same as
2993 * the current one, return false.
2994 */
2995 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07002996 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002997 Tab currentTab = mTabControl.getCurrentTab();
2998 if (tab == null || tab == currentTab) {
2999 return false;
3000 }
3001 setActiveTab(tab);
3002 return true;
3003 }
3004
3005 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07003006 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07003007 closeCurrentTab(false);
3008 }
3009
3010 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003011 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07003012 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07003013 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08003014 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07003015 return;
3016 }
Michael Kolbc831b632011-05-11 09:30:34 -07003017 final Tab current = mTabControl.getCurrentTab();
3018 final int pos = mTabControl.getCurrentPosition();
3019 Tab newTab = current.getParent();
3020 if (newTab == null) {
3021 newTab = mTabControl.getTab(pos + 1);
3022 if (newTab == null) {
3023 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07003024 }
3025 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07003026 if (andQuit) {
3027 mTabControl.setCurrentTab(newTab);
3028 closeTab(current);
3029 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003030 // Close window
3031 closeTab(current);
3032 }
3033 }
3034
3035 /**
3036 * Close the tab, remove its associated title bar, and adjust mTabControl's
3037 * current tab to a valid value.
3038 */
3039 @Override
3040 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07003041 if (tab == mTabControl.getCurrentTab()) {
3042 closeCurrentTab();
3043 } else {
3044 removeTab(tab);
3045 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003046 }
3047
Afzal Najamd4e33312012-04-26 01:54:01 -04003048 /**
3049 * Close all tabs except the current one
3050 */
3051 @Override
3052 public void closeOtherTabs() {
3053 int inactiveTabs = mTabControl.getTabCount() - 1;
3054 for (int i = inactiveTabs; i >= 0; i--) {
3055 Tab tab = mTabControl.getTab(i);
3056 if (tab != mTabControl.getCurrentTab()) {
3057 removeTab(tab);
3058 }
3059 }
3060 }
3061
Michael Kolb8233fac2010-10-26 16:08:53 -07003062 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07003063 protected void loadUrlFromContext(String url) {
3064 Tab tab = getCurrentTab();
3065 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07003066 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07003067 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003068 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixone1d6dfc2012-12-17 13:39:17 -08003069 if (!((BrowserWebView) view).getWebViewClient().
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00003070 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07003071 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07003072 }
3073 }
3074 }
3075
3076 /**
3077 * Load the URL into the given WebView and update the title bar
3078 * to reflect the new load. Call this instead of WebView.loadUrl
3079 * directly.
3080 * @param view The WebView used to load url.
3081 * @param url The URL to load.
3082 */
John Reck71e51422011-07-01 16:49:28 -07003083 @Override
3084 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07003085 loadUrl(tab, url, null);
3086 }
3087
3088 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
3089 if (tab != null) {
3090 dismissSubWindow(tab);
Vivek Sekhar0e10a202014-09-12 19:13:23 -07003091 mHomepageHandler.registerJsInterface(tab.getWebView(), url);
John Reck26b18322011-06-21 13:08:58 -07003092 tab.loadUrl(url, headers);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003093 if (tab.hasCrashed) {
3094 tab.replaceCrashView(tab.getWebView(), tab.getViewContainer());
3095 }
Michael Kolba53c9892011-10-05 13:31:40 -07003096 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07003097 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003098 }
3099
3100 /**
3101 * Load UrlData into a Tab and update the title bar to reflect the new
3102 * load. Call this instead of UrlData.loadIn directly.
3103 * @param t The Tab used to load.
3104 * @param data The UrlData being loaded.
3105 */
3106 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07003107 if (data != null) {
Michael Kolb5ff5c8b2012-05-03 11:37:58 -07003108 if (data.isPreloaded()) {
Michael Kolb14612442011-06-24 13:06:29 -07003109 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07003110 } else {
John Reck38b39652012-06-05 09:22:59 -07003111 if (t != null && data.mDisableUrlOverride) {
3112 t.disableUrlOverridingForLoad();
3113 }
John Reck26b18322011-06-21 13:08:58 -07003114 loadUrl(t, data.mUrl, data.mHeaders);
3115 }
3116 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003117 }
3118
John Reck30c714c2010-12-16 17:30:34 -08003119 @Override
3120 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08003121 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07003122 if (tab.canGoBack()) {
3123 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08003124 } else {
John Reckef654f12011-07-12 16:42:08 -07003125 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08003126 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003127 }
3128
3129 void goBackOnePageOrQuit() {
3130 Tab current = mTabControl.getCurrentTab();
3131 if (current == null) {
Panos Thomas4bdb5252014-11-13 16:20:11 -08003132 if (BrowserConfig.getInstance(getContext()).hasFeature(BrowserConfig.Feature.EXIT_DIALOG)) {
3133 showExitDialog(mActivity);
3134 } else {
3135 /*
3136 * Instead of finishing the activity, simply push this to the back
3137 * of the stack and let ActivityManager to choose the foreground
3138 * activity. As BrowserActivity is singleTask, it will be always the
3139 * root of the task. So we can use either true or false for
3140 * moveTaskToBack().
3141 */
3142 mActivity.moveTaskToBack(true);
3143 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003144 return;
3145 }
John Reckef654f12011-07-12 16:42:08 -07003146 if (current.canGoBack()) {
3147 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07003148 } else {
3149 // Check to see if we are closing a window that was created by
3150 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07003151 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07003152 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07003153 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07003154 // Now we close the other tab
3155 closeTab(current);
Panos Thomas4bdb5252014-11-13 16:20:11 -08003156 } else if (BrowserConfig.getInstance(getContext())
3157 .hasFeature(BrowserConfig.Feature.EXIT_DIALOG)) {
3158 showExitDialog(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -07003159 } else {
Panos Thomas4bdb5252014-11-13 16:20:11 -08003160 if ((current.getAppId() != null) || current.closeOnBack()) {
3161 closeCurrentTab(true);
3162 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003163 /*
3164 * Instead of finishing the activity, simply push this to the back
3165 * of the stack and let ActivityManager to choose the foreground
3166 * activity. As BrowserActivity is singleTask, it will be always the
3167 * root of the task. So we can use either true or false for
3168 * moveTaskToBack().
3169 */
Panos Thomas4bdb5252014-11-13 16:20:11 -08003170 mActivity.moveTaskToBack(true);
Michael Kolb8233fac2010-10-26 16:08:53 -07003171 }
3172 }
3173 }
3174
3175 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07003176 * helper method for key handler
3177 * returns the current tab if it can't advance
3178 */
Michael Kolbc831b632011-05-11 09:30:34 -07003179 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08003180 int pos = mTabControl.getCurrentPosition() + 1;
3181 if (pos >= mTabControl.getTabCount()) {
3182 pos = 0;
3183 }
3184 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07003185 }
3186
3187 /**
3188 * helper method for key handler
3189 * returns the current tab if it can't advance
3190 */
Michael Kolbc831b632011-05-11 09:30:34 -07003191 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08003192 int pos = mTabControl.getCurrentPosition() - 1;
3193 if ( pos < 0) {
3194 pos = mTabControl.getTabCount() - 1;
3195 }
3196 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07003197 }
3198
John Reckbcef87f2012-02-03 14:58:34 -08003199 boolean isMenuOrCtrlKey(int keyCode) {
3200 return (KeyEvent.KEYCODE_MENU == keyCode)
3201 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
3202 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
3203 }
3204
Michael Kolb0035fad2011-03-14 13:25:28 -07003205 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07003206 * handle key events in browser
3207 *
3208 * @param keyCode
3209 * @param event
3210 * @return true if handled, false to pass to super
3211 */
John Reck9c35b9c2012-05-30 10:08:50 -07003212 @Override
3213 public boolean onKeyDown(int keyCode, KeyEvent event) {
Pankaj Garg49b79252014-11-07 17:33:41 -08003214 if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
3215 // Hardware menu key
Enrico Ros1f5a0952014-11-18 20:15:48 -08003216 mAppMenuHandler.showAppMenu(mActivity.findViewById(R.id.taburlbar),
Pankaj Garg49b79252014-11-07 17:33:41 -08003217 true, false);
3218 return true;
3219 }
3220
Cary Clark160bbb92011-01-10 11:17:07 -05003221 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07003222 // Even if MENU is already held down, we need to call to super to open
3223 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08003224 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003225 mMenuIsDown = true;
3226 return false;
3227 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003228
Cary Clark8ff8c662010-12-29 15:03:05 -05003229 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07003230 Tab tab = getCurrentTab();
3231 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05003232
Cary Clark160bbb92011-01-10 11:17:07 -05003233 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
3234 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05003235
Michael Kolb8233fac2010-10-26 16:08:53 -07003236 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07003237 case KeyEvent.KEYCODE_TAB:
3238 if (event.isCtrlPressed()) {
3239 if (event.isShiftPressed()) {
3240 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07003241 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07003242 } else {
3243 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07003244 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07003245 }
3246 return true;
3247 }
3248 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07003249 case KeyEvent.KEYCODE_SPACE:
3250 // WebView/WebTextView handle the keys in the KeyDown. As
3251 // the Activity's shortcut keys are only handled when WebView
3252 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05003253 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003254 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05003255 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003256 pageDown();
3257 }
3258 return true;
3259 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05003260 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08003261 event.startTracking();
3262 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07003263 case KeyEvent.KEYCODE_FORWARD:
3264 if (!noModifiers) break;
3265 tab.goForward();
3266 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05003267 case KeyEvent.KEYCODE_DPAD_LEFT:
3268 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07003269 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05003270 return true;
3271 }
3272 break;
3273 case KeyEvent.KEYCODE_DPAD_RIGHT:
3274 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07003275 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05003276 return true;
3277 }
3278 break;
3279 case KeyEvent.KEYCODE_A:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003280 if (ctrl) {
3281 webView.selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05003282 return true;
3283 }
3284 break;
Michael Kolba4183062011-01-16 10:43:21 -08003285// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003286 case KeyEvent.KEYCODE_C:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003287 if (ctrl ) {
3288 webView.copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05003289 return true;
3290 }
3291 break;
Michael Kolba4183062011-01-16 10:43:21 -08003292// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003293// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08003294// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003295// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08003296// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003297// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08003298// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003299// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08003300// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003301// case KeyEvent.KEYCODE_M: // unused
3302// case KeyEvent.KEYCODE_N: // in Chrome: new window
3303// case KeyEvent.KEYCODE_O: // in Chrome: open file
3304// case KeyEvent.KEYCODE_P: // in Chrome: print page
3305// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003306// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05003307// case KeyEvent.KEYCODE_S: // in Chrome: saves page
3308 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003309 // we can't use the ctrl/shift flags, they check for
3310 // exclusive use of a modifier
3311 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05003312 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07003313 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05003314 } else {
3315 openTabToHomePage();
3316 }
3317 return true;
3318 }
3319 break;
3320// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
3321// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07003322// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003323// case KeyEvent.KEYCODE_X: // text view intercepts to cut
3324// case KeyEvent.KEYCODE_Y: // unused
3325// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07003326 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003327 // it is a regular key and webview is not null
3328 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07003329 }
3330
John Reck9c35b9c2012-05-30 10:08:50 -07003331 @Override
3332 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
John Recke6bf4ab2011-02-24 15:48:05 -08003333 switch(keyCode) {
3334 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07003335 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07003336 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08003337 return true;
3338 }
3339 break;
3340 }
3341 return false;
3342 }
3343
John Reck9c35b9c2012-05-30 10:08:50 -07003344 @Override
3345 public boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08003346 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07003347 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08003348 if (KeyEvent.KEYCODE_MENU == keyCode
3349 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07003350 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07003351 }
3352 }
Cary Clark160bbb92011-01-10 11:17:07 -05003353 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07003354 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003355 case KeyEvent.KEYCODE_BACK:
3356 if (event.isTracking() && !event.isCanceled()) {
3357 onBackKey();
3358 return true;
3359 }
3360 break;
3361 }
3362 return false;
3363 }
3364
3365 public boolean isMenuDown() {
3366 return mMenuIsDown;
3367 }
3368
John Reck9c35b9c2012-05-30 10:08:50 -07003369 @Override
Ben Murdoch8029a772010-11-16 11:58:21 +00003370 public void setupAutoFill(Message message) {
3371 // Open the settings activity at the AutoFill profile fragment so that
3372 // the user can create a new profile. When they return, we will dispatch
3373 // the message so that we can autofill the form using their new profile.
Ben Murdoch8029a772010-11-16 11:58:21 +00003374 mAutoFillSetupMessage = message;
Enrico Rosd6efa972014-12-02 19:49:59 -08003375 BrowserPreferencesPage.startPreferenceFragmentForResult(mActivity,
3376 AutoFillSettingsFragment.class.getName(), AUTOFILL_SETUP);
Ben Murdoch8029a772010-11-16 11:58:21 +00003377 }
John Reckb3417f02011-01-14 11:01:05 -08003378
John Reck9c35b9c2012-05-30 10:08:50 -07003379 @Override
Michael Kolbfbc579a2011-07-07 15:59:33 -07003380 public boolean onSearchRequested() {
Michael Kolb1f9b3562012-04-24 14:38:34 -07003381 mUi.editUrl(false, true);
Michael Kolbfbc579a2011-07-07 15:59:33 -07003382 return true;
3383 }
3384
John Reck1cf4b792011-07-26 10:22:22 -07003385 @Override
3386 public boolean shouldCaptureThumbnails() {
3387 return mUi.shouldCaptureThumbnails();
3388 }
3389
Michael Kolbc3af0672011-08-09 10:24:41 -07003390 @Override
Michael Kolb0b129122012-06-04 16:31:58 -07003391 public boolean supportsVoice() {
3392 PackageManager pm = mActivity.getPackageManager();
3393 List activities = pm.queryIntentActivities(new Intent(
3394 RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
3395 return activities.size() != 0;
3396 }
3397
3398 @Override
3399 public void startVoiceRecognizer() {
3400 Intent voice = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003401 voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
Michael Kolb0b129122012-06-04 16:31:58 -07003402 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
3403 voice.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
3404 mActivity.startActivityForResult(voice, VOICE_RESULT);
3405 }
3406
Pankaj Garg7b279f62014-08-12 14:47:18 -07003407 public void setWindowDimming(float level) {
3408 if (level != 0) {
3409 WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
3410 lp.dimAmount = level;
3411 mActivity.getWindow().setAttributes(lp);
3412 mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
3413 } else {
3414 mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
3415 }
3416 }
3417
Michael Kolb0b129122012-06-04 16:31:58 -07003418 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003419 public void setBlockEvents(boolean block) {
3420 mBlockEvents = block;
3421 }
3422
John Reck9c35b9c2012-05-30 10:08:50 -07003423 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003424 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07003425 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003426 }
3427
John Reck9c35b9c2012-05-30 10:08:50 -07003428 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003429 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07003430 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003431 }
3432
John Reck9c35b9c2012-05-30 10:08:50 -07003433 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003434 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003435 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003436 }
3437
John Reck9c35b9c2012-05-30 10:08:50 -07003438 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003439 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003440 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003441 }
3442
John Reck9c35b9c2012-05-30 10:08:50 -07003443 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003444 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003445 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003446 }
3447
Pankaj Garg49b79252014-11-07 17:33:41 -08003448 @Override
3449 public boolean shouldShowAppMenu() {
3450 return true;
3451 }
3452
3453 @Override
3454 public int getMenuThemeResourceId() {
3455 return R.style.OverflowMenuTheme;
3456 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003457}