blob: 181b14803deb6c19790748f005d3fc158c69c9bd [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;
Michael Kolb8233fac2010-10-26 16:08:53 -070043import android.graphics.Canvas;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080044import android.graphics.Paint;
45import android.graphics.Rect;
kaiyiza016da12013-08-26 17:50:22 +080046import android.net.ConnectivityManager;
47import android.net.NetworkInfo;
Michael Kolb8233fac2010-10-26 16:08:53 -070048import android.net.Uri;
49import android.net.http.SslError;
kaiyiza016da12013-08-26 17:50:22 +080050import android.net.wifi.WifiManager;
kaiyizb7bf1f22013-10-02 11:42:23 +080051import android.net.wifi.ScanResult;
Michael Kolb8233fac2010-10-26 16:08:53 -070052import android.os.AsyncTask;
53import android.os.Bundle;
George Mount387d45d2011-10-07 15:57:53 -070054import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070055import android.os.Handler;
56import android.os.Message;
57import android.os.PowerManager;
58import android.os.PowerManager.WakeLock;
Ben Murdoch8029a772010-11-16 11:58:21 +000059import android.preference.PreferenceActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -070060import android.provider.ContactsContract;
61import android.provider.ContactsContract.Intents.Insert;
kaiyiza016da12013-08-26 17:50:22 +080062import android.provider.Settings;
Michael Kolb0b129122012-06-04 16:31:58 -070063import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070064import android.text.TextUtils;
65import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080066import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070067import android.view.ActionMode;
68import android.view.ContextMenu;
69import android.view.ContextMenu.ContextMenuInfo;
70import android.view.Gravity;
71import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070072import android.view.Menu;
73import android.view.MenuInflater;
74import android.view.MenuItem;
75import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070076import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070077import android.view.View;
Pankaj Garg7b279f62014-08-12 14:47:18 -070078import android.view.WindowManager;
George Mount387d45d2011-10-07 15:57:53 -070079import android.webkit.MimeTypeMap;
Michael Kolb8233fac2010-10-26 16:08:53 -070080import android.webkit.ValueCallback;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080081import android.webkit.WebChromeClient.CustomViewCallback;
Pankaj Garg49b79252014-11-07 17:33:41 -080082import android.widget.Button;
83import android.widget.EditText;
Leon Scrogginsac993842011-02-02 12:54:07 -050084import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070085
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080086import org.codeaurora.swe.CookieManager;
87import org.codeaurora.swe.CookieSyncManager;
88import org.codeaurora.swe.HttpAuthHandler;
89import org.codeaurora.swe.SslErrorHandler;
90import org.codeaurora.swe.WebSettings;
91import org.codeaurora.swe.WebView;
Vivek Sekhar0e10a202014-09-12 19:13:23 -070092import org.codeaurora.swe.WebBackForwardList;
93import org.codeaurora.swe.WebHistoryItem;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080094
Axesh R. Ajmera34d3f142014-06-30 20:05:36 -070095import com.android.browser.AppAdapter;
Bijan Amirzada41242f22014-03-21 12:12:18 -070096import com.android.browser.R;
97import com.android.browser.IntentHandler.UrlData;
98import com.android.browser.UI.ComboViews;
99import com.android.browser.mynavigation.AddMyNavigationPage;
100import com.android.browser.mynavigation.MyNavigationUtil;
Bijan Amirzada3f04dc72014-06-25 11:48:36 -0700101import com.android.browser.platformsupport.Browser;
Bijan Amirzada41242f22014-03-21 12:12:18 -0700102import com.android.browser.platformsupport.BrowserContract;
103import com.android.browser.platformsupport.WebAddress;
104import com.android.browser.platformsupport.BrowserContract.Images;
105import com.android.browser.provider.BrowserProvider2.Thumbnails;
106import com.android.browser.provider.SnapshotProvider.Snapshots;
107import com.android.browser.reflect.ReflectHelper;
Pankaj Garg49b79252014-11-07 17:33:41 -0800108import com.android.browser.appmenu.AppMenuHandler;
109import com.android.browser.appmenu.AppMenuPropertiesDelegate;
Michael Kolb4bd767d2011-05-27 11:33:55 -0700110
Michael Kolb8233fac2010-10-26 16:08:53 -0700111import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -0700112import java.io.File;
113import java.io.FileOutputStream;
114import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -0700115import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -0700116import java.text.DateFormat;
117import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -0700118import java.util.ArrayList;
Michael Kolb8233fac2010-10-26 16:08:53 -0700119import java.util.Calendar;
George Mount387d45d2011-10-07 15:57:53 -0700120import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -0700121import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800122import java.util.List;
Johan Redestigaa676182012-10-03 13:33:01 +0200123import java.util.Locale;
John Reck26b18322011-06-21 13:08:58 -0700124import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700125
126/**
127 * Controller for browser
128 */
129public class Controller
Pankaj Garg49b79252014-11-07 17:33:41 -0800130 implements WebViewController, UiController, ActivityController,
131 AppMenuPropertiesDelegate {
Michael Kolb8233fac2010-10-26 16:08:53 -0700132
133 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800134 private static final String SEND_APP_ID_EXTRA =
135 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700136 private static final String INCOGNITO_URI = "browser:incognito";
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800137
Vivek Sekharb54614f2014-05-01 19:03:37 -0700138 // Remind switch to data connection if wifi is unavailable
139 private static final int NETWORK_SWITCH_TYPE_OK = 1;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800140
Michael Kolb8233fac2010-10-26 16:08:53 -0700141 // public message ids
142 public final static int LOAD_URL = 1001;
143 public final static int STOP_LOAD = 1002;
144
145 // Message Ids
146 private static final int FOCUS_NODE_HREF = 102;
147 private static final int RELEASE_WAKELOCK = 107;
148
149 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
150
151 private static final int OPEN_BOOKMARKS = 201;
kaiyiz591110b2013-08-06 17:11:06 +0800152 private static final int OPEN_MENU = 202;
Michael Kolb8233fac2010-10-26 16:08:53 -0700153
154 private static final int EMPTY_MENU = -1;
155
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700157 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700158 final static int PREFERENCES_PAGE = 3;
159 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000160 final static int AUTOFILL_SETUP = 5;
Michael Kolb0b129122012-06-04 16:31:58 -0700161 final static int VOICE_RESULT = 6;
kaiyiz6e5b3e02013-08-19 20:02:01 +0800162 final static int MY_NAVIGATION = 7;
Ben Murdoch8029a772010-11-16 11:58:21 +0000163
Michael Kolb8233fac2010-10-26 16:08:53 -0700164 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
165
166 // As the ids are dynamically created, we can't guarantee that they will
167 // be in sequence, so this static array maps ids to a window number.
168 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
169 { R.id.window_one_menu_id, R.id.window_two_menu_id,
170 R.id.window_three_menu_id, R.id.window_four_menu_id,
171 R.id.window_five_menu_id, R.id.window_six_menu_id,
172 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
173
174 // "source" parameter for Google search through search key
175 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
176 // "source" parameter for Google search through simplily type
177 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
178
George Mount387d45d2011-10-07 15:57:53 -0700179 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700180 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
181
John Reckd7dd9b22011-08-30 09:18:29 -0700182 // A bitmap that is re-used in createScreenshot as scratch space
183 private static Bitmap sThumbnailBitmap;
184
Michael Kolb8233fac2010-10-26 16:08:53 -0700185 private Activity mActivity;
186 private UI mUi;
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700187 private HomepageHandler mHomepageHandler;
188 protected TabControl mTabControl;
Michael Kolb8233fac2010-10-26 16:08:53 -0700189 private BrowserSettings mSettings;
190 private WebViewFactory mFactory;
191
192 private WakeLock mWakeLock;
193
194 private UrlHandler mUrlHandler;
195 private UploadHandler mUploadHandler;
196 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700197 private PageDialogsHandler mPageDialogsHandler;
198 private NetworkStateHandler mNetworkHandler;
199
Ben Murdoch8029a772010-11-16 11:58:21 +0000200 private Message mAutoFillSetupMessage;
201
Michael Kolb8233fac2010-10-26 16:08:53 -0700202 private boolean mShouldShowErrorConsole;
kaiyiza016da12013-08-26 17:50:22 +0800203 private boolean mNetworkShouldNotify = true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700204
Michael Kolb8233fac2010-10-26 16:08:53 -0700205 // FIXME, temp address onPrepareMenu performance problem.
206 // When we move everything out of view, we should rewrite this.
207 private int mCurrentMenuState = 0;
Kulanthaivel Palanichamy77942682014-10-28 11:52:06 -0700208 private int mMenuState = EMPTY_MENU;
Michael Kolb8233fac2010-10-26 16:08:53 -0700209 private int mOldMenuState = EMPTY_MENU;
210 private Menu mCachedMenu;
211
Michael Kolb8233fac2010-10-26 16:08:53 -0700212 private boolean mMenuIsDown;
213
Pankaj Garg49b79252014-11-07 17:33:41 -0800214 private boolean mWasInPageLoad = false;
215 private AppMenuHandler mAppMenuHandler;
216
Michael Kolb8233fac2010-10-26 16:08:53 -0700217 // For select and find, we keep track of the ActionMode so that
218 // finish() can be called as desired.
219 private ActionMode mActionMode;
220
221 /**
222 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
223 * of whether the configuration has changed. The first onMenuOpened call
224 * after a configuration change is simply a reopening of the same menu
225 * (i.e. mIconView did not change).
226 */
227 private boolean mConfigChanged;
228
229 /**
230 * Keeps track of whether the options menu is open. This is important in
231 * determining whether to show or hide the title bar overlay
232 */
233 private boolean mOptionsMenuOpen;
234
235 /**
236 * Whether or not the options menu is in its bigger, popup menu form. When
237 * true, we want the title bar overlay to be gone. When false, we do not.
238 * Only meaningful if mOptionsMenuOpen is true.
239 */
240 private boolean mExtendedMenuOpen;
241
Michael Kolb8233fac2010-10-26 16:08:53 -0700242 private boolean mActivityPaused = true;
243 private boolean mLoadStopped;
244
245 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500246 // Checks to see when the bookmarks database has changed, and updates the
247 // Tabs' notion of whether they represent bookmarked sites.
248 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700249 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700250
Michael Kolbc3af0672011-08-09 10:24:41 -0700251 private boolean mBlockEvents;
252
Michael Kolb0b129122012-06-04 16:31:58 -0700253 private String mVoiceResult;
kaiyiz6e5b3e02013-08-19 20:02:01 +0800254 private boolean mUpdateMyNavThumbnail;
255 private String mUpdateMyNavThumbnailUrl;
Michael Kolb0b129122012-06-04 16:31:58 -0700256
George Mount3636d0a2011-11-21 09:08:21 -0800257 public Controller(Activity browser) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700258 mActivity = browser;
259 mSettings = BrowserSettings.getInstance();
260 mTabControl = new TabControl(this);
261 mSettings.setController(this);
John Reck378a4102011-06-09 16:23:01 -0700262 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
George Mount3636d0a2011-11-21 09:08:21 -0800263 mCrashRecoveryHandler.preloadCrashState();
Michael Kolb14612442011-06-24 13:06:29 -0700264 mFactory = new BrowserWebViewFactory(browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700265
266 mUrlHandler = new UrlHandler(this);
267 mIntentHandler = new IntentHandler(mActivity, this);
Michael Kolb8233fac2010-10-26 16:08:53 -0700268 mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
269
Michael Kolb8233fac2010-10-26 16:08:53 -0700270 startHandler();
Leon Scroggins1961ed22010-12-07 15:22:21 -0500271 mBookmarksObserver = new ContentObserver(mHandler) {
272 @Override
273 public void onChange(boolean selfChange) {
274 int size = mTabControl.getTabCount();
275 for (int i = 0; i < size; i++) {
276 mTabControl.getTab(i).updateBookmarkedStatus();
277 }
278 }
279
280 };
281 browser.getContentResolver().registerContentObserver(
282 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700283
284 mNetworkHandler = new NetworkStateHandler(mActivity, this);
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700285 mHomepageHandler = new HomepageHandler(browser, this);
Pankaj Garg49b79252014-11-07 17:33:41 -0800286 mAppMenuHandler = new AppMenuHandler(browser, this, R.menu.browser);
Michael Kolb8233fac2010-10-26 16:08:53 -0700287 }
288
John Reck9c35b9c2012-05-30 10:08:50 -0700289 @Override
290 public void start(final Intent intent) {
Kulanthaivel Palanichamy77942682014-10-28 11:52:06 -0700291 mMenuState = R.id.MAIN_MENU;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800292 WebView.setShouldMonitorWebCoreThread();
George Mount3636d0a2011-11-21 09:08:21 -0800293 // mCrashRecoverHandler has any previously saved state.
294 mCrashRecoveryHandler.startRecovery(intent);
John Reck847b5322011-04-14 17:02:18 -0700295 }
296
George Mount3636d0a2011-11-21 09:08:21 -0800297 void doStart(final Bundle icicle, final Intent intent) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800298 // we dont want to ever recover incognito tabs
299 final boolean restoreIncognitoTabs = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700300
Patrick Scott7d50a932011-02-04 09:27:26 -0500301 // Find out if we will restore any state and remember the tab.
Michael Kolbc831b632011-05-11 09:30:34 -0700302 final long currentTabId =
Patrick Scott7d50a932011-02-04 09:27:26 -0500303 mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
Kristian Monsen2cd97012010-12-07 11:11:40 +0000304
Michael Kolbc831b632011-05-11 09:30:34 -0700305 if (currentTabId == -1) {
Patrick Scott7d50a932011-02-04 09:27:26 -0500306 // Not able to restore so we go ahead and clear session cookies. We
307 // must do this before trying to login the user as we don't want to
308 // clear any session cookies set during login.
309 CookieManager.getInstance().removeSessionCookie();
John Reck1cf4b792011-07-26 10:22:22 -0700310 BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
George Mount3636d0a2011-11-21 09:08:21 -0800311 if (intent == null) {
312 // This won't happen under common scenarios. The icicle is
313 // not null, but there aren't any tabs to restore.
314 openTabToHomePage();
Michael Kolb7bcafde2011-05-09 13:55:59 -0700315 } else {
George Mount3636d0a2011-11-21 09:08:21 -0800316 final Bundle extra = intent.getExtras();
317 // Create an initial tab.
318 // If the intent is ACTION_VIEW and data is not null, the Browser is
319 // invoked to view the content by another application. In this case,
320 // the tab will be close when exit.
kaiyiz6e5b3e02013-08-19 20:02:01 +0800321 UrlData urlData = null;
322 if (intent.getData() != null
323 && Intent.ACTION_VIEW.equals(intent.getAction())
324 && intent.getData().toString().startsWith("content://")) {
325 urlData = new UrlData(intent.getData().toString());
326 } else {
327 urlData = IntentHandler.getUrlDataFromIntent(intent);
328 }
George Mount3636d0a2011-11-21 09:08:21 -0800329 Tab t = null;
330 if (urlData.isEmpty()) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700331 String landingPage = mActivity.getResources().getString(
332 R.string.def_landing_page);
333 if (!landingPage.isEmpty()) {
334 t = openTab(landingPage, false, true, true);
kaiyiz6e5b3e02013-08-19 20:02:01 +0800335 } else {
336 t = openTabToHomePage();
337 }
George Mount3636d0a2011-11-21 09:08:21 -0800338 } else {
339 t = openTab(urlData);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700340 t.setDerivedFromIntent(true);
George Mount3636d0a2011-11-21 09:08:21 -0800341 }
342 if (t != null) {
343 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
344 }
345 WebView webView = t.getWebView();
346 if (extra != null) {
347 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
348 if (scale > 0 && scale <= 1000) {
349 webView.setInitialScale(scale);
350 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700351 }
352 }
John Reckd8c74522011-06-14 08:45:00 -0700353 mUi.updateTabs(mTabControl.getTabs());
Michael Kolb8233fac2010-10-26 16:08:53 -0700354 } else {
Michael Kolbc831b632011-05-11 09:30:34 -0700355 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
Patrick Scott7d50a932011-02-04 09:27:26 -0500356 mUi.needsRestoreAllTabs());
John Reck1cf4b792011-07-26 10:22:22 -0700357 List<Tab> tabs = mTabControl.getTabs();
358 ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700359
John Reck1cf4b792011-07-26 10:22:22 -0700360 for (Tab t : tabs) {
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700361 //handle restored pages that may require a JS interface
362 if (t.getWebView() != null) {
363 WebBackForwardList backForwardList = t.getWebView().copyBackForwardList();
364 if (backForwardList != null) {
365 for (int i = 0; i < backForwardList.getSize(); i++) {
366 WebHistoryItem item = backForwardList.getItemAtIndex(i);
367 mHomepageHandler.registerJsInterface( t.getWebView(), item.getUrl());
368 }
369 }
370 }
John Reck1cf4b792011-07-26 10:22:22 -0700371 restoredTabs.add(t.getId());
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700372 if (t != mTabControl.getCurrentTab()) {
373 t.pause();
374 }
John Reck1cf4b792011-07-26 10:22:22 -0700375 }
376 BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
John Reck52be4782011-08-26 15:37:29 -0700377 if (tabs.size() == 0) {
378 openTabToHomePage();
379 }
John Reck1cf4b792011-07-26 10:22:22 -0700380 mUi.updateTabs(tabs);
Michael Kolb8233fac2010-10-26 16:08:53 -0700381 // TabControl.restoreState() will create a new tab even if
382 // restoring the state fails.
383 setActiveTab(mTabControl.getCurrentTab());
George Mount3636d0a2011-11-21 09:08:21 -0800384 // Intent is non-null when framework thinks the browser should be
385 // launching with a new intent (icicle is null).
386 if (intent != null) {
John Reck9dd4a412011-10-05 14:55:30 -0700387 mIntentHandler.onNewIntent(intent);
388 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700389 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700390 // Read JavaScript flags if it exists.
John Reck35e9dd62011-04-25 09:01:54 -0700391 String jsFlags = getSettings().getJsEngineFlags();
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800392 if (jsFlags.trim().length() != 0) {
393 getCurrentWebView().setJsFlags(jsFlags);
Michael Kolb8233fac2010-10-26 16:08:53 -0700394 }
George Mount3636d0a2011-11-21 09:08:21 -0800395 if (intent != null
396 && BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
Michael Kolb315d5022011-10-13 12:47:11 -0700397 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
John Reck439c9a52010-12-14 10:04:39 -0800398 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700399 }
400
John Reck1cf4b792011-07-26 10:22:22 -0700401 private static class PruneThumbnails implements Runnable {
402 private Context mContext;
403 private List<Long> mIds;
404
405 PruneThumbnails(Context context, List<Long> preserveIds) {
406 mContext = context.getApplicationContext();
407 mIds = preserveIds;
408 }
409
410 @Override
411 public void run() {
412 ContentResolver cr = mContext.getContentResolver();
413 if (mIds == null || mIds.size() == 0) {
414 cr.delete(Thumbnails.CONTENT_URI, null, null);
415 } else {
416 int length = mIds.size();
417 StringBuilder where = new StringBuilder();
418 where.append(Thumbnails._ID);
419 where.append(" not in (");
420 for (int i = 0; i < length; i++) {
421 where.append(mIds.get(i));
422 if (i < (length - 1)) {
423 where.append(",");
424 }
425 }
426 where.append(")");
427 cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
428 }
429 }
430
431 }
432
Michael Kolb1514bb72010-11-22 09:11:48 -0800433 @Override
434 public WebViewFactory getWebViewFactory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700435 return mFactory;
436 }
437
438 @Override
Michael Kolba713ec82010-11-29 17:27:06 -0800439 public void onSetWebView(Tab tab, WebView view) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800440 if (tab.hasCrashed)
441 tab.showCrashView();
442 else
443 mUi.onSetWebView(tab, view);
Michael Kolba713ec82010-11-29 17:27:06 -0800444 }
445
446 @Override
Michael Kolb1514bb72010-11-22 09:11:48 -0800447 public void createSubWindow(Tab tab) {
448 endActionMode();
449 WebView mainView = tab.getWebView();
450 WebView subView = mFactory.createWebView((mainView == null)
451 ? false
452 : mainView.isPrivateBrowsingEnabled());
453 mUi.createSubWindow(tab, subView);
454 }
455
456 @Override
Michael Kolb14612442011-06-24 13:06:29 -0700457 public Context getContext() {
458 return mActivity;
459 }
460
461 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -0700462 public Activity getActivity() {
463 return mActivity;
464 }
465
466 void setUi(UI ui) {
467 mUi = ui;
468 }
469
Michael Kolbaf63dba2012-05-16 12:58:05 -0700470 @Override
471 public BrowserSettings getSettings() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700472 return mSettings;
473 }
474
475 IntentHandler getIntentHandler() {
476 return mIntentHandler;
477 }
478
479 @Override
480 public UI getUi() {
481 return mUi;
482 }
483
484 int getMaxTabs() {
485 return mActivity.getResources().getInteger(R.integer.max_tabs);
486 }
487
488 @Override
489 public TabControl getTabControl() {
490 return mTabControl;
491 }
492
Michael Kolb1bf23132010-11-19 12:55:12 -0800493 @Override
494 public List<Tab> getTabs() {
495 return mTabControl.getTabs();
496 }
497
Michael Kolb8233fac2010-10-26 16:08:53 -0700498 private void startHandler() {
499 mHandler = new Handler() {
500
501 @Override
502 public void handleMessage(Message msg) {
503 switch (msg.what) {
504 case OPEN_BOOKMARKS:
Michael Kolb315d5022011-10-13 12:47:11 -0700505 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
Michael Kolb8233fac2010-10-26 16:08:53 -0700506 break;
507 case FOCUS_NODE_HREF:
508 {
509 String url = (String) msg.getData().get("url");
510 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500511 String src = (String) msg.getData().get("src");
512 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700513 if (TextUtils.isEmpty(url)) {
514 break;
515 }
516 HashMap focusNodeMap = (HashMap) msg.obj;
517 WebView view = (WebView) focusNodeMap.get("webview");
518 // Only apply the action if the top window did not change.
519 if (getCurrentTopWebView() != view) {
520 break;
521 }
522 switch (msg.arg1) {
523 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700524 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700525 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500526 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700527 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500528 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500529 case R.id.open_newtab_context_menu_id:
530 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700531 openTab(url, parent,
532 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500533 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700534 case R.id.copy_link_context_menu_id:
535 copy(url);
536 break;
537 case R.id.save_link_context_menu_id:
538 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500539 DownloadHandler.onDownloadStartNoStream(
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800540 mActivity, url, view.getSettings().getUserAgentString(),
541 null, null, null, view.isPrivateBrowsingEnabled(), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -0700542 break;
Tarun Nainani700b69b2014-03-26 16:07:25 -0700543 case R.id.save_link_bookmark_context_menu_id:
Tarun Nainani9f27c612014-04-02 14:34:03 -0700544 if(title == null || title == "")
545 title = url;
546
547 Intent bookmarkIntent = new Intent(mActivity, AddBookmarkPage.class);
548 //SWE TODO: No thumbnail support for the url obtained via
549 //browser context menu as its not loaded in webview.
550 if (bookmarkIntent != null) {
551 bookmarkIntent.putExtra(BrowserContract.Bookmarks.URL, url);
552 bookmarkIntent.putExtra(BrowserContract.Bookmarks.TITLE, title);
553 mActivity.startActivity(bookmarkIntent);
554 }
Tarun Nainani700b69b2014-03-26 16:07:25 -0700555 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700556 }
557 break;
558 }
559
560 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700561 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700562 break;
563
564 case STOP_LOAD:
565 stopLoading();
566 break;
567
568 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700569 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700570 mWakeLock.release();
571 // if we reach here, Browser should be still in the
572 // background loading after WAKELOCK_TIMEOUT (5-min).
573 // To avoid burning the battery, stop loading.
574 mTabControl.stopAllLoading();
575 }
576 break;
577
578 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800579 Tab tab = (Tab) msg.obj;
580 if (tab != null) {
581 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700582 }
583 break;
kaiyiz591110b2013-08-06 17:11:06 +0800584 case OPEN_MENU:
585 if (!mOptionsMenuOpen && mActivity != null ) {
586 mActivity.openOptionsMenu();
587 }
588 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700589 }
590 }
591 };
592
593 }
594
John Reckef654f12011-07-12 16:42:08 -0700595 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200596 public Tab getCurrentTab() {
597 return mTabControl.getCurrentTab();
598 }
599
Michael Kolbba99c5d2010-11-29 14:57:41 -0800600 @Override
601 public void shareCurrentPage() {
602 shareCurrentPage(mTabControl.getCurrentTab());
603 }
604
605 private void shareCurrentPage(Tab tab) {
Tarun Nainaniea28dde2014-08-27 17:25:09 -0700606 if (tab == null || tab.getWebView() == null)
607 return;
608
609 final Tab mytab = tab;
610 final ValueCallback<Bitmap> onScreenshot = new ValueCallback<Bitmap>() {
611 @Override
612 public void onReceiveValue(Bitmap bitmap) {
613 sharePage(mActivity, mytab.getTitle(), mytab.getUrl(),
614 mytab.getFavicon(), bitmap);
615 }
616 };
617
618 createScreenshotAsync(
619 tab.getWebView(),
620 getDesiredThumbnailWidth(mActivity),
621 getDesiredThumbnailHeight(mActivity),
622 new ValueCallback<Bitmap>() {
623 @Override
624 public void onReceiveValue(Bitmap bitmap) {
625 sharePage(mActivity, mytab.getTitle(), mytab.getUrl(),
626 mytab.getFavicon(), bitmap);
627 }
628 });
Michael Kolbba99c5d2010-11-29 14:57:41 -0800629 }
630
Michael Kolb8233fac2010-10-26 16:08:53 -0700631 /**
632 * Share a page, providing the title, url, favicon, and a screenshot. Uses
633 * an {@link Intent} to launch the Activity chooser.
634 * @param c Context used to launch a new Activity.
635 * @param title Title of the page. Stored in the Intent with
636 * {@link Intent#EXTRA_SUBJECT}
637 * @param url URL of the page. Stored in the Intent with
638 * {@link Intent#EXTRA_TEXT}
639 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
640 * with {@link Browser#EXTRA_SHARE_FAVICON}
641 * @param screenshot Bitmap of a screenshot of the page. Stored in the
642 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
643 */
644 static final void sharePage(Context c, String title, String url,
645 Bitmap favicon, Bitmap screenshot) {
Axesh R. Ajmera34d3f142014-06-30 20:05:36 -0700646
647 ShareDialog sDialog = new ShareDialog((Activity)c, title, url, favicon, screenshot);
648 final AppAdapter adapter = new AppAdapter(c, c.getPackageManager(),
649 R.layout.app_row, sDialog.getApps());
650 sDialog.loadView(adapter);
Michael Kolb8233fac2010-10-26 16:08:53 -0700651 }
652
653 private void copy(CharSequence text) {
654 ClipboardManager cm = (ClipboardManager) mActivity
655 .getSystemService(Context.CLIPBOARD_SERVICE);
656 cm.setText(text);
657 }
658
659 // lifecycle
660
John Reck9c35b9c2012-05-30 10:08:50 -0700661 @Override
662 public void onConfgurationChanged(Configuration config) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700663 mConfigChanged = true;
Michael Kolb18f252f2012-03-06 13:36:20 -0800664 // update the menu in case of a locale change
665 mActivity.invalidateOptionsMenu();
Pankaj Garg49b79252014-11-07 17:33:41 -0800666 mAppMenuHandler.hideAppMenu();
kaiyiz591110b2013-08-06 17:11:06 +0800667 if (mOptionsMenuOpen) {
668 mActivity.closeOptionsMenu();
669 mHandler.sendMessageDelayed(mHandler.obtainMessage(OPEN_MENU), 100);
670 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700671 if (mPageDialogsHandler != null) {
672 mPageDialogsHandler.onConfigurationChanged(config);
673 }
674 mUi.onConfigurationChanged(config);
675 }
676
677 @Override
678 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700679 if (!mUi.isWebShowing()) {
680 mUi.showWeb(false);
681 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700682 mIntentHandler.onNewIntent(intent);
683 }
684
John Reck9c35b9c2012-05-30 10:08:50 -0700685 @Override
686 public void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800687 if (mUi.isCustomViewShowing()) {
688 hideCustomView();
689 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700690 if (mActivityPaused) {
691 Log.e(LOGTAG, "BrowserActivity is already paused.");
692 return;
693 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700694 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800695 Tab tab = mTabControl.getCurrentTab();
696 if (tab != null) {
697 tab.pause();
698 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700699 if (mWakeLock == null) {
700 PowerManager pm = (PowerManager) mActivity
701 .getSystemService(Context.POWER_SERVICE);
702 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
703 }
Michael Kolb70976932010-11-30 11:34:01 -0800704 mWakeLock.acquire();
705 mHandler.sendMessageDelayed(mHandler
706 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
707 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700708 }
709 mUi.onPause();
710 mNetworkHandler.onPause();
711
712 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100713 NfcHandler.unregister(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700714 }
715
John Reck9c35b9c2012-05-30 10:08:50 -0700716 @Override
717 public void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700718 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800719 Bundle saveState = createSaveState();
720
721 // crash recovery manages all save & restore state
722 mCrashRecoveryHandler.writeState(saveState);
723 mSettings.setLastRunPaused(true);
724 }
725
726 /**
727 * Save the current state to outState. Does not write the state to
728 * disk.
729 * @return Bundle containing the current state of all tabs.
730 */
731 /* package */ Bundle createSaveState() {
732 Bundle saveState = new Bundle();
733 mTabControl.saveState(saveState);
George Mount3636d0a2011-11-21 09:08:21 -0800734 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700735 }
736
John Reck9c35b9c2012-05-30 10:08:50 -0700737 @Override
738 public void onResume() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700739 if (!mActivityPaused) {
740 Log.e(LOGTAG, "BrowserActivity is already resumed.");
741 return;
742 }
George Mount3636d0a2011-11-21 09:08:21 -0800743 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700744 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800745 Tab current = mTabControl.getCurrentTab();
746 if (current != null) {
747 current.resume();
748 resumeWebViewTimers(current);
749 }
John Reckf57c0292011-07-21 18:15:39 -0700750 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200751
Michael Kolb8233fac2010-10-26 16:08:53 -0700752 mUi.onResume();
753 mNetworkHandler.onResume();
754 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100755 NfcHandler.register(mActivity, this);
Michael Kolb0b129122012-06-04 16:31:58 -0700756 if (mVoiceResult != null) {
757 mUi.onVoiceResult(mVoiceResult);
758 mVoiceResult = null;
759 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800760 if (current != null && current.hasCrashed) {
Vivek Sekhar2868b8d2014-12-03 17:22:50 -0800761 current.replaceCrashView(current.getWebView(), current.getViewContainer());
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800762 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700763 }
764
John Reckf57c0292011-07-21 18:15:39 -0700765 private void releaseWakeLock() {
766 if (mWakeLock != null && mWakeLock.isHeld()) {
767 mHandler.removeMessages(RELEASE_WAKELOCK);
768 mWakeLock.release();
769 }
770 }
771
Michael Kolb70976932010-11-30 11:34:01 -0800772 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800773 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800774 * @param tab guaranteed non-null
775 */
776 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700777 boolean inLoad = tab.inPageLoad();
778 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
779 CookieSyncManager.getInstance().startSync();
780 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100781 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700782 }
783 }
784
Michael Kolb70976932010-11-30 11:34:01 -0800785 /**
786 * Pause all WebView timers using the WebView of the given tab
787 * @param tab
788 * @return true if the timers are paused or tab is null
789 */
790 private boolean pauseWebViewTimers(Tab tab) {
791 if (tab == null) {
792 return true;
793 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700794 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100795 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700796 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700797 }
Michael Kolb70976932010-11-30 11:34:01 -0800798 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700799 }
800
John Reck9c35b9c2012-05-30 10:08:50 -0700801 @Override
802 public void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800803 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700804 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
805 mUploadHandler = null;
806 }
807 if (mTabControl == null) return;
808 mUi.onDestroy();
809 // Remove the current tab and sub window
810 Tab t = mTabControl.getCurrentTab();
811 if (t != null) {
812 dismissSubWindow(t);
813 removeTab(t);
814 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500815 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700816 // Destroy all the tabs
817 mTabControl.destroy();
Michael Kolb8233fac2010-10-26 16:08:53 -0700818 }
819
820 protected boolean isActivityPaused() {
821 return mActivityPaused;
822 }
823
John Reck9c35b9c2012-05-30 10:08:50 -0700824 @Override
825 public void onLowMemory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700826 mTabControl.freeMemory();
827 }
828
829 @Override
830 public boolean shouldShowErrorConsole() {
831 return mShouldShowErrorConsole;
832 }
833
834 protected void setShouldShowErrorConsole(boolean show) {
835 if (show == mShouldShowErrorConsole) {
836 // Nothing to do.
837 return;
838 }
839 mShouldShowErrorConsole = show;
840 Tab t = mTabControl.getCurrentTab();
841 if (t == null) {
842 // There is no current tab so we cannot toggle the error console
843 return;
844 }
845 mUi.setShouldShowErrorConsole(t, show);
846 }
847
848 @Override
849 public void stopLoading() {
850 mLoadStopped = true;
851 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700852 WebView w = getCurrentTopWebView();
Michael Kolb778a4882012-04-12 15:27:28 -0700853 if (w != null) {
854 w.stopLoading();
855 mUi.onPageStopped(tab);
856 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700857 }
858
859 boolean didUserStopLoading() {
860 return mLoadStopped;
861 }
862
kaiyiza016da12013-08-26 17:50:22 +0800863 private void handleNetworkNotify(WebView view) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700864 final String reminderType = getContext().getResources().getString(
865 R.string.def_wifi_browser_interaction_remind_type);
866 final String selectionConnnection = getContext().getResources().getString(
867 R.string.def_action_wifi_selection_data_connections);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700868 final String wifiSelection = getContext().getResources().getString(
869 R.string.def_intent_pick_network);
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700870
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700871 if (reminderType.isEmpty() || selectionConnnection.isEmpty() ||
872 wifiSelection.isEmpty())
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700873 return;
874
kaiyiza016da12013-08-26 17:50:22 +0800875 ConnectivityManager conMgr = (ConnectivityManager) this.getContext().getSystemService(
Vivek Sekharb54614f2014-05-01 19:03:37 -0700876 Context.CONNECTIVITY_SERVICE);
877 NetworkInfo networkInfo = conMgr.getActiveNetworkInfo();
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700878 WifiManager wifiMgr = (WifiManager) this.getContext()
879 .getSystemService(Context.WIFI_SERVICE);
Vivek Sekharb54614f2014-05-01 19:03:37 -0700880 if (networkInfo == null
881 || (networkInfo != null && (networkInfo.getType() !=
882 ConnectivityManager.TYPE_WIFI))) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700883 int isReminder = Settings.System.getInt(mActivity.getContentResolver(),
884 reminderType, NETWORK_SWITCH_TYPE_OK);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700885 List<ScanResult> list = wifiMgr.getScanResults();
886 // Have no AP's for Wifi's fall back to data
887 if (list != null && list.size() == 0 && isReminder == NETWORK_SWITCH_TYPE_OK) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700888 Intent intent = new Intent(selectionConnnection);
Vivek Sekharb54614f2014-05-01 19:03:37 -0700889 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
890 this.getContext().startActivity(intent);
891 } else {
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700892 // Request to select Wifi AP
893 try {
894 Intent intent = new Intent(wifiSelection);
895 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
896 this.getContext().startActivity(intent);
897 } catch (Exception e) {
898 String err_msg = this.getContext().getString(
899 R.string.acivity_not_found, wifiSelection);
900 Toast.makeText(this.getContext(), err_msg, Toast.LENGTH_LONG).show();
901 }
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700902 }
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700903 mNetworkShouldNotify = false;
kaiyiza016da12013-08-26 17:50:22 +0800904 }
905 }
Vivek Sekharb54614f2014-05-01 19:03:37 -0700906
Michael Kolb8233fac2010-10-26 16:08:53 -0700907 // WebViewController
908
909 @Override
John Reck324d4402011-01-11 16:56:42 -0800910 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700911
912 // We've started to load a new page. If there was a pending message
913 // to save a screenshot then we will now take the new page and save
914 // an incorrect screenshot. Therefore, remove any pending thumbnail
915 // messages from the queue.
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700916 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700917
918 // reset sync timer to avoid sync starts during loading a page
919 CookieSyncManager.getInstance().resetSync();
Vivek Sekharb54614f2014-05-01 19:03:37 -0700920 WifiManager wifiMgr = (WifiManager) this.getContext()
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700921 .getSystemService(Context.WIFI_SERVICE);
Panos Thomas4bdb5252014-11-13 16:20:11 -0800922 boolean networkNotifier = BrowserConfig.getInstance(getContext())
923 .hasFeature(BrowserConfig.Feature.NETWORK_NOTIFIER);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700924 if (networkNotifier && mNetworkShouldNotify && wifiMgr.isWifiEnabled()){
Vivek Sekharb54614f2014-05-01 19:03:37 -0700925 handleNetworkNotify(view);
kaiyiza016da12013-08-26 17:50:22 +0800926 } else {
927 if (!mNetworkHandler.isNetworkUp()) {
928 view.setNetworkAvailable(false);
929 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700930 }
931
932 // when BrowserActivity just starts, onPageStarted may be called before
933 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
934 // to start the timer. As we won't switch tabs while an activity is in
935 // pause state, we can ensure calling resume and pause in pair.
936 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800937 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700938 }
939 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700940 endActionMode();
941
John Reck30c714c2010-12-16 17:30:34 -0800942 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700943
John Reck324d4402011-01-11 16:56:42 -0800944 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700945 // update the bookmark database for favicon
946 maybeUpdateFavicon(tab, null, url, favicon);
947
948 Performance.tracePageStart(url);
949
950 // Performance probe
951 if (false) {
952 Performance.onPageStarted();
953 }
954
955 }
956
957 @Override
John Reck324d4402011-01-11 16:56:42 -0800958 public void onPageFinished(Tab tab) {
Michael Kolb72864272012-05-03 15:42:15 -0700959 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800960 mUi.onTabDataChanged(tab);
Martijn Coenenb2f93552011-06-14 10:48:35 +0200961
Michael Kolb8233fac2010-10-26 16:08:53 -0700962 // Performance probe
963 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800964 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700965 }
966
Tarun Nainani8eb00912014-07-17 12:28:32 -0700967 tab.onPageFinished();
968
Michael Kolb8233fac2010-10-26 16:08:53 -0700969 Performance.tracePageFinished();
970 }
971
972 @Override
John Reck30c714c2010-12-16 17:30:34 -0800973 public void onProgressChanged(Tab tab) {
974 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -0700975
976 if (newProgress == 100) {
977 CookieSyncManager.getInstance().sync();
978 // onProgressChanged() may continue to be called after the main
979 // frame has finished loading, as any remaining sub frames continue
980 // to load. We'll only get called once though with newProgress as
981 // 100 when everything is loaded. (onPageFinished is called once
982 // when the main frame completes loading regardless of the state of
983 // any sub frames so calls to onProgressChanges may continue after
984 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800985 if (tab.inPageLoad()) {
Pankaj Garg49b79252014-11-07 17:33:41 -0800986 mWasInPageLoad = true;
Michael Kolbb1fb70c2011-11-21 12:38:14 -0800987 updateInLoadMenuItems(mCachedMenu, tab);
Pankaj Garg49b79252014-11-07 17:33:41 -0800988 } else if (mWasInPageLoad) {
989 mWasInPageLoad = false;
990 updateInLoadMenuItems(mCachedMenu, tab);
991 }
992
993 if (mActivityPaused && pauseWebViewTimers(tab)) {
Mattias Falk9cc2d032012-05-25 09:40:31 +0200994 // pause the WebView timer and release the wake lock if it is
995 // finished while BrowserActivity is in pause state.
996 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -0700997 }
John Reckd9862372012-02-21 15:04:50 -0800998 if (!tab.isPrivateBrowsingEnabled()
999 && !TextUtils.isEmpty(tab.getUrl())
1000 && !tab.isSnapshot()) {
1001 // Only update the bookmark screenshot if the user did not
1002 // cancel the load early and there is not already
1003 // a pending update for the tab.
Michael Kolb72864272012-05-03 15:42:15 -07001004 if (tab.shouldUpdateThumbnail() &&
1005 (tab.inForeground() && !didUserStopLoading()
1006 || !tab.inForeground())) {
John Reckd9862372012-02-21 15:04:50 -08001007 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
1008 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1009 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001010 1500);
John Reckd9862372012-02-21 15:04:50 -08001011 }
1012 }
1013 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001014 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001015 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001016 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001017 // still loading
1018 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -07001019 // update the menu items.
Pankaj Garg49b79252014-11-07 17:33:41 -08001020 mWasInPageLoad = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001021 updateInLoadMenuItems(mCachedMenu, tab);
Pankaj Garg49b79252014-11-07 17:33:41 -08001022 } else {
1023 mWasInPageLoad = true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001024 }
1025 }
John Reck30c714c2010-12-16 17:30:34 -08001026 mUi.onProgressChanged(tab);
1027 }
1028
1029 @Override
Steve Block2466eff2011-10-03 15:33:09 +01001030 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08001031 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001032 }
1033
1034 @Override
1035 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -08001036 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -08001037 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -08001038 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -07001039 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
1040 return;
1041 }
1042 // Update the title in the history database if not in private browsing mode
1043 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -07001044 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -07001045 }
1046 }
1047
1048 @Override
1049 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -08001050 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001051 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
1052 }
1053
1054 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -08001055 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
1056 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07001057 }
1058
1059 @Override
1060 public boolean shouldOverrideKeyEvent(KeyEvent event) {
1061 if (mMenuIsDown) {
1062 // only check shortcut key when MENU is held
1063 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
1064 event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001065 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001066 int keyCode = event.getKeyCode();
1067 // We need to send almost every key to WebKit. However:
1068 // 1. We don't want to block the device on the renderer for
1069 // some keys like menu, home, call.
1070 // 2. There are no WebKit equivalents for some of these keys
1071 // (see app/keyboard_codes_win.h)
1072 // Note that these are not the same set as KeyEvent.isSystemKey:
1073 // for instance, AKEYCODE_MEDIA_* will be dispatched to webkit.
1074 if (keyCode == KeyEvent.KEYCODE_MENU ||
1075 keyCode == KeyEvent.KEYCODE_HOME ||
1076 keyCode == KeyEvent.KEYCODE_BACK ||
1077 keyCode == KeyEvent.KEYCODE_CALL ||
1078 keyCode == KeyEvent.KEYCODE_ENDCALL ||
1079 keyCode == KeyEvent.KEYCODE_POWER ||
1080 keyCode == KeyEvent.KEYCODE_HEADSETHOOK ||
1081 keyCode == KeyEvent.KEYCODE_CAMERA ||
1082 keyCode == KeyEvent.KEYCODE_FOCUS ||
1083 keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
1084 keyCode == KeyEvent.KEYCODE_VOLUME_MUTE ||
1085 keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
1086 return true;
1087 }
1088
1089 // We also have to intercept some shortcuts before we send them to the ContentView.
1090 if (event.isCtrlPressed() && (
1091 keyCode == KeyEvent.KEYCODE_TAB ||
1092 keyCode == KeyEvent.KEYCODE_W ||
1093 keyCode == KeyEvent.KEYCODE_F4)) {
1094 return true;
1095 }
1096
1097 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07001098 }
1099
1100 @Override
John Reck997b1b72012-04-19 18:08:25 -07001101 public boolean onUnhandledKeyEvent(KeyEvent event) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001102 if (!isActivityPaused()) {
1103 if (event.getAction() == KeyEvent.ACTION_DOWN) {
John Reck997b1b72012-04-19 18:08:25 -07001104 return mActivity.onKeyDown(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001105 } else {
John Reck997b1b72012-04-19 18:08:25 -07001106 return mActivity.onKeyUp(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001107 }
1108 }
John Reck997b1b72012-04-19 18:08:25 -07001109 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07001110 }
1111
1112 @Override
John Reck324d4402011-01-11 16:56:42 -08001113 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Panos Thomas4bdb5252014-11-13 16:20:11 -08001114 // Don't save anything in private browsing mode or when disabling history
1115 // for regular tabs is enabled
1116 if (tab.isPrivateBrowsingEnabled() || BrowserConfig.getInstance(getContext())
1117 .hasFeature(BrowserConfig.Feature.DISABLE_HISTORY))
1118 return;
Bijan Amirzadae75909d2014-05-06 14:18:54 -07001119
John Reck49a603c2011-03-03 09:33:05 -08001120 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -07001121
John Reck324d4402011-01-11 16:56:42 -08001122 if (TextUtils.isEmpty(url)
1123 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001124 return;
1125 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001126
John Reckf57c0292011-07-21 18:15:39 -07001127 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -07001128 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07001129 }
1130
1131 @Override
1132 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1133 AsyncTask<Void, Void, String[]> task =
1134 new AsyncTask<Void, Void, String[]>() {
1135 @Override
1136 public String[] doInBackground(Void... unused) {
Bijan Amirzada3f04dc72014-06-25 11:48:36 -07001137 return (String[]) Browser.getVisitedHistory(mActivity.getContentResolver());
Michael Kolb8233fac2010-10-26 16:08:53 -07001138 }
1139 @Override
1140 public void onPostExecute(String[] result) {
1141 callback.onReceiveValue(result);
1142 }
1143 };
1144 task.execute();
1145 }
1146
1147 @Override
1148 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
1149 final HttpAuthHandler handler, final String host,
1150 final String realm) {
1151 String username = null;
1152 String password = null;
1153
1154 boolean reuseHttpAuthUsernamePassword
1155 = handler.useHttpAuthUsernamePassword();
1156
1157 if (reuseHttpAuthUsernamePassword && view != null) {
1158 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
1159 if (credentials != null && credentials.length == 2) {
1160 username = credentials[0];
1161 password = credentials[1];
1162 }
1163 }
1164
1165 if (username != null && password != null) {
1166 handler.proceed(username, password);
1167 } else {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001168 if (tab.inForeground() /*&& !handler.suppressDialog()*/) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001169 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1170 } else {
1171 handler.cancel();
1172 }
1173 }
1174 }
1175
1176 @Override
1177 public void onDownloadStart(Tab tab, String url, String userAgent,
Selim Gurun0b3d66f2012-08-29 13:08:13 -07001178 String contentDisposition, String mimetype, String referer,
1179 long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001180 WebView w = tab.getWebView();
Axesh R. Ajmera87c5aba2014-11-06 14:13:36 -08001181 if ( w == null) return;
qqzhoua95a2e22013-04-18 17:28:31 +08001182 boolean ret = DownloadHandler.onDownloadStart(mActivity, url, userAgent,
luxiaol62677b02013-07-22 07:54:49 +08001183 contentDisposition, mimetype, referer, w.isPrivateBrowsingEnabled(), contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +08001184 if (ret == false && w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001185 // This Tab was opened for the sole purpose of downloading a
1186 // file. Remove it.
1187 if (tab == mTabControl.getCurrentTab()) {
1188 // In this case, the Tab is still on top.
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07001189 if (tab.getDerivedFromIntent())
1190 closeTab(tab);
1191 else
1192 goBackOnePageOrQuit();
Michael Kolb8233fac2010-10-26 16:08:53 -07001193 } else {
1194 // In this case, it is not.
1195 closeTab(tab);
1196 }
1197 }
1198 }
1199
1200 @Override
1201 public Bitmap getDefaultVideoPoster() {
1202 return mUi.getDefaultVideoPoster();
1203 }
1204
1205 @Override
1206 public View getVideoLoadingProgressView() {
1207 return mUi.getVideoLoadingProgressView();
1208 }
1209
1210 @Override
1211 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1212 SslError error) {
1213 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1214 }
1215
1216 // helper method
1217
1218 /*
1219 * Update the favorites icon if the private browsing isn't enabled and the
1220 * icon is valid.
1221 */
1222 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1223 final String url, Bitmap favicon) {
1224 if (favicon == null) {
1225 return;
1226 }
1227 if (!tab.isPrivateBrowsingEnabled()) {
1228 Bookmarks.updateFavicon(mActivity
1229 .getContentResolver(), originalUrl, url, favicon);
1230 }
1231 }
1232
Leon Scroggins4cd97792010-12-03 15:31:56 -05001233 @Override
1234 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001235 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001236 mUi.bookmarkedStatusHasChanged(tab);
1237 }
1238
Michael Kolb8233fac2010-10-26 16:08:53 -07001239 // end WebViewController
1240
1241 protected void pageUp() {
1242 getCurrentTopWebView().pageUp(false);
1243 }
1244
1245 protected void pageDown() {
1246 getCurrentTopWebView().pageDown(false);
1247 }
1248
1249 // callback from phone title bar
John Reck9c35b9c2012-05-30 10:08:50 -07001250 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07001251 public void editUrl() {
1252 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolb1f9b3562012-04-24 14:38:34 -07001253 mUi.editUrl(false, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001254 }
1255
John Reck9c35b9c2012-05-30 10:08:50 -07001256 @Override
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001257 public void showCustomView(Tab tab, View view, int requestedOrientation,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001258 CustomViewCallback callback) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001259 if (tab.inForeground()) {
1260 if (mUi.isCustomViewShowing()) {
1261 callback.onCustomViewHidden();
1262 return;
1263 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001264 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001265 // Save the menu state and set it to empty while the custom
1266 // view is showing.
1267 mOldMenuState = mMenuState;
1268 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001269 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001270 }
1271 }
1272
1273 @Override
1274 public void hideCustomView() {
1275 if (mUi.isCustomViewShowing()) {
1276 mUi.onHideCustomView();
1277 // Reset the old menu state.
1278 mMenuState = mOldMenuState;
1279 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001280 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001281 }
1282 }
1283
John Reck9c35b9c2012-05-30 10:08:50 -07001284 @Override
1285 public void onActivityResult(int requestCode, int resultCode,
Michael Kolb8233fac2010-10-26 16:08:53 -07001286 Intent intent) {
1287 if (getCurrentTopWebView() == null) return;
1288 switch (requestCode) {
1289 case PREFERENCES_PAGE:
1290 if (resultCode == Activity.RESULT_OK && intent != null) {
1291 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001292 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001293 mTabControl.removeParentChildRelationShips();
1294 }
1295 }
1296 break;
1297 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001298 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001299 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001300 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001301 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001302 case AUTOFILL_SETUP:
1303 // Determine whether a profile was actually set up or not
1304 // and if so, send the message back to the WebTextView to
1305 // fill the form with the new profile.
1306 if (getSettings().getAutoFillProfile() != null) {
1307 mAutoFillSetupMessage.sendToTarget();
1308 mAutoFillSetupMessage = null;
1309 }
1310 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001311 case COMBO_VIEW:
1312 if (intent == null || resultCode != Activity.RESULT_OK) {
1313 break;
1314 }
John Reck3ba45532011-08-11 16:26:53 -07001315 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001316 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1317 Tab t = getCurrentTab();
1318 Uri uri = intent.getData();
kaiyiz6e5b3e02013-08-19 20:02:01 +08001319 mUpdateMyNavThumbnail = true;
1320 mUpdateMyNavThumbnailUrl = uri.toString();
John Reckd3e4d5b2011-07-13 15:48:43 -07001321 loadUrl(t, uri.toString());
1322 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1323 String[] urls = intent.getStringArrayExtra(
1324 ComboViewActivity.EXTRA_OPEN_ALL);
1325 Tab parent = getCurrentTab();
1326 for (String url : urls) {
kaiyiz47097d62013-08-09 09:30:28 +08001327 if (url != null) {
1328 parent = openTab(url, parent,
1329 !mSettings.openInBackground(), true);
1330 }
John Reckd3e4d5b2011-07-13 15:48:43 -07001331 }
1332 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1333 long id = intent.getLongExtra(
1334 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1335 if (id >= 0) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001336 createNewSnapshotTab(id, true);
John Reckd3e4d5b2011-07-13 15:48:43 -07001337 }
1338 }
1339 break;
Michael Kolb0b129122012-06-04 16:31:58 -07001340 case VOICE_RESULT:
1341 if (resultCode == Activity.RESULT_OK && intent != null) {
1342 ArrayList<String> results = intent.getStringArrayListExtra(
1343 RecognizerIntent.EXTRA_RESULTS);
1344 if (results.size() >= 1) {
1345 mVoiceResult = results.get(0);
1346 }
1347 }
1348 break;
kaiyiz6e5b3e02013-08-19 20:02:01 +08001349 case MY_NAVIGATION:
1350 if (intent == null || resultCode != Activity.RESULT_OK) {
1351 break;
1352 }
1353
1354 if (intent.getBooleanExtra("need_refresh", false) &&
1355 getCurrentTopWebView() != null) {
1356 getCurrentTopWebView().reload();
1357 }
1358 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001359 default:
1360 break;
1361 }
1362 getCurrentTopWebView().requestFocus();
1363 }
1364
1365 /**
1366 * Open the Go page.
1367 * @param startWithHistory If true, open starting on the history tab.
1368 * Otherwise, start with the bookmarks tab.
1369 */
1370 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001371 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001372 if (mTabControl.getCurrentWebView() == null) {
1373 return;
1374 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001375 // clear action mode
1376 if (isInCustomActionMode()) {
1377 endActionMode();
1378 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001379 Bundle extras = new Bundle();
1380 // Disable opening in a new window if we have maxed out the windows
1381 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1382 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001383 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001384 }
1385
1386 // combo view callbacks
1387
Michael Kolb8233fac2010-10-26 16:08:53 -07001388 // key handling
1389 protected void onBackKey() {
1390 if (!mUi.onBackKey()) {
1391 WebView subwindow = mTabControl.getCurrentSubWindow();
1392 if (subwindow != null) {
1393 if (subwindow.canGoBack()) {
1394 subwindow.goBack();
1395 } else {
1396 dismissSubWindow(mTabControl.getCurrentTab());
1397 }
1398 } else {
1399 goBackOnePageOrQuit();
1400 }
1401 }
1402 }
1403
Michael Kolb4bd767d2011-05-27 11:33:55 -07001404 protected boolean onMenuKey() {
1405 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001406 }
1407
Michael Kolb8233fac2010-10-26 16:08:53 -07001408 // menu handling and state
1409 // TODO: maybe put into separate handler
1410
John Reck9c35b9c2012-05-30 10:08:50 -07001411 @Override
1412 public boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001413 if (mMenuState == EMPTY_MENU) {
1414 return false;
1415 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001416 MenuInflater inflater = mActivity.getMenuInflater();
1417 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001418 return true;
1419 }
1420
John Reck9c35b9c2012-05-30 10:08:50 -07001421 @Override
1422 public void onCreateContextMenu(ContextMenu menu, View v,
Michael Kolb8233fac2010-10-26 16:08:53 -07001423 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001424 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001425 return;
1426 }
1427 if (!(v instanceof WebView)) {
1428 return;
1429 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001430 final WebView webview = (WebView) v;
Michael Kolb8233fac2010-10-26 16:08:53 -07001431 WebView.HitTestResult result = webview.getHitTestResult();
1432 if (result == null) {
1433 return;
1434 }
1435
1436 int type = result.getType();
1437 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1438 Log.w(LOGTAG,
1439 "We should not show context menu when nothing is touched");
1440 return;
1441 }
1442 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1443 // let TextView handles context menu
1444 return;
1445 }
1446
1447 // Note, http://b/issue?id=1106666 is requesting that
1448 // an inflated menu can be used again. This is not available
1449 // yet, so inflate each time (yuk!)
1450 MenuInflater inflater = mActivity.getMenuInflater();
1451 inflater.inflate(R.menu.browsercontext, menu);
1452
1453 // Show the correct menu group
1454 final String extra = result.getExtra();
kaiyiz6e5b3e02013-08-19 20:02:01 +08001455 final String navigationUrl = MyNavigationUtil.getMyNavigationUrl(extra);
Michael Kolbc159c1a2011-12-15 16:06:38 -08001456 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001457 menu.setGroupVisible(R.id.PHONE_MENU,
1458 type == WebView.HitTestResult.PHONE_TYPE);
1459 menu.setGroupVisible(R.id.EMAIL_MENU,
1460 type == WebView.HitTestResult.EMAIL_TYPE);
1461 menu.setGroupVisible(R.id.GEO_MENU,
1462 type == WebView.HitTestResult.GEO_TYPE);
kaiyiz6e5b3e02013-08-19 20:02:01 +08001463 String itemUrl = null;
1464 String url = webview.getOriginalUrl();
1465 if (url != null && url.equalsIgnoreCase(MyNavigationUtil.MY_NAVIGATION)) {
1466 itemUrl = Uri.decode(navigationUrl);
1467 if (itemUrl != null && !MyNavigationUtil.isDefaultMyNavigation(itemUrl)) {
1468 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU,
1469 type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1470 } else {
1471 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU, false);
1472 }
1473 menu.setGroupVisible(R.id.IMAGE_MENU, false);
1474 menu.setGroupVisible(R.id.ANCHOR_MENU, false);
1475 } else {
1476 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU, false);
1477
1478 menu.setGroupVisible(R.id.IMAGE_MENU,
1479 type == WebView.HitTestResult.IMAGE_TYPE
1480 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1481 menu.setGroupVisible(R.id.ANCHOR_MENU,
1482 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1483 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Vivek Sekharcc4bc5e2014-05-13 12:46:37 -07001484 menu.findItem(R.id.save_link_context_menu_id).setEnabled(
1485 UrlUtils.isDownloadableScheme(extra));
kaiyiz6e5b3e02013-08-19 20:02:01 +08001486 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001487 // Setup custom handling depending on the type
1488 switch (type) {
1489 case WebView.HitTestResult.PHONE_TYPE:
1490 menu.setHeaderTitle(Uri.decode(extra));
1491 menu.findItem(R.id.dial_context_menu_id).setIntent(
1492 new Intent(Intent.ACTION_VIEW, Uri
1493 .parse(WebView.SCHEME_TEL + extra)));
1494 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1495 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1496 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1497 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1498 addIntent);
1499 menu.findItem(R.id.copy_phone_context_menu_id)
1500 .setOnMenuItemClickListener(
1501 new Copy(extra));
1502 break;
1503
1504 case WebView.HitTestResult.EMAIL_TYPE:
1505 menu.setHeaderTitle(extra);
1506 menu.findItem(R.id.email_context_menu_id).setIntent(
1507 new Intent(Intent.ACTION_VIEW, Uri
1508 .parse(WebView.SCHEME_MAILTO + extra)));
1509 menu.findItem(R.id.copy_mail_context_menu_id)
1510 .setOnMenuItemClickListener(
1511 new Copy(extra));
1512 break;
1513
1514 case WebView.HitTestResult.GEO_TYPE:
1515 menu.setHeaderTitle(extra);
1516 menu.findItem(R.id.map_context_menu_id).setIntent(
1517 new Intent(Intent.ACTION_VIEW, Uri
1518 .parse(WebView.SCHEME_GEO
1519 + URLEncoder.encode(extra))));
1520 menu.findItem(R.id.copy_geo_context_menu_id)
1521 .setOnMenuItemClickListener(
1522 new Copy(extra));
1523 break;
1524
1525 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1526 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001527 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001528 // decide whether to show the open link in new tab option
1529 boolean showNewTab = mTabControl.canCreateNewTab();
1530 MenuItem newTabItem
1531 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001532 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001533 ? R.string.contextmenu_openlink_newwindow_background
1534 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001535 newTabItem.setVisible(showNewTab);
1536 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001537 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1538 newTabItem.setOnMenuItemClickListener(
1539 new MenuItem.OnMenuItemClickListener() {
1540 @Override
1541 public boolean onMenuItemClick(MenuItem item) {
1542 final HashMap<String, WebView> hrefMap =
1543 new HashMap<String, WebView>();
1544 hrefMap.put("webview", webview);
1545 final Message msg = mHandler.obtainMessage(
1546 FOCUS_NODE_HREF,
1547 R.id.open_newtab_context_menu_id,
1548 0, hrefMap);
1549 webview.requestFocusNodeHref(msg);
1550 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001551 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001552 });
1553 } else {
1554 newTabItem.setOnMenuItemClickListener(
1555 new MenuItem.OnMenuItemClickListener() {
1556 @Override
1557 public boolean onMenuItemClick(MenuItem item) {
1558 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001559 openTab(extra, parent,
1560 !mSettings.openInBackground(),
1561 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001562 return true;
1563 }
1564 });
1565 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001566 }
kaiyiz6e5b3e02013-08-19 20:02:01 +08001567 if (url != null && url.equalsIgnoreCase(MyNavigationUtil.MY_NAVIGATION)) {
1568 menu.setHeaderTitle(navigationUrl);
1569 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(false);
1570
1571 if (itemUrl != null) {
1572 if (!MyNavigationUtil.isDefaultMyNavigation(itemUrl)) {
1573 menu.findItem(R.id.edit_my_navigation_context_menu_id)
1574 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1575 @Override
1576 public boolean onMenuItemClick(MenuItem item) {
1577 final Intent intent = new Intent(Controller.this
1578 .getContext(),
1579 AddMyNavigationPage.class);
1580 Bundle bundle = new Bundle();
1581 String url = Uri.decode(navigationUrl);
1582 bundle.putBoolean("isAdding", false);
1583 bundle.putString("url", url);
1584 bundle.putString("name", getNameFromUrl(url));
1585 intent.putExtra("websites", bundle);
1586 mActivity.startActivityForResult(intent, MY_NAVIGATION);
1587 return false;
1588 }
1589 });
1590 menu.findItem(R.id.delete_my_navigation_context_menu_id)
1591 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1592 @Override
1593 public boolean onMenuItemClick(MenuItem item) {
1594 showMyNavigationDeleteDialog(Uri.decode(navigationUrl));
1595 return false;
1596 }
1597 });
1598 }
1599 } else {
1600 Log.e(LOGTAG, "mynavigation onCreateContextMenu itemUrl is null!");
1601 }
1602 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001603 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1604 break;
1605 }
1606 // otherwise fall through to handle image part
1607 case WebView.HitTestResult.IMAGE_TYPE:
Victoria Lease5987b802012-03-12 13:05:23 -07001608 MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
1609 shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
Michael Kolb8233fac2010-10-26 16:08:53 -07001610 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1611 menu.setHeaderTitle(extra);
Victoria Lease5987b802012-03-12 13:05:23 -07001612 shareItem.setOnMenuItemClickListener(
1613 new MenuItem.OnMenuItemClickListener() {
1614 @Override
1615 public boolean onMenuItemClick(MenuItem item) {
1616 sharePage(mActivity, null, extra, null,
1617 null);
1618 return true;
1619 }
1620 }
1621 );
Michael Kolb8233fac2010-10-26 16:08:53 -07001622 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001623 menu.findItem(R.id.view_image_context_menu_id)
1624 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1625 @Override
1626 public boolean onMenuItemClick(MenuItem item) {
1627 openTab(extra, mTabControl.getCurrentTab(), true, true);
1628 return false;
1629 }
1630 });
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02001631 menu.findItem(R.id.download_context_menu_id).setOnMenuItemClickListener(
1632 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled(),
1633 webview.getSettings().getUserAgentString()));
John Reck3527dd12011-02-22 10:35:29 -08001634 menu.findItem(R.id.set_wallpaper_context_menu_id).
1635 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1636 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001637 break;
1638
1639 default:
1640 Log.w(LOGTAG, "We should not get here.");
1641 break;
1642 }
1643 //update the ui
1644 mUi.onContextMenuCreated(menu);
1645 }
1646
kaiyiz6e5b3e02013-08-19 20:02:01 +08001647 public void startAddMyNavigation(String url) {
1648 final Intent intent = new Intent(Controller.this.getContext(), AddMyNavigationPage.class);
1649 Bundle bundle = new Bundle();
1650 bundle.putBoolean("isAdding", true);
1651 bundle.putString("url", url);
1652 bundle.putString("name", getNameFromUrl(url));
1653 intent.putExtra("websites", bundle);
1654 mActivity.startActivityForResult(intent, MY_NAVIGATION);
1655 }
1656
1657 private void showMyNavigationDeleteDialog(final String itemUrl) {
1658 new AlertDialog.Builder(this.getContext())
1659 .setTitle(R.string.my_navigation_delete_label)
1660 .setIcon(android.R.drawable.ic_dialog_alert)
1661 .setMessage(R.string.my_navigation_delete_msg)
1662 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
1663 @Override
1664 public void onClick(DialogInterface dialog, int whichButton) {
1665 deleteMyNavigationItem(itemUrl);
1666 }
1667 })
1668 .setNegativeButton(R.string.cancel, null)
1669 .show();
1670 }
1671
1672 private void deleteMyNavigationItem(final String itemUrl) {
1673 ContentResolver cr = this.getContext().getContentResolver();
1674 Cursor cursor = null;
1675
1676 try {
1677 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1678 new String[] {
1679 MyNavigationUtil.ID
1680 }, "url = ?", new String[] {
1681 itemUrl
1682 }, null);
1683 if (null != cursor && cursor.moveToFirst()) {
1684 Uri uri = ContentUris.withAppendedId(MyNavigationUtil.MY_NAVIGATION_URI,
1685 cursor.getLong(0));
1686
1687 ContentValues values = new ContentValues();
1688 values.put(MyNavigationUtil.TITLE, "");
1689 values.put(MyNavigationUtil.URL, "ae://" + cursor.getLong(0) + "add-fav");
1690 values.put(MyNavigationUtil.WEBSITE, 0 + "");
1691 ByteArrayOutputStream os = new ByteArrayOutputStream();
1692 Bitmap bm = BitmapFactory.decodeResource(this.getContext().getResources(),
1693 R.raw.my_navigation_add);
1694 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1695 values.put(MyNavigationUtil.THUMBNAIL, os.toByteArray());
1696 Log.d(LOGTAG, "deleteMyNavigationItem uri is : " + uri);
1697 cr.update(uri, values, null, null);
1698 } else {
1699 Log.e(LOGTAG, "deleteMyNavigationItem the item does not exist!");
1700 }
1701 } catch (IllegalStateException e) {
1702 Log.e(LOGTAG, "deleteMyNavigationItem", e);
1703 } finally {
1704 if (null != cursor) {
1705 cursor.close();
1706 }
1707 }
1708
1709 if (getCurrentTopWebView() != null) {
1710 getCurrentTopWebView().reload();
1711 }
1712 }
1713
1714 private String getNameFromUrl(String itemUrl) {
1715 ContentResolver cr = this.getContext().getContentResolver();
1716 Cursor cursor = null;
1717 String name = null;
1718
1719 try {
1720 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1721 new String[] {
1722 MyNavigationUtil.TITLE
1723 }, "url = ?", new String[] {
1724 itemUrl
1725 }, null);
1726 if (null != cursor && cursor.moveToFirst()) {
1727 name = cursor.getString(0);
1728 } else {
1729 Log.e(LOGTAG, "this item does not exist!");
1730 }
1731 } catch (IllegalStateException e) {
1732 Log.e(LOGTAG, "getNameFromUrl", e);
1733 } finally {
1734 if (null != cursor) {
1735 cursor.close();
1736 }
1737 }
1738 return name;
1739 }
1740
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07001741 private void updateMyNavigationThumbnail(final String itemUrl, final Bitmap bitmap) {
1742 if (bitmap == null) {
kaiyiz6e5b3e02013-08-19 20:02:01 +08001743 Log.e(LOGTAG, "updateMyNavigationThumbnail bm is null!");
1744 return;
1745 }
1746
1747 final ContentResolver cr = mActivity.getContentResolver();
1748 new AsyncTask<Void, Void, Void>() {
1749 @Override
1750 protected Void doInBackground(Void... unused) {
1751 ContentResolver cr = mActivity.getContentResolver();
1752 Cursor cursor = null;
1753 try {
1754 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1755 new String[] {
1756 MyNavigationUtil.ID
1757 }, "url = ?", new String[] {
1758 itemUrl
1759 }, null);
1760 if (null != cursor && cursor.moveToFirst()) {
1761 final ByteArrayOutputStream os = new ByteArrayOutputStream();
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07001762 bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
kaiyiz6e5b3e02013-08-19 20:02:01 +08001763
1764 ContentValues values = new ContentValues();
1765 values.put(MyNavigationUtil.THUMBNAIL, os.toByteArray());
1766 Uri uri = ContentUris.withAppendedId(MyNavigationUtil.MY_NAVIGATION_URI,
1767 cursor.getLong(0));
1768 Log.d(LOGTAG, "updateMyNavigationThumbnail uri is " + uri);
1769 cr.update(uri, values, null, null);
1770 os.close();
1771 }
1772 } catch (IllegalStateException e) {
1773 Log.e(LOGTAG, "updateMyNavigationThumbnail", e);
1774 } catch (IOException e) {
1775 Log.e(LOGTAG, "updateMyNavigationThumbnail", e);
1776 } finally {
1777 if (null != cursor) {
1778 cursor.close();
1779 }
1780 }
1781 return null;
1782 }
1783 }.execute();
1784 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001785 /**
1786 * As the menu can be open when loading state changes
1787 * we must manually update the state of the stop/reload menu
1788 * item
1789 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001790 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001791 if (menu == null) {
1792 return;
1793 }
1794 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001795 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001796 menu.findItem(R.id.stop_menu_id):
1797 menu.findItem(R.id.reload_menu_id);
1798 if (src != null) {
1799 dest.setIcon(src.getIcon());
1800 dest.setTitle(src.getTitle());
1801 }
Pankaj Garg49b79252014-11-07 17:33:41 -08001802 mActivity.invalidateOptionsMenu();
1803 }
1804
1805 public void invalidateOptionsMenu() {
1806 mAppMenuHandler.invalidateAppMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001807 }
1808
John Reck9c35b9c2012-05-30 10:08:50 -07001809 @Override
1810 public boolean onPrepareOptionsMenu(Menu menu) {
Pankaj Garg49b79252014-11-07 17:33:41 -08001811 // Software menu key (toolbar key)
1812 mAppMenuHandler.showAppMenu(mActivity.findViewById(R.id.more_browser_settings), false, false);
1813 return true;
1814 }
1815
1816 @Override
1817 public void prepareMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001818 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001819 // hold on to the menu reference here; it is used by the page callbacks
1820 // to update the menu based on loading state
1821 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001822 // Note: setVisible will decide whether an item is visible; while
1823 // setEnabled() will decide whether an item is enabled, which also means
1824 // whether the matching shortcut key will function.
1825 switch (mMenuState) {
1826 case EMPTY_MENU:
1827 if (mCurrentMenuState != mMenuState) {
1828 menu.setGroupVisible(R.id.MAIN_MENU, false);
1829 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1830 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1831 }
1832 break;
1833 default:
1834 if (mCurrentMenuState != mMenuState) {
1835 menu.setGroupVisible(R.id.MAIN_MENU, true);
1836 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1837 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1838 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001839 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001840 break;
1841 }
1842 mCurrentMenuState = mMenuState;
Pankaj Garg49b79252014-11-07 17:33:41 -08001843 mUi.onPrepareOptionsMenu(menu);
1844 }
1845
1846 private void setMenuItemVisibility(Menu menu, int id,
1847 boolean visibility) {
1848 MenuItem item = menu.findItem(id);
1849 if (item != null) {
1850 item.setVisible(visibility);
1851 }
1852 }
1853
1854 private int lookupBookmark(String title, String url) {
1855 final ContentResolver cr = getActivity().getContentResolver();
1856
1857 Cursor cursor = cr.query(BrowserContract.Bookmarks.CONTENT_URI,
1858 BookmarksLoader.PROJECTION,
1859 "title = ? OR url = ?",
1860 new String[] {
1861 title, url
1862 },
1863 null);
1864
1865 if (cursor == null) {
1866 return 0;
1867 }
1868
1869 return cursor.getCount();
1870 }
1871
1872 private void resetMenuItems(Menu menu) {
1873 setMenuItemVisibility(menu, R.id.history_menu_id, true);
1874 setMenuItemVisibility(menu, R.id.find_menu_id, true);
1875
1876 WebView w = getCurrentTopWebView();
1877 MenuItem bookmark_icon = menu.findItem(R.id.bookmark_this_page_id);
1878
1879 String title = w.getTitle();
1880 String url = w.getUrl();
1881 if (title != null && url != null && lookupBookmark(title, url) > 0) {
1882 bookmark_icon.setChecked(true);
1883 } else {
1884 bookmark_icon.setChecked(false);
1885 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001886 }
1887
Michael Kolb4bf79712011-07-14 14:18:12 -07001888 @Override
1889 public void updateMenuState(Tab tab, Menu menu) {
Michael Kolb4bf79712011-07-14 14:18:12 -07001890 boolean canGoForward = false;
John Reck42229bc2011-08-19 13:26:43 -07001891 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001892 boolean isLive = false;
Tarun Nainani8eb00912014-07-17 12:28:32 -07001893 // Following flag is used to identify schemes for which the LIVE_MENU
1894 // items defined in res/menu/browser.xml should be enabled
1895 boolean isLiveScheme = false;
1896 boolean isPageFinished = false;
Pankaj Garg49b79252014-11-07 17:33:41 -08001897
1898 resetMenuItems(menu);
1899
Michael Kolb4bf79712011-07-14 14:18:12 -07001900 if (tab != null) {
Michael Kolb4bf79712011-07-14 14:18:12 -07001901 canGoForward = tab.canGoForward();
John Reck42229bc2011-08-19 13:26:43 -07001902 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001903 isLive = !tab.isSnapshot();
Tarun Nainani8eb00912014-07-17 12:28:32 -07001904 isLiveScheme = UrlUtils.isLiveScheme(tab.getWebView().getUrl());
Pankaj Garg49b79252014-11-07 17:33:41 -08001905 isPageFinished = (tab.getPageFinishedStatus() || !tab.inPageLoad());
Michael Kolb4bf79712011-07-14 14:18:12 -07001906 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001907
1908 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1909 forward.setEnabled(canGoForward);
1910
Michael Kolb4bf79712011-07-14 14:18:12 -07001911 // decide whether to show the share link option
1912 PackageManager pm = mActivity.getPackageManager();
1913 Intent send = new Intent(Intent.ACTION_SEND);
1914 send.setType("text/plain");
1915 ResolveInfo ri = pm.resolveActivity(send,
1916 PackageManager.MATCH_DEFAULT_ONLY);
1917 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1918
1919 boolean isNavDump = mSettings.enableNavDump();
1920 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1921 nav.setVisible(isNavDump);
1922 nav.setEnabled(isNavDump);
1923
1924 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001925 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1926 uaSwitcher.setChecked(isDesktopUa);
Tarun Nainani8eb00912014-07-17 12:28:32 -07001927 menu.setGroupVisible(R.id.LIVE_MENU, isLive && isLiveScheme);
Pankaj Garg49b79252014-11-07 17:33:41 -08001928 menu.setGroupVisible(R.id.NAV_MENU, isLive && isLiveScheme);
1929 setMenuItemVisibility(menu, R.id.find_menu_id, isLive && isLiveScheme);
John Recke1a03a32011-09-14 17:04:16 -07001930 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Pankaj Garg49b79252014-11-07 17:33:41 -08001931 setMenuItemVisibility(menu, R.id.add_to_homescreen,
1932 isLive && isLiveScheme && isPageFinished);
1933 setMenuItemVisibility(menu, R.id.save_snapshot_menu_id,
1934 isLive && isLiveScheme && isPageFinished);
kaiyiza8b6dbb2013-07-29 18:11:22 +08001935 // history and snapshots item are the members of COMBO menu group,
1936 // so if show history item, only make snapshots item invisible.
1937 menu.findItem(R.id.snapshots_menu_id).setVisible(false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001938
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001939 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001940 }
1941
John Reck9c35b9c2012-05-30 10:08:50 -07001942 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07001943 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001944 if (null == getCurrentTopWebView()) {
1945 return false;
1946 }
1947 if (mMenuIsDown) {
1948 // The shortcut action consumes the MENU. Even if it is still down,
1949 // it won't trigger the next shortcut action. In the case of the
1950 // shortcut action triggering a new activity, like Bookmarks, we
1951 // won't get onKeyUp for MENU. So it is important to reset it here.
1952 mMenuIsDown = false;
1953 }
Michael Kolb3ca12752011-07-20 13:52:25 -07001954 if (mUi.onOptionsItemSelected(item)) {
1955 // ui callback handled it
1956 return true;
1957 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001958 switch (item.getItemId()) {
1959 // -- Main menu
1960 case R.id.new_tab_menu_id:
1961 openTabToHomePage();
1962 break;
1963
1964 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07001965 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07001966 break;
1967
1968 case R.id.goto_menu_id:
1969 editUrl();
1970 break;
1971
1972 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07001973 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
1974 break;
1975
1976 case R.id.history_menu_id:
1977 bookmarksOrHistoryPicker(ComboViews.History);
1978 break;
1979
1980 case R.id.snapshots_menu_id:
1981 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07001982 break;
1983
Pankaj Garg49b79252014-11-07 17:33:41 -08001984 case R.id.bookmark_this_page_id:
Michael Kolb80f75082012-04-10 10:50:06 -07001985 bookmarkCurrentPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07001986 break;
1987
1988 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001989 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001990 stopLoading();
1991 } else {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001992 Tab currentTab = mTabControl.getCurrentTab();
1993 if (currentTab.hasCrashed) {
1994 currentTab.replaceCrashView(getCurrentTopWebView(),
1995 currentTab.getViewContainer());
1996 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001997 getCurrentTopWebView().reload();
1998 }
1999 break;
2000
Michael Kolb8233fac2010-10-26 16:08:53 -07002001 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07002002 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07002003 break;
2004
2005 case R.id.close_menu_id:
2006 // Close the subwindow if it exists.
2007 if (mTabControl.getCurrentSubWindow() != null) {
2008 dismissSubWindow(mTabControl.getCurrentTab());
2009 break;
2010 }
2011 closeCurrentTab();
2012 break;
2013
kaiyiza8b6dbb2013-07-29 18:11:22 +08002014 case R.id.exit_menu_id:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002015 Object[] params = { new String("persist.debug.browsermonkeytest")};
2016 Class[] type = new Class[] {String.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -07002017 String ret = (String)ReflectHelper.invokeMethod(
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002018 "android.os.SystemProperties","get", type, params);
kaiyiza8b6dbb2013-07-29 18:11:22 +08002019 if (ret != null && ret.equals("enable"))
2020 break;
Panos Thomas4bdb5252014-11-13 16:20:11 -08002021 if (BrowserConfig.getInstance(getContext())
2022 .hasFeature(BrowserConfig.Feature.EXIT_DIALOG))
2023 showExitDialog(mActivity);
luxiaolb40014b2013-07-19 10:01:43 +08002024 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002025 case R.id.homepage_menu_id:
2026 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002027 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07002028 break;
2029
2030 case R.id.preferences_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002031 openPreferences();
Michael Kolb8233fac2010-10-26 16:08:53 -07002032 break;
2033
2034 case R.id.find_menu_id:
Michael Kolbe11b9212012-04-13 13:39:54 -07002035 findOnPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07002036 break;
2037
John Reck2bc80422011-06-30 15:11:49 -07002038 case R.id.save_snapshot_menu_id:
2039 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07002040 if (source == null) break;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002041 createScreenshotAsync(
2042 source.getWebView(),
2043 getDesiredThumbnailWidth(mActivity),
2044 getDesiredThumbnailHeight(mActivity),
2045 new ValueCallback<Bitmap>() {
2046 @Override
2047 public void onReceiveValue(Bitmap bitmap) {
2048 new SaveSnapshotTask(source, bitmap).execute();
2049 }
2050 });
Leon Scrogginsac993842011-02-02 12:54:07 -05002051 break;
2052
Michael Kolb8233fac2010-10-26 16:08:53 -07002053 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07002054 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 break;
2056
John Recke1a03a32011-09-14 17:04:16 -07002057 case R.id.snapshot_go_live:
2058 goLive();
2059 return true;
2060
Michael Kolb8233fac2010-10-26 16:08:53 -07002061 case R.id.share_page_menu_id:
2062 Tab currentTab = mTabControl.getCurrentTab();
2063 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002064 return false;
2065 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08002066 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002067 break;
2068
2069 case R.id.dump_nav_menu_id:
2070 getCurrentTopWebView().debugDump();
2071 break;
2072
Michael Kolb8233fac2010-10-26 16:08:53 -07002073 case R.id.zoom_in_menu_id:
2074 getCurrentTopWebView().zoomIn();
2075 break;
2076
2077 case R.id.zoom_out_menu_id:
2078 getCurrentTopWebView().zoomOut();
2079 break;
2080
2081 case R.id.view_downloads_menu_id:
2082 viewDownloads();
2083 break;
2084
John Reck42229bc2011-08-19 13:26:43 -07002085 case R.id.ua_desktop_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002086 toggleUserAgent();
John Reck42229bc2011-08-19 13:26:43 -07002087 break;
2088
Michael Kolb8233fac2010-10-26 16:08:53 -07002089 case R.id.window_one_menu_id:
2090 case R.id.window_two_menu_id:
2091 case R.id.window_three_menu_id:
2092 case R.id.window_four_menu_id:
2093 case R.id.window_five_menu_id:
2094 case R.id.window_six_menu_id:
2095 case R.id.window_seven_menu_id:
2096 case R.id.window_eight_menu_id:
2097 {
2098 int menuid = item.getItemId();
2099 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
2100 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
2101 Tab desiredTab = mTabControl.getTab(id);
2102 if (desiredTab != null &&
2103 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07002104 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002105 }
2106 break;
2107 }
2108 }
2109 }
2110 break;
2111
Axesh R. Ajmera652d08e2014-06-16 16:36:33 -07002112 case R.id.about_menu_id:
2113 final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
2114 builder.setTitle(R.string.about);
2115 builder.setCancelable(true);
2116 String ua = "";
2117 final WebView currentWebView = getCurrentWebView();
2118 if (currentWebView != null) {
2119 final WebSettings s = currentWebView.getSettings();
2120 if (s != null) {
2121 ua = s.getUserAgentString();
2122 }
2123 }
2124 builder.setMessage("Agent:" + ua);
2125 builder.setPositiveButton(android.R.string.ok, null);
2126 builder.create().show();
2127 break;
2128
Pankaj Garg49b79252014-11-07 17:33:41 -08002129 case R.id.add_to_homescreen:
2130 final WebView w = getCurrentTopWebView();
2131 final EditText input = new EditText(getContext());
2132 input.setText(w.getTitle());
2133 new AlertDialog.Builder(getContext())
2134 .setTitle("Add to homescreen")
2135 .setMessage("Title")
2136 .setView(input)
2137 .setPositiveButton("Add", new DialogInterface.OnClickListener() {
2138 public void onClick(DialogInterface dialog, int whichButton) {
2139 mActivity.sendBroadcast(BookmarkUtils.createAddToHomeIntent(
2140 getContext(),
2141 w.getUrl(),
2142 input.getText().toString(),
2143 w.getViewportBitmap(),
2144 w.getFavicon()));
2145
2146 mActivity.startActivity(new Intent(Intent.ACTION_MAIN)
2147 .addCategory(Intent.CATEGORY_HOME));
2148 }})
2149 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
2150 public void onClick(DialogInterface dialog, int whichButton) {
2151 // Do nothing.
2152 }
2153 })
2154 .show();
2155 break;
2156
Michael Kolb8233fac2010-10-26 16:08:53 -07002157 default:
2158 return false;
2159 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002160 return true;
2161 }
2162
John Reck68234a92012-04-19 15:27:12 -07002163 private class SaveSnapshotTask extends AsyncTask<Void, Void, Long>
2164 implements OnCancelListener {
2165
2166 private Tab mTab;
2167 private Dialog mProgressDialog;
2168 private ContentValues mValues;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002169 private Bitmap mBitmap;
John Reck68234a92012-04-19 15:27:12 -07002170
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002171 private SaveSnapshotTask(Tab tab, Bitmap bm) {
John Reck68234a92012-04-19 15:27:12 -07002172 mTab = tab;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002173 mBitmap = bm;
John Reck68234a92012-04-19 15:27:12 -07002174 }
2175
2176 @Override
2177 protected void onPreExecute() {
2178 CharSequence message = mActivity.getText(R.string.saving_snapshot);
2179 mProgressDialog = ProgressDialog.show(mActivity, null, message,
2180 true, true, this);
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002181 mValues = mTab.createSnapshotValues(mBitmap);
John Reck68234a92012-04-19 15:27:12 -07002182 }
2183
2184 @Override
2185 protected Long doInBackground(Void... params) {
2186 if (!mTab.saveViewState(mValues)) {
2187 return null;
2188 }
2189 if (isCancelled()) {
2190 String path = mValues.getAsString(Snapshots.VIEWSTATE_PATH);
2191 File file = mActivity.getFileStreamPath(path);
2192 if (!file.delete()) {
2193 file.deleteOnExit();
2194 }
2195 return null;
2196 }
2197 final ContentResolver cr = mActivity.getContentResolver();
2198 Uri result = cr.insert(Snapshots.CONTENT_URI, mValues);
2199 if (result == null) {
2200 return null;
2201 }
2202 long id = ContentUris.parseId(result);
2203 return id;
2204 }
2205
2206 @Override
2207 protected void onPostExecute(Long id) {
2208 if (isCancelled()) {
2209 return;
2210 }
2211 mProgressDialog.dismiss();
2212 if (id == null) {
2213 Toast.makeText(mActivity, R.string.snapshot_failed,
2214 Toast.LENGTH_SHORT).show();
2215 return;
2216 }
2217 Bundle b = new Bundle();
2218 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
2219 mUi.showComboView(ComboViews.Snapshots, b);
2220 }
2221
2222 @Override
2223 public void onCancel(DialogInterface dialog) {
2224 cancel(true);
2225 }
2226 }
2227
Michael Kolb80f75082012-04-10 10:50:06 -07002228 @Override
2229 public void toggleUserAgent() {
2230 WebView web = getCurrentWebView();
2231 mSettings.toggleDesktopUseragent(web);
Michael Kolb80f75082012-04-10 10:50:06 -07002232 }
2233
2234 @Override
2235 public void findOnPage() {
2236 getCurrentTopWebView().showFindDialog(null, true);
2237 }
2238
2239 @Override
2240 public void openPreferences() {
Enrico Rosd6efa972014-12-02 19:49:59 -08002241 BrowserPreferencesPage.startPreferencesForResult(mActivity, getCurrentTopWebView().getUrl(), PREFERENCES_PAGE);
Michael Kolb80f75082012-04-10 10:50:06 -07002242 }
2243
2244 @Override
2245 public void bookmarkCurrentPage() {
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002246 WebView w = getCurrentTopWebView();
2247 if (w == null)
2248 return;
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002249 final Intent i = createBookmarkCurrentPageIntent(false);
2250 createScreenshotAsync(
2251 w, getDesiredThumbnailWidth(mActivity),
2252 getDesiredThumbnailHeight(mActivity),
2253 new ValueCallback<Bitmap>() {
2254 @Override
2255 public void onReceiveValue(Bitmap bitmap) {
2256 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL, bitmap);
2257 mActivity.startActivity(i);
2258 }
2259 });
Michael Kolb80f75082012-04-10 10:50:06 -07002260 }
2261
John Recke1a03a32011-09-14 17:04:16 -07002262 private void goLive() {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002263 SnapshotTab t = (SnapshotTab) getCurrentTab();
Tarun Nainani8eb00912014-07-17 12:28:32 -07002264 String url = t.getLiveUrl();
Axesh R. Ajmera8b3ed5d2014-10-22 16:35:25 -07002265 boolean onlySingleTabRemaining = false;
2266 if (mTabControl.getTabCount() > 1) {
2267 // destroy the old snapshot tab
2268 closeCurrentTab();
2269 } else {
2270 onlySingleTabRemaining = true;
2271 }
Tarun Nainani8eb00912014-07-17 12:28:32 -07002272 Tab liveTab = createNewTab(false, true, false);
Axesh R. Ajmera8b3ed5d2014-10-22 16:35:25 -07002273 if (onlySingleTabRemaining) {
2274 closeTab(t);
2275 }
2276
Tarun Nainani8eb00912014-07-17 12:28:32 -07002277 loadUrl(liveTab, url);
John Recke1a03a32011-09-14 17:04:16 -07002278 }
2279
luxiaolb40014b2013-07-19 10:01:43 +08002280 private void showExitDialog(final Activity activity) {
2281 new AlertDialog.Builder(activity)
2282 .setTitle(R.string.exit_browser_title)
Enrico Ros1f5a0952014-11-18 20:15:48 -08002283 /* disabled, was worrying people: .setIcon(android.R.drawable.ic_dialog_alert) */
luxiaolb40014b2013-07-19 10:01:43 +08002284 .setMessage(R.string.exit_browser_msg)
2285 .setNegativeButton(R.string.exit_minimize, new DialogInterface.OnClickListener() {
2286 public void onClick(DialogInterface dialog, int which) {
2287 activity.moveTaskToBack(true);
2288 dialog.dismiss();
2289 }
2290 })
2291 .setPositiveButton(R.string.exit_quit, new DialogInterface.OnClickListener() {
2292 public void onClick(DialogInterface dialog, int which) {
2293 activity.finish();
2294 mHandler.postDelayed(new Runnable() {
2295 @Override
2296 public void run() {
luxiaolb40014b2013-07-19 10:01:43 +08002297 mCrashRecoveryHandler.clearState(true);
2298 int pid = android.os.Process.myPid();
2299 android.os.Process.killProcess(pid);
2300 }
2301 }, 300);
2302 dialog.dismiss();
2303 }
2304 })
2305 .show();
2306 }
Michael Kolb315d5022011-10-13 12:47:11 -07002307 @Override
2308 public void showPageInfo() {
2309 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
2310 }
2311
John Reck9c35b9c2012-05-30 10:08:50 -07002312 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002313 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08002314 // Let the History and Bookmark fragments handle menus they created.
2315 if (item.getGroupId() == R.id.CONTEXT_MENU) {
2316 return false;
2317 }
2318
Michael Kolb8233fac2010-10-26 16:08:53 -07002319 int id = item.getItemId();
2320 boolean result = true;
2321 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002322 // -- Browser context menu
2323 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07002324 case R.id.save_link_context_menu_id:
Tarun Nainani700b69b2014-03-26 16:07:25 -07002325 case R.id.save_link_bookmark_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07002326 case R.id.copy_link_context_menu_id:
2327 final WebView webView = getCurrentTopWebView();
2328 if (null == webView) {
2329 result = false;
2330 break;
2331 }
2332 final HashMap<String, WebView> hrefMap =
2333 new HashMap<String, WebView>();
2334 hrefMap.put("webview", webView);
2335 final Message msg = mHandler.obtainMessage(
2336 FOCUS_NODE_HREF, id, 0, hrefMap);
2337 webView.requestFocusNodeHref(msg);
2338 break;
2339
2340 default:
2341 // For other context menus
2342 result = onOptionsItemSelected(item);
2343 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002344 return result;
2345 }
2346
2347 /**
2348 * support programmatically opening the context menu
2349 */
2350 public void openContextMenu(View view) {
2351 mActivity.openContextMenu(view);
2352 }
2353
2354 /**
2355 * programmatically open the options menu
2356 */
2357 public void openOptionsMenu() {
2358 mActivity.openOptionsMenu();
2359 }
2360
John Reck9c35b9c2012-05-30 10:08:50 -07002361 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002362 public boolean onMenuOpened(int featureId, Menu menu) {
2363 if (mOptionsMenuOpen) {
2364 if (mConfigChanged) {
2365 // We do not need to make any changes to the state of the
2366 // title bar, since the only thing that happened was a
2367 // change in orientation
2368 mConfigChanged = false;
2369 } else {
2370 if (!mExtendedMenuOpen) {
2371 mExtendedMenuOpen = true;
2372 mUi.onExtendedMenuOpened();
2373 } else {
2374 // Switching the menu back to icon view, so show the
2375 // title bar once again.
2376 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002377 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002378 }
2379 }
2380 } else {
2381 // The options menu is closed, so open it, and show the title
2382 mOptionsMenuOpen = true;
2383 mConfigChanged = false;
2384 mExtendedMenuOpen = false;
2385 mUi.onOptionsMenuOpened();
2386 }
2387 return true;
2388 }
2389
John Reck9c35b9c2012-05-30 10:08:50 -07002390 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002391 public void onOptionsMenuClosed(Menu menu) {
2392 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002393 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002394 }
2395
John Reck9c35b9c2012-05-30 10:08:50 -07002396 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002397 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002398 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002399 }
2400
2401 // Helper method for getting the top window.
2402 @Override
2403 public WebView getCurrentTopWebView() {
2404 return mTabControl.getCurrentTopWebView();
2405 }
2406
2407 @Override
2408 public WebView getCurrentWebView() {
2409 return mTabControl.getCurrentWebView();
2410 }
2411
2412 /*
2413 * This method is called as a result of the user selecting the options
2414 * menu to see the download window. It shows the download window on top of
2415 * the current window.
2416 */
2417 void viewDownloads() {
2418 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2419 mActivity.startActivity(intent);
2420 }
2421
John Reck30b065e2011-07-19 10:58:05 -07002422 int getActionModeHeight() {
2423 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
2424 new int[] { android.R.attr.actionBarSize });
2425 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
2426 actionBarSizeTypedArray.recycle();
2427 return size;
2428 }
2429
Michael Kolb8233fac2010-10-26 16:08:53 -07002430 // action mode
2431
John Reck9c35b9c2012-05-30 10:08:50 -07002432 @Override
2433 public void onActionModeStarted(ActionMode mode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002434 mUi.onActionModeStarted(mode);
2435 mActionMode = mode;
2436 }
2437
2438 /*
2439 * True if a custom ActionMode (i.e. find or select) is in use.
2440 */
2441 @Override
2442 public boolean isInCustomActionMode() {
2443 return mActionMode != null;
2444 }
2445
2446 /*
2447 * End the current ActionMode.
2448 */
2449 @Override
2450 public void endActionMode() {
2451 if (mActionMode != null) {
2452 mActionMode.finish();
2453 }
2454 }
2455
2456 /*
2457 * Called by find and select when they are finished. Replace title bars
2458 * as necessary.
2459 */
John Reck9c35b9c2012-05-30 10:08:50 -07002460 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002461 public void onActionModeFinished(ActionMode mode) {
2462 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002463 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002464 mActionMode = null;
2465 }
2466
2467 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08002468 final Tab tab = getCurrentTab();
2469 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002470 }
2471
2472 // bookmark handling
2473
2474 /**
2475 * add the current page as a bookmark to the given folder id
2476 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07002477 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05002478 * bookmarked, and if it is, edit that bookmark. If false, and
2479 * the site is already bookmarked, do not attempt to edit the
2480 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07002481 */
2482 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07002483 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07002484 WebView w = getCurrentTopWebView();
2485 if (w == null) {
2486 return null;
2487 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002488 Intent i = new Intent(mActivity,
2489 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07002490 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
2491 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
2492 String touchIconUrl = w.getTouchIconUrl();
2493 if (touchIconUrl != null) {
2494 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
2495 WebSettings settings = w.getSettings();
2496 if (settings != null) {
2497 i.putExtra(AddBookmarkPage.USER_AGENT,
2498 settings.getUserAgentString());
2499 }
2500 }
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002501 //SWE: Thumbnail will need to be set asynchronously
Michael Kolb8233fac2010-10-26 16:08:53 -07002502 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07002503 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05002504 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
2505 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002506 // Put the dialog at the upper right of the screen, covering the
2507 // star on the title bar.
2508 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07002509 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07002510 }
2511
2512 // file chooser
John Reck9c35b9c2012-05-30 10:08:50 -07002513 @Override
Ben Murdoch8cad4132012-01-11 10:56:43 +00002514 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002515 mUploadHandler = new UploadHandler(this);
Ben Murdoch8cad4132012-01-11 10:56:43 +00002516 mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
Michael Kolb8233fac2010-10-26 16:08:53 -07002517 }
2518
Vivek Sekharb54614f2014-05-01 19:03:37 -07002519 @Override
2520 public void showFileChooser(ValueCallback<String[]> uploadFilePaths, String acceptTypes,
2521 boolean capture) {
2522 mUploadHandler = new UploadHandler(this);
2523 mUploadHandler.showFileChooser(uploadFilePaths, acceptTypes, capture);
2524 }
2525
Michael Kolb8233fac2010-10-26 16:08:53 -07002526 // thumbnails
2527
2528 /**
2529 * Return the desired width 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 width for thumbnail screenshot.
2533 */
2534 static int getDesiredThumbnailWidth(Context context) {
2535 return context.getResources().getDimensionPixelOffset(
2536 R.dimen.bookmarkThumbnailWidth);
2537 }
2538
2539 /**
2540 * Return the desired height for thumbnail screenshots, which are stored in
2541 * the database, and used on the bookmarks screen.
2542 * @param context Context for finding out the density of the screen.
2543 * @return desired height for thumbnail screenshot.
2544 */
2545 static int getDesiredThumbnailHeight(Context context) {
2546 return context.getResources().getDimensionPixelOffset(
2547 R.dimen.bookmarkThumbnailHeight);
2548 }
2549
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002550 static void createScreenshotAsync(WebView view, int width, int height,
2551 final ValueCallback<Bitmap> cb) {
2552 if (view == null || width == 0 || height == 0) {
2553 return;
2554 }
2555
2556 view.getContentBitmapAsync(
2557 (float) width / view.getWidth(),
2558 new Rect(),
2559 new ValueCallback<Bitmap>() {
2560 @Override
2561 public void onReceiveValue(Bitmap bitmap) {
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002562 if (bitmap != null)
2563 bitmap = bitmap.copy(Bitmap.Config.RGB_565, false);
2564 cb.onReceiveValue(bitmap);
2565 }});
2566 }
2567
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002568 private void updateScreenshot(final Tab tab) {
2569 createScreenshotAsync(
2570 tab.getWebView(),
2571 getDesiredThumbnailWidth(mActivity),
2572 getDesiredThumbnailHeight(mActivity),
2573 new ValueCallback<Bitmap>() {
2574 @Override
2575 public void onReceiveValue(Bitmap bitmap) {
2576 updateScreenshot(tab, bitmap);
2577 }
2578 });
2579 }
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002580
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002581 private void updateScreenshot(Tab tab, final Bitmap bm) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002582 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002583 // FIXME: Would like to make sure there is actually something to
2584 // draw, but the API for that (WebViewCore.pictureReady()) is not
2585 // currently accessible here.
2586
John Reck34ef2672011-02-10 11:30:55 -08002587 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002588 if (view == null) {
2589 // Tab was destroyed
2590 return;
2591 }
John Reck34ef2672011-02-10 11:30:55 -08002592 final String url = tab.getUrl();
2593 final String originalUrl = view.getOriginalUrl();
kaiyiz6e5b3e02013-08-19 20:02:01 +08002594 final String thumbnailUrl = mUpdateMyNavThumbnailUrl;
John Reck34ef2672011-02-10 11:30:55 -08002595 if (TextUtils.isEmpty(url)) {
2596 return;
2597 }
2598
kaiyiz6e5b3e02013-08-19 20:02:01 +08002599 //update My Navigation Thumbnails
2600 boolean isMyNavigationUrl = MyNavigationUtil.isMyNavigationUrl(mActivity, url);
2601 if (isMyNavigationUrl) {
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002602 updateMyNavigationThumbnail(url, bm);
kaiyiz6e5b3e02013-08-19 20:02:01 +08002603 }
John Reck34ef2672011-02-10 11:30:55 -08002604 // Only update thumbnails for web urls (http(s)://), not for
2605 // about:, javascript:, data:, etc...
2606 // Unless it is a bookmarked site, then always update
2607 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2608 return;
2609 }
2610
kaiyiz6e5b3e02013-08-19 20:02:01 +08002611 if (url != null && mUpdateMyNavThumbnailUrl != null
2612 && Patterns.WEB_URL.matcher(url).matches()
2613 && Patterns.WEB_URL.matcher(mUpdateMyNavThumbnailUrl).matches()) {
2614 String urlHost = (new WebAddress(url)).getHost();
2615 String bookmarkHost = (new WebAddress(mUpdateMyNavThumbnailUrl)).getHost();
2616 if (urlHost == null || urlHost.length() == 0 || bookmarkHost == null
2617 || bookmarkHost.length() == 0) {
2618 return;
2619 }
2620 String urlDomain = urlHost.substring(urlHost.indexOf('.'), urlHost.length());
2621 String bookmarkDomain = bookmarkHost.substring(bookmarkHost.indexOf('.'),
2622 bookmarkHost.length());
2623 Log.d(LOGTAG, "addressUrl domain is " + urlDomain);
2624 Log.d(LOGTAG, "bookmarkUrl domain is " + bookmarkDomain);
2625 if (!bookmarkDomain.equals(urlDomain)) {
2626 return;
2627 }
2628 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002629 if (bm == null) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002630 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
2631 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2632 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
2633 500);
2634 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002635 return;
2636 }
2637
2638 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002639 new AsyncTask<Void, Void, Void>() {
2640 @Override
2641 protected Void doInBackground(Void... unused) {
2642 Cursor cursor = null;
2643 try {
2644 // TODO: Clean this up
kaiyiz6e5b3e02013-08-19 20:02:01 +08002645 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl,
2646 mUpdateMyNavThumbnail ? ((thumbnailUrl != null) ? thumbnailUrl : url)
2647 : url);
2648 if (mUpdateMyNavThumbnail) {
2649 mUpdateMyNavThumbnail = false;
2650 mUpdateMyNavThumbnailUrl = null;
2651 }
John Reck34ef2672011-02-10 11:30:55 -08002652 if (cursor != null && cursor.moveToFirst()) {
2653 final ByteArrayOutputStream os =
2654 new ByteArrayOutputStream();
2655 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002656
John Reck34ef2672011-02-10 11:30:55 -08002657 ContentValues values = new ContentValues();
2658 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002659
John Reck34ef2672011-02-10 11:30:55 -08002660 do {
John Reck617fd832011-02-16 14:35:59 -08002661 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002662 cr.update(Images.CONTENT_URI, values, null, null);
2663 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002664 }
John Reck34ef2672011-02-10 11:30:55 -08002665 } catch (IllegalStateException e) {
2666 // Ignore
Mattias Nilsson561d1952011-10-04 10:18:50 +02002667 } catch (SQLiteException s) {
2668 // Added for possible error when user tries to remove the same bookmark
2669 // that is being updated with a screen shot
2670 Log.w(LOGTAG, "Error when running updateScreenshot ", s);
John Reck34ef2672011-02-10 11:30:55 -08002671 } finally {
2672 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002673 }
John Reck34ef2672011-02-10 11:30:55 -08002674 return null;
2675 }
2676 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002677 }
2678
2679 private class Copy implements OnMenuItemClickListener {
2680 private CharSequence mText;
2681
John Reck9c35b9c2012-05-30 10:08:50 -07002682 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002683 public boolean onMenuItemClick(MenuItem item) {
2684 copy(mText);
2685 return true;
2686 }
2687
2688 public Copy(CharSequence toCopy) {
2689 mText = toCopy;
2690 }
2691 }
2692
Leon Scroggins63c02662010-11-18 15:16:27 -05002693 private static class Download implements OnMenuItemClickListener {
2694 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002695 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002696 private boolean mPrivateBrowsing;
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002697 private String mUserAgent;
George Mount387d45d2011-10-07 15:57:53 -07002698 private static final String FALLBACK_EXTENSION = "dat";
2699 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002700
John Reck9c35b9c2012-05-30 10:08:50 -07002701 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002702 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002703 if (DataUri.isDataUri(mText)) {
2704 saveDataUri();
2705 } else {
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002706 DownloadHandler.onDownloadStartNoStream(mActivity, mText, mUserAgent,
luxiaol62677b02013-07-22 07:54:49 +08002707 null, null, null, mPrivateBrowsing, 0);
George Mount387d45d2011-10-07 15:57:53 -07002708 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002709 return true;
2710 }
2711
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002712 public Download(Activity activity, String toDownload, boolean privateBrowsing,
2713 String userAgent) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002714 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002715 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002716 mPrivateBrowsing = privateBrowsing;
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002717 mUserAgent = userAgent;
Michael Kolb8233fac2010-10-26 16:08:53 -07002718 }
George Mount387d45d2011-10-07 15:57:53 -07002719
2720 /**
2721 * Treats mText as a data URI and writes its contents to a file
2722 * based on the current time.
2723 */
2724 private void saveDataUri() {
2725 FileOutputStream outputStream = null;
2726 try {
2727 DataUri uri = new DataUri(mText);
2728 File target = getTarget(uri);
2729 outputStream = new FileOutputStream(target);
2730 outputStream.write(uri.getData());
2731 final DownloadManager manager =
2732 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2733 manager.addCompletedDownload(target.getName(),
2734 mActivity.getTitle().toString(), false,
2735 uri.getMimeType(), target.getAbsolutePath(),
John Reck9c35b9c2012-05-30 10:08:50 -07002736 uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002737 } catch (IOException e) {
2738 Log.e(LOGTAG, "Could not save data URL");
2739 } finally {
2740 if (outputStream != null) {
2741 try {
2742 outputStream.close();
2743 } catch (IOException e) {
2744 // ignore close errors
2745 }
2746 }
2747 }
2748 }
2749
2750 /**
2751 * Creates a File based on the current time stamp and uses
2752 * the mime type of the DataUri to get the extension.
2753 */
2754 private File getTarget(DataUri uri) throws IOException {
2755 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
Johan Redestigaa676182012-10-03 13:33:01 +02002756 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT, Locale.US);
George Mount387d45d2011-10-07 15:57:53 -07002757 String nameBase = format.format(new Date());
2758 String mimeType = uri.getMimeType();
2759 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2760 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2761 if (extension == null) {
2762 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2763 extension = FALLBACK_EXTENSION;
2764 }
2765 extension = "." + extension; // createTempFile needs the '.'
2766 File targetFile = File.createTempFile(nameBase, extension, dir);
2767 return targetFile;
2768 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002769 }
2770
Cary Clark8974d282010-11-22 10:46:05 -05002771 private static class SelectText implements OnMenuItemClickListener {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002772 private WebView mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002773
John Reck9c35b9c2012-05-30 10:08:50 -07002774 @Override
Cary Clark8974d282010-11-22 10:46:05 -05002775 public boolean onMenuItemClick(MenuItem item) {
2776 if (mWebView != null) {
2777 return mWebView.selectText();
2778 }
2779 return false;
2780 }
2781
2782 public SelectText(WebView webView) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002783 mWebView = webView;
Cary Clark8974d282010-11-22 10:46:05 -05002784 }
2785
2786 }
2787
Michael Kolb8233fac2010-10-26 16:08:53 -07002788 /********************** TODO: UI stuff *****************************/
2789
2790 // these methods have been copied, they still need to be cleaned up
2791
2792 /****************** tabs ***************************************************/
2793
2794 // basic tab interactions:
2795
2796 // it is assumed that tabcontrol already knows about the tab
2797 protected void addTab(Tab tab) {
2798 mUi.addTab(tab);
2799 }
2800
2801 protected void removeTab(Tab tab) {
2802 mUi.removeTab(tab);
2803 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002804 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002805 }
2806
Michael Kolbf2055602011-04-09 17:20:03 -07002807 @Override
2808 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002809 // monkey protection against delayed start
2810 if (tab != null) {
2811 mTabControl.setCurrentTab(tab);
2812 // the tab is guaranteed to have a webview after setCurrentTab
2813 mUi.setActiveTab(tab);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002814 tab.setTimeStamp();
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07002815 //Purge active tabs
2816 MemoryMonitor.purgeActiveTabs(mActivity.getApplicationContext(), this, mSettings);
Michael Kolbcd424e92011-02-24 10:26:26 -08002817 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002818 }
2819
John Reck8bcafc12011-08-29 16:43:02 -07002820 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002821 Tab current = mTabControl.getCurrentTab();
2822 if (current != null
2823 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002824 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002825 }
2826 }
2827
John Reck26b18322011-06-21 13:08:58 -07002828 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002829 // Dismiss the subwindow if applicable.
2830 dismissSubWindow(appTab);
2831 // Since we might kill the WebView, remove it from the
2832 // content view first.
2833 mUi.detachTab(appTab);
2834 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002835 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002836 // TODO: analyze why the remove and add are necessary
2837 mUi.attachTab(appTab);
2838 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002839 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002840 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002841 } else {
2842 // If the tab was the current tab, we have to attach
2843 // it to the view system again.
2844 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002845 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002846 }
2847 }
2848
2849 // Remove the sub window if it exists. Also called by TabControl when the
2850 // user clicks the 'X' to dismiss a sub window.
John Reck9c35b9c2012-05-30 10:08:50 -07002851 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002852 public void dismissSubWindow(Tab tab) {
2853 removeSubWindow(tab);
2854 // dismiss the subwindow. This will destroy the WebView.
2855 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002856 WebView wv = getCurrentTopWebView();
2857 if (wv != null) {
2858 wv.requestFocus();
2859 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002860 }
2861
2862 @Override
2863 public void removeSubWindow(Tab t) {
2864 if (t.getSubWebView() != null) {
2865 mUi.removeSubWindow(t.getSubViewContainer());
2866 }
2867 }
2868
2869 @Override
2870 public void attachSubWindow(Tab tab) {
2871 if (tab.getSubWebView() != null) {
2872 mUi.attachSubWindow(tab.getSubViewContainer());
2873 getCurrentTopWebView().requestFocus();
2874 }
2875 }
2876
Mathew Inwood29721c22011-06-29 17:55:24 +01002877 private Tab showPreloadedTab(final UrlData urlData) {
2878 if (!urlData.isPreloaded()) {
2879 return null;
2880 }
2881 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2882 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2883 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002884 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002885 // Could not submit query. Fallback to regular tab creation
2886 tabControl.destroy();
2887 return null;
2888 }
2889 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002890 // check tab count and make room for new tab
2891 if (!mTabControl.canCreateNewTab()) {
2892 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2893 if (leastUsed != null) {
2894 closeTab(leastUsed);
2895 }
2896 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002897 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002898 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002899 mTabControl.addPreloadedTab(t);
2900 addTab(t);
2901 setActiveTab(t);
2902 return t;
2903 }
2904
Michael Kolb7bcafde2011-05-09 13:55:59 -07002905 // open a non inconito tab with the given url data
2906 // and set as active tab
2907 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002908 Tab tab = showPreloadedTab(urlData);
2909 if (tab == null) {
2910 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002911 if ((tab != null) && !urlData.isEmpty()) {
2912 loadUrlDataIn(tab, urlData);
2913 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002914 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002915 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002916 }
2917
Michael Kolb843510f2010-12-09 10:51:49 -08002918 @Override
2919 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002920 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002921 }
2922
Michael Kolb8233fac2010-10-26 16:08:53 -07002923 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002924 public Tab openIncognitoTab() {
2925 return openTab(INCOGNITO_URI, true, true, false);
2926 }
2927
2928 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002929 public Tab openTab(String url, boolean incognito, boolean setActive,
2930 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002931 return openTab(url, incognito, setActive, useCurrent, null);
2932 }
2933
2934 @Override
2935 public Tab openTab(String url, Tab parent, boolean setActive,
2936 boolean useCurrent) {
2937 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2938 setActive, useCurrent, parent);
2939 }
2940
2941 public Tab openTab(String url, boolean incognito, boolean setActive,
2942 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002943 Tab tab = createNewTab(incognito, setActive, useCurrent);
2944 if (tab != null) {
Vivek Sekhar871172e2014-07-23 12:16:54 -07002945 if (parent instanceof SnapshotTab) {
2946 addTab(tab);
2947 if (setActive)
2948 setActiveTab(tab);
2949 }else if (parent != null && parent != tab) {
John Reck5949c662011-05-27 09:52:29 -07002950 parent.addChildTab(tab);
2951 }
Michael Kolb519d2282011-05-09 17:03:19 -07002952 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07002953 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07002954 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002955 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002956 return tab;
2957 }
2958
2959 // this method will attempt to create a new tab
2960 // incognito: private browsing tab
2961 // setActive: ste tab as current tab
2962 // useCurrent: if no new tab can be created, return current tab
2963 private Tab createNewTab(boolean incognito, boolean setActive,
2964 boolean useCurrent) {
2965 Tab tab = null;
2966 if (mTabControl.canCreateNewTab()) {
2967 tab = mTabControl.createNewTab(incognito);
2968 addTab(tab);
2969 if (setActive) {
2970 setActiveTab(tab);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07002971 } else {
2972 tab.pause();
Michael Kolb7bcafde2011-05-09 13:55:59 -07002973 }
2974 } else {
2975 if (useCurrent) {
2976 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002977 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07002978 } else {
2979 mUi.showMaxTabsWarning();
2980 }
2981 }
2982 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07002983 }
2984
John Reck2bc80422011-06-30 15:11:49 -07002985 @Override
2986 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
2987 SnapshotTab tab = null;
2988 if (mTabControl.canCreateNewTab()) {
2989 tab = mTabControl.createSnapshotTab(snapshotId);
2990 addTab(tab);
2991 if (setActive) {
2992 setActiveTab(tab);
2993 }
2994 } else {
2995 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07002996 }
2997 return tab;
2998 }
2999
Michael Kolb8233fac2010-10-26 16:08:53 -07003000 /**
Michael Kolbc831b632011-05-11 09:30:34 -07003001 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07003002 * @return boolean True if we successfully switched to a different tab. If
3003 * the indexth tab is null, or if that tab is the same as
3004 * the current one, return false.
3005 */
3006 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07003007 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003008 Tab currentTab = mTabControl.getCurrentTab();
3009 if (tab == null || tab == currentTab) {
3010 return false;
3011 }
3012 setActiveTab(tab);
3013 return true;
3014 }
3015
3016 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07003017 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07003018 closeCurrentTab(false);
3019 }
3020
3021 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003022 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07003023 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07003024 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08003025 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07003026 return;
3027 }
Michael Kolbc831b632011-05-11 09:30:34 -07003028 final Tab current = mTabControl.getCurrentTab();
3029 final int pos = mTabControl.getCurrentPosition();
3030 Tab newTab = current.getParent();
3031 if (newTab == null) {
3032 newTab = mTabControl.getTab(pos + 1);
3033 if (newTab == null) {
3034 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07003035 }
3036 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07003037 if (andQuit) {
3038 mTabControl.setCurrentTab(newTab);
3039 closeTab(current);
3040 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003041 // Close window
3042 closeTab(current);
3043 }
3044 }
3045
3046 /**
3047 * Close the tab, remove its associated title bar, and adjust mTabControl's
3048 * current tab to a valid value.
3049 */
3050 @Override
3051 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07003052 if (tab == mTabControl.getCurrentTab()) {
3053 closeCurrentTab();
3054 } else {
3055 removeTab(tab);
3056 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003057 }
3058
Afzal Najamd4e33312012-04-26 01:54:01 -04003059 /**
3060 * Close all tabs except the current one
3061 */
3062 @Override
3063 public void closeOtherTabs() {
3064 int inactiveTabs = mTabControl.getTabCount() - 1;
3065 for (int i = inactiveTabs; i >= 0; i--) {
3066 Tab tab = mTabControl.getTab(i);
3067 if (tab != mTabControl.getCurrentTab()) {
3068 removeTab(tab);
3069 }
3070 }
3071 }
3072
Michael Kolb8233fac2010-10-26 16:08:53 -07003073 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07003074 protected void loadUrlFromContext(String url) {
3075 Tab tab = getCurrentTab();
3076 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07003077 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07003078 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003079 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixone1d6dfc2012-12-17 13:39:17 -08003080 if (!((BrowserWebView) view).getWebViewClient().
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00003081 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07003082 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07003083 }
3084 }
3085 }
3086
3087 /**
3088 * Load the URL into the given WebView and update the title bar
3089 * to reflect the new load. Call this instead of WebView.loadUrl
3090 * directly.
3091 * @param view The WebView used to load url.
3092 * @param url The URL to load.
3093 */
John Reck71e51422011-07-01 16:49:28 -07003094 @Override
3095 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07003096 loadUrl(tab, url, null);
3097 }
3098
3099 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
3100 if (tab != null) {
3101 dismissSubWindow(tab);
Vivek Sekhar0e10a202014-09-12 19:13:23 -07003102 mHomepageHandler.registerJsInterface(tab.getWebView(), url);
John Reck26b18322011-06-21 13:08:58 -07003103 tab.loadUrl(url, headers);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003104 if (tab.hasCrashed) {
3105 tab.replaceCrashView(tab.getWebView(), tab.getViewContainer());
3106 }
Michael Kolba53c9892011-10-05 13:31:40 -07003107 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07003108 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003109 }
3110
3111 /**
3112 * Load UrlData into a Tab and update the title bar to reflect the new
3113 * load. Call this instead of UrlData.loadIn directly.
3114 * @param t The Tab used to load.
3115 * @param data The UrlData being loaded.
3116 */
3117 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07003118 if (data != null) {
Michael Kolb5ff5c8b2012-05-03 11:37:58 -07003119 if (data.isPreloaded()) {
Michael Kolb14612442011-06-24 13:06:29 -07003120 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07003121 } else {
John Reck38b39652012-06-05 09:22:59 -07003122 if (t != null && data.mDisableUrlOverride) {
3123 t.disableUrlOverridingForLoad();
3124 }
John Reck26b18322011-06-21 13:08:58 -07003125 loadUrl(t, data.mUrl, data.mHeaders);
3126 }
3127 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003128 }
3129
John Reck30c714c2010-12-16 17:30:34 -08003130 @Override
3131 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08003132 // TODO: Figure out the "right" behavior
John Reckef654f12011-07-12 16:42:08 -07003133 if (tab.canGoBack()) {
3134 tab.goBack();
John Reck30c714c2010-12-16 17:30:34 -08003135 } else {
John Reckef654f12011-07-12 16:42:08 -07003136 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08003137 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003138 }
3139
3140 void goBackOnePageOrQuit() {
3141 Tab current = mTabControl.getCurrentTab();
3142 if (current == null) {
Panos Thomas4bdb5252014-11-13 16:20:11 -08003143 if (BrowserConfig.getInstance(getContext()).hasFeature(BrowserConfig.Feature.EXIT_DIALOG)) {
3144 showExitDialog(mActivity);
3145 } else {
3146 /*
3147 * Instead of finishing the activity, simply push this to the back
3148 * of the stack and let ActivityManager to choose the foreground
3149 * activity. As BrowserActivity is singleTask, it will be always the
3150 * root of the task. So we can use either true or false for
3151 * moveTaskToBack().
3152 */
3153 mActivity.moveTaskToBack(true);
3154 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003155 return;
3156 }
John Reckef654f12011-07-12 16:42:08 -07003157 if (current.canGoBack()) {
3158 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07003159 } else {
3160 // Check to see if we are closing a window that was created by
3161 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07003162 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07003163 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07003164 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07003165 // Now we close the other tab
3166 closeTab(current);
Panos Thomas4bdb5252014-11-13 16:20:11 -08003167 } else if (BrowserConfig.getInstance(getContext())
3168 .hasFeature(BrowserConfig.Feature.EXIT_DIALOG)) {
3169 showExitDialog(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -07003170 } else {
Panos Thomas4bdb5252014-11-13 16:20:11 -08003171 if ((current.getAppId() != null) || current.closeOnBack()) {
3172 closeCurrentTab(true);
3173 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003174 /*
3175 * Instead of finishing the activity, simply push this to the back
3176 * of the stack and let ActivityManager to choose the foreground
3177 * activity. As BrowserActivity is singleTask, it will be always the
3178 * root of the task. So we can use either true or false for
3179 * moveTaskToBack().
3180 */
Panos Thomas4bdb5252014-11-13 16:20:11 -08003181 mActivity.moveTaskToBack(true);
Michael Kolb8233fac2010-10-26 16:08:53 -07003182 }
3183 }
3184 }
3185
3186 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07003187 * helper method for key handler
3188 * returns the current tab if it can't advance
3189 */
Michael Kolbc831b632011-05-11 09:30:34 -07003190 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08003191 int pos = mTabControl.getCurrentPosition() + 1;
3192 if (pos >= mTabControl.getTabCount()) {
3193 pos = 0;
3194 }
3195 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07003196 }
3197
3198 /**
3199 * helper method for key handler
3200 * returns the current tab if it can't advance
3201 */
Michael Kolbc831b632011-05-11 09:30:34 -07003202 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08003203 int pos = mTabControl.getCurrentPosition() - 1;
3204 if ( pos < 0) {
3205 pos = mTabControl.getTabCount() - 1;
3206 }
3207 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07003208 }
3209
John Reckbcef87f2012-02-03 14:58:34 -08003210 boolean isMenuOrCtrlKey(int keyCode) {
3211 return (KeyEvent.KEYCODE_MENU == keyCode)
3212 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
3213 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
3214 }
3215
Michael Kolb0035fad2011-03-14 13:25:28 -07003216 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07003217 * handle key events in browser
3218 *
3219 * @param keyCode
3220 * @param event
3221 * @return true if handled, false to pass to super
3222 */
John Reck9c35b9c2012-05-30 10:08:50 -07003223 @Override
3224 public boolean onKeyDown(int keyCode, KeyEvent event) {
Pankaj Garg49b79252014-11-07 17:33:41 -08003225 if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
3226 // Hardware menu key
Enrico Ros1f5a0952014-11-18 20:15:48 -08003227 mAppMenuHandler.showAppMenu(mActivity.findViewById(R.id.taburlbar),
Pankaj Garg49b79252014-11-07 17:33:41 -08003228 true, false);
3229 return true;
3230 }
3231
Cary Clark160bbb92011-01-10 11:17:07 -05003232 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07003233 // Even if MENU is already held down, we need to call to super to open
3234 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08003235 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003236 mMenuIsDown = true;
3237 return false;
3238 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003239
Cary Clark8ff8c662010-12-29 15:03:05 -05003240 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07003241 Tab tab = getCurrentTab();
3242 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05003243
Cary Clark160bbb92011-01-10 11:17:07 -05003244 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
3245 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05003246
Michael Kolb8233fac2010-10-26 16:08:53 -07003247 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07003248 case KeyEvent.KEYCODE_TAB:
3249 if (event.isCtrlPressed()) {
3250 if (event.isShiftPressed()) {
3251 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07003252 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07003253 } else {
3254 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07003255 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07003256 }
3257 return true;
3258 }
3259 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07003260 case KeyEvent.KEYCODE_SPACE:
3261 // WebView/WebTextView handle the keys in the KeyDown. As
3262 // the Activity's shortcut keys are only handled when WebView
3263 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05003264 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003265 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05003266 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003267 pageDown();
3268 }
3269 return true;
3270 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05003271 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08003272 event.startTracking();
3273 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07003274 case KeyEvent.KEYCODE_FORWARD:
3275 if (!noModifiers) break;
3276 tab.goForward();
3277 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05003278 case KeyEvent.KEYCODE_DPAD_LEFT:
3279 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07003280 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05003281 return true;
3282 }
3283 break;
3284 case KeyEvent.KEYCODE_DPAD_RIGHT:
3285 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07003286 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05003287 return true;
3288 }
3289 break;
3290 case KeyEvent.KEYCODE_A:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003291 if (ctrl) {
3292 webView.selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05003293 return true;
3294 }
3295 break;
Michael Kolba4183062011-01-16 10:43:21 -08003296// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003297 case KeyEvent.KEYCODE_C:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003298 if (ctrl ) {
3299 webView.copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05003300 return true;
3301 }
3302 break;
Michael Kolba4183062011-01-16 10:43:21 -08003303// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003304// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08003305// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003306// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08003307// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003308// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08003309// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003310// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08003311// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003312// case KeyEvent.KEYCODE_M: // unused
3313// case KeyEvent.KEYCODE_N: // in Chrome: new window
3314// case KeyEvent.KEYCODE_O: // in Chrome: open file
3315// case KeyEvent.KEYCODE_P: // in Chrome: print page
3316// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003317// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05003318// case KeyEvent.KEYCODE_S: // in Chrome: saves page
3319 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003320 // we can't use the ctrl/shift flags, they check for
3321 // exclusive use of a modifier
3322 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05003323 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07003324 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05003325 } else {
3326 openTabToHomePage();
3327 }
3328 return true;
3329 }
3330 break;
3331// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
3332// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07003333// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003334// case KeyEvent.KEYCODE_X: // text view intercepts to cut
3335// case KeyEvent.KEYCODE_Y: // unused
3336// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07003337 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003338 // it is a regular key and webview is not null
3339 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07003340 }
3341
John Reck9c35b9c2012-05-30 10:08:50 -07003342 @Override
3343 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
John Recke6bf4ab2011-02-24 15:48:05 -08003344 switch(keyCode) {
3345 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07003346 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07003347 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08003348 return true;
3349 }
3350 break;
3351 }
3352 return false;
3353 }
3354
John Reck9c35b9c2012-05-30 10:08:50 -07003355 @Override
3356 public boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08003357 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07003358 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08003359 if (KeyEvent.KEYCODE_MENU == keyCode
3360 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07003361 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07003362 }
3363 }
Cary Clark160bbb92011-01-10 11:17:07 -05003364 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07003365 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003366 case KeyEvent.KEYCODE_BACK:
3367 if (event.isTracking() && !event.isCanceled()) {
3368 onBackKey();
3369 return true;
3370 }
3371 break;
3372 }
3373 return false;
3374 }
3375
3376 public boolean isMenuDown() {
3377 return mMenuIsDown;
3378 }
3379
John Reck9c35b9c2012-05-30 10:08:50 -07003380 @Override
Ben Murdoch8029a772010-11-16 11:58:21 +00003381 public void setupAutoFill(Message message) {
3382 // Open the settings activity at the AutoFill profile fragment so that
3383 // the user can create a new profile. When they return, we will dispatch
3384 // the message so that we can autofill the form using their new profile.
Ben Murdoch8029a772010-11-16 11:58:21 +00003385 mAutoFillSetupMessage = message;
Enrico Rosd6efa972014-12-02 19:49:59 -08003386 BrowserPreferencesPage.startPreferenceFragmentForResult(mActivity,
3387 AutoFillSettingsFragment.class.getName(), AUTOFILL_SETUP);
Ben Murdoch8029a772010-11-16 11:58:21 +00003388 }
John Reckb3417f02011-01-14 11:01:05 -08003389
John Reck9c35b9c2012-05-30 10:08:50 -07003390 @Override
Michael Kolbfbc579a2011-07-07 15:59:33 -07003391 public boolean onSearchRequested() {
Michael Kolb1f9b3562012-04-24 14:38:34 -07003392 mUi.editUrl(false, true);
Michael Kolbfbc579a2011-07-07 15:59:33 -07003393 return true;
3394 }
3395
John Reck1cf4b792011-07-26 10:22:22 -07003396 @Override
3397 public boolean shouldCaptureThumbnails() {
3398 return mUi.shouldCaptureThumbnails();
3399 }
3400
Michael Kolbc3af0672011-08-09 10:24:41 -07003401 @Override
Michael Kolb0b129122012-06-04 16:31:58 -07003402 public boolean supportsVoice() {
3403 PackageManager pm = mActivity.getPackageManager();
3404 List activities = pm.queryIntentActivities(new Intent(
3405 RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
3406 return activities.size() != 0;
3407 }
3408
3409 @Override
3410 public void startVoiceRecognizer() {
3411 Intent voice = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003412 voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
Michael Kolb0b129122012-06-04 16:31:58 -07003413 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
3414 voice.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
3415 mActivity.startActivityForResult(voice, VOICE_RESULT);
3416 }
3417
Pankaj Garg7b279f62014-08-12 14:47:18 -07003418 public void setWindowDimming(float level) {
3419 if (level != 0) {
3420 WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
3421 lp.dimAmount = level;
3422 mActivity.getWindow().setAttributes(lp);
3423 mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
3424 } else {
3425 mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
3426 }
3427 }
3428
Michael Kolb0b129122012-06-04 16:31:58 -07003429 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003430 public void setBlockEvents(boolean block) {
3431 mBlockEvents = block;
3432 }
3433
John Reck9c35b9c2012-05-30 10:08:50 -07003434 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003435 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07003436 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003437 }
3438
John Reck9c35b9c2012-05-30 10:08:50 -07003439 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003440 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07003441 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003442 }
3443
John Reck9c35b9c2012-05-30 10:08:50 -07003444 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003445 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003446 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003447 }
3448
John Reck9c35b9c2012-05-30 10:08:50 -07003449 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003450 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003451 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003452 }
3453
John Reck9c35b9c2012-05-30 10:08:50 -07003454 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003455 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003456 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003457 }
3458
Pankaj Garg49b79252014-11-07 17:33:41 -08003459 @Override
3460 public boolean shouldShowAppMenu() {
3461 return true;
3462 }
3463
3464 @Override
3465 public int getMenuThemeResourceId() {
3466 return R.style.OverflowMenuTheme;
3467 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003468}