blob: 62f3e10753fbcec4b7c8d807e65cb8b943e2a93b [file] [log] [blame]
Michael Kolb8233fac2010-10-26 16:08:53 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Bijan Amirzada41242f22014-03-21 12:12:18 -070017package com.android.browser;
Michael Kolb8233fac2010-10-26 16:08:53 -070018
Michael Kolb8233fac2010-10-26 16:08:53 -070019import android.app.Activity;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080020
luxiaolb40014b2013-07-19 10:01:43 +080021import android.app.AlertDialog;
John Reck68234a92012-04-19 15:27:12 -070022import android.app.Dialog;
Michael Kolb8233fac2010-10-26 16:08:53 -070023import android.app.DownloadManager;
John Reck68234a92012-04-19 15:27:12 -070024import android.app.ProgressDialog;
Vivek Sekharce2a4832014-03-26 13:26:53 -070025import android.content.Context;
Michael Kolb8233fac2010-10-26 16:08:53 -070026import android.content.ClipboardManager;
Michael Kolb8233fac2010-10-26 16:08:53 -070027import android.content.ContentResolver;
John Reckd8c74522011-06-14 08:45:00 -070028import android.content.ContentUris;
Michael Kolb8233fac2010-10-26 16:08:53 -070029import android.content.ContentValues;
John Reck68234a92012-04-19 15:27:12 -070030import android.content.DialogInterface;
31import android.content.DialogInterface.OnCancelListener;
Michael Kolb8233fac2010-10-26 16:08:53 -070032import android.content.Intent;
33import android.content.pm.PackageManager;
34import android.content.pm.ResolveInfo;
35import android.content.res.Configuration;
John Reck30b065e2011-07-19 10:58:05 -070036import android.content.res.TypedArray;
Leon Scroggins1961ed22010-12-07 15:22:21 -050037import android.database.ContentObserver;
Michael Kolb8233fac2010-10-26 16:08:53 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Mattias Nilsson561d1952011-10-04 10:18:50 +020040import android.database.sqlite.SQLiteException;
Michael Kolb8233fac2010-10-26 16:08:53 -070041import android.graphics.Bitmap;
kaiyiz6e5b3e02013-08-19 20:02:01 +080042import android.graphics.BitmapFactory;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080043import android.graphics.Rect;
kaiyiza016da12013-08-26 17:50:22 +080044import android.net.ConnectivityManager;
45import android.net.NetworkInfo;
Michael Kolb8233fac2010-10-26 16:08:53 -070046import android.net.Uri;
47import android.net.http.SslError;
kaiyiza016da12013-08-26 17:50:22 +080048import android.net.wifi.WifiManager;
kaiyizb7bf1f22013-10-02 11:42:23 +080049import android.net.wifi.ScanResult;
Michael Kolb8233fac2010-10-26 16:08:53 -070050import android.os.AsyncTask;
51import android.os.Bundle;
George Mount387d45d2011-10-07 15:57:53 -070052import android.os.Environment;
Michael Kolb8233fac2010-10-26 16:08:53 -070053import android.os.Handler;
54import android.os.Message;
55import android.os.PowerManager;
56import android.os.PowerManager.WakeLock;
Michael Kolb8233fac2010-10-26 16:08:53 -070057import android.provider.ContactsContract;
58import android.provider.ContactsContract.Intents.Insert;
kaiyiza016da12013-08-26 17:50:22 +080059import android.provider.Settings;
Michael Kolb0b129122012-06-04 16:31:58 -070060import android.speech.RecognizerIntent;
Michael Kolb8233fac2010-10-26 16:08:53 -070061import android.text.TextUtils;
62import android.util.Log;
John Recka00cbbd2010-12-16 12:38:19 -080063import android.util.Patterns;
Michael Kolb8233fac2010-10-26 16:08:53 -070064import android.view.ActionMode;
65import android.view.ContextMenu;
66import android.view.ContextMenu.ContextMenuInfo;
67import android.view.Gravity;
68import android.view.KeyEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070069import android.view.Menu;
70import android.view.MenuInflater;
71import android.view.MenuItem;
72import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolbc3af0672011-08-09 10:24:41 -070073import android.view.MotionEvent;
Michael Kolb8233fac2010-10-26 16:08:53 -070074import android.view.View;
Pankaj Garg7b279f62014-08-12 14:47:18 -070075import android.view.WindowManager;
George Mount387d45d2011-10-07 15:57:53 -070076import android.webkit.MimeTypeMap;
Michael Kolb8233fac2010-10-26 16:08:53 -070077import android.webkit.ValueCallback;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080078import android.webkit.WebChromeClient.CustomViewCallback;
Pankaj Garg49b79252014-11-07 17:33:41 -080079import android.widget.EditText;
Leon Scrogginsac993842011-02-02 12:54:07 -050080import android.widget.Toast;
Michael Kolb8233fac2010-10-26 16:08:53 -070081
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080082import org.codeaurora.swe.CookieManager;
83import org.codeaurora.swe.CookieSyncManager;
Pankaj Garg18902562014-12-05 16:18:51 -080084import org.codeaurora.swe.Engine;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080085import org.codeaurora.swe.HttpAuthHandler;
86import org.codeaurora.swe.SslErrorHandler;
87import org.codeaurora.swe.WebSettings;
88import org.codeaurora.swe.WebView;
Vivek Sekhar0e10a202014-09-12 19:13:23 -070089import org.codeaurora.swe.WebBackForwardList;
90import org.codeaurora.swe.WebHistoryItem;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080091
Axesh R. Ajmera34d3f142014-06-30 20:05:36 -070092import com.android.browser.AppAdapter;
Bijan Amirzada41242f22014-03-21 12:12:18 -070093import com.android.browser.R;
94import com.android.browser.IntentHandler.UrlData;
95import com.android.browser.UI.ComboViews;
96import com.android.browser.mynavigation.AddMyNavigationPage;
97import com.android.browser.mynavigation.MyNavigationUtil;
Bijan Amirzada3f04dc72014-06-25 11:48:36 -070098import com.android.browser.platformsupport.Browser;
Bijan Amirzada41242f22014-03-21 12:12:18 -070099import com.android.browser.platformsupport.BrowserContract;
100import com.android.browser.platformsupport.WebAddress;
101import com.android.browser.platformsupport.BrowserContract.Images;
Pankaj Garg18902562014-12-05 16:18:51 -0800102import com.android.browser.preferences.AboutPreferencesFragment;
Bijan Amirzada41242f22014-03-21 12:12:18 -0700103import com.android.browser.provider.BrowserProvider2.Thumbnails;
104import com.android.browser.provider.SnapshotProvider.Snapshots;
105import com.android.browser.reflect.ReflectHelper;
Pankaj Garg49b79252014-11-07 17:33:41 -0800106import com.android.browser.appmenu.AppMenuHandler;
107import com.android.browser.appmenu.AppMenuPropertiesDelegate;
Michael Kolb4bd767d2011-05-27 11:33:55 -0700108
Michael Kolb8233fac2010-10-26 16:08:53 -0700109import java.io.ByteArrayOutputStream;
George Mount387d45d2011-10-07 15:57:53 -0700110import java.io.File;
111import java.io.FileOutputStream;
112import java.io.IOException;
Michael Kolb8233fac2010-10-26 16:08:53 -0700113import java.net.URLEncoder;
George Mount387d45d2011-10-07 15:57:53 -0700114import java.text.DateFormat;
115import java.text.SimpleDateFormat;
John Reck1cf4b792011-07-26 10:22:22 -0700116import java.util.ArrayList;
George Mount387d45d2011-10-07 15:57:53 -0700117import java.util.Date;
Michael Kolb8233fac2010-10-26 16:08:53 -0700118import java.util.HashMap;
Michael Kolb1bf23132010-11-19 12:55:12 -0800119import java.util.List;
Johan Redestigaa676182012-10-03 13:33:01 +0200120import java.util.Locale;
John Reck26b18322011-06-21 13:08:58 -0700121import java.util.Map;
Michael Kolb8233fac2010-10-26 16:08:53 -0700122
123/**
124 * Controller for browser
125 */
126public class Controller
Pankaj Garg49b79252014-11-07 17:33:41 -0800127 implements WebViewController, UiController, ActivityController,
128 AppMenuPropertiesDelegate {
Michael Kolb8233fac2010-10-26 16:08:53 -0700129
130 private static final String LOGTAG = "Controller";
Michael Kolbcfa3af52010-12-14 10:36:11 -0800131 private static final String SEND_APP_ID_EXTRA =
132 "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolba4261fd2011-05-05 11:27:37 -0700133 private static final String INCOGNITO_URI = "browser:incognito";
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800134
Vivek Sekharb54614f2014-05-01 19:03:37 -0700135 // Remind switch to data connection if wifi is unavailable
136 private static final int NETWORK_SWITCH_TYPE_OK = 1;
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800137
Michael Kolb8233fac2010-10-26 16:08:53 -0700138 // public message ids
139 public final static int LOAD_URL = 1001;
140 public final static int STOP_LOAD = 1002;
141
142 // Message Ids
143 private static final int FOCUS_NODE_HREF = 102;
144 private static final int RELEASE_WAKELOCK = 107;
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -0800145 private static final int UNKNOWN_TYPE_MSG = 109;
Michael Kolb8233fac2010-10-26 16:08:53 -0700146
147 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
148
149 private static final int OPEN_BOOKMARKS = 201;
kaiyiz591110b2013-08-06 17:11:06 +0800150 private static final int OPEN_MENU = 202;
Michael Kolb8233fac2010-10-26 16:08:53 -0700151
152 private static final int EMPTY_MENU = -1;
153
Michael Kolb8233fac2010-10-26 16:08:53 -0700154 // activity requestCode
John Reckd3e4d5b2011-07-13 15:48:43 -0700155 final static int COMBO_VIEW = 1;
Michael Kolb8233fac2010-10-26 16:08:53 -0700156 final static int PREFERENCES_PAGE = 3;
157 final static int FILE_SELECTED = 4;
Ben Murdoch8029a772010-11-16 11:58:21 +0000158 final static int AUTOFILL_SETUP = 5;
Michael Kolb0b129122012-06-04 16:31:58 -0700159 final static int VOICE_RESULT = 6;
kaiyiz6e5b3e02013-08-19 20:02:01 +0800160 final static int MY_NAVIGATION = 7;
Ben Murdoch8029a772010-11-16 11:58:21 +0000161
Michael Kolb8233fac2010-10-26 16:08:53 -0700162 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
163
164 // As the ids are dynamically created, we can't guarantee that they will
165 // be in sequence, so this static array maps ids to a window number.
166 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
167 { R.id.window_one_menu_id, R.id.window_two_menu_id,
168 R.id.window_three_menu_id, R.id.window_four_menu_id,
169 R.id.window_five_menu_id, R.id.window_six_menu_id,
170 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
171
172 // "source" parameter for Google search through search key
173 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
174 // "source" parameter for Google search through simplily type
175 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
176
George Mount387d45d2011-10-07 15:57:53 -0700177 // "no-crash-recovery" parameter in intent to suppress crash recovery
Guang Zhu9e78f512011-05-04 11:45:11 -0700178 final static String NO_CRASH_RECOVERY = "no-crash-recovery";
179
John Reckd7dd9b22011-08-30 09:18:29 -0700180 // A bitmap that is re-used in createScreenshot as scratch space
181 private static Bitmap sThumbnailBitmap;
182
Michael Kolb8233fac2010-10-26 16:08:53 -0700183 private Activity mActivity;
184 private UI mUi;
Vivek Sekhar0e10a202014-09-12 19:13:23 -0700185 private HomepageHandler mHomepageHandler;
186 protected TabControl mTabControl;
Michael Kolb8233fac2010-10-26 16:08:53 -0700187 private BrowserSettings mSettings;
188 private WebViewFactory mFactory;
189
190 private WakeLock mWakeLock;
191
192 private UrlHandler mUrlHandler;
193 private UploadHandler mUploadHandler;
194 private IntentHandler mIntentHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700195 private PageDialogsHandler mPageDialogsHandler;
196 private NetworkStateHandler mNetworkHandler;
197
Ben Murdoch8029a772010-11-16 11:58:21 +0000198 private Message mAutoFillSetupMessage;
199
Michael Kolb8233fac2010-10-26 16:08:53 -0700200 private boolean mShouldShowErrorConsole;
kaiyiza016da12013-08-26 17:50:22 +0800201 private boolean mNetworkShouldNotify = true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700202
Michael Kolb8233fac2010-10-26 16:08:53 -0700203 // FIXME, temp address onPrepareMenu performance problem.
204 // When we move everything out of view, we should rewrite this.
205 private int mCurrentMenuState = 0;
Kulanthaivel Palanichamy77942682014-10-28 11:52:06 -0700206 private int mMenuState = EMPTY_MENU;
Michael Kolb8233fac2010-10-26 16:08:53 -0700207 private int mOldMenuState = EMPTY_MENU;
208 private Menu mCachedMenu;
209
Michael Kolb8233fac2010-10-26 16:08:53 -0700210 private boolean mMenuIsDown;
211
Pankaj Garg49b79252014-11-07 17:33:41 -0800212 private boolean mWasInPageLoad = false;
213 private AppMenuHandler mAppMenuHandler;
214
Michael Kolb8233fac2010-10-26 16:08:53 -0700215 // For select and find, we keep track of the ActionMode so that
216 // finish() can be called as desired.
217 private ActionMode mActionMode;
218
219 /**
220 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
221 * of whether the configuration has changed. The first onMenuOpened call
222 * after a configuration change is simply a reopening of the same menu
223 * (i.e. mIconView did not change).
224 */
225 private boolean mConfigChanged;
226
227 /**
228 * Keeps track of whether the options menu is open. This is important in
229 * determining whether to show or hide the title bar overlay
230 */
231 private boolean mOptionsMenuOpen;
232
233 /**
234 * Whether or not the options menu is in its bigger, popup menu form. When
235 * true, we want the title bar overlay to be gone. When false, we do not.
236 * Only meaningful if mOptionsMenuOpen is true.
237 */
238 private boolean mExtendedMenuOpen;
239
Michael Kolb8233fac2010-10-26 16:08:53 -0700240 private boolean mActivityPaused = true;
241 private boolean mLoadStopped;
242
243 private Handler mHandler;
Leon Scroggins1961ed22010-12-07 15:22:21 -0500244 // Checks to see when the bookmarks database has changed, and updates the
245 // Tabs' notion of whether they represent bookmarked sites.
246 private ContentObserver mBookmarksObserver;
John Reck847b5322011-04-14 17:02:18 -0700247 private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb8233fac2010-10-26 16:08:53 -0700248
Michael Kolbc3af0672011-08-09 10:24:41 -0700249 private boolean mBlockEvents;
250
Michael Kolb0b129122012-06-04 16:31:58 -0700251 private String mVoiceResult;
kaiyiz6e5b3e02013-08-19 20:02:01 +0800252 private boolean mUpdateMyNavThumbnail;
253 private String mUpdateMyNavThumbnailUrl;
Vivek Sekharb991edb2014-12-17 18:18:07 -0800254 private float mLevel = 0.0f;
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -0800255 private WebView.HitTestResult mResult;
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;
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -0800507 case UNKNOWN_TYPE_MSG:
508 HashMap unknownTypeMap = (HashMap) msg.obj;
509 WebView viewForUnknownType = (WebView) unknownTypeMap.get("webview");
510 /*
511 * When the context menu is shown to the user
512 * we need to assure that its happening on the current webview
513 * and its the current webview only which had sent the UNKNOWN_TYPE_MSG
514 */
515 if (getCurrentWebView() != viewForUnknownType)
516 break;
517
518 String unknown_type_src = (String)msg.getData().get("src");
519 WebView.HitTestResult result = new WebView.HitTestResult();
520
521 //setting the HitTestResult with new RESULT TYPE
522 if (!TextUtils.isEmpty(unknown_type_src)) {
523 result.setType(WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
524 result.setExtra(unknown_type_src);
525 } else {
526 result.setType(WebView.HitTestResult.SRC_ANCHOR_TYPE);
527 result.setExtra("about:blank");
528 }
529
530 mResult = result;
531 openContextMenu(viewForUnknownType);
532 mResult = null;
533
534 break;
535
Michael Kolb8233fac2010-10-26 16:08:53 -0700536 case FOCUS_NODE_HREF:
537 {
538 String url = (String) msg.getData().get("url");
539 String title = (String) msg.getData().get("title");
Cary Clark043c2d62010-12-15 11:19:39 -0500540 String src = (String) msg.getData().get("src");
541 if (url == "") url = src; // use image if no anchor
Michael Kolb8233fac2010-10-26 16:08:53 -0700542 if (TextUtils.isEmpty(url)) {
543 break;
544 }
545 HashMap focusNodeMap = (HashMap) msg.obj;
546 WebView view = (WebView) focusNodeMap.get("webview");
547 // Only apply the action if the top window did not change.
548 if (getCurrentTopWebView() != view) {
549 break;
550 }
551 switch (msg.arg1) {
552 case R.id.open_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700553 loadUrlFromContext(url);
Michael Kolb8233fac2010-10-26 16:08:53 -0700554 break;
Cary Clark043c2d62010-12-15 11:19:39 -0500555 case R.id.view_image_context_menu_id:
John Reck26b18322011-06-21 13:08:58 -0700556 loadUrlFromContext(src);
Cary Clark043c2d62010-12-15 11:19:39 -0500557 break;
Leon Scroggins026f2542010-11-22 13:26:12 -0500558 case R.id.open_newtab_context_menu_id:
559 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -0700560 openTab(url, parent,
561 !mSettings.openInBackground(), true);
Leon Scroggins026f2542010-11-22 13:26:12 -0500562 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700563 case R.id.copy_link_context_menu_id:
564 copy(url);
565 break;
566 case R.id.save_link_context_menu_id:
567 case R.id.download_context_menu_id:
Leon Scroggins63c02662010-11-18 15:16:27 -0500568 DownloadHandler.onDownloadStartNoStream(
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800569 mActivity, url, view.getSettings().getUserAgentString(),
570 null, null, null, view.isPrivateBrowsingEnabled(), 0);
Michael Kolb8233fac2010-10-26 16:08:53 -0700571 break;
Tarun Nainani700b69b2014-03-26 16:07:25 -0700572 case R.id.save_link_bookmark_context_menu_id:
Tarun Nainani9f27c612014-04-02 14:34:03 -0700573 if(title == null || title == "")
574 title = url;
575
576 Intent bookmarkIntent = new Intent(mActivity, AddBookmarkPage.class);
577 //SWE TODO: No thumbnail support for the url obtained via
578 //browser context menu as its not loaded in webview.
579 if (bookmarkIntent != null) {
580 bookmarkIntent.putExtra(BrowserContract.Bookmarks.URL, url);
581 bookmarkIntent.putExtra(BrowserContract.Bookmarks.TITLE, title);
582 mActivity.startActivity(bookmarkIntent);
583 }
Tarun Nainani700b69b2014-03-26 16:07:25 -0700584 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700585 }
586 break;
587 }
588
589 case LOAD_URL:
John Reck26b18322011-06-21 13:08:58 -0700590 loadUrlFromContext((String) msg.obj);
Michael Kolb8233fac2010-10-26 16:08:53 -0700591 break;
592
593 case STOP_LOAD:
594 stopLoading();
595 break;
596
597 case RELEASE_WAKELOCK:
John Reckf57c0292011-07-21 18:15:39 -0700598 if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700599 mWakeLock.release();
600 // if we reach here, Browser should be still in the
601 // background loading after WAKELOCK_TIMEOUT (5-min).
602 // To avoid burning the battery, stop loading.
603 mTabControl.stopAllLoading();
604 }
605 break;
606
607 case UPDATE_BOOKMARK_THUMBNAIL:
John Reck34ef2672011-02-10 11:30:55 -0800608 Tab tab = (Tab) msg.obj;
609 if (tab != null) {
610 updateScreenshot(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700611 }
612 break;
kaiyiz591110b2013-08-06 17:11:06 +0800613 case OPEN_MENU:
614 if (!mOptionsMenuOpen && mActivity != null ) {
615 mActivity.openOptionsMenu();
616 }
617 break;
Michael Kolb8233fac2010-10-26 16:08:53 -0700618 }
619 }
620 };
621
622 }
623
John Reckef654f12011-07-12 16:42:08 -0700624 @Override
Martijn Coenenb2f93552011-06-14 10:48:35 +0200625 public Tab getCurrentTab() {
626 return mTabControl.getCurrentTab();
627 }
628
Michael Kolbba99c5d2010-11-29 14:57:41 -0800629 @Override
630 public void shareCurrentPage() {
631 shareCurrentPage(mTabControl.getCurrentTab());
632 }
633
634 private void shareCurrentPage(Tab tab) {
Tarun Nainaniea28dde2014-08-27 17:25:09 -0700635 if (tab == null || tab.getWebView() == null)
636 return;
637
638 final Tab mytab = tab;
639 final ValueCallback<Bitmap> onScreenshot = new ValueCallback<Bitmap>() {
640 @Override
641 public void onReceiveValue(Bitmap bitmap) {
642 sharePage(mActivity, mytab.getTitle(), mytab.getUrl(),
643 mytab.getFavicon(), bitmap);
644 }
645 };
646
647 createScreenshotAsync(
648 tab.getWebView(),
649 getDesiredThumbnailWidth(mActivity),
650 getDesiredThumbnailHeight(mActivity),
651 new ValueCallback<Bitmap>() {
652 @Override
653 public void onReceiveValue(Bitmap bitmap) {
654 sharePage(mActivity, mytab.getTitle(), mytab.getUrl(),
655 mytab.getFavicon(), bitmap);
656 }
657 });
Michael Kolbba99c5d2010-11-29 14:57:41 -0800658 }
659
Michael Kolb8233fac2010-10-26 16:08:53 -0700660 /**
661 * Share a page, providing the title, url, favicon, and a screenshot. Uses
662 * an {@link Intent} to launch the Activity chooser.
663 * @param c Context used to launch a new Activity.
664 * @param title Title of the page. Stored in the Intent with
665 * {@link Intent#EXTRA_SUBJECT}
666 * @param url URL of the page. Stored in the Intent with
667 * {@link Intent#EXTRA_TEXT}
668 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
669 * with {@link Browser#EXTRA_SHARE_FAVICON}
670 * @param screenshot Bitmap of a screenshot of the page. Stored in the
671 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
672 */
673 static final void sharePage(Context c, String title, String url,
674 Bitmap favicon, Bitmap screenshot) {
Axesh R. Ajmera34d3f142014-06-30 20:05:36 -0700675
676 ShareDialog sDialog = new ShareDialog((Activity)c, title, url, favicon, screenshot);
677 final AppAdapter adapter = new AppAdapter(c, c.getPackageManager(),
678 R.layout.app_row, sDialog.getApps());
679 sDialog.loadView(adapter);
Michael Kolb8233fac2010-10-26 16:08:53 -0700680 }
681
682 private void copy(CharSequence text) {
683 ClipboardManager cm = (ClipboardManager) mActivity
684 .getSystemService(Context.CLIPBOARD_SERVICE);
685 cm.setText(text);
686 }
687
688 // lifecycle
689
John Reck9c35b9c2012-05-30 10:08:50 -0700690 @Override
691 public void onConfgurationChanged(Configuration config) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700692 mConfigChanged = true;
Michael Kolb18f252f2012-03-06 13:36:20 -0800693 // update the menu in case of a locale change
694 mActivity.invalidateOptionsMenu();
Pankaj Garg49b79252014-11-07 17:33:41 -0800695 mAppMenuHandler.hideAppMenu();
kaiyiz591110b2013-08-06 17:11:06 +0800696 if (mOptionsMenuOpen) {
697 mActivity.closeOptionsMenu();
698 mHandler.sendMessageDelayed(mHandler.obtainMessage(OPEN_MENU), 100);
699 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700700 if (mPageDialogsHandler != null) {
701 mPageDialogsHandler.onConfigurationChanged(config);
702 }
703 mUi.onConfigurationChanged(config);
704 }
705
706 @Override
707 public void handleNewIntent(Intent intent) {
Michael Kolb59e232c2011-08-18 17:19:53 -0700708 if (!mUi.isWebShowing()) {
709 mUi.showWeb(false);
710 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700711 mIntentHandler.onNewIntent(intent);
712 }
713
John Reck9c35b9c2012-05-30 10:08:50 -0700714 @Override
715 public void onPause() {
Michael Kolb11fe02d2011-02-02 09:52:16 -0800716 if (mUi.isCustomViewShowing()) {
717 hideCustomView();
718 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700719 if (mActivityPaused) {
720 Log.e(LOGTAG, "BrowserActivity is already paused.");
721 return;
722 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700723 mActivityPaused = true;
Michael Kolb70976932010-11-30 11:34:01 -0800724 Tab tab = mTabControl.getCurrentTab();
725 if (tab != null) {
726 tab.pause();
727 if (!pauseWebViewTimers(tab)) {
John Reckf57c0292011-07-21 18:15:39 -0700728 if (mWakeLock == null) {
729 PowerManager pm = (PowerManager) mActivity
730 .getSystemService(Context.POWER_SERVICE);
731 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
732 }
Michael Kolb70976932010-11-30 11:34:01 -0800733 mWakeLock.acquire();
734 mHandler.sendMessageDelayed(mHandler
735 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
736 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700737 }
738 mUi.onPause();
739 mNetworkHandler.onPause();
740
741 WebView.disablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100742 NfcHandler.unregister(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -0700743 }
744
John Reck9c35b9c2012-05-30 10:08:50 -0700745 @Override
746 public void onSaveInstanceState(Bundle outState) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700747 // Save all the tabs
George Mount3636d0a2011-11-21 09:08:21 -0800748 Bundle saveState = createSaveState();
749
750 // crash recovery manages all save & restore state
751 mCrashRecoveryHandler.writeState(saveState);
752 mSettings.setLastRunPaused(true);
753 }
754
755 /**
756 * Save the current state to outState. Does not write the state to
757 * disk.
758 * @return Bundle containing the current state of all tabs.
759 */
760 /* package */ Bundle createSaveState() {
761 Bundle saveState = new Bundle();
762 mTabControl.saveState(saveState);
George Mount3636d0a2011-11-21 09:08:21 -0800763 return saveState;
Michael Kolb8233fac2010-10-26 16:08:53 -0700764 }
765
John Reck9c35b9c2012-05-30 10:08:50 -0700766 @Override
767 public void onResume() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700768 if (!mActivityPaused) {
769 Log.e(LOGTAG, "BrowserActivity is already resumed.");
770 return;
771 }
George Mount3636d0a2011-11-21 09:08:21 -0800772 mSettings.setLastRunPaused(false);
Michael Kolb8233fac2010-10-26 16:08:53 -0700773 mActivityPaused = false;
Michael Kolb70976932010-11-30 11:34:01 -0800774 Tab current = mTabControl.getCurrentTab();
775 if (current != null) {
776 current.resume();
777 resumeWebViewTimers(current);
778 }
John Reckf57c0292011-07-21 18:15:39 -0700779 releaseWakeLock();
Martijn Coenenb2f93552011-06-14 10:48:35 +0200780
Michael Kolb8233fac2010-10-26 16:08:53 -0700781 mUi.onResume();
782 mNetworkHandler.onResume();
783 WebView.enablePlatformNotifications();
Ben Murdoch015e1e32011-09-01 23:45:31 +0100784 NfcHandler.register(mActivity, this);
Michael Kolb0b129122012-06-04 16:31:58 -0700785 if (mVoiceResult != null) {
786 mUi.onVoiceResult(mVoiceResult);
787 mVoiceResult = null;
788 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800789 if (current != null && current.hasCrashed) {
Vivek Sekhar2868b8d2014-12-03 17:22:50 -0800790 current.replaceCrashView(current.getWebView(), current.getViewContainer());
Bijan Amirzada9b1e9882014-02-26 17:15:46 -0800791 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700792 }
793
John Reckf57c0292011-07-21 18:15:39 -0700794 private void releaseWakeLock() {
795 if (mWakeLock != null && mWakeLock.isHeld()) {
796 mHandler.removeMessages(RELEASE_WAKELOCK);
797 mWakeLock.release();
798 }
799 }
800
Michael Kolb70976932010-11-30 11:34:01 -0800801 /**
Michael Kolbba99c5d2010-11-29 14:57:41 -0800802 * resume all WebView timers using the WebView instance of the given tab
Michael Kolb70976932010-11-30 11:34:01 -0800803 * @param tab guaranteed non-null
804 */
805 private void resumeWebViewTimers(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700806 boolean inLoad = tab.inPageLoad();
807 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
808 CookieSyncManager.getInstance().startSync();
809 WebView w = tab.getWebView();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100810 WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb8233fac2010-10-26 16:08:53 -0700811 }
812 }
813
Michael Kolb70976932010-11-30 11:34:01 -0800814 /**
815 * Pause all WebView timers using the WebView of the given tab
816 * @param tab
817 * @return true if the timers are paused or tab is null
818 */
819 private boolean pauseWebViewTimers(Tab tab) {
820 if (tab == null) {
821 return true;
822 } else if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700823 CookieSyncManager.getInstance().stopSync();
Mathew Inwoode1dbb952011-07-08 17:27:38 +0100824 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb8233fac2010-10-26 16:08:53 -0700825 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -0700826 }
Michael Kolb70976932010-11-30 11:34:01 -0800827 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700828 }
829
John Reck9c35b9c2012-05-30 10:08:50 -0700830 @Override
831 public void onDestroy() {
John Reck38b4bf52011-02-22 14:39:34 -0800832 if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700833 mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
834 mUploadHandler = null;
835 }
836 if (mTabControl == null) return;
837 mUi.onDestroy();
838 // Remove the current tab and sub window
839 Tab t = mTabControl.getCurrentTab();
840 if (t != null) {
841 dismissSubWindow(t);
842 removeTab(t);
843 }
Leon Scroggins1961ed22010-12-07 15:22:21 -0500844 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb8233fac2010-10-26 16:08:53 -0700845 // Destroy all the tabs
846 mTabControl.destroy();
Michael Kolb8233fac2010-10-26 16:08:53 -0700847 }
848
849 protected boolean isActivityPaused() {
850 return mActivityPaused;
851 }
852
John Reck9c35b9c2012-05-30 10:08:50 -0700853 @Override
854 public void onLowMemory() {
Michael Kolb8233fac2010-10-26 16:08:53 -0700855 mTabControl.freeMemory();
856 }
857
858 @Override
859 public boolean shouldShowErrorConsole() {
860 return mShouldShowErrorConsole;
861 }
862
863 protected void setShouldShowErrorConsole(boolean show) {
864 if (show == mShouldShowErrorConsole) {
865 // Nothing to do.
866 return;
867 }
868 mShouldShowErrorConsole = show;
869 Tab t = mTabControl.getCurrentTab();
870 if (t == null) {
871 // There is no current tab so we cannot toggle the error console
872 return;
873 }
874 mUi.setShouldShowErrorConsole(t, show);
875 }
876
877 @Override
878 public void stopLoading() {
879 mLoadStopped = true;
880 Tab tab = mTabControl.getCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -0700881 WebView w = getCurrentTopWebView();
Michael Kolb778a4882012-04-12 15:27:28 -0700882 if (w != null) {
883 w.stopLoading();
884 mUi.onPageStopped(tab);
885 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700886 }
887
888 boolean didUserStopLoading() {
889 return mLoadStopped;
890 }
891
kaiyiza016da12013-08-26 17:50:22 +0800892 private void handleNetworkNotify(WebView view) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700893 final String reminderType = getContext().getResources().getString(
894 R.string.def_wifi_browser_interaction_remind_type);
895 final String selectionConnnection = getContext().getResources().getString(
896 R.string.def_action_wifi_selection_data_connections);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700897 final String wifiSelection = getContext().getResources().getString(
898 R.string.def_intent_pick_network);
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700899
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700900 if (reminderType.isEmpty() || selectionConnnection.isEmpty() ||
901 wifiSelection.isEmpty())
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700902 return;
903
kaiyiza016da12013-08-26 17:50:22 +0800904 ConnectivityManager conMgr = (ConnectivityManager) this.getContext().getSystemService(
Vivek Sekharb54614f2014-05-01 19:03:37 -0700905 Context.CONNECTIVITY_SERVICE);
906 NetworkInfo networkInfo = conMgr.getActiveNetworkInfo();
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700907 WifiManager wifiMgr = (WifiManager) this.getContext()
908 .getSystemService(Context.WIFI_SERVICE);
Vivek Sekharb54614f2014-05-01 19:03:37 -0700909 if (networkInfo == null
910 || (networkInfo != null && (networkInfo.getType() !=
911 ConnectivityManager.TYPE_WIFI))) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700912 int isReminder = Settings.System.getInt(mActivity.getContentResolver(),
913 reminderType, NETWORK_SWITCH_TYPE_OK);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700914 List<ScanResult> list = wifiMgr.getScanResults();
915 // Have no AP's for Wifi's fall back to data
916 if (list != null && list.size() == 0 && isReminder == NETWORK_SWITCH_TYPE_OK) {
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700917 Intent intent = new Intent(selectionConnnection);
Vivek Sekharb54614f2014-05-01 19:03:37 -0700918 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
919 this.getContext().startActivity(intent);
920 } else {
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700921 // Request to select Wifi AP
922 try {
923 Intent intent = new Intent(wifiSelection);
924 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
925 this.getContext().startActivity(intent);
926 } catch (Exception e) {
927 String err_msg = this.getContext().getString(
928 R.string.acivity_not_found, wifiSelection);
929 Toast.makeText(this.getContext(), err_msg, Toast.LENGTH_LONG).show();
930 }
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700931 }
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700932 mNetworkShouldNotify = false;
kaiyiza016da12013-08-26 17:50:22 +0800933 }
934 }
Vivek Sekharb54614f2014-05-01 19:03:37 -0700935
Michael Kolb8233fac2010-10-26 16:08:53 -0700936 // WebViewController
937
938 @Override
John Reck324d4402011-01-11 16:56:42 -0800939 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb8233fac2010-10-26 16:08:53 -0700940
941 // We've started to load a new page. If there was a pending message
942 // to save a screenshot then we will now take the new page and save
943 // an incorrect screenshot. Therefore, remove any pending thumbnail
944 // messages from the queue.
Bijan Amirzadae75909d2014-05-06 14:18:54 -0700945 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL, tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700946
947 // reset sync timer to avoid sync starts during loading a page
948 CookieSyncManager.getInstance().resetSync();
Vivek Sekharb54614f2014-05-01 19:03:37 -0700949 WifiManager wifiMgr = (WifiManager) this.getContext()
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700950 .getSystemService(Context.WIFI_SERVICE);
Panos Thomas4bdb5252014-11-13 16:20:11 -0800951 boolean networkNotifier = BrowserConfig.getInstance(getContext())
952 .hasFeature(BrowserConfig.Feature.NETWORK_NOTIFIER);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -0700953 if (networkNotifier && mNetworkShouldNotify && wifiMgr.isWifiEnabled()){
Vivek Sekharb54614f2014-05-01 19:03:37 -0700954 handleNetworkNotify(view);
kaiyiza016da12013-08-26 17:50:22 +0800955 } else {
956 if (!mNetworkHandler.isNetworkUp()) {
957 view.setNetworkAvailable(false);
958 }
Michael Kolb8233fac2010-10-26 16:08:53 -0700959 }
960
961 // when BrowserActivity just starts, onPageStarted may be called before
962 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
963 // to start the timer. As we won't switch tabs while an activity is in
964 // pause state, we can ensure calling resume and pause in pair.
965 if (mActivityPaused) {
Michael Kolb70976932010-11-30 11:34:01 -0800966 resumeWebViewTimers(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700967 }
968 mLoadStopped = false;
Michael Kolb8233fac2010-10-26 16:08:53 -0700969 endActionMode();
970
John Reck30c714c2010-12-16 17:30:34 -0800971 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -0700972
John Reck324d4402011-01-11 16:56:42 -0800973 String url = tab.getUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -0700974 // update the bookmark database for favicon
975 maybeUpdateFavicon(tab, null, url, favicon);
976
977 Performance.tracePageStart(url);
978
979 // Performance probe
980 if (false) {
981 Performance.onPageStarted();
982 }
983
984 }
985
986 @Override
John Reck324d4402011-01-11 16:56:42 -0800987 public void onPageFinished(Tab tab) {
Michael Kolb72864272012-05-03 15:42:15 -0700988 mCrashRecoveryHandler.backupState();
John Reck30c714c2010-12-16 17:30:34 -0800989 mUi.onTabDataChanged(tab);
Martijn Coenenb2f93552011-06-14 10:48:35 +0200990
Michael Kolb8233fac2010-10-26 16:08:53 -0700991 // Performance probe
992 if (false) {
John Reck324d4402011-01-11 16:56:42 -0800993 Performance.onPageFinished(tab.getUrl());
Michael Kolb8233fac2010-10-26 16:08:53 -0700994 }
995
Tarun Nainani8eb00912014-07-17 12:28:32 -0700996 tab.onPageFinished();
997
Michael Kolb8233fac2010-10-26 16:08:53 -0700998 Performance.tracePageFinished();
999 }
1000
1001 @Override
John Reck30c714c2010-12-16 17:30:34 -08001002 public void onProgressChanged(Tab tab) {
1003 int newProgress = tab.getLoadProgress();
Michael Kolb8233fac2010-10-26 16:08:53 -07001004
1005 if (newProgress == 100) {
1006 CookieSyncManager.getInstance().sync();
1007 // onProgressChanged() may continue to be called after the main
1008 // frame has finished loading, as any remaining sub frames continue
1009 // to load. We'll only get called once though with newProgress as
1010 // 100 when everything is loaded. (onPageFinished is called once
1011 // when the main frame completes loading regardless of the state of
1012 // any sub frames so calls to onProgressChanges may continue after
1013 // onPageFinished has executed)
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001014 if (tab.inPageLoad()) {
Pankaj Garg49b79252014-11-07 17:33:41 -08001015 mWasInPageLoad = true;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001016 updateInLoadMenuItems(mCachedMenu, tab);
Pankaj Garg49b79252014-11-07 17:33:41 -08001017 } else if (mWasInPageLoad) {
1018 mWasInPageLoad = false;
1019 updateInLoadMenuItems(mCachedMenu, tab);
1020 }
1021
1022 if (mActivityPaused && pauseWebViewTimers(tab)) {
Mattias Falk9cc2d032012-05-25 09:40:31 +02001023 // pause the WebView timer and release the wake lock if it is
1024 // finished while BrowserActivity is in pause state.
1025 releaseWakeLock();
Michael Kolb8233fac2010-10-26 16:08:53 -07001026 }
John Reckd9862372012-02-21 15:04:50 -08001027 if (!tab.isPrivateBrowsingEnabled()
1028 && !TextUtils.isEmpty(tab.getUrl())
1029 && !tab.isSnapshot()) {
1030 // Only update the bookmark screenshot if the user did not
1031 // cancel the load early and there is not already
1032 // a pending update for the tab.
Michael Kolb72864272012-05-03 15:42:15 -07001033 if (tab.shouldUpdateThumbnail() &&
1034 (tab.inForeground() && !didUserStopLoading()
1035 || !tab.inForeground())) {
John Reckd9862372012-02-21 15:04:50 -08001036 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
1037 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1038 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001039 1500);
John Reckd9862372012-02-21 15:04:50 -08001040 }
1041 }
1042 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001043 } else {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001044 if (!tab.inPageLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001045 // onPageFinished may have already been called but a subframe is
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001046 // still loading
1047 // updating the progress and
Michael Kolb8233fac2010-10-26 16:08:53 -07001048 // update the menu items.
Pankaj Garg49b79252014-11-07 17:33:41 -08001049 mWasInPageLoad = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001050 updateInLoadMenuItems(mCachedMenu, tab);
Pankaj Garg49b79252014-11-07 17:33:41 -08001051 } else {
1052 mWasInPageLoad = true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001053 }
1054 }
John Reck30c714c2010-12-16 17:30:34 -08001055 mUi.onProgressChanged(tab);
1056 }
1057
1058 @Override
Steve Block2466eff2011-10-03 15:33:09 +01001059 public void onUpdatedSecurityState(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08001060 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001061 }
1062
1063 @Override
1064 public void onReceivedTitle(Tab tab, final String title) {
John Reck30c714c2010-12-16 17:30:34 -08001065 mUi.onTabDataChanged(tab);
John Reck49a603c2011-03-03 09:33:05 -08001066 final String pageUrl = tab.getOriginalUrl();
John Reck324d4402011-01-11 16:56:42 -08001067 if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb8233fac2010-10-26 16:08:53 -07001068 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
1069 return;
1070 }
1071 // Update the title in the history database if not in private browsing mode
1072 if (!tab.isPrivateBrowsingEnabled()) {
John Reckf57c0292011-07-21 18:15:39 -07001073 DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb8233fac2010-10-26 16:08:53 -07001074 }
1075 }
1076
1077 @Override
1078 public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck30c714c2010-12-16 17:30:34 -08001079 mUi.onTabDataChanged(tab);
Michael Kolb8233fac2010-10-26 16:08:53 -07001080 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
1081 }
1082
1083 @Override
Michael Kolb18eb3772010-12-10 14:29:51 -08001084 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
1085 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07001086 }
1087
1088 @Override
1089 public boolean shouldOverrideKeyEvent(KeyEvent event) {
1090 if (mMenuIsDown) {
1091 // only check shortcut key when MENU is held
1092 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
1093 event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001094 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001095 int keyCode = event.getKeyCode();
1096 // We need to send almost every key to WebKit. However:
1097 // 1. We don't want to block the device on the renderer for
1098 // some keys like menu, home, call.
1099 // 2. There are no WebKit equivalents for some of these keys
1100 // (see app/keyboard_codes_win.h)
1101 // Note that these are not the same set as KeyEvent.isSystemKey:
1102 // for instance, AKEYCODE_MEDIA_* will be dispatched to webkit.
1103 if (keyCode == KeyEvent.KEYCODE_MENU ||
1104 keyCode == KeyEvent.KEYCODE_HOME ||
1105 keyCode == KeyEvent.KEYCODE_BACK ||
1106 keyCode == KeyEvent.KEYCODE_CALL ||
1107 keyCode == KeyEvent.KEYCODE_ENDCALL ||
1108 keyCode == KeyEvent.KEYCODE_POWER ||
1109 keyCode == KeyEvent.KEYCODE_HEADSETHOOK ||
1110 keyCode == KeyEvent.KEYCODE_CAMERA ||
1111 keyCode == KeyEvent.KEYCODE_FOCUS ||
1112 keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
1113 keyCode == KeyEvent.KEYCODE_VOLUME_MUTE ||
1114 keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
1115 return true;
1116 }
1117
1118 // We also have to intercept some shortcuts before we send them to the ContentView.
1119 if (event.isCtrlPressed() && (
1120 keyCode == KeyEvent.KEYCODE_TAB ||
1121 keyCode == KeyEvent.KEYCODE_W ||
1122 keyCode == KeyEvent.KEYCODE_F4)) {
1123 return true;
1124 }
1125
1126 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07001127 }
1128
1129 @Override
John Reck997b1b72012-04-19 18:08:25 -07001130 public boolean onUnhandledKeyEvent(KeyEvent event) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001131 if (!isActivityPaused()) {
1132 if (event.getAction() == KeyEvent.ACTION_DOWN) {
John Reck997b1b72012-04-19 18:08:25 -07001133 return mActivity.onKeyDown(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001134 } else {
John Reck997b1b72012-04-19 18:08:25 -07001135 return mActivity.onKeyUp(event.getKeyCode(), event);
Michael Kolb8233fac2010-10-26 16:08:53 -07001136 }
1137 }
John Reck997b1b72012-04-19 18:08:25 -07001138 return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07001139 }
1140
1141 @Override
John Reck324d4402011-01-11 16:56:42 -08001142 public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Panos Thomas4bdb5252014-11-13 16:20:11 -08001143 // Don't save anything in private browsing mode or when disabling history
1144 // for regular tabs is enabled
1145 if (tab.isPrivateBrowsingEnabled() || BrowserConfig.getInstance(getContext())
1146 .hasFeature(BrowserConfig.Feature.DISABLE_HISTORY))
1147 return;
Bijan Amirzadae75909d2014-05-06 14:18:54 -07001148
John Reck49a603c2011-03-03 09:33:05 -08001149 String url = tab.getOriginalUrl();
Michael Kolb8233fac2010-10-26 16:08:53 -07001150
John Reck324d4402011-01-11 16:56:42 -08001151 if (TextUtils.isEmpty(url)
1152 || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001153 return;
1154 }
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001155
John Reckf57c0292011-07-21 18:15:39 -07001156 DataController.getInstance(mActivity).updateVisitedHistory(url);
John Reck6c2e2f32011-08-22 13:41:23 -07001157 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07001158 }
1159
1160 @Override
1161 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1162 AsyncTask<Void, Void, String[]> task =
1163 new AsyncTask<Void, Void, String[]>() {
1164 @Override
1165 public String[] doInBackground(Void... unused) {
Bijan Amirzada3f04dc72014-06-25 11:48:36 -07001166 return (String[]) Browser.getVisitedHistory(mActivity.getContentResolver());
Michael Kolb8233fac2010-10-26 16:08:53 -07001167 }
1168 @Override
1169 public void onPostExecute(String[] result) {
1170 callback.onReceiveValue(result);
1171 }
1172 };
1173 task.execute();
1174 }
1175
1176 @Override
1177 public void onReceivedHttpAuthRequest(Tab tab, WebView view,
1178 final HttpAuthHandler handler, final String host,
1179 final String realm) {
1180 String username = null;
1181 String password = null;
1182
1183 boolean reuseHttpAuthUsernamePassword
1184 = handler.useHttpAuthUsernamePassword();
1185
1186 if (reuseHttpAuthUsernamePassword && view != null) {
1187 String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
1188 if (credentials != null && credentials.length == 2) {
1189 username = credentials[0];
1190 password = credentials[1];
1191 }
1192 }
1193
1194 if (username != null && password != null) {
1195 handler.proceed(username, password);
1196 } else {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001197 if (tab.inForeground() /*&& !handler.suppressDialog()*/) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001198 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
1199 } else {
1200 handler.cancel();
1201 }
1202 }
1203 }
1204
1205 @Override
1206 public void onDownloadStart(Tab tab, String url, String userAgent,
Selim Gurun0b3d66f2012-08-29 13:08:13 -07001207 String contentDisposition, String mimetype, String referer,
1208 long contentLength) {
Kristian Monsenbc5cc752011-03-02 13:14:03 +00001209 WebView w = tab.getWebView();
Axesh R. Ajmera87c5aba2014-11-06 14:13:36 -08001210 if ( w == null) return;
qqzhoua95a2e22013-04-18 17:28:31 +08001211 boolean ret = DownloadHandler.onDownloadStart(mActivity, url, userAgent,
luxiaol62677b02013-07-22 07:54:49 +08001212 contentDisposition, mimetype, referer, w.isPrivateBrowsingEnabled(), contentLength);
qqzhoua95a2e22013-04-18 17:28:31 +08001213 if (ret == false && w.copyBackForwardList().getSize() == 0) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001214 // This Tab was opened for the sole purpose of downloading a
1215 // file. Remove it.
1216 if (tab == mTabControl.getCurrentTab()) {
1217 // In this case, the Tab is still on top.
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07001218 if (tab.getDerivedFromIntent())
1219 closeTab(tab);
1220 else
1221 goBackOnePageOrQuit();
Michael Kolb8233fac2010-10-26 16:08:53 -07001222 } else {
1223 // In this case, it is not.
1224 closeTab(tab);
1225 }
1226 }
1227 }
1228
1229 @Override
1230 public Bitmap getDefaultVideoPoster() {
1231 return mUi.getDefaultVideoPoster();
1232 }
1233
1234 @Override
1235 public View getVideoLoadingProgressView() {
1236 return mUi.getVideoLoadingProgressView();
1237 }
1238
1239 @Override
1240 public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
1241 SslError error) {
1242 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
1243 }
1244
1245 // helper method
1246
1247 /*
1248 * Update the favorites icon if the private browsing isn't enabled and the
1249 * icon is valid.
1250 */
1251 private void maybeUpdateFavicon(Tab tab, final String originalUrl,
1252 final String url, Bitmap favicon) {
1253 if (favicon == null) {
1254 return;
1255 }
1256 if (!tab.isPrivateBrowsingEnabled()) {
1257 Bookmarks.updateFavicon(mActivity
1258 .getContentResolver(), originalUrl, url, favicon);
1259 }
1260 }
1261
Leon Scroggins4cd97792010-12-03 15:31:56 -05001262 @Override
1263 public void bookmarkedStatusHasChanged(Tab tab) {
John Recke969cc52010-12-21 17:24:43 -08001264 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
Leon Scroggins4cd97792010-12-03 15:31:56 -05001265 mUi.bookmarkedStatusHasChanged(tab);
1266 }
1267
Michael Kolb8233fac2010-10-26 16:08:53 -07001268 // end WebViewController
1269
1270 protected void pageUp() {
1271 getCurrentTopWebView().pageUp(false);
1272 }
1273
1274 protected void pageDown() {
1275 getCurrentTopWebView().pageDown(false);
1276 }
1277
1278 // callback from phone title bar
John Reck9c35b9c2012-05-30 10:08:50 -07001279 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07001280 public void editUrl() {
1281 if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolb1f9b3562012-04-24 14:38:34 -07001282 mUi.editUrl(false, true);
Michael Kolb8233fac2010-10-26 16:08:53 -07001283 }
1284
John Reck9c35b9c2012-05-30 10:08:50 -07001285 @Override
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001286 public void showCustomView(Tab tab, View view, int requestedOrientation,
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001287 CustomViewCallback callback) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001288 if (tab.inForeground()) {
1289 if (mUi.isCustomViewShowing()) {
1290 callback.onCustomViewHidden();
1291 return;
1292 }
Derek Sollenberger2d4f1e22011-06-01 14:50:42 -04001293 mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb8233fac2010-10-26 16:08:53 -07001294 // Save the menu state and set it to empty while the custom
1295 // view is showing.
1296 mOldMenuState = mMenuState;
1297 mMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001298 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001299 }
1300 }
1301
1302 @Override
1303 public void hideCustomView() {
1304 if (mUi.isCustomViewShowing()) {
1305 mUi.onHideCustomView();
1306 // Reset the old menu state.
1307 mMenuState = mOldMenuState;
1308 mOldMenuState = EMPTY_MENU;
John Reckd73c5a22010-12-22 10:22:50 -08001309 mActivity.invalidateOptionsMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001310 }
1311 }
1312
John Reck9c35b9c2012-05-30 10:08:50 -07001313 @Override
1314 public void onActivityResult(int requestCode, int resultCode,
Michael Kolb8233fac2010-10-26 16:08:53 -07001315 Intent intent) {
1316 if (getCurrentTopWebView() == null) return;
1317 switch (requestCode) {
1318 case PREFERENCES_PAGE:
1319 if (resultCode == Activity.RESULT_OK && intent != null) {
1320 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck35e9dd62011-04-25 09:01:54 -07001321 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001322 mTabControl.removeParentChildRelationShips();
1323 }
1324 }
1325 break;
1326 case FILE_SELECTED:
Ben Murdoch51f6a2f2011-02-21 12:27:07 +00001327 // Chose a file from the file picker.
John Reck9dfcdb12011-02-22 16:40:46 -08001328 if (null == mUploadHandler) break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001329 mUploadHandler.onResult(resultCode, intent);
Michael Kolb8233fac2010-10-26 16:08:53 -07001330 break;
Ben Murdoch8029a772010-11-16 11:58:21 +00001331 case AUTOFILL_SETUP:
1332 // Determine whether a profile was actually set up or not
1333 // and if so, send the message back to the WebTextView to
1334 // fill the form with the new profile.
1335 if (getSettings().getAutoFillProfile() != null) {
1336 mAutoFillSetupMessage.sendToTarget();
1337 mAutoFillSetupMessage = null;
1338 }
1339 break;
John Reckd3e4d5b2011-07-13 15:48:43 -07001340 case COMBO_VIEW:
1341 if (intent == null || resultCode != Activity.RESULT_OK) {
1342 break;
1343 }
John Reck3ba45532011-08-11 16:26:53 -07001344 mUi.showWeb(false);
John Reckd3e4d5b2011-07-13 15:48:43 -07001345 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
1346 Tab t = getCurrentTab();
1347 Uri uri = intent.getData();
kaiyiz6e5b3e02013-08-19 20:02:01 +08001348 mUpdateMyNavThumbnail = true;
1349 mUpdateMyNavThumbnailUrl = uri.toString();
John Reckd3e4d5b2011-07-13 15:48:43 -07001350 loadUrl(t, uri.toString());
1351 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
1352 String[] urls = intent.getStringArrayExtra(
1353 ComboViewActivity.EXTRA_OPEN_ALL);
1354 Tab parent = getCurrentTab();
1355 for (String url : urls) {
kaiyiz47097d62013-08-09 09:30:28 +08001356 if (url != null) {
1357 parent = openTab(url, parent,
1358 !mSettings.openInBackground(), true);
1359 }
John Reckd3e4d5b2011-07-13 15:48:43 -07001360 }
1361 } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
1362 long id = intent.getLongExtra(
1363 ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
1364 if (id >= 0) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08001365 createNewSnapshotTab(id, true);
John Reckd3e4d5b2011-07-13 15:48:43 -07001366 }
1367 }
1368 break;
Michael Kolb0b129122012-06-04 16:31:58 -07001369 case VOICE_RESULT:
1370 if (resultCode == Activity.RESULT_OK && intent != null) {
1371 ArrayList<String> results = intent.getStringArrayListExtra(
1372 RecognizerIntent.EXTRA_RESULTS);
1373 if (results.size() >= 1) {
1374 mVoiceResult = results.get(0);
1375 }
1376 }
1377 break;
kaiyiz6e5b3e02013-08-19 20:02:01 +08001378 case MY_NAVIGATION:
1379 if (intent == null || resultCode != Activity.RESULT_OK) {
1380 break;
1381 }
1382
1383 if (intent.getBooleanExtra("need_refresh", false) &&
1384 getCurrentTopWebView() != null) {
1385 getCurrentTopWebView().reload();
1386 }
1387 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07001388 default:
1389 break;
1390 }
1391 getCurrentTopWebView().requestFocus();
1392 }
1393
1394 /**
1395 * Open the Go page.
1396 * @param startWithHistory If true, open starting on the history tab.
1397 * Otherwise, start with the bookmarks tab.
1398 */
1399 @Override
Michael Kolb315d5022011-10-13 12:47:11 -07001400 public void bookmarksOrHistoryPicker(ComboViews startView) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001401 if (mTabControl.getCurrentWebView() == null) {
1402 return;
1403 }
Michael Kolbbd3dd942011-01-12 11:09:38 -08001404 // clear action mode
1405 if (isInCustomActionMode()) {
1406 endActionMode();
1407 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001408 Bundle extras = new Bundle();
1409 // Disable opening in a new window if we have maxed out the windows
1410 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
1411 !mTabControl.canCreateNewTab());
Michael Kolb315d5022011-10-13 12:47:11 -07001412 mUi.showComboView(startView, extras);
Michael Kolb8233fac2010-10-26 16:08:53 -07001413 }
1414
1415 // combo view callbacks
1416
Michael Kolb8233fac2010-10-26 16:08:53 -07001417 // key handling
1418 protected void onBackKey() {
1419 if (!mUi.onBackKey()) {
1420 WebView subwindow = mTabControl.getCurrentSubWindow();
1421 if (subwindow != null) {
1422 if (subwindow.canGoBack()) {
1423 subwindow.goBack();
1424 } else {
1425 dismissSubWindow(mTabControl.getCurrentTab());
1426 }
1427 } else {
1428 goBackOnePageOrQuit();
1429 }
1430 }
1431 }
1432
Michael Kolb4bd767d2011-05-27 11:33:55 -07001433 protected boolean onMenuKey() {
1434 return mUi.onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07001435 }
1436
Michael Kolb8233fac2010-10-26 16:08:53 -07001437 // menu handling and state
1438 // TODO: maybe put into separate handler
1439
John Reck9c35b9c2012-05-30 10:08:50 -07001440 @Override
1441 public boolean onCreateOptionsMenu(Menu menu) {
John Reckd73c5a22010-12-22 10:22:50 -08001442 if (mMenuState == EMPTY_MENU) {
1443 return false;
1444 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001445 MenuInflater inflater = mActivity.getMenuInflater();
1446 inflater.inflate(R.menu.browser, menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001447 return true;
1448 }
1449
John Reck9c35b9c2012-05-30 10:08:50 -07001450 @Override
1451 public void onCreateContextMenu(ContextMenu menu, View v,
Michael Kolb8233fac2010-10-26 16:08:53 -07001452 ContextMenuInfo menuInfo) {
John Reck0f602f32011-07-07 15:38:43 -07001453 if (v instanceof TitleBar) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001454 return;
1455 }
1456 if (!(v instanceof WebView)) {
1457 return;
1458 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001459 final WebView webview = (WebView) v;
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -08001460 WebView.HitTestResult result;
1461
1462 /* Determine whether the ContextMenu got triggered because
1463 * of user action of long click or because of the UNKNOWN_TYPE_MSG
1464 * received. The mResult acts as a flag to identify, how it got trigerred
1465 */
1466 if (mResult == null){
1467 result = webview.getHitTestResult();
1468 } else {
1469 result = mResult;
1470 }
1471
Michael Kolb8233fac2010-10-26 16:08:53 -07001472 if (result == null) {
1473 return;
1474 }
1475
1476 int type = result.getType();
1477 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
Axesh R. Ajmera7d5eb332015-01-06 11:00:34 -08001478
1479 HashMap<String, Object> unknownTypeMap = new HashMap<String, Object>();
1480 unknownTypeMap.put("webview", webview);
1481 final Message msg = mHandler.obtainMessage(
1482 UNKNOWN_TYPE_MSG, unknownTypeMap);
1483 /* As defined in android developers guide
1484 * when UNKNOWN_TYPE is received as a result of HitTest
1485 * you need to determing the type by invoking requestFocusNodeHref
1486 */
1487 webview.requestFocusNodeHref(msg);
1488
Michael Kolb8233fac2010-10-26 16:08:53 -07001489 Log.w(LOGTAG,
1490 "We should not show context menu when nothing is touched");
1491 return;
1492 }
1493 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1494 // let TextView handles context menu
1495 return;
1496 }
1497
1498 // Note, http://b/issue?id=1106666 is requesting that
1499 // an inflated menu can be used again. This is not available
1500 // yet, so inflate each time (yuk!)
1501 MenuInflater inflater = mActivity.getMenuInflater();
1502 inflater.inflate(R.menu.browsercontext, menu);
1503
1504 // Show the correct menu group
1505 final String extra = result.getExtra();
kaiyiz6e5b3e02013-08-19 20:02:01 +08001506 final String navigationUrl = MyNavigationUtil.getMyNavigationUrl(extra);
Michael Kolbc159c1a2011-12-15 16:06:38 -08001507 if (extra == null) return;
Michael Kolb8233fac2010-10-26 16:08:53 -07001508 menu.setGroupVisible(R.id.PHONE_MENU,
1509 type == WebView.HitTestResult.PHONE_TYPE);
1510 menu.setGroupVisible(R.id.EMAIL_MENU,
1511 type == WebView.HitTestResult.EMAIL_TYPE);
1512 menu.setGroupVisible(R.id.GEO_MENU,
1513 type == WebView.HitTestResult.GEO_TYPE);
kaiyiz6e5b3e02013-08-19 20:02:01 +08001514 String itemUrl = null;
1515 String url = webview.getOriginalUrl();
1516 if (url != null && url.equalsIgnoreCase(MyNavigationUtil.MY_NAVIGATION)) {
1517 itemUrl = Uri.decode(navigationUrl);
1518 if (itemUrl != null && !MyNavigationUtil.isDefaultMyNavigation(itemUrl)) {
1519 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU,
1520 type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1521 } else {
1522 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU, false);
1523 }
1524 menu.setGroupVisible(R.id.IMAGE_MENU, false);
1525 menu.setGroupVisible(R.id.ANCHOR_MENU, false);
1526 } else {
1527 menu.setGroupVisible(R.id.MY_NAVIGATION_MENU, false);
1528
1529 menu.setGroupVisible(R.id.IMAGE_MENU,
1530 type == WebView.HitTestResult.IMAGE_TYPE
1531 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1532 menu.setGroupVisible(R.id.ANCHOR_MENU,
1533 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1534 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Vivek Sekharcc4bc5e2014-05-13 12:46:37 -07001535 menu.findItem(R.id.save_link_context_menu_id).setEnabled(
1536 UrlUtils.isDownloadableScheme(extra));
kaiyiz6e5b3e02013-08-19 20:02:01 +08001537 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001538 // Setup custom handling depending on the type
1539 switch (type) {
1540 case WebView.HitTestResult.PHONE_TYPE:
1541 menu.setHeaderTitle(Uri.decode(extra));
1542 menu.findItem(R.id.dial_context_menu_id).setIntent(
1543 new Intent(Intent.ACTION_VIEW, Uri
1544 .parse(WebView.SCHEME_TEL + extra)));
1545 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1546 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1547 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1548 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1549 addIntent);
1550 menu.findItem(R.id.copy_phone_context_menu_id)
1551 .setOnMenuItemClickListener(
1552 new Copy(extra));
1553 break;
1554
1555 case WebView.HitTestResult.EMAIL_TYPE:
1556 menu.setHeaderTitle(extra);
1557 menu.findItem(R.id.email_context_menu_id).setIntent(
1558 new Intent(Intent.ACTION_VIEW, Uri
1559 .parse(WebView.SCHEME_MAILTO + extra)));
1560 menu.findItem(R.id.copy_mail_context_menu_id)
1561 .setOnMenuItemClickListener(
1562 new Copy(extra));
1563 break;
1564
1565 case WebView.HitTestResult.GEO_TYPE:
1566 menu.setHeaderTitle(extra);
1567 menu.findItem(R.id.map_context_menu_id).setIntent(
1568 new Intent(Intent.ACTION_VIEW, Uri
1569 .parse(WebView.SCHEME_GEO
1570 + URLEncoder.encode(extra))));
1571 menu.findItem(R.id.copy_geo_context_menu_id)
1572 .setOnMenuItemClickListener(
1573 new Copy(extra));
1574 break;
1575
1576 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1577 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb4c537ce2011-01-13 15:19:33 -08001578 menu.setHeaderTitle(extra);
Michael Kolb8233fac2010-10-26 16:08:53 -07001579 // decide whether to show the open link in new tab option
1580 boolean showNewTab = mTabControl.canCreateNewTab();
1581 MenuItem newTabItem
1582 = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck35e9dd62011-04-25 09:01:54 -07001583 newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb2dd65c82011-01-14 11:07:38 -08001584 ? R.string.contextmenu_openlink_newwindow_background
1585 : R.string.contextmenu_openlink_newwindow);
Michael Kolb8233fac2010-10-26 16:08:53 -07001586 newTabItem.setVisible(showNewTab);
1587 if (showNewTab) {
Leon Scroggins026f2542010-11-22 13:26:12 -05001588 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
1589 newTabItem.setOnMenuItemClickListener(
1590 new MenuItem.OnMenuItemClickListener() {
1591 @Override
1592 public boolean onMenuItemClick(MenuItem item) {
1593 final HashMap<String, WebView> hrefMap =
1594 new HashMap<String, WebView>();
1595 hrefMap.put("webview", webview);
1596 final Message msg = mHandler.obtainMessage(
1597 FOCUS_NODE_HREF,
1598 R.id.open_newtab_context_menu_id,
1599 0, hrefMap);
1600 webview.requestFocusNodeHref(msg);
1601 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07001602 }
Leon Scroggins026f2542010-11-22 13:26:12 -05001603 });
1604 } else {
1605 newTabItem.setOnMenuItemClickListener(
1606 new MenuItem.OnMenuItemClickListener() {
1607 @Override
1608 public boolean onMenuItemClick(MenuItem item) {
1609 final Tab parent = mTabControl.getCurrentTab();
John Reck5949c662011-05-27 09:52:29 -07001610 openTab(extra, parent,
1611 !mSettings.openInBackground(),
1612 true);
Leon Scroggins026f2542010-11-22 13:26:12 -05001613 return true;
1614 }
1615 });
1616 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001617 }
kaiyiz6e5b3e02013-08-19 20:02:01 +08001618 if (url != null && url.equalsIgnoreCase(MyNavigationUtil.MY_NAVIGATION)) {
1619 menu.setHeaderTitle(navigationUrl);
1620 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(false);
1621
1622 if (itemUrl != null) {
1623 if (!MyNavigationUtil.isDefaultMyNavigation(itemUrl)) {
1624 menu.findItem(R.id.edit_my_navigation_context_menu_id)
1625 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1626 @Override
1627 public boolean onMenuItemClick(MenuItem item) {
1628 final Intent intent = new Intent(Controller.this
1629 .getContext(),
1630 AddMyNavigationPage.class);
1631 Bundle bundle = new Bundle();
1632 String url = Uri.decode(navigationUrl);
1633 bundle.putBoolean("isAdding", false);
1634 bundle.putString("url", url);
1635 bundle.putString("name", getNameFromUrl(url));
1636 intent.putExtra("websites", bundle);
1637 mActivity.startActivityForResult(intent, MY_NAVIGATION);
1638 return false;
1639 }
1640 });
1641 menu.findItem(R.id.delete_my_navigation_context_menu_id)
1642 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1643 @Override
1644 public boolean onMenuItemClick(MenuItem item) {
1645 showMyNavigationDeleteDialog(Uri.decode(navigationUrl));
1646 return false;
1647 }
1648 });
1649 }
1650 } else {
1651 Log.e(LOGTAG, "mynavigation onCreateContextMenu itemUrl is null!");
1652 }
1653 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001654 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1655 break;
1656 }
1657 // otherwise fall through to handle image part
1658 case WebView.HitTestResult.IMAGE_TYPE:
Victoria Lease5987b802012-03-12 13:05:23 -07001659 MenuItem shareItem = menu.findItem(R.id.share_link_context_menu_id);
1660 shareItem.setVisible(type == WebView.HitTestResult.IMAGE_TYPE);
Michael Kolb8233fac2010-10-26 16:08:53 -07001661 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1662 menu.setHeaderTitle(extra);
Victoria Lease5987b802012-03-12 13:05:23 -07001663 shareItem.setOnMenuItemClickListener(
1664 new MenuItem.OnMenuItemClickListener() {
1665 @Override
1666 public boolean onMenuItemClick(MenuItem item) {
1667 sharePage(mActivity, null, extra, null,
1668 null);
1669 return true;
1670 }
1671 }
1672 );
Michael Kolb8233fac2010-10-26 16:08:53 -07001673 }
Michael Kolb3639c4c2011-09-28 15:36:40 -07001674 menu.findItem(R.id.view_image_context_menu_id)
1675 .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1676 @Override
1677 public boolean onMenuItemClick(MenuItem item) {
1678 openTab(extra, mTabControl.getCurrentTab(), true, true);
1679 return false;
1680 }
1681 });
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02001682 menu.findItem(R.id.download_context_menu_id).setOnMenuItemClickListener(
1683 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled(),
1684 webview.getSettings().getUserAgentString()));
John Reck3527dd12011-02-22 10:35:29 -08001685 menu.findItem(R.id.set_wallpaper_context_menu_id).
1686 setOnMenuItemClickListener(new WallpaperHandler(mActivity,
1687 extra));
Michael Kolb8233fac2010-10-26 16:08:53 -07001688 break;
1689
1690 default:
1691 Log.w(LOGTAG, "We should not get here.");
1692 break;
1693 }
1694 //update the ui
1695 mUi.onContextMenuCreated(menu);
1696 }
1697
kaiyiz6e5b3e02013-08-19 20:02:01 +08001698 public void startAddMyNavigation(String url) {
1699 final Intent intent = new Intent(Controller.this.getContext(), AddMyNavigationPage.class);
1700 Bundle bundle = new Bundle();
1701 bundle.putBoolean("isAdding", true);
1702 bundle.putString("url", url);
1703 bundle.putString("name", getNameFromUrl(url));
1704 intent.putExtra("websites", bundle);
1705 mActivity.startActivityForResult(intent, MY_NAVIGATION);
1706 }
1707
1708 private void showMyNavigationDeleteDialog(final String itemUrl) {
1709 new AlertDialog.Builder(this.getContext())
1710 .setTitle(R.string.my_navigation_delete_label)
1711 .setIcon(android.R.drawable.ic_dialog_alert)
1712 .setMessage(R.string.my_navigation_delete_msg)
1713 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
1714 @Override
1715 public void onClick(DialogInterface dialog, int whichButton) {
1716 deleteMyNavigationItem(itemUrl);
1717 }
1718 })
1719 .setNegativeButton(R.string.cancel, null)
1720 .show();
1721 }
1722
1723 private void deleteMyNavigationItem(final String itemUrl) {
1724 ContentResolver cr = this.getContext().getContentResolver();
1725 Cursor cursor = null;
1726
1727 try {
1728 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1729 new String[] {
1730 MyNavigationUtil.ID
1731 }, "url = ?", new String[] {
1732 itemUrl
1733 }, null);
1734 if (null != cursor && cursor.moveToFirst()) {
1735 Uri uri = ContentUris.withAppendedId(MyNavigationUtil.MY_NAVIGATION_URI,
1736 cursor.getLong(0));
1737
1738 ContentValues values = new ContentValues();
1739 values.put(MyNavigationUtil.TITLE, "");
1740 values.put(MyNavigationUtil.URL, "ae://" + cursor.getLong(0) + "add-fav");
1741 values.put(MyNavigationUtil.WEBSITE, 0 + "");
1742 ByteArrayOutputStream os = new ByteArrayOutputStream();
1743 Bitmap bm = BitmapFactory.decodeResource(this.getContext().getResources(),
1744 R.raw.my_navigation_add);
1745 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
1746 values.put(MyNavigationUtil.THUMBNAIL, os.toByteArray());
1747 Log.d(LOGTAG, "deleteMyNavigationItem uri is : " + uri);
1748 cr.update(uri, values, null, null);
1749 } else {
1750 Log.e(LOGTAG, "deleteMyNavigationItem the item does not exist!");
1751 }
1752 } catch (IllegalStateException e) {
1753 Log.e(LOGTAG, "deleteMyNavigationItem", e);
1754 } finally {
1755 if (null != cursor) {
1756 cursor.close();
1757 }
1758 }
1759
1760 if (getCurrentTopWebView() != null) {
1761 getCurrentTopWebView().reload();
1762 }
1763 }
1764
1765 private String getNameFromUrl(String itemUrl) {
1766 ContentResolver cr = this.getContext().getContentResolver();
1767 Cursor cursor = null;
1768 String name = null;
1769
1770 try {
1771 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1772 new String[] {
1773 MyNavigationUtil.TITLE
1774 }, "url = ?", new String[] {
1775 itemUrl
1776 }, null);
1777 if (null != cursor && cursor.moveToFirst()) {
1778 name = cursor.getString(0);
1779 } else {
1780 Log.e(LOGTAG, "this item does not exist!");
1781 }
1782 } catch (IllegalStateException e) {
1783 Log.e(LOGTAG, "getNameFromUrl", e);
1784 } finally {
1785 if (null != cursor) {
1786 cursor.close();
1787 }
1788 }
1789 return name;
1790 }
1791
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07001792 private void updateMyNavigationThumbnail(final String itemUrl, final Bitmap bitmap) {
kaiyiz6e5b3e02013-08-19 20:02:01 +08001793 final ContentResolver cr = mActivity.getContentResolver();
1794 new AsyncTask<Void, Void, Void>() {
1795 @Override
1796 protected Void doInBackground(Void... unused) {
Tarun Nainanicc8ac9e2015-01-08 14:45:21 -08001797 boolean isMyNavigationUrl = MyNavigationUtil.isMyNavigationUrl(mActivity, itemUrl);
1798 if(!isMyNavigationUrl)
1799 return null;
1800
kaiyiz6e5b3e02013-08-19 20:02:01 +08001801 ContentResolver cr = mActivity.getContentResolver();
1802 Cursor cursor = null;
1803 try {
1804 cursor = cr.query(MyNavigationUtil.MY_NAVIGATION_URI,
1805 new String[] {
1806 MyNavigationUtil.ID
1807 }, "url = ?", new String[] {
1808 itemUrl
1809 }, null);
1810 if (null != cursor && cursor.moveToFirst()) {
1811 final ByteArrayOutputStream os = new ByteArrayOutputStream();
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07001812 bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
kaiyiz6e5b3e02013-08-19 20:02:01 +08001813
1814 ContentValues values = new ContentValues();
1815 values.put(MyNavigationUtil.THUMBNAIL, os.toByteArray());
1816 Uri uri = ContentUris.withAppendedId(MyNavigationUtil.MY_NAVIGATION_URI,
1817 cursor.getLong(0));
1818 Log.d(LOGTAG, "updateMyNavigationThumbnail uri is " + uri);
1819 cr.update(uri, values, null, null);
1820 os.close();
1821 }
1822 } catch (IllegalStateException e) {
1823 Log.e(LOGTAG, "updateMyNavigationThumbnail", e);
1824 } catch (IOException e) {
1825 Log.e(LOGTAG, "updateMyNavigationThumbnail", e);
1826 } finally {
1827 if (null != cursor) {
1828 cursor.close();
1829 }
1830 }
1831 return null;
1832 }
1833 }.execute();
1834 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001835 /**
1836 * As the menu can be open when loading state changes
1837 * we must manually update the state of the stop/reload menu
1838 * item
1839 */
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001840 private void updateInLoadMenuItems(Menu menu, Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07001841 if (menu == null) {
1842 return;
1843 }
1844 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolbb8337132011-11-28 15:07:39 -08001845 MenuItem src = ((tab != null) && tab.inPageLoad()) ?
Michael Kolb8233fac2010-10-26 16:08:53 -07001846 menu.findItem(R.id.stop_menu_id):
1847 menu.findItem(R.id.reload_menu_id);
1848 if (src != null) {
1849 dest.setIcon(src.getIcon());
1850 dest.setTitle(src.getTitle());
1851 }
Pankaj Garg49b79252014-11-07 17:33:41 -08001852 mActivity.invalidateOptionsMenu();
1853 }
1854
1855 public void invalidateOptionsMenu() {
1856 mAppMenuHandler.invalidateAppMenu();
Michael Kolb8233fac2010-10-26 16:08:53 -07001857 }
1858
John Reck9c35b9c2012-05-30 10:08:50 -07001859 @Override
1860 public boolean onPrepareOptionsMenu(Menu menu) {
Pankaj Garg49b79252014-11-07 17:33:41 -08001861 // Software menu key (toolbar key)
1862 mAppMenuHandler.showAppMenu(mActivity.findViewById(R.id.more_browser_settings), false, false);
1863 return true;
1864 }
1865
1866 @Override
1867 public void prepareMenu(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08001868 updateInLoadMenuItems(menu, getCurrentTab());
John Recke1a03a32011-09-14 17:04:16 -07001869 // hold on to the menu reference here; it is used by the page callbacks
1870 // to update the menu based on loading state
1871 mCachedMenu = menu;
Michael Kolb8233fac2010-10-26 16:08:53 -07001872 // Note: setVisible will decide whether an item is visible; while
1873 // setEnabled() will decide whether an item is enabled, which also means
1874 // whether the matching shortcut key will function.
1875 switch (mMenuState) {
1876 case EMPTY_MENU:
1877 if (mCurrentMenuState != mMenuState) {
1878 menu.setGroupVisible(R.id.MAIN_MENU, false);
1879 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1880 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1881 }
1882 break;
1883 default:
1884 if (mCurrentMenuState != mMenuState) {
1885 menu.setGroupVisible(R.id.MAIN_MENU, true);
1886 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1887 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1888 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001889 updateMenuState(getCurrentTab(), menu);
Michael Kolb8233fac2010-10-26 16:08:53 -07001890 break;
1891 }
1892 mCurrentMenuState = mMenuState;
Pankaj Garg49b79252014-11-07 17:33:41 -08001893 mUi.onPrepareOptionsMenu(menu);
1894 }
1895
1896 private void setMenuItemVisibility(Menu menu, int id,
1897 boolean visibility) {
1898 MenuItem item = menu.findItem(id);
1899 if (item != null) {
1900 item.setVisible(visibility);
1901 }
1902 }
1903
1904 private int lookupBookmark(String title, String url) {
1905 final ContentResolver cr = getActivity().getContentResolver();
Tarun Nainanif7c4cfc2015-01-07 12:43:46 -08001906 int count = 0;
1907 Cursor cursor = null;
1908 try {
1909 cursor = cr.query(BrowserContract.Bookmarks.CONTENT_URI,
1910 BookmarksLoader.PROJECTION,
1911 "title = ? OR url = ?",
1912 new String[] {
Pankaj Garg49b79252014-11-07 17:33:41 -08001913 title, url
Tarun Nainanif7c4cfc2015-01-07 12:43:46 -08001914 },
1915 null);
Pankaj Garg49b79252014-11-07 17:33:41 -08001916
Tarun Nainanif7c4cfc2015-01-07 12:43:46 -08001917 if (cursor != null)
1918 count = cursor.getCount();
1919
1920 } catch (IllegalStateException e) {
1921 Log.e(LOGTAG, "lookupBookmark ", e);
1922 } finally {
1923 if (null != cursor) {
1924 cursor.close();
1925 }
Pankaj Garg49b79252014-11-07 17:33:41 -08001926 }
Tarun Nainanif7c4cfc2015-01-07 12:43:46 -08001927 return count;
Pankaj Garg49b79252014-11-07 17:33:41 -08001928 }
1929
1930 private void resetMenuItems(Menu menu) {
1931 setMenuItemVisibility(menu, R.id.history_menu_id, true);
1932 setMenuItemVisibility(menu, R.id.find_menu_id, true);
1933
1934 WebView w = getCurrentTopWebView();
1935 MenuItem bookmark_icon = menu.findItem(R.id.bookmark_this_page_id);
1936
1937 String title = w.getTitle();
1938 String url = w.getUrl();
1939 if (title != null && url != null && lookupBookmark(title, url) > 0) {
1940 bookmark_icon.setChecked(true);
1941 } else {
1942 bookmark_icon.setChecked(false);
1943 }
Michael Kolb8233fac2010-10-26 16:08:53 -07001944 }
1945
Michael Kolb4bf79712011-07-14 14:18:12 -07001946 @Override
1947 public void updateMenuState(Tab tab, Menu menu) {
Michael Kolb4bf79712011-07-14 14:18:12 -07001948 boolean canGoForward = false;
John Reck42229bc2011-08-19 13:26:43 -07001949 boolean isDesktopUa = false;
John Recke1a03a32011-09-14 17:04:16 -07001950 boolean isLive = false;
Tarun Nainani8eb00912014-07-17 12:28:32 -07001951 // Following flag is used to identify schemes for which the LIVE_MENU
1952 // items defined in res/menu/browser.xml should be enabled
1953 boolean isLiveScheme = false;
1954 boolean isPageFinished = false;
Pankaj Garg49b79252014-11-07 17:33:41 -08001955
1956 resetMenuItems(menu);
1957
Michael Kolb4bf79712011-07-14 14:18:12 -07001958 if (tab != null) {
Michael Kolb4bf79712011-07-14 14:18:12 -07001959 canGoForward = tab.canGoForward();
John Reck42229bc2011-08-19 13:26:43 -07001960 isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
John Recke1a03a32011-09-14 17:04:16 -07001961 isLive = !tab.isSnapshot();
Tarun Nainani8eb00912014-07-17 12:28:32 -07001962 isLiveScheme = UrlUtils.isLiveScheme(tab.getWebView().getUrl());
Pankaj Garg49b79252014-11-07 17:33:41 -08001963 isPageFinished = (tab.getPageFinishedStatus() || !tab.inPageLoad());
Michael Kolb4bf79712011-07-14 14:18:12 -07001964 }
Michael Kolb4bf79712011-07-14 14:18:12 -07001965
1966 final MenuItem forward = menu.findItem(R.id.forward_menu_id);
1967 forward.setEnabled(canGoForward);
1968
Michael Kolb4bf79712011-07-14 14:18:12 -07001969 // decide whether to show the share link option
1970 PackageManager pm = mActivity.getPackageManager();
1971 Intent send = new Intent(Intent.ACTION_SEND);
1972 send.setType("text/plain");
1973 ResolveInfo ri = pm.resolveActivity(send,
1974 PackageManager.MATCH_DEFAULT_ONLY);
1975 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1976
1977 boolean isNavDump = mSettings.enableNavDump();
1978 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1979 nav.setVisible(isNavDump);
1980 nav.setEnabled(isNavDump);
1981
1982 boolean showDebugSettings = mSettings.isDebugEnabled();
John Reck42229bc2011-08-19 13:26:43 -07001983 final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
1984 uaSwitcher.setChecked(isDesktopUa);
Tarun Nainani8eb00912014-07-17 12:28:32 -07001985 menu.setGroupVisible(R.id.LIVE_MENU, isLive && isLiveScheme);
Pankaj Garg49b79252014-11-07 17:33:41 -08001986 menu.setGroupVisible(R.id.NAV_MENU, isLive && isLiveScheme);
1987 setMenuItemVisibility(menu, R.id.find_menu_id, isLive && isLiveScheme);
John Recke1a03a32011-09-14 17:04:16 -07001988 menu.setGroupVisible(R.id.SNAPSHOT_MENU, !isLive);
Pankaj Garg49b79252014-11-07 17:33:41 -08001989 setMenuItemVisibility(menu, R.id.add_to_homescreen,
1990 isLive && isLiveScheme && isPageFinished);
1991 setMenuItemVisibility(menu, R.id.save_snapshot_menu_id,
1992 isLive && isLiveScheme && isPageFinished);
kaiyiza8b6dbb2013-07-29 18:11:22 +08001993 // history and snapshots item are the members of COMBO menu group,
1994 // so if show history item, only make snapshots item invisible.
1995 menu.findItem(R.id.snapshots_menu_id).setVisible(false);
Michael Kolb4bf79712011-07-14 14:18:12 -07001996
Michael Kolb7bdee0b2011-08-01 11:55:38 -07001997 mUi.updateMenuState(tab, menu);
Michael Kolb4bf79712011-07-14 14:18:12 -07001998 }
1999
John Reck9c35b9c2012-05-30 10:08:50 -07002000 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002001 public boolean onOptionsItemSelected(MenuItem item) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002002 if (null == getCurrentTopWebView()) {
2003 return false;
2004 }
2005 if (mMenuIsDown) {
2006 // The shortcut action consumes the MENU. Even if it is still down,
2007 // it won't trigger the next shortcut action. In the case of the
2008 // shortcut action triggering a new activity, like Bookmarks, we
2009 // won't get onKeyUp for MENU. So it is important to reset it here.
2010 mMenuIsDown = false;
2011 }
Michael Kolb3ca12752011-07-20 13:52:25 -07002012 if (mUi.onOptionsItemSelected(item)) {
2013 // ui callback handled it
2014 return true;
2015 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002016 switch (item.getItemId()) {
2017 // -- Main menu
2018 case R.id.new_tab_menu_id:
2019 openTabToHomePage();
2020 break;
2021
2022 case R.id.incognito_menu_id:
Michael Kolb519d2282011-05-09 17:03:19 -07002023 openIncognitoTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002024 break;
2025
2026 case R.id.goto_menu_id:
2027 editUrl();
2028 break;
2029
2030 case R.id.bookmarks_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07002031 bookmarksOrHistoryPicker(ComboViews.Bookmarks);
2032 break;
2033
2034 case R.id.history_menu_id:
2035 bookmarksOrHistoryPicker(ComboViews.History);
2036 break;
2037
2038 case R.id.snapshots_menu_id:
2039 bookmarksOrHistoryPicker(ComboViews.Snapshots);
Michael Kolb8233fac2010-10-26 16:08:53 -07002040 break;
2041
Pankaj Garg49b79252014-11-07 17:33:41 -08002042 case R.id.bookmark_this_page_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002043 bookmarkCurrentPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07002044 break;
2045
2046 case R.id.stop_reload_menu_id:
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002047 if (isInLoad()) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002048 stopLoading();
2049 } else {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002050 Tab currentTab = mTabControl.getCurrentTab();
2051 if (currentTab.hasCrashed) {
2052 currentTab.replaceCrashView(getCurrentTopWebView(),
2053 currentTab.getViewContainer());
2054 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002055 getCurrentTopWebView().reload();
2056 }
2057 break;
2058
Michael Kolb8233fac2010-10-26 16:08:53 -07002059 case R.id.forward_menu_id:
John Reckef654f12011-07-12 16:42:08 -07002060 getCurrentTab().goForward();
Michael Kolb8233fac2010-10-26 16:08:53 -07002061 break;
2062
2063 case R.id.close_menu_id:
2064 // Close the subwindow if it exists.
2065 if (mTabControl.getCurrentSubWindow() != null) {
2066 dismissSubWindow(mTabControl.getCurrentTab());
2067 break;
2068 }
2069 closeCurrentTab();
2070 break;
2071
kaiyiza8b6dbb2013-07-29 18:11:22 +08002072 case R.id.exit_menu_id:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002073 Object[] params = { new String("persist.debug.browsermonkeytest")};
2074 Class[] type = new Class[] {String.class};
Bijan Amirzada58383e72014-04-01 14:45:22 -07002075 String ret = (String)ReflectHelper.invokeMethod(
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002076 "android.os.SystemProperties","get", type, params);
kaiyiza8b6dbb2013-07-29 18:11:22 +08002077 if (ret != null && ret.equals("enable"))
2078 break;
Panos Thomas4bdb5252014-11-13 16:20:11 -08002079 if (BrowserConfig.getInstance(getContext())
2080 .hasFeature(BrowserConfig.Feature.EXIT_DIALOG))
2081 showExitDialog(mActivity);
luxiaolb40014b2013-07-19 10:01:43 +08002082 return true;
Michael Kolb8233fac2010-10-26 16:08:53 -07002083 case R.id.homepage_menu_id:
2084 Tab current = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07002085 loadUrl(current, mSettings.getHomePage());
Michael Kolb8233fac2010-10-26 16:08:53 -07002086 break;
2087
2088 case R.id.preferences_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002089 openPreferences();
Michael Kolb8233fac2010-10-26 16:08:53 -07002090 break;
2091
2092 case R.id.find_menu_id:
Michael Kolbe11b9212012-04-13 13:39:54 -07002093 findOnPage();
Michael Kolb8233fac2010-10-26 16:08:53 -07002094 break;
2095
John Reck2bc80422011-06-30 15:11:49 -07002096 case R.id.save_snapshot_menu_id:
2097 final Tab source = getTabControl().getCurrentTab();
John Reckf33b1632011-06-04 20:00:23 -07002098 if (source == null) break;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002099 createScreenshotAsync(
2100 source.getWebView(),
2101 getDesiredThumbnailWidth(mActivity),
2102 getDesiredThumbnailHeight(mActivity),
2103 new ValueCallback<Bitmap>() {
2104 @Override
2105 public void onReceiveValue(Bitmap bitmap) {
2106 new SaveSnapshotTask(source, bitmap).execute();
2107 }
2108 });
Leon Scrogginsac993842011-02-02 12:54:07 -05002109 break;
2110
Michael Kolb8233fac2010-10-26 16:08:53 -07002111 case R.id.page_info_menu_id:
Michael Kolb315d5022011-10-13 12:47:11 -07002112 showPageInfo();
Michael Kolb8233fac2010-10-26 16:08:53 -07002113 break;
2114
John Recke1a03a32011-09-14 17:04:16 -07002115 case R.id.snapshot_go_live:
2116 goLive();
2117 return true;
2118
Michael Kolb8233fac2010-10-26 16:08:53 -07002119 case R.id.share_page_menu_id:
2120 Tab currentTab = mTabControl.getCurrentTab();
2121 if (null == currentTab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002122 return false;
2123 }
Michael Kolbba99c5d2010-11-29 14:57:41 -08002124 shareCurrentPage(currentTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002125 break;
2126
2127 case R.id.dump_nav_menu_id:
2128 getCurrentTopWebView().debugDump();
2129 break;
2130
Michael Kolb8233fac2010-10-26 16:08:53 -07002131 case R.id.zoom_in_menu_id:
2132 getCurrentTopWebView().zoomIn();
2133 break;
2134
2135 case R.id.zoom_out_menu_id:
2136 getCurrentTopWebView().zoomOut();
2137 break;
2138
2139 case R.id.view_downloads_menu_id:
2140 viewDownloads();
2141 break;
2142
John Reck42229bc2011-08-19 13:26:43 -07002143 case R.id.ua_desktop_menu_id:
Michael Kolb80f75082012-04-10 10:50:06 -07002144 toggleUserAgent();
John Reck42229bc2011-08-19 13:26:43 -07002145 break;
2146
Michael Kolb8233fac2010-10-26 16:08:53 -07002147 case R.id.window_one_menu_id:
2148 case R.id.window_two_menu_id:
2149 case R.id.window_three_menu_id:
2150 case R.id.window_four_menu_id:
2151 case R.id.window_five_menu_id:
2152 case R.id.window_six_menu_id:
2153 case R.id.window_seven_menu_id:
2154 case R.id.window_eight_menu_id:
2155 {
2156 int menuid = item.getItemId();
2157 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
2158 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
2159 Tab desiredTab = mTabControl.getTab(id);
2160 if (desiredTab != null &&
2161 desiredTab != mTabControl.getCurrentTab()) {
Michael Kolbc831b632011-05-11 09:30:34 -07002162 switchToTab(desiredTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002163 }
2164 break;
2165 }
2166 }
2167 }
2168 break;
2169
Axesh R. Ajmera652d08e2014-06-16 16:36:33 -07002170 case R.id.about_menu_id:
Pankaj Garg18902562014-12-05 16:18:51 -08002171 Bundle bundle = new Bundle();
2172 bundle.putCharSequence("UA", Engine.getDefaultUserAgent());
2173 bundle.putCharSequence("TabTitle", mTabControl.getCurrentTab().getTitle());
2174 bundle.putCharSequence("TabURL", mTabControl.getCurrentTab().getUrl());
2175 BrowserPreferencesPage.startPreferenceFragmentExtraForResult(mActivity,
2176 AboutPreferencesFragment.class.getName(), bundle, 0);
Axesh R. Ajmera652d08e2014-06-16 16:36:33 -07002177 break;
2178
Pankaj Garg49b79252014-11-07 17:33:41 -08002179 case R.id.add_to_homescreen:
2180 final WebView w = getCurrentTopWebView();
2181 final EditText input = new EditText(getContext());
2182 input.setText(w.getTitle());
2183 new AlertDialog.Builder(getContext())
2184 .setTitle("Add to homescreen")
2185 .setMessage("Title")
2186 .setView(input)
2187 .setPositiveButton("Add", new DialogInterface.OnClickListener() {
2188 public void onClick(DialogInterface dialog, int whichButton) {
2189 mActivity.sendBroadcast(BookmarkUtils.createAddToHomeIntent(
2190 getContext(),
2191 w.getUrl(),
2192 input.getText().toString(),
2193 w.getViewportBitmap(),
2194 w.getFavicon()));
2195
2196 mActivity.startActivity(new Intent(Intent.ACTION_MAIN)
2197 .addCategory(Intent.CATEGORY_HOME));
2198 }})
2199 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
2200 public void onClick(DialogInterface dialog, int whichButton) {
2201 // Do nothing.
2202 }
2203 })
2204 .show();
2205 break;
2206
Michael Kolb8233fac2010-10-26 16:08:53 -07002207 default:
2208 return false;
2209 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002210 return true;
2211 }
2212
John Reck68234a92012-04-19 15:27:12 -07002213 private class SaveSnapshotTask extends AsyncTask<Void, Void, Long>
2214 implements OnCancelListener {
2215
2216 private Tab mTab;
2217 private Dialog mProgressDialog;
2218 private ContentValues mValues;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002219 private Bitmap mBitmap;
John Reck68234a92012-04-19 15:27:12 -07002220
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002221 private SaveSnapshotTask(Tab tab, Bitmap bm) {
John Reck68234a92012-04-19 15:27:12 -07002222 mTab = tab;
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002223 mBitmap = bm;
John Reck68234a92012-04-19 15:27:12 -07002224 }
2225
2226 @Override
2227 protected void onPreExecute() {
2228 CharSequence message = mActivity.getText(R.string.saving_snapshot);
2229 mProgressDialog = ProgressDialog.show(mActivity, null, message,
2230 true, true, this);
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002231 mValues = mTab.createSnapshotValues(mBitmap);
John Reck68234a92012-04-19 15:27:12 -07002232 }
2233
2234 @Override
2235 protected Long doInBackground(Void... params) {
2236 if (!mTab.saveViewState(mValues)) {
2237 return null;
2238 }
2239 if (isCancelled()) {
2240 String path = mValues.getAsString(Snapshots.VIEWSTATE_PATH);
2241 File file = mActivity.getFileStreamPath(path);
2242 if (!file.delete()) {
2243 file.deleteOnExit();
2244 }
2245 return null;
2246 }
2247 final ContentResolver cr = mActivity.getContentResolver();
2248 Uri result = cr.insert(Snapshots.CONTENT_URI, mValues);
2249 if (result == null) {
2250 return null;
2251 }
2252 long id = ContentUris.parseId(result);
2253 return id;
2254 }
2255
2256 @Override
2257 protected void onPostExecute(Long id) {
2258 if (isCancelled()) {
2259 return;
2260 }
2261 mProgressDialog.dismiss();
2262 if (id == null) {
2263 Toast.makeText(mActivity, R.string.snapshot_failed,
2264 Toast.LENGTH_SHORT).show();
2265 return;
2266 }
2267 Bundle b = new Bundle();
2268 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
2269 mUi.showComboView(ComboViews.Snapshots, b);
2270 }
2271
2272 @Override
2273 public void onCancel(DialogInterface dialog) {
2274 cancel(true);
2275 }
2276 }
2277
Michael Kolb80f75082012-04-10 10:50:06 -07002278 @Override
2279 public void toggleUserAgent() {
2280 WebView web = getCurrentWebView();
2281 mSettings.toggleDesktopUseragent(web);
Michael Kolb80f75082012-04-10 10:50:06 -07002282 }
2283
2284 @Override
2285 public void findOnPage() {
2286 getCurrentTopWebView().showFindDialog(null, true);
2287 }
2288
2289 @Override
2290 public void openPreferences() {
Enrico Rosd6efa972014-12-02 19:49:59 -08002291 BrowserPreferencesPage.startPreferencesForResult(mActivity, getCurrentTopWebView().getUrl(), PREFERENCES_PAGE);
Michael Kolb80f75082012-04-10 10:50:06 -07002292 }
2293
2294 @Override
2295 public void bookmarkCurrentPage() {
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002296 WebView w = getCurrentTopWebView();
2297 if (w == null)
2298 return;
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002299 final Intent i = createBookmarkCurrentPageIntent(false);
2300 createScreenshotAsync(
2301 w, getDesiredThumbnailWidth(mActivity),
2302 getDesiredThumbnailHeight(mActivity),
2303 new ValueCallback<Bitmap>() {
2304 @Override
2305 public void onReceiveValue(Bitmap bitmap) {
2306 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL, bitmap);
2307 mActivity.startActivity(i);
2308 }
2309 });
Michael Kolb80f75082012-04-10 10:50:06 -07002310 }
2311
John Recke1a03a32011-09-14 17:04:16 -07002312 private void goLive() {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002313 SnapshotTab t = (SnapshotTab) getCurrentTab();
Tarun Nainani8eb00912014-07-17 12:28:32 -07002314 String url = t.getLiveUrl();
Axesh R. Ajmera8b3ed5d2014-10-22 16:35:25 -07002315 boolean onlySingleTabRemaining = false;
2316 if (mTabControl.getTabCount() > 1) {
2317 // destroy the old snapshot tab
2318 closeCurrentTab();
2319 } else {
2320 onlySingleTabRemaining = true;
2321 }
Tarun Nainani8eb00912014-07-17 12:28:32 -07002322 Tab liveTab = createNewTab(false, true, false);
Axesh R. Ajmera8b3ed5d2014-10-22 16:35:25 -07002323 if (onlySingleTabRemaining) {
2324 closeTab(t);
2325 }
2326
Tarun Nainani8eb00912014-07-17 12:28:32 -07002327 loadUrl(liveTab, url);
John Recke1a03a32011-09-14 17:04:16 -07002328 }
2329
luxiaolb40014b2013-07-19 10:01:43 +08002330 private void showExitDialog(final Activity activity) {
2331 new AlertDialog.Builder(activity)
2332 .setTitle(R.string.exit_browser_title)
Enrico Ros1f5a0952014-11-18 20:15:48 -08002333 /* disabled, was worrying people: .setIcon(android.R.drawable.ic_dialog_alert) */
luxiaolb40014b2013-07-19 10:01:43 +08002334 .setMessage(R.string.exit_browser_msg)
2335 .setNegativeButton(R.string.exit_minimize, new DialogInterface.OnClickListener() {
2336 public void onClick(DialogInterface dialog, int which) {
2337 activity.moveTaskToBack(true);
2338 dialog.dismiss();
2339 }
2340 })
2341 .setPositiveButton(R.string.exit_quit, new DialogInterface.OnClickListener() {
2342 public void onClick(DialogInterface dialog, int which) {
2343 activity.finish();
2344 mHandler.postDelayed(new Runnable() {
2345 @Override
2346 public void run() {
luxiaolb40014b2013-07-19 10:01:43 +08002347 mCrashRecoveryHandler.clearState(true);
2348 int pid = android.os.Process.myPid();
2349 android.os.Process.killProcess(pid);
2350 }
2351 }, 300);
2352 dialog.dismiss();
2353 }
2354 })
2355 .show();
2356 }
Michael Kolb315d5022011-10-13 12:47:11 -07002357 @Override
2358 public void showPageInfo() {
2359 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
2360 }
2361
John Reck9c35b9c2012-05-30 10:08:50 -07002362 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002363 public boolean onContextItemSelected(MenuItem item) {
John Reckdbf57df2010-11-09 16:34:03 -08002364 // Let the History and Bookmark fragments handle menus they created.
2365 if (item.getGroupId() == R.id.CONTEXT_MENU) {
2366 return false;
2367 }
2368
Michael Kolb8233fac2010-10-26 16:08:53 -07002369 int id = item.getItemId();
2370 boolean result = true;
2371 switch (id) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002372 // -- Browser context menu
2373 case R.id.open_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07002374 case R.id.save_link_context_menu_id:
Tarun Nainani700b69b2014-03-26 16:07:25 -07002375 case R.id.save_link_bookmark_context_menu_id:
Michael Kolb8233fac2010-10-26 16:08:53 -07002376 case R.id.copy_link_context_menu_id:
2377 final WebView webView = getCurrentTopWebView();
2378 if (null == webView) {
2379 result = false;
2380 break;
2381 }
2382 final HashMap<String, WebView> hrefMap =
2383 new HashMap<String, WebView>();
2384 hrefMap.put("webview", webView);
2385 final Message msg = mHandler.obtainMessage(
2386 FOCUS_NODE_HREF, id, 0, hrefMap);
2387 webView.requestFocusNodeHref(msg);
2388 break;
2389
2390 default:
2391 // For other context menus
2392 result = onOptionsItemSelected(item);
2393 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002394 return result;
2395 }
2396
2397 /**
2398 * support programmatically opening the context menu
2399 */
2400 public void openContextMenu(View view) {
2401 mActivity.openContextMenu(view);
2402 }
2403
2404 /**
2405 * programmatically open the options menu
2406 */
2407 public void openOptionsMenu() {
2408 mActivity.openOptionsMenu();
2409 }
2410
John Reck9c35b9c2012-05-30 10:08:50 -07002411 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002412 public boolean onMenuOpened(int featureId, Menu menu) {
2413 if (mOptionsMenuOpen) {
2414 if (mConfigChanged) {
2415 // We do not need to make any changes to the state of the
2416 // title bar, since the only thing that happened was a
2417 // change in orientation
2418 mConfigChanged = false;
2419 } else {
2420 if (!mExtendedMenuOpen) {
2421 mExtendedMenuOpen = true;
2422 mUi.onExtendedMenuOpened();
2423 } else {
2424 // Switching the menu back to icon view, so show the
2425 // title bar once again.
2426 mExtendedMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002427 mUi.onExtendedMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002428 }
2429 }
2430 } else {
2431 // The options menu is closed, so open it, and show the title
2432 mOptionsMenuOpen = true;
2433 mConfigChanged = false;
2434 mExtendedMenuOpen = false;
2435 mUi.onOptionsMenuOpened();
2436 }
2437 return true;
2438 }
2439
John Reck9c35b9c2012-05-30 10:08:50 -07002440 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002441 public void onOptionsMenuClosed(Menu menu) {
2442 mOptionsMenuOpen = false;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002443 mUi.onOptionsMenuClosed(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002444 }
2445
John Reck9c35b9c2012-05-30 10:08:50 -07002446 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002447 public void onContextMenuClosed(Menu menu) {
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002448 mUi.onContextMenuClosed(menu, isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002449 }
2450
2451 // Helper method for getting the top window.
2452 @Override
2453 public WebView getCurrentTopWebView() {
2454 return mTabControl.getCurrentTopWebView();
2455 }
2456
2457 @Override
2458 public WebView getCurrentWebView() {
2459 return mTabControl.getCurrentWebView();
2460 }
2461
2462 /*
2463 * This method is called as a result of the user selecting the options
2464 * menu to see the download window. It shows the download window on top of
2465 * the current window.
2466 */
2467 void viewDownloads() {
2468 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2469 mActivity.startActivity(intent);
2470 }
2471
John Reck30b065e2011-07-19 10:58:05 -07002472 int getActionModeHeight() {
2473 TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
2474 new int[] { android.R.attr.actionBarSize });
2475 int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
2476 actionBarSizeTypedArray.recycle();
2477 return size;
2478 }
2479
Michael Kolb8233fac2010-10-26 16:08:53 -07002480 // action mode
2481
John Reck9c35b9c2012-05-30 10:08:50 -07002482 @Override
2483 public void onActionModeStarted(ActionMode mode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002484 mUi.onActionModeStarted(mode);
2485 mActionMode = mode;
2486 }
2487
2488 /*
2489 * True if a custom ActionMode (i.e. find or select) is in use.
2490 */
2491 @Override
2492 public boolean isInCustomActionMode() {
2493 return mActionMode != null;
2494 }
2495
2496 /*
2497 * End the current ActionMode.
2498 */
2499 @Override
2500 public void endActionMode() {
2501 if (mActionMode != null) {
2502 mActionMode.finish();
2503 }
2504 }
2505
2506 /*
2507 * Called by find and select when they are finished. Replace title bars
2508 * as necessary.
2509 */
John Reck9c35b9c2012-05-30 10:08:50 -07002510 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002511 public void onActionModeFinished(ActionMode mode) {
2512 if (!isInCustomActionMode()) return;
Michael Kolbb1fb70c2011-11-21 12:38:14 -08002513 mUi.onActionModeFinished(isInLoad());
Michael Kolb8233fac2010-10-26 16:08:53 -07002514 mActionMode = null;
2515 }
2516
2517 boolean isInLoad() {
Michael Kolbc5b0b2d2011-11-29 16:13:35 -08002518 final Tab tab = getCurrentTab();
2519 return (tab != null) && tab.inPageLoad();
Michael Kolb8233fac2010-10-26 16:08:53 -07002520 }
2521
2522 // bookmark handling
2523
2524 /**
2525 * add the current page as a bookmark to the given folder id
2526 * @param folderId use -1 for the default folder
John Reckd3e4d5b2011-07-13 15:48:43 -07002527 * @param editExisting If true, check to see whether the site is already
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05002528 * bookmarked, and if it is, edit that bookmark. If false, and
2529 * the site is already bookmarked, do not attempt to edit the
2530 * existing bookmark.
Michael Kolb8233fac2010-10-26 16:08:53 -07002531 */
2532 @Override
John Reckd3e4d5b2011-07-13 15:48:43 -07002533 public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
John Recka60fffa2011-09-06 16:30:29 -07002534 WebView w = getCurrentTopWebView();
2535 if (w == null) {
2536 return null;
2537 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002538 Intent i = new Intent(mActivity,
2539 AddBookmarkPage.class);
Michael Kolb8233fac2010-10-26 16:08:53 -07002540 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
2541 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
2542 String touchIconUrl = w.getTouchIconUrl();
2543 if (touchIconUrl != null) {
2544 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
2545 WebSettings settings = w.getSettings();
2546 if (settings != null) {
2547 i.putExtra(AddBookmarkPage.USER_AGENT,
2548 settings.getUserAgentString());
2549 }
2550 }
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002551 //SWE: Thumbnail will need to be set asynchronously
Michael Kolb8233fac2010-10-26 16:08:53 -07002552 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reckd3e4d5b2011-07-13 15:48:43 -07002553 if (editExisting) {
Leon Scrogginsbdff8a72011-02-11 15:49:04 -05002554 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
2555 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002556 // Put the dialog at the upper right of the screen, covering the
2557 // star on the title bar.
2558 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reckd3e4d5b2011-07-13 15:48:43 -07002559 return i;
Michael Kolb8233fac2010-10-26 16:08:53 -07002560 }
2561
2562 // file chooser
John Reck9c35b9c2012-05-30 10:08:50 -07002563 @Override
Ben Murdoch8cad4132012-01-11 10:56:43 +00002564 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002565 mUploadHandler = new UploadHandler(this);
Ben Murdoch8cad4132012-01-11 10:56:43 +00002566 mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
Michael Kolb8233fac2010-10-26 16:08:53 -07002567 }
2568
Vivek Sekharb54614f2014-05-01 19:03:37 -07002569 @Override
2570 public void showFileChooser(ValueCallback<String[]> uploadFilePaths, String acceptTypes,
2571 boolean capture) {
2572 mUploadHandler = new UploadHandler(this);
2573 mUploadHandler.showFileChooser(uploadFilePaths, acceptTypes, capture);
2574 }
2575
Michael Kolb8233fac2010-10-26 16:08:53 -07002576 // thumbnails
2577
2578 /**
2579 * Return the desired width for thumbnail screenshots, which are stored in
2580 * the database, and used on the bookmarks screen.
2581 * @param context Context for finding out the density of the screen.
2582 * @return desired width for thumbnail screenshot.
2583 */
2584 static int getDesiredThumbnailWidth(Context context) {
2585 return context.getResources().getDimensionPixelOffset(
2586 R.dimen.bookmarkThumbnailWidth);
2587 }
2588
2589 /**
2590 * Return the desired height for thumbnail screenshots, which are stored in
2591 * the database, and used on the bookmarks screen.
2592 * @param context Context for finding out the density of the screen.
2593 * @return desired height for thumbnail screenshot.
2594 */
2595 static int getDesiredThumbnailHeight(Context context) {
2596 return context.getResources().getDimensionPixelOffset(
2597 R.dimen.bookmarkThumbnailHeight);
2598 }
2599
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002600 static void createScreenshotAsync(WebView view, int width, int height,
2601 final ValueCallback<Bitmap> cb) {
2602 if (view == null || width == 0 || height == 0) {
2603 return;
2604 }
2605
2606 view.getContentBitmapAsync(
2607 (float) width / view.getWidth(),
2608 new Rect(),
2609 new ValueCallback<Bitmap>() {
2610 @Override
2611 public void onReceiveValue(Bitmap bitmap) {
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002612 if (bitmap != null)
2613 bitmap = bitmap.copy(Bitmap.Config.RGB_565, false);
2614 cb.onReceiveValue(bitmap);
2615 }});
2616 }
2617
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002618 private void updateScreenshot(final Tab tab) {
2619 createScreenshotAsync(
2620 tab.getWebView(),
2621 getDesiredThumbnailWidth(mActivity),
2622 getDesiredThumbnailHeight(mActivity),
2623 new ValueCallback<Bitmap>() {
2624 @Override
2625 public void onReceiveValue(Bitmap bitmap) {
2626 updateScreenshot(tab, bitmap);
2627 }
2628 });
2629 }
Tarun Nainaniea28dde2014-08-27 17:25:09 -07002630
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002631 private void updateScreenshot(Tab tab, final Bitmap bm) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002632 // If this is a bookmarked site, add a screenshot to the database.
Michael Kolb8233fac2010-10-26 16:08:53 -07002633 // FIXME: Would like to make sure there is actually something to
2634 // draw, but the API for that (WebViewCore.pictureReady()) is not
2635 // currently accessible here.
2636
John Reck34ef2672011-02-10 11:30:55 -08002637 WebView view = tab.getWebView();
John Reck7a591202011-02-16 15:44:01 -08002638 if (view == null) {
2639 // Tab was destroyed
2640 return;
2641 }
John Reck34ef2672011-02-10 11:30:55 -08002642 final String url = tab.getUrl();
2643 final String originalUrl = view.getOriginalUrl();
kaiyiz6e5b3e02013-08-19 20:02:01 +08002644 final String thumbnailUrl = mUpdateMyNavThumbnailUrl;
John Reck34ef2672011-02-10 11:30:55 -08002645 if (TextUtils.isEmpty(url)) {
2646 return;
2647 }
2648
kaiyiz6e5b3e02013-08-19 20:02:01 +08002649 //update My Navigation Thumbnails
Tarun Nainanicc8ac9e2015-01-08 14:45:21 -08002650 if (bm != null) {
Vivek Sekhar46c3ec02014-10-09 17:28:57 -07002651 updateMyNavigationThumbnail(url, bm);
kaiyiz6e5b3e02013-08-19 20:02:01 +08002652 }
John Reck34ef2672011-02-10 11:30:55 -08002653 // Only update thumbnails for web urls (http(s)://), not for
2654 // about:, javascript:, data:, etc...
2655 // Unless it is a bookmarked site, then always update
2656 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
2657 return;
2658 }
2659
kaiyiz6e5b3e02013-08-19 20:02:01 +08002660 if (url != null && mUpdateMyNavThumbnailUrl != null
2661 && Patterns.WEB_URL.matcher(url).matches()
2662 && Patterns.WEB_URL.matcher(mUpdateMyNavThumbnailUrl).matches()) {
2663 String urlHost = (new WebAddress(url)).getHost();
2664 String bookmarkHost = (new WebAddress(mUpdateMyNavThumbnailUrl)).getHost();
2665 if (urlHost == null || urlHost.length() == 0 || bookmarkHost == null
2666 || bookmarkHost.length() == 0) {
2667 return;
2668 }
2669 String urlDomain = urlHost.substring(urlHost.indexOf('.'), urlHost.length());
2670 String bookmarkDomain = bookmarkHost.substring(bookmarkHost.indexOf('.'),
2671 bookmarkHost.length());
2672 Log.d(LOGTAG, "addressUrl domain is " + urlDomain);
2673 Log.d(LOGTAG, "bookmarkUrl domain is " + bookmarkDomain);
2674 if (!bookmarkDomain.equals(urlDomain)) {
2675 return;
2676 }
2677 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002678 if (bm == null) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002679 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
2680 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2681 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
2682 500);
2683 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002684 return;
2685 }
2686
2687 final ContentResolver cr = mActivity.getContentResolver();
John Reck34ef2672011-02-10 11:30:55 -08002688 new AsyncTask<Void, Void, Void>() {
2689 @Override
2690 protected Void doInBackground(Void... unused) {
2691 Cursor cursor = null;
2692 try {
2693 // TODO: Clean this up
kaiyiz6e5b3e02013-08-19 20:02:01 +08002694 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl,
2695 mUpdateMyNavThumbnail ? ((thumbnailUrl != null) ? thumbnailUrl : url)
2696 : url);
2697 if (mUpdateMyNavThumbnail) {
2698 mUpdateMyNavThumbnail = false;
2699 mUpdateMyNavThumbnailUrl = null;
2700 }
John Reck34ef2672011-02-10 11:30:55 -08002701 if (cursor != null && cursor.moveToFirst()) {
2702 final ByteArrayOutputStream os =
2703 new ByteArrayOutputStream();
2704 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Michael Kolb8233fac2010-10-26 16:08:53 -07002705
John Reck34ef2672011-02-10 11:30:55 -08002706 ContentValues values = new ContentValues();
2707 values.put(Images.THUMBNAIL, os.toByteArray());
Michael Kolb8233fac2010-10-26 16:08:53 -07002708
John Reck34ef2672011-02-10 11:30:55 -08002709 do {
John Reck617fd832011-02-16 14:35:59 -08002710 values.put(Images.URL, cursor.getString(0));
John Reck34ef2672011-02-10 11:30:55 -08002711 cr.update(Images.CONTENT_URI, values, null, null);
2712 } while (cursor.moveToNext());
Michael Kolb8233fac2010-10-26 16:08:53 -07002713 }
John Reck34ef2672011-02-10 11:30:55 -08002714 } catch (IllegalStateException e) {
2715 // Ignore
Mattias Nilsson561d1952011-10-04 10:18:50 +02002716 } catch (SQLiteException s) {
2717 // Added for possible error when user tries to remove the same bookmark
2718 // that is being updated with a screen shot
2719 Log.w(LOGTAG, "Error when running updateScreenshot ", s);
John Reck34ef2672011-02-10 11:30:55 -08002720 } finally {
2721 if (cursor != null) cursor.close();
Michael Kolb8233fac2010-10-26 16:08:53 -07002722 }
John Reck34ef2672011-02-10 11:30:55 -08002723 return null;
2724 }
2725 }.execute();
Michael Kolb8233fac2010-10-26 16:08:53 -07002726 }
2727
2728 private class Copy implements OnMenuItemClickListener {
2729 private CharSequence mText;
2730
John Reck9c35b9c2012-05-30 10:08:50 -07002731 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002732 public boolean onMenuItemClick(MenuItem item) {
2733 copy(mText);
2734 return true;
2735 }
2736
2737 public Copy(CharSequence toCopy) {
2738 mText = toCopy;
2739 }
2740 }
2741
Leon Scroggins63c02662010-11-18 15:16:27 -05002742 private static class Download implements OnMenuItemClickListener {
2743 private Activity mActivity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002744 private String mText;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002745 private boolean mPrivateBrowsing;
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002746 private String mUserAgent;
George Mount387d45d2011-10-07 15:57:53 -07002747 private static final String FALLBACK_EXTENSION = "dat";
2748 private static final String IMAGE_BASE_FORMAT = "yyyy-MM-dd-HH-mm-ss-";
Michael Kolb8233fac2010-10-26 16:08:53 -07002749
John Reck9c35b9c2012-05-30 10:08:50 -07002750 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002751 public boolean onMenuItemClick(MenuItem item) {
George Mount387d45d2011-10-07 15:57:53 -07002752 if (DataUri.isDataUri(mText)) {
2753 saveDataUri();
2754 } else {
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002755 DownloadHandler.onDownloadStartNoStream(mActivity, mText, mUserAgent,
luxiaol62677b02013-07-22 07:54:49 +08002756 null, null, null, mPrivateBrowsing, 0);
George Mount387d45d2011-10-07 15:57:53 -07002757 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002758 return true;
2759 }
2760
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002761 public Download(Activity activity, String toDownload, boolean privateBrowsing,
2762 String userAgent) {
Leon Scroggins63c02662010-11-18 15:16:27 -05002763 mActivity = activity;
Michael Kolb8233fac2010-10-26 16:08:53 -07002764 mText = toDownload;
Kristian Monsenbc5cc752011-03-02 13:14:03 +00002765 mPrivateBrowsing = privateBrowsing;
Andreas Sandblad8e4ce662012-06-11 11:02:49 +02002766 mUserAgent = userAgent;
Michael Kolb8233fac2010-10-26 16:08:53 -07002767 }
George Mount387d45d2011-10-07 15:57:53 -07002768
2769 /**
2770 * Treats mText as a data URI and writes its contents to a file
2771 * based on the current time.
2772 */
2773 private void saveDataUri() {
2774 FileOutputStream outputStream = null;
2775 try {
2776 DataUri uri = new DataUri(mText);
2777 File target = getTarget(uri);
2778 outputStream = new FileOutputStream(target);
2779 outputStream.write(uri.getData());
2780 final DownloadManager manager =
2781 (DownloadManager) mActivity.getSystemService(Context.DOWNLOAD_SERVICE);
2782 manager.addCompletedDownload(target.getName(),
2783 mActivity.getTitle().toString(), false,
2784 uri.getMimeType(), target.getAbsolutePath(),
John Reck9c35b9c2012-05-30 10:08:50 -07002785 uri.getData().length, true);
George Mount387d45d2011-10-07 15:57:53 -07002786 } catch (IOException e) {
2787 Log.e(LOGTAG, "Could not save data URL");
2788 } finally {
2789 if (outputStream != null) {
2790 try {
2791 outputStream.close();
2792 } catch (IOException e) {
2793 // ignore close errors
2794 }
2795 }
2796 }
2797 }
2798
2799 /**
2800 * Creates a File based on the current time stamp and uses
2801 * the mime type of the DataUri to get the extension.
2802 */
2803 private File getTarget(DataUri uri) throws IOException {
2804 File dir = mActivity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
Johan Redestigaa676182012-10-03 13:33:01 +02002805 DateFormat format = new SimpleDateFormat(IMAGE_BASE_FORMAT, Locale.US);
George Mount387d45d2011-10-07 15:57:53 -07002806 String nameBase = format.format(new Date());
2807 String mimeType = uri.getMimeType();
2808 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
2809 String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
2810 if (extension == null) {
2811 Log.w(LOGTAG, "Unknown mime type in data URI" + mimeType);
2812 extension = FALLBACK_EXTENSION;
2813 }
2814 extension = "." + extension; // createTempFile needs the '.'
2815 File targetFile = File.createTempFile(nameBase, extension, dir);
2816 return targetFile;
2817 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002818 }
2819
Cary Clark8974d282010-11-22 10:46:05 -05002820 private static class SelectText implements OnMenuItemClickListener {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002821 private WebView mWebView;
Cary Clark8974d282010-11-22 10:46:05 -05002822
John Reck9c35b9c2012-05-30 10:08:50 -07002823 @Override
Cary Clark8974d282010-11-22 10:46:05 -05002824 public boolean onMenuItemClick(MenuItem item) {
2825 if (mWebView != null) {
2826 return mWebView.selectText();
2827 }
2828 return false;
2829 }
2830
2831 public SelectText(WebView webView) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002832 mWebView = webView;
Cary Clark8974d282010-11-22 10:46:05 -05002833 }
2834
2835 }
2836
Michael Kolb8233fac2010-10-26 16:08:53 -07002837 /********************** TODO: UI stuff *****************************/
2838
2839 // these methods have been copied, they still need to be cleaned up
2840
2841 /****************** tabs ***************************************************/
2842
2843 // basic tab interactions:
2844
2845 // it is assumed that tabcontrol already knows about the tab
2846 protected void addTab(Tab tab) {
2847 mUi.addTab(tab);
2848 }
2849
2850 protected void removeTab(Tab tab) {
2851 mUi.removeTab(tab);
2852 mTabControl.removeTab(tab);
John Reck378a4102011-06-09 16:23:01 -07002853 mCrashRecoveryHandler.backupState();
Michael Kolb8233fac2010-10-26 16:08:53 -07002854 }
2855
Michael Kolbf2055602011-04-09 17:20:03 -07002856 @Override
2857 public void setActiveTab(Tab tab) {
Michael Kolbcd424e92011-02-24 10:26:26 -08002858 // monkey protection against delayed start
2859 if (tab != null) {
2860 mTabControl.setCurrentTab(tab);
2861 // the tab is guaranteed to have a webview after setCurrentTab
2862 mUi.setActiveTab(tab);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08002863 tab.setTimeStamp();
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07002864 //Purge active tabs
2865 MemoryMonitor.purgeActiveTabs(mActivity.getApplicationContext(), this, mSettings);
Michael Kolbcd424e92011-02-24 10:26:26 -08002866 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002867 }
2868
John Reck8bcafc12011-08-29 16:43:02 -07002869 protected void closeEmptyTab() {
Michael Kolb8233fac2010-10-26 16:08:53 -07002870 Tab current = mTabControl.getCurrentTab();
2871 if (current != null
2872 && current.getWebView().copyBackForwardList().getSize() == 0) {
John Reck8bcafc12011-08-29 16:43:02 -07002873 closeCurrentTab();
Michael Kolb8233fac2010-10-26 16:08:53 -07002874 }
2875 }
2876
John Reck26b18322011-06-21 13:08:58 -07002877 protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb8233fac2010-10-26 16:08:53 -07002878 // Dismiss the subwindow if applicable.
2879 dismissSubWindow(appTab);
2880 // Since we might kill the WebView, remove it from the
2881 // content view first.
2882 mUi.detachTab(appTab);
2883 // Recreate the main WebView after destroying the old one.
John Reck30c714c2010-12-16 17:30:34 -08002884 mTabControl.recreateWebView(appTab);
Michael Kolb8233fac2010-10-26 16:08:53 -07002885 // TODO: analyze why the remove and add are necessary
2886 mUi.attachTab(appTab);
2887 if (mTabControl.getCurrentTab() != appTab) {
Michael Kolbc831b632011-05-11 09:30:34 -07002888 switchToTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002889 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002890 } else {
2891 // If the tab was the current tab, we have to attach
2892 // it to the view system again.
2893 setActiveTab(appTab);
John Reck30c714c2010-12-16 17:30:34 -08002894 loadUrlDataIn(appTab, urlData);
Michael Kolb8233fac2010-10-26 16:08:53 -07002895 }
2896 }
2897
2898 // Remove the sub window if it exists. Also called by TabControl when the
2899 // user clicks the 'X' to dismiss a sub window.
John Reck9c35b9c2012-05-30 10:08:50 -07002900 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07002901 public void dismissSubWindow(Tab tab) {
2902 removeSubWindow(tab);
2903 // dismiss the subwindow. This will destroy the WebView.
2904 tab.dismissSubWindow();
Michael Kolbe8c97572011-11-21 14:03:56 -08002905 WebView wv = getCurrentTopWebView();
2906 if (wv != null) {
2907 wv.requestFocus();
2908 }
Michael Kolb8233fac2010-10-26 16:08:53 -07002909 }
2910
2911 @Override
2912 public void removeSubWindow(Tab t) {
2913 if (t.getSubWebView() != null) {
2914 mUi.removeSubWindow(t.getSubViewContainer());
2915 }
2916 }
2917
2918 @Override
2919 public void attachSubWindow(Tab tab) {
2920 if (tab.getSubWebView() != null) {
2921 mUi.attachSubWindow(tab.getSubViewContainer());
2922 getCurrentTopWebView().requestFocus();
2923 }
2924 }
2925
Mathew Inwood29721c22011-06-29 17:55:24 +01002926 private Tab showPreloadedTab(final UrlData urlData) {
2927 if (!urlData.isPreloaded()) {
2928 return null;
2929 }
2930 final PreloadedTabControl tabControl = urlData.getPreloadedTab();
2931 final String sbQuery = urlData.getSearchBoxQueryToSubmit();
2932 if (sbQuery != null) {
Mathew Inwood9ad1eac2011-09-15 11:29:50 +01002933 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002934 // Could not submit query. Fallback to regular tab creation
2935 tabControl.destroy();
2936 return null;
2937 }
2938 }
Michael Kolbff6a7482011-07-26 16:37:15 -07002939 // check tab count and make room for new tab
2940 if (!mTabControl.canCreateNewTab()) {
2941 Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
2942 if (leastUsed != null) {
2943 closeTab(leastUsed);
2944 }
2945 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002946 Tab t = tabControl.getTab();
Mathew Inwoode09305e2011-09-02 12:03:26 +01002947 t.refreshIdAfterPreload();
Mathew Inwood29721c22011-06-29 17:55:24 +01002948 mTabControl.addPreloadedTab(t);
2949 addTab(t);
2950 setActiveTab(t);
2951 return t;
2952 }
2953
Michael Kolb7bcafde2011-05-09 13:55:59 -07002954 // open a non inconito tab with the given url data
2955 // and set as active tab
2956 public Tab openTab(UrlData urlData) {
Mathew Inwood29721c22011-06-29 17:55:24 +01002957 Tab tab = showPreloadedTab(urlData);
2958 if (tab == null) {
2959 tab = createNewTab(false, true, true);
Michael Kolb14612442011-06-24 13:06:29 -07002960 if ((tab != null) && !urlData.isEmpty()) {
2961 loadUrlDataIn(tab, urlData);
2962 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07002963 }
Mathew Inwood29721c22011-06-29 17:55:24 +01002964 return tab;
Michael Kolb7bcafde2011-05-09 13:55:59 -07002965 }
2966
Michael Kolb843510f2010-12-09 10:51:49 -08002967 @Override
2968 public Tab openTabToHomePage() {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002969 return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb8233fac2010-10-26 16:08:53 -07002970 }
2971
Michael Kolb8233fac2010-10-26 16:08:53 -07002972 @Override
Michael Kolb519d2282011-05-09 17:03:19 -07002973 public Tab openIncognitoTab() {
2974 return openTab(INCOGNITO_URI, true, true, false);
2975 }
2976
2977 @Override
Michael Kolb7bcafde2011-05-09 13:55:59 -07002978 public Tab openTab(String url, boolean incognito, boolean setActive,
2979 boolean useCurrent) {
John Reck5949c662011-05-27 09:52:29 -07002980 return openTab(url, incognito, setActive, useCurrent, null);
2981 }
2982
2983 @Override
2984 public Tab openTab(String url, Tab parent, boolean setActive,
2985 boolean useCurrent) {
2986 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
2987 setActive, useCurrent, parent);
2988 }
2989
2990 public Tab openTab(String url, boolean incognito, boolean setActive,
2991 boolean useCurrent, Tab parent) {
Michael Kolb7bcafde2011-05-09 13:55:59 -07002992 Tab tab = createNewTab(incognito, setActive, useCurrent);
2993 if (tab != null) {
Vivek Sekhar871172e2014-07-23 12:16:54 -07002994 if (parent instanceof SnapshotTab) {
2995 addTab(tab);
2996 if (setActive)
2997 setActiveTab(tab);
2998 }else if (parent != null && parent != tab) {
John Reck5949c662011-05-27 09:52:29 -07002999 parent.addChildTab(tab);
3000 }
Michael Kolb519d2282011-05-09 17:03:19 -07003001 if (url != null) {
John Reck26b18322011-06-21 13:08:58 -07003002 loadUrl(tab, url);
Michael Kolb519d2282011-05-09 17:03:19 -07003003 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003004 }
Michael Kolb7bcafde2011-05-09 13:55:59 -07003005 return tab;
3006 }
3007
3008 // this method will attempt to create a new tab
3009 // incognito: private browsing tab
3010 // setActive: ste tab as current tab
3011 // useCurrent: if no new tab can be created, return current tab
3012 private Tab createNewTab(boolean incognito, boolean setActive,
3013 boolean useCurrent) {
3014 Tab tab = null;
3015 if (mTabControl.canCreateNewTab()) {
Stewart Chaoe0e132e2014-12-01 18:28:22 -05003016 tab = mTabControl.createNewTab(incognito, !setActive);
Michael Kolb7bcafde2011-05-09 13:55:59 -07003017 addTab(tab);
3018 if (setActive) {
3019 setActiveTab(tab);
Axesh R. Ajmera2e241242014-05-19 15:53:38 -07003020 } else {
3021 tab.pause();
Michael Kolb7bcafde2011-05-09 13:55:59 -07003022 }
3023 } else {
3024 if (useCurrent) {
3025 tab = mTabControl.getCurrentTab();
John Reck26b18322011-06-21 13:08:58 -07003026 reuseTab(tab, null);
Michael Kolb7bcafde2011-05-09 13:55:59 -07003027 } else {
3028 mUi.showMaxTabsWarning();
3029 }
3030 }
3031 return tab;
Michael Kolb8233fac2010-10-26 16:08:53 -07003032 }
3033
John Reck2bc80422011-06-30 15:11:49 -07003034 @Override
3035 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
3036 SnapshotTab tab = null;
3037 if (mTabControl.canCreateNewTab()) {
3038 tab = mTabControl.createSnapshotTab(snapshotId);
3039 addTab(tab);
3040 if (setActive) {
3041 setActiveTab(tab);
3042 }
3043 } else {
3044 mUi.showMaxTabsWarning();
John Reckd8c74522011-06-14 08:45:00 -07003045 }
3046 return tab;
3047 }
3048
Michael Kolb8233fac2010-10-26 16:08:53 -07003049 /**
Michael Kolbc831b632011-05-11 09:30:34 -07003050 * @param tab the tab to switch to
Michael Kolb8233fac2010-10-26 16:08:53 -07003051 * @return boolean True if we successfully switched to a different tab. If
3052 * the indexth tab is null, or if that tab is the same as
3053 * the current one, return false.
3054 */
3055 @Override
Michael Kolbc831b632011-05-11 09:30:34 -07003056 public boolean switchToTab(Tab tab) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003057 Tab currentTab = mTabControl.getCurrentTab();
3058 if (tab == null || tab == currentTab) {
3059 return false;
3060 }
3061 setActiveTab(tab);
3062 return true;
3063 }
3064
3065 @Override
Michael Kolb8233fac2010-10-26 16:08:53 -07003066 public void closeCurrentTab() {
Michael Kolb2ae6ef72011-08-22 14:49:34 -07003067 closeCurrentTab(false);
3068 }
3069
3070 protected void closeCurrentTab(boolean andQuit) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003071 if (mTabControl.getTabCount() == 1) {
John Reckbc490d22011-07-22 15:04:59 -07003072 mCrashRecoveryHandler.clearState();
Michael Kolbc1eeb122011-08-01 09:56:26 -07003073 mTabControl.removeTab(getCurrentTab());
John Reck958b2422010-12-03 17:56:17 -08003074 mActivity.finish();
Michael Kolb8233fac2010-10-26 16:08:53 -07003075 return;
3076 }
Michael Kolbc831b632011-05-11 09:30:34 -07003077 final Tab current = mTabControl.getCurrentTab();
3078 final int pos = mTabControl.getCurrentPosition();
3079 Tab newTab = current.getParent();
3080 if (newTab == null) {
3081 newTab = mTabControl.getTab(pos + 1);
3082 if (newTab == null) {
3083 newTab = mTabControl.getTab(pos - 1);
Michael Kolb8233fac2010-10-26 16:08:53 -07003084 }
3085 }
Michael Kolb2ae6ef72011-08-22 14:49:34 -07003086 if (andQuit) {
3087 mTabControl.setCurrentTab(newTab);
3088 closeTab(current);
3089 } else if (switchToTab(newTab)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003090 // Close window
3091 closeTab(current);
3092 }
3093 }
3094
3095 /**
3096 * Close the tab, remove its associated title bar, and adjust mTabControl's
3097 * current tab to a valid value.
3098 */
3099 @Override
3100 public void closeTab(Tab tab) {
John Reck28263772011-10-11 17:13:42 -07003101 if (tab == mTabControl.getCurrentTab()) {
3102 closeCurrentTab();
3103 } else {
3104 removeTab(tab);
3105 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003106 }
3107
Afzal Najamd4e33312012-04-26 01:54:01 -04003108 /**
3109 * Close all tabs except the current one
3110 */
3111 @Override
3112 public void closeOtherTabs() {
3113 int inactiveTabs = mTabControl.getTabCount() - 1;
3114 for (int i = inactiveTabs; i >= 0; i--) {
3115 Tab tab = mTabControl.getTab(i);
3116 if (tab != mTabControl.getCurrentTab()) {
3117 removeTab(tab);
3118 }
3119 }
3120 }
3121
Michael Kolb8233fac2010-10-26 16:08:53 -07003122 // Called when loading from context menu or LOAD_URL message
John Reck26b18322011-06-21 13:08:58 -07003123 protected void loadUrlFromContext(String url) {
3124 Tab tab = getCurrentTab();
3125 WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb8233fac2010-10-26 16:08:53 -07003126 // In case the user enters nothing.
John Reck26b18322011-06-21 13:08:58 -07003127 if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003128 url = UrlUtils.smartUrlFilter(url);
Jonathan Dixone1d6dfc2012-12-17 13:39:17 -08003129 if (!((BrowserWebView) view).getWebViewClient().
Jonathan Dixon4d2fcab2012-02-24 00:13:06 +00003130 shouldOverrideUrlLoading(view, url)) {
John Reck26b18322011-06-21 13:08:58 -07003131 loadUrl(tab, url);
Michael Kolb8233fac2010-10-26 16:08:53 -07003132 }
3133 }
3134 }
3135
3136 /**
3137 * Load the URL into the given WebView and update the title bar
3138 * to reflect the new load. Call this instead of WebView.loadUrl
3139 * directly.
3140 * @param view The WebView used to load url.
3141 * @param url The URL to load.
3142 */
John Reck71e51422011-07-01 16:49:28 -07003143 @Override
3144 public void loadUrl(Tab tab, String url) {
John Reck26b18322011-06-21 13:08:58 -07003145 loadUrl(tab, url, null);
3146 }
3147
3148 protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
3149 if (tab != null) {
3150 dismissSubWindow(tab);
Vivek Sekhar0e10a202014-09-12 19:13:23 -07003151 mHomepageHandler.registerJsInterface(tab.getWebView(), url);
John Reck26b18322011-06-21 13:08:58 -07003152 tab.loadUrl(url, headers);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003153 if (tab.hasCrashed) {
3154 tab.replaceCrashView(tab.getWebView(), tab.getViewContainer());
3155 }
Michael Kolba53c9892011-10-05 13:31:40 -07003156 mUi.onProgressChanged(tab);
John Reck26b18322011-06-21 13:08:58 -07003157 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003158 }
3159
3160 /**
3161 * Load UrlData into a Tab and update the title bar to reflect the new
3162 * load. Call this instead of UrlData.loadIn directly.
3163 * @param t The Tab used to load.
3164 * @param data The UrlData being loaded.
3165 */
3166 protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck26b18322011-06-21 13:08:58 -07003167 if (data != null) {
Michael Kolb5ff5c8b2012-05-03 11:37:58 -07003168 if (data.isPreloaded()) {
Michael Kolb14612442011-06-24 13:06:29 -07003169 // this isn't called for preloaded tabs
John Reck26b18322011-06-21 13:08:58 -07003170 } else {
John Reck38b39652012-06-05 09:22:59 -07003171 if (t != null && data.mDisableUrlOverride) {
3172 t.disableUrlOverridingForLoad();
3173 }
John Reck26b18322011-06-21 13:08:58 -07003174 loadUrl(t, data.mUrl, data.mHeaders);
3175 }
3176 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003177 }
3178
John Reck30c714c2010-12-16 17:30:34 -08003179 @Override
3180 public void onUserCanceledSsl(Tab tab) {
John Reck30c714c2010-12-16 17:30:34 -08003181 // TODO: Figure out the "right" behavior
Tarun Nainani1f481922014-12-18 13:54:54 -08003182 //In case of tab can go back (aka tab has navigation entry) do nothing
3183 //else just load homepage in current tab.
3184 if (!tab.canGoBack()) {
John Reckef654f12011-07-12 16:42:08 -07003185 tab.loadUrl(mSettings.getHomePage(), null);
John Reck30c714c2010-12-16 17:30:34 -08003186 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003187 }
3188
3189 void goBackOnePageOrQuit() {
3190 Tab current = mTabControl.getCurrentTab();
3191 if (current == null) {
Panos Thomas4bdb5252014-11-13 16:20:11 -08003192 if (BrowserConfig.getInstance(getContext()).hasFeature(BrowserConfig.Feature.EXIT_DIALOG)) {
3193 showExitDialog(mActivity);
3194 } else {
3195 /*
3196 * Instead of finishing the activity, simply push this to the back
3197 * of the stack and let ActivityManager to choose the foreground
3198 * activity. As BrowserActivity is singleTask, it will be always the
3199 * root of the task. So we can use either true or false for
3200 * moveTaskToBack().
3201 */
3202 mActivity.moveTaskToBack(true);
3203 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003204 return;
3205 }
John Reckef654f12011-07-12 16:42:08 -07003206 if (current.canGoBack()) {
3207 current.goBack();
Michael Kolb8233fac2010-10-26 16:08:53 -07003208 } else {
3209 // Check to see if we are closing a window that was created by
3210 // another window. If so, we switch back to that window.
Michael Kolbc831b632011-05-11 09:30:34 -07003211 Tab parent = current.getParent();
Michael Kolb8233fac2010-10-26 16:08:53 -07003212 if (parent != null) {
Michael Kolbc831b632011-05-11 09:30:34 -07003213 switchToTab(parent);
Michael Kolb8233fac2010-10-26 16:08:53 -07003214 // Now we close the other tab
3215 closeTab(current);
Panos Thomas4bdb5252014-11-13 16:20:11 -08003216 } else if (BrowserConfig.getInstance(getContext())
3217 .hasFeature(BrowserConfig.Feature.EXIT_DIALOG)) {
3218 showExitDialog(mActivity);
Michael Kolb8233fac2010-10-26 16:08:53 -07003219 } else {
Panos Thomas4bdb5252014-11-13 16:20:11 -08003220 if ((current.getAppId() != null) || current.closeOnBack()) {
3221 closeCurrentTab(true);
3222 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003223 /*
3224 * Instead of finishing the activity, simply push this to the back
3225 * of the stack and let ActivityManager to choose the foreground
3226 * activity. As BrowserActivity is singleTask, it will be always the
3227 * root of the task. So we can use either true or false for
3228 * moveTaskToBack().
3229 */
Panos Thomas4bdb5252014-11-13 16:20:11 -08003230 mActivity.moveTaskToBack(true);
Michael Kolb8233fac2010-10-26 16:08:53 -07003231 }
3232 }
3233 }
3234
3235 /**
Michael Kolb0035fad2011-03-14 13:25:28 -07003236 * helper method for key handler
3237 * returns the current tab if it can't advance
3238 */
Michael Kolbc831b632011-05-11 09:30:34 -07003239 private Tab getNextTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08003240 int pos = mTabControl.getCurrentPosition() + 1;
3241 if (pos >= mTabControl.getTabCount()) {
3242 pos = 0;
3243 }
3244 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07003245 }
3246
3247 /**
3248 * helper method for key handler
3249 * returns the current tab if it can't advance
3250 */
Michael Kolbc831b632011-05-11 09:30:34 -07003251 private Tab getPrevTab() {
Michael Kolbf5261da2011-12-15 15:07:35 -08003252 int pos = mTabControl.getCurrentPosition() - 1;
3253 if ( pos < 0) {
3254 pos = mTabControl.getTabCount() - 1;
3255 }
3256 return mTabControl.getTab(pos);
Michael Kolb0035fad2011-03-14 13:25:28 -07003257 }
3258
John Reckbcef87f2012-02-03 14:58:34 -08003259 boolean isMenuOrCtrlKey(int keyCode) {
3260 return (KeyEvent.KEYCODE_MENU == keyCode)
3261 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
3262 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode);
3263 }
3264
Michael Kolb0035fad2011-03-14 13:25:28 -07003265 /**
Michael Kolb8233fac2010-10-26 16:08:53 -07003266 * handle key events in browser
3267 *
3268 * @param keyCode
3269 * @param event
3270 * @return true if handled, false to pass to super
3271 */
John Reck9c35b9c2012-05-30 10:08:50 -07003272 @Override
3273 public boolean onKeyDown(int keyCode, KeyEvent event) {
Pankaj Garg49b79252014-11-07 17:33:41 -08003274 if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
3275 // Hardware menu key
Enrico Ros1f5a0952014-11-18 20:15:48 -08003276 mAppMenuHandler.showAppMenu(mActivity.findViewById(R.id.taburlbar),
Pankaj Garg49b79252014-11-07 17:33:41 -08003277 true, false);
3278 return true;
3279 }
3280
Cary Clark160bbb92011-01-10 11:17:07 -05003281 boolean noModifiers = event.hasNoModifiers();
Michael Kolb8233fac2010-10-26 16:08:53 -07003282 // Even if MENU is already held down, we need to call to super to open
3283 // the IME on long press.
John Reckbcef87f2012-02-03 14:58:34 -08003284 if (!noModifiers && isMenuOrCtrlKey(keyCode)) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003285 mMenuIsDown = true;
3286 return false;
3287 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003288
Cary Clark8ff8c662010-12-29 15:03:05 -05003289 WebView webView = getCurrentTopWebView();
John Reckef654f12011-07-12 16:42:08 -07003290 Tab tab = getCurrentTab();
3291 if (webView == null || tab == null) return false;
Cary Clark8ff8c662010-12-29 15:03:05 -05003292
Cary Clark160bbb92011-01-10 11:17:07 -05003293 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
3294 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark8ff8c662010-12-29 15:03:05 -05003295
Michael Kolb8233fac2010-10-26 16:08:53 -07003296 switch(keyCode) {
Michael Kolb0035fad2011-03-14 13:25:28 -07003297 case KeyEvent.KEYCODE_TAB:
3298 if (event.isCtrlPressed()) {
3299 if (event.isShiftPressed()) {
3300 // prev tab
Michael Kolbc831b632011-05-11 09:30:34 -07003301 switchToTab(getPrevTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07003302 } else {
3303 // next tab
Michael Kolbc831b632011-05-11 09:30:34 -07003304 switchToTab(getNextTab());
Michael Kolb0035fad2011-03-14 13:25:28 -07003305 }
3306 return true;
3307 }
3308 break;
Michael Kolb8233fac2010-10-26 16:08:53 -07003309 case KeyEvent.KEYCODE_SPACE:
3310 // WebView/WebTextView handle the keys in the KeyDown. As
3311 // the Activity's shortcut keys are only handled when WebView
3312 // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark160bbb92011-01-10 11:17:07 -05003313 if (shift) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003314 pageUp();
Cary Clark160bbb92011-01-10 11:17:07 -05003315 } else if (noModifiers) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003316 pageDown();
3317 }
3318 return true;
3319 case KeyEvent.KEYCODE_BACK:
Cary Clark160bbb92011-01-10 11:17:07 -05003320 if (!noModifiers) break;
John Recke6bf4ab2011-02-24 15:48:05 -08003321 event.startTracking();
3322 return true;
Michael Kolbe9e1d4a2011-07-14 15:02:17 -07003323 case KeyEvent.KEYCODE_FORWARD:
3324 if (!noModifiers) break;
3325 tab.goForward();
3326 return true;
Cary Clark8ff8c662010-12-29 15:03:05 -05003327 case KeyEvent.KEYCODE_DPAD_LEFT:
3328 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07003329 tab.goBack();
Cary Clark8ff8c662010-12-29 15:03:05 -05003330 return true;
3331 }
3332 break;
3333 case KeyEvent.KEYCODE_DPAD_RIGHT:
3334 if (ctrl) {
John Reckef654f12011-07-12 16:42:08 -07003335 tab.goForward();
Cary Clark8ff8c662010-12-29 15:03:05 -05003336 return true;
3337 }
3338 break;
3339 case KeyEvent.KEYCODE_A:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003340 if (ctrl) {
3341 webView.selectAll();
Cary Clark8ff8c662010-12-29 15:03:05 -05003342 return true;
3343 }
3344 break;
Michael Kolba4183062011-01-16 10:43:21 -08003345// case KeyEvent.KEYCODE_B: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003346 case KeyEvent.KEYCODE_C:
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003347 if (ctrl ) {
3348 webView.copySelection();
Cary Clark8ff8c662010-12-29 15:03:05 -05003349 return true;
3350 }
3351 break;
Michael Kolba4183062011-01-16 10:43:21 -08003352// case KeyEvent.KEYCODE_D: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003353// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08003354// case KeyEvent.KEYCODE_F: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003355// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
Michael Kolba4183062011-01-16 10:43:21 -08003356// case KeyEvent.KEYCODE_H: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003357// case KeyEvent.KEYCODE_I: // unused
Michael Kolba4183062011-01-16 10:43:21 -08003358// case KeyEvent.KEYCODE_J: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003359// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
Michael Kolba4183062011-01-16 10:43:21 -08003360// case KeyEvent.KEYCODE_L: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003361// case KeyEvent.KEYCODE_M: // unused
3362// case KeyEvent.KEYCODE_N: // in Chrome: new window
3363// case KeyEvent.KEYCODE_O: // in Chrome: open file
3364// case KeyEvent.KEYCODE_P: // in Chrome: print page
3365// case KeyEvent.KEYCODE_Q: // unused
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003366// case KeyEvent.KEYCODE_R:
Cary Clark8ff8c662010-12-29 15:03:05 -05003367// case KeyEvent.KEYCODE_S: // in Chrome: saves page
3368 case KeyEvent.KEYCODE_T:
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003369 // we can't use the ctrl/shift flags, they check for
3370 // exclusive use of a modifier
3371 if (event.isCtrlPressed()) {
Cary Clark8ff8c662010-12-29 15:03:05 -05003372 if (event.isShiftPressed()) {
Michael Kolb519d2282011-05-09 17:03:19 -07003373 openIncognitoTab();
Cary Clark8ff8c662010-12-29 15:03:05 -05003374 } else {
3375 openTabToHomePage();
3376 }
3377 return true;
3378 }
3379 break;
3380// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
3381// case KeyEvent.KEYCODE_V: // text view intercepts to paste
Michael Kolb5ae15bd2011-08-16 17:09:27 -07003382// case KeyEvent.KEYCODE_W: // menu
Cary Clark8ff8c662010-12-29 15:03:05 -05003383// case KeyEvent.KEYCODE_X: // text view intercepts to cut
3384// case KeyEvent.KEYCODE_Y: // unused
3385// case KeyEvent.KEYCODE_Z: // unused
Michael Kolb8233fac2010-10-26 16:08:53 -07003386 }
Michael Kolbdc2ee1b2011-02-14 14:34:40 -08003387 // it is a regular key and webview is not null
3388 return mUi.dispatchKey(keyCode, event);
Michael Kolb8233fac2010-10-26 16:08:53 -07003389 }
3390
John Reck9c35b9c2012-05-30 10:08:50 -07003391 @Override
3392 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
John Recke6bf4ab2011-02-24 15:48:05 -08003393 switch(keyCode) {
3394 case KeyEvent.KEYCODE_BACK:
John Reck3ba45532011-08-11 16:26:53 -07003395 if (mUi.isWebShowing()) {
Michael Kolb315d5022011-10-13 12:47:11 -07003396 bookmarksOrHistoryPicker(ComboViews.History);
John Recke6bf4ab2011-02-24 15:48:05 -08003397 return true;
3398 }
3399 break;
3400 }
3401 return false;
3402 }
3403
John Reck9c35b9c2012-05-30 10:08:50 -07003404 @Override
3405 public boolean onKeyUp(int keyCode, KeyEvent event) {
John Reckbcef87f2012-02-03 14:58:34 -08003406 if (isMenuOrCtrlKey(keyCode)) {
Michael Kolb2814a362011-05-19 15:49:41 -07003407 mMenuIsDown = false;
John Reckbcef87f2012-02-03 14:58:34 -08003408 if (KeyEvent.KEYCODE_MENU == keyCode
3409 && event.isTracking() && !event.isCanceled()) {
Michael Kolb4bd767d2011-05-27 11:33:55 -07003410 return onMenuKey();
Michael Kolb2814a362011-05-19 15:49:41 -07003411 }
3412 }
Cary Clark160bbb92011-01-10 11:17:07 -05003413 if (!event.hasNoModifiers()) return false;
Michael Kolb8233fac2010-10-26 16:08:53 -07003414 switch(keyCode) {
Michael Kolb8233fac2010-10-26 16:08:53 -07003415 case KeyEvent.KEYCODE_BACK:
3416 if (event.isTracking() && !event.isCanceled()) {
3417 onBackKey();
3418 return true;
3419 }
3420 break;
3421 }
3422 return false;
3423 }
3424
3425 public boolean isMenuDown() {
3426 return mMenuIsDown;
3427 }
3428
John Reck9c35b9c2012-05-30 10:08:50 -07003429 @Override
Ben Murdoch8029a772010-11-16 11:58:21 +00003430 public void setupAutoFill(Message message) {
3431 // Open the settings activity at the AutoFill profile fragment so that
3432 // the user can create a new profile. When they return, we will dispatch
3433 // the message so that we can autofill the form using their new profile.
Ben Murdoch8029a772010-11-16 11:58:21 +00003434 mAutoFillSetupMessage = message;
Enrico Rosd6efa972014-12-02 19:49:59 -08003435 BrowserPreferencesPage.startPreferenceFragmentForResult(mActivity,
3436 AutoFillSettingsFragment.class.getName(), AUTOFILL_SETUP);
Ben Murdoch8029a772010-11-16 11:58:21 +00003437 }
John Reckb3417f02011-01-14 11:01:05 -08003438
John Reck9c35b9c2012-05-30 10:08:50 -07003439 @Override
Michael Kolbfbc579a2011-07-07 15:59:33 -07003440 public boolean onSearchRequested() {
Michael Kolb1f9b3562012-04-24 14:38:34 -07003441 mUi.editUrl(false, true);
Michael Kolbfbc579a2011-07-07 15:59:33 -07003442 return true;
3443 }
3444
John Reck1cf4b792011-07-26 10:22:22 -07003445 @Override
3446 public boolean shouldCaptureThumbnails() {
3447 return mUi.shouldCaptureThumbnails();
3448 }
3449
Michael Kolbc3af0672011-08-09 10:24:41 -07003450 @Override
Michael Kolb0b129122012-06-04 16:31:58 -07003451 public boolean supportsVoice() {
3452 PackageManager pm = mActivity.getPackageManager();
3453 List activities = pm.queryIntentActivities(new Intent(
3454 RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
3455 return activities.size() != 0;
3456 }
3457
3458 @Override
3459 public void startVoiceRecognizer() {
3460 Intent voice = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
Bijan Amirzada9b1e9882014-02-26 17:15:46 -08003461 voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
Michael Kolb0b129122012-06-04 16:31:58 -07003462 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
3463 voice.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
3464 mActivity.startActivityForResult(voice, VOICE_RESULT);
3465 }
3466
Pankaj Garg7b279f62014-08-12 14:47:18 -07003467 public void setWindowDimming(float level) {
Vivek Sekharb991edb2014-12-17 18:18:07 -08003468 if (mLevel == level)
3469 return;
3470 mLevel = level;
3471 if (level != 0.0f) {
Pankaj Garg7b279f62014-08-12 14:47:18 -07003472 WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
3473 lp.dimAmount = level;
3474 mActivity.getWindow().setAttributes(lp);
3475 mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
3476 } else {
3477 mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
3478 }
3479 }
3480
Michael Kolb0b129122012-06-04 16:31:58 -07003481 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003482 public void setBlockEvents(boolean block) {
3483 mBlockEvents = block;
3484 }
3485
John Reck9c35b9c2012-05-30 10:08:50 -07003486 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003487 public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07003488 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003489 }
3490
John Reck9c35b9c2012-05-30 10:08:50 -07003491 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003492 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb87357642011-08-24 14:19:18 -07003493 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003494 }
3495
John Reck9c35b9c2012-05-30 10:08:50 -07003496 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003497 public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003498 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003499 }
3500
John Reck9c35b9c2012-05-30 10:08:50 -07003501 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003502 public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003503 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003504 }
3505
John Reck9c35b9c2012-05-30 10:08:50 -07003506 @Override
Michael Kolbc3af0672011-08-09 10:24:41 -07003507 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb87357642011-08-24 14:19:18 -07003508 return mBlockEvents;
Michael Kolbc3af0672011-08-09 10:24:41 -07003509 }
3510
Pankaj Garg49b79252014-11-07 17:33:41 -08003511 @Override
3512 public boolean shouldShowAppMenu() {
3513 return true;
3514 }
3515
3516 @Override
3517 public int getMenuThemeResourceId() {
3518 return R.style.OverflowMenuTheme;
3519 }
Michael Kolb8233fac2010-10-26 16:08:53 -07003520}