This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 305
/
GeckoApp.java
2689 lines (2290 loc) · 100 KB
/
GeckoApp.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko;
import org.mozilla.gecko.db.BrowserDB;
import org.mozilla.gecko.gfx.Layer;
import org.mozilla.gecko.gfx.LayerView;
import org.mozilla.gecko.gfx.PluginLayer;
import org.mozilla.gecko.gfx.PointUtils;
import org.mozilla.gecko.ui.PanZoomController;
import org.mozilla.gecko.util.GeckoAsyncTask;
import org.mozilla.gecko.util.GeckoBackgroundThread;
import org.mozilla.gecko.util.GeckoEventListener;
import org.mozilla.gecko.util.GeckoEventResponder;
import org.mozilla.gecko.GeckoAccessibility;
import org.mozilla.gecko.updater.UpdateServiceHelper;
import org.mozilla.gecko.updater.UpdateService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.Signature;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.location.LocationListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.StrictMode;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
abstract public class GeckoApp
extends GeckoActivity
implements GeckoEventListener, SensorEventListener, LocationListener,
GeckoApplication.ApplicationLifecycleCallbacks,
Tabs.OnTabsChangedListener, GeckoEventResponder
{
private static final String LOGTAG = "GeckoApp";
public static enum StartupMode {
NORMAL,
NEW_VERSION,
NEW_PROFILE
}
public static final String ACTION_ALERT_CLICK = "org.mozilla.gecko.ACTION_ALERT_CLICK";
public static final String ACTION_ALERT_CLEAR = "org.mozilla.gecko.ACTION_ALERT_CLEAR";
public static final String ACTION_ALERT_CALLBACK = "org.mozilla.gecko.ACTION_ALERT_CALLBACK";
public static final String ACTION_WEBAPP_PREFIX = "org.mozilla.gecko.WEBAPP";
public static final String ACTION_DEBUG = "org.mozilla.gecko.DEBUG";
public static final String ACTION_BOOKMARK = "org.mozilla.gecko.BOOKMARK";
public static final String ACTION_LOAD = "org.mozilla.gecko.LOAD";
public static final String ACTION_INIT_PW = "org.mozilla.gecko.INIT_PW";
public static final String SAVED_STATE_TITLE = "title";
public static final String SAVED_STATE_IN_BACKGROUND = "inBackground";
public static final String PREFS_NAME = "GeckoApp";
public static final String PREFS_OOM_EXCEPTION = "OOMException";
public static final String PREFS_WAS_STOPPED = "wasStopped";
StartupMode mStartupMode = null;
protected LinearLayout mMainLayout;
protected RelativeLayout mGeckoLayout;
public View getView() { return mGeckoLayout; }
public SurfaceView cameraView;
public static GeckoApp mAppContext;
public boolean mDOMFullScreen = false;
protected MenuPanel mMenuPanel;
protected Menu mMenu;
private static GeckoThread sGeckoThread;
public Handler mMainHandler;
private GeckoProfile mProfile;
public static boolean sIsGeckoReady = false;
public static int mOrientation;
private boolean mIsRestoringActivity;
private String mCurrentResponse = "";
public static boolean sIsUsingCustomProfile = false;
private GeckoConnectivityReceiver mConnectivityReceiver;
private GeckoBatteryManager mBatteryReceiver;
private PromptService mPromptService;
private Favicons mFavicons;
private TextSelection mTextSelection;
protected DoorHangerPopup mDoorHangerPopup;
protected FormAssistPopup mFormAssistPopup;
protected TabsPanel mTabsPanel;
private LayerView mLayerView;
private AbsoluteLayout mPluginContainer;
private FullScreenHolder mFullScreenPluginContainer;
private View mFullScreenPluginView;
private HashMap<String, PowerManager.WakeLock> mWakeLocks = new HashMap<String, PowerManager.WakeLock>();
protected int mRestoreMode = GeckoAppShell.RESTORE_NONE;
protected boolean mInitialized = false;
public enum LaunchState {Launching, WaitForDebugger,
Launched, GeckoRunning, GeckoExiting};
private static LaunchState sLaunchState = LaunchState.Launching;
abstract public int getLayout();
abstract public boolean hasTabsSideBar();
abstract protected String getDefaultProfileName();
public static boolean checkLaunchState(LaunchState checkState) {
synchronized(sLaunchState) {
return sLaunchState == checkState;
}
}
static void setLaunchState(LaunchState setState) {
synchronized(sLaunchState) {
sLaunchState = setState;
}
}
// if mLaunchState is equal to checkState this sets mLaunchState to setState
// and return true. Otherwise we return false.
static boolean checkAndSetLaunchState(LaunchState checkState, LaunchState setState) {
synchronized(sLaunchState) {
if (sLaunchState != checkState)
return false;
sLaunchState = setState;
return true;
}
}
void toggleChrome(final Boolean aShow) { }
void focusChrome() { }
public void onTabChanged(Tab tab, Tabs.TabEvents msg, Object data) {
// When a tab is closed, it is always unselected first.
// When a tab is unselected, another tab is always selected first.
switch(msg) {
case UNSELECTED:
hidePlugins(tab);
break;
case LOCATION_CHANGE:
// We only care about location change for the selected tab.
if (!Tabs.getInstance().isSelectedTab(tab))
break;
// Fall through...
case SELECTED:
invalidateOptionsMenu();
break;
}
}
public void refreshChrome() { }
public static final String PLUGIN_ACTION = "android.webkit.PLUGIN";
/**
* A plugin that wish to be loaded in the WebView must provide this permission
* in their AndroidManifest.xml.
*/
public static final String PLUGIN_PERMISSION = "android.webkit.permission.PLUGIN";
private static final String PLUGIN_SYSTEM_LIB = "/system/lib/plugins/";
private static final String PLUGIN_TYPE = "type";
private static final String TYPE_NATIVE = "native";
public ArrayList<PackageInfo> mPackageInfoCache = new ArrayList<PackageInfo>();
// Returns null if plugins are blocked on the device.
String[] getPluginDirectories() {
// An awful hack to detect Tegra devices. Easiest way to do it without spinning up a EGL context.
boolean isTegra = (new File("/system/lib/hw/gralloc.tegra.so")).exists();
if (isTegra) {
// disable Flash on Tegra ICS with CM9 and other custom firmware (bug 736421)
File vfile = new File("/proc/version");
FileReader vreader = null;
try {
if (vfile.canRead()) {
vreader = new FileReader(vfile);
String version = new BufferedReader(vreader).readLine();
if (version.indexOf("CM9") != -1 ||
version.indexOf("cyanogen") != -1 ||
version.indexOf("Nova") != -1)
{
Log.w(LOGTAG, "Blocking plugins because of Tegra 2 + unofficial ICS bug (bug 736421)");
return null;
}
}
} catch (IOException ex) {
// nothing
} finally {
try {
if (vreader != null) {
vreader.close();
}
} catch (IOException ex) {
// nothing
}
}
}
Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - start of getPluginDirectories");
ArrayList<String> directories = new ArrayList<String>();
PackageManager pm = mAppContext.getPackageManager();
List<ResolveInfo> plugins = pm.queryIntentServices(new Intent(PLUGIN_ACTION),
PackageManager.GET_SERVICES | PackageManager.GET_META_DATA);
synchronized(mPackageInfoCache) {
// clear the list of existing packageInfo objects
mPackageInfoCache.clear();
for (ResolveInfo info : plugins) {
// retrieve the plugin's service information
ServiceInfo serviceInfo = info.serviceInfo;
if (serviceInfo == null) {
Log.w(LOGTAG, "Ignore bad plugin");
continue;
}
// Blacklist HTC's flash lite.
// See bug #704516 - We're not quite sure what Flash Lite does,
// but loading it causes Flash to give errors and fail to draw.
if (serviceInfo.packageName.equals("com.htc.flashliteplugin")) {
Log.w(LOGTAG, "Skipping HTC's flash lite plugin");
continue;
}
Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName);
// retrieve information from the plugin's manifest
PackageInfo pkgInfo;
try {
pkgInfo = pm.getPackageInfo(serviceInfo.packageName,
PackageManager.GET_PERMISSIONS
| PackageManager.GET_SIGNATURES);
} catch (Exception e) {
Log.w(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
continue;
}
if (pkgInfo == null) {
Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Could not load package information.");
continue;
}
/*
* find the location of the plugin's shared library. The default
* is to assume the app is either a user installed app or an
* updated system app. In both of these cases the library is
* stored in the app's data directory.
*/
String directory = pkgInfo.applicationInfo.dataDir + "/lib";
final int appFlags = pkgInfo.applicationInfo.flags;
final int updatedSystemFlags = ApplicationInfo.FLAG_SYSTEM |
ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
// preloaded system app with no user updates
if ((appFlags & updatedSystemFlags) == ApplicationInfo.FLAG_SYSTEM) {
directory = PLUGIN_SYSTEM_LIB + pkgInfo.packageName;
}
// check if the plugin has the required permissions
String permissions[] = pkgInfo.requestedPermissions;
if (permissions == null) {
Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Does not have required permission.");
continue;
}
boolean permissionOk = false;
for (String permit : permissions) {
if (PLUGIN_PERMISSION.equals(permit)) {
permissionOk = true;
break;
}
}
if (!permissionOk) {
Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Does not have required permission (2).");
continue;
}
// check to ensure the plugin is properly signed
Signature signatures[] = pkgInfo.signatures;
if (signatures == null) {
Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Not signed.");
continue;
}
// determine the type of plugin from the manifest
if (serviceInfo.metaData == null) {
Log.e(LOGTAG, "The plugin '" + serviceInfo.name + "' has no type defined");
continue;
}
String pluginType = serviceInfo.metaData.getString(PLUGIN_TYPE);
if (!TYPE_NATIVE.equals(pluginType)) {
Log.e(LOGTAG, "Unrecognized plugin type: " + pluginType);
continue;
}
try {
Class<?> cls = getPluginClass(serviceInfo.packageName, serviceInfo.name);
//TODO implement any requirements of the plugin class here!
boolean classFound = true;
if (!classFound) {
Log.e(LOGTAG, "The plugin's class' " + serviceInfo.name + "' does not extend the appropriate class.");
continue;
}
} catch (NameNotFoundException e) {
Log.e(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
continue;
} catch (ClassNotFoundException e) {
Log.e(LOGTAG, "Can't find plugin's class: " + serviceInfo.name);
continue;
}
// if all checks have passed then make the plugin available
mPackageInfoCache.add(pkgInfo);
directories.add(directory);
}
}
String [] result = directories.toArray(new String[directories.size()]);
Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - end of getPluginDirectories");
return result;
}
String getPluginPackage(String pluginLib) {
if (pluginLib == null || pluginLib.length() == 0) {
return null;
}
synchronized(mPackageInfoCache) {
for (PackageInfo pkgInfo : mPackageInfoCache) {
if (pluginLib.contains(pkgInfo.packageName)) {
return pkgInfo.packageName;
}
}
}
return null;
}
synchronized Favicons getFavicons() {
if (mFavicons == null)
mFavicons = new Favicons(this);
return mFavicons;
}
Class<?> getPluginClass(String packageName, String className)
throws NameNotFoundException, ClassNotFoundException {
Context pluginContext = mAppContext.createPackageContext(packageName,
Context.CONTEXT_INCLUDE_CODE |
Context.CONTEXT_IGNORE_SECURITY);
ClassLoader pluginCL = pluginContext.getClassLoader();
return pluginCL.loadClass(className);
}
@Override
public void invalidateOptionsMenu() {
if (mMenu == null)
return;
onPrepareOptionsMenu(mMenu);
if (Build.VERSION.SDK_INT >= 11)
super.invalidateOptionsMenu();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mMenu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.gecko_app_menu, mMenu);
return true;
}
@Override
public MenuInflater getMenuInflater() {
if (Build.VERSION.SDK_INT >= 11)
return new GeckoMenuInflater(mAppContext);
else
return super.getMenuInflater();
}
public View getMenuPanel() {
return mMenuPanel;
}
// MenuPanel holds the scrollable Menu
public static class MenuPanel extends ScrollView {
public MenuPanel(Context context, AttributeSet attrs) {
super(context, attrs);
setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// heightPixels changes during rotation.
DisplayMetrics metrics = GeckoApp.mAppContext.getResources().getDisplayMetrics();
int restrictedHeightSpec = MeasureSpec.makeMeasureSpec((int) (0.75 * metrics.heightPixels), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, restrictedHeightSpec);
}
@Override
public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event) {
if (Build.VERSION.SDK_INT >= 14) // Build.VERSION_CODES.ICE_CREAM_SANDWICH
onPopulateAccessibilityEvent(event);
return true;
}
}
@Override
public View onCreatePanelView(int featureId) {
if (Build.VERSION.SDK_INT >= 11 && featureId == Window.FEATURE_OPTIONS_PANEL) {
if (mMenuPanel == null) {
mMenuPanel = new MenuPanel(mAppContext, null);
} else {
// Prepare the panel everytime before showing the menu.
onPreparePanel(featureId, mMenuPanel, mMenu);
}
return mMenuPanel;
}
return super.onCreatePanelView(featureId);
}
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (Build.VERSION.SDK_INT >= 11 && featureId == Window.FEATURE_OPTIONS_PANEL) {
if (mMenuPanel == null) {
mMenuPanel = (MenuPanel) onCreatePanelView(featureId);
}
GeckoMenu gMenu = new GeckoMenu(mAppContext, null);
menu = gMenu;
mMenuPanel.addView(gMenu);
return onCreateOptionsMenu(menu);
}
return super.onCreatePanelMenu(featureId, menu);
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (Build.VERSION.SDK_INT >= 11 && featureId == Window.FEATURE_OPTIONS_PANEL)
return onPrepareOptionsMenu(menu);
return super.onPreparePanel(featureId, view, menu);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if (Build.VERSION.SDK_INT >= 11 && featureId == Window.FEATURE_OPTIONS_PANEL) {
if (mMenu == null) {
onCreatePanelMenu(featureId, menu);
onPreparePanel(featureId, mMenuPanel, mMenu);
}
// Scroll custom menu to the top
if (mMenuPanel != null)
mMenuPanel.scrollTo(0, 0);
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.quit:
synchronized(sLaunchState) {
if (sLaunchState == LaunchState.GeckoRunning)
GeckoAppShell.notifyGeckoOfEvent(
GeckoEvent.createBroadcastEvent("Browser:Quit", null));
else
System.exit(0);
sLaunchState = LaunchState.GeckoExiting;
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Custom Menu should be opened when hardware menu key is pressed.
if (Build.VERSION.SDK_INT >= 11 && keyCode == KeyEvent.KEYCODE_MENU) {
openOptionsMenu();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void shareCurrentUrl() {
Tab tab = Tabs.getInstance().getSelectedTab();
if (tab == null)
return;
String url = tab.getURL();
if (url == null)
return;
if (ReaderModeUtils.isAboutReader(url))
url = ReaderModeUtils.getUrlFromAboutReader(url);
GeckoAppShell.openUriExternal(url, "text/plain", "", "",
Intent.ACTION_SEND, tab.getDisplayTitle());
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(LOGTAG, "onSaveInstanceState");
if (outState == null)
outState = new Bundle();
Tab tab = Tabs.getInstance().getSelectedTab();
if (tab != null)
outState.putString(SAVED_STATE_TITLE, tab.getDisplayTitle());
boolean inBackground =
((GeckoApplication)getApplication()).isApplicationInBackground();
outState.putBoolean(SAVED_STATE_IN_BACKGROUND, inBackground);
}
void getAndProcessThumbnailForTab(final Tab tab) {
if ("about:home".equals(tab.getURL())) {
tab.updateThumbnail(null);
return;
}
if (tab.getState() == Tab.STATE_DELAYED) {
byte[] thumbnail = BrowserDB.getThumbnailForUrl(getContentResolver(), tab.getURL());
if (thumbnail != null)
processThumbnail(tab, null, thumbnail);
return;
}
int dw = tab.getThumbnailWidth();
int dh = tab.getThumbnailHeight();
GeckoAppShell.sendEventToGecko(GeckoEvent.createScreenshotEvent(tab.getId(), 0, 0, 0, 0, 0, 0, dw, dh, dw, dh, ScreenshotHandler.SCREENSHOT_THUMBNAIL, tab.getThumbnailBuffer()));
}
void handleThumbnailData(Tab tab, ByteBuffer data) {
if (shouldUpdateThumbnail(tab)) {
Bitmap b = tab.getThumbnailBitmap();
b.copyPixelsFromBuffer(data);
processThumbnail(tab, b, null);
}
}
void processThumbnail(Tab thumbnailTab, Bitmap bitmap, byte[] compressed) {
try {
if (bitmap == null) {
if (compressed == null) {
Log.e(LOGTAG, "processThumbnail: one of bitmap or compressed must be non-null!");
return;
}
bitmap = BitmapFactory.decodeByteArray(compressed, 0, compressed.length);
}
thumbnailTab.updateThumbnail(bitmap);
} catch (OutOfMemoryError ome) {
Log.w(LOGTAG, "decoding byte array ran out of memory", ome);
}
}
private boolean shouldUpdateThumbnail(Tab tab) {
return (Tabs.getInstance().isSelectedTab(tab) || areTabsShown());
}
public void hideFormAssistPopup() {
if (mFormAssistPopup != null)
mFormAssistPopup.hide();
}
void handleSecurityChange(final int tabId, final JSONObject identityData) {
final Tab tab = Tabs.getInstance().getTab(tabId);
if (tab == null)
return;
tab.updateIdentityData(identityData);
}
void handleReaderEnabled(final int tabId) {
final Tab tab = Tabs.getInstance().getTab(tabId);
if (tab == null)
return;
tab.setReaderEnabled(true);
}
void handleFaviconRequest(final String url) {
(new GeckoAsyncTask<Void, Void, String>(mAppContext, GeckoAppShell.getHandler()) {
@Override
public String doInBackground(Void... params) {
return getFavicons().getFaviconUrlForPageUrl(url);
}
@Override
public void onPostExecute(String faviconUrl) {
JSONObject args = new JSONObject();
if (faviconUrl != null) {
try {
args.put("url", url);
args.put("faviconUrl", faviconUrl);
} catch (JSONException e) {
Log.e(LOGTAG, "error building json arguments");
}
}
GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Reader:FaviconReturn", args.toString()));
}
}).execute();
}
void handleLoadError(final int tabId, final String uri, final String title) {
final Tab tab = Tabs.getInstance().getTab(tabId);
if (tab == null)
return;
// When a load error occurs, the URLBar can get corrupt so we reset it
mMainHandler.post(new Runnable() {
public void run() {
Tabs.getInstance().notifyListeners(tab, Tabs.TabEvents.LOAD_ERROR);
}
});
}
void handlePageShow(final int tabId) { }
void handleClearHistory() {
BrowserDB.clearHistory(getContentResolver());
getFavicons().clearFavicons();
}
public StartupMode getStartupMode() {
// This function might touch the disk and should not
// be called from UI's main thread.
synchronized(this) {
if (mStartupMode != null)
return mStartupMode;
String packageName = getPackageName();
SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
// This key should be profile-dependent. For now, we're simply hardcoding
// the "default" profile here.
String profileName = getDefaultProfileName();
if (profileName == null)
profileName = "default";
String keyName = packageName + "." + profileName + ".startup_version";
String appVersion = null;
try {
PackageInfo pkgInfo = getPackageManager().getPackageInfo(packageName, 0);
appVersion = pkgInfo.versionName;
} catch(NameNotFoundException nnfe) {
// If, for some reason, we can't fetch the app version
// we fallback to NORMAL startup mode.
mStartupMode = StartupMode.NORMAL;
return mStartupMode;
}
String startupVersion = settings.getString(keyName, null);
if (startupVersion == null) {
mStartupMode = StartupMode.NEW_PROFILE;
} else {
if (startupVersion.equals(appVersion))
mStartupMode = StartupMode.NORMAL;
else
mStartupMode = StartupMode.NEW_VERSION;
}
if (mStartupMode != StartupMode.NORMAL)
settings.edit().putString(keyName, appVersion).commit();
Log.i(LOGTAG, "Startup mode: " + mStartupMode);
return mStartupMode;
}
}
void addTab() { }
public void showLocalTabs() { }
public void showRemoteTabs() { }
private void showTabs(TabsPanel.Panel panel) { }
public void hideTabs() { }
/**
* Close the tab UI indirectly (not as the result of a direct user
* action). This does not force the UI to close; for example in Firefox
* tablet mode it will remain open unless the user explicitly closes it.
*
* @return True if the tab UI was hidden.
*/
public boolean autoHideTabs() { return false; }
public boolean areTabsShown() { return false; }
public boolean hasPermanentMenuKey() {
boolean hasMenu = true;
if (Build.VERSION.SDK_INT >= 11)
hasMenu = false;
if (Build.VERSION.SDK_INT >= 14)
hasMenu = ViewConfiguration.get(GeckoApp.mAppContext).hasPermanentMenuKey();
return hasMenu;
}
public void handleMessage(String event, JSONObject message) {
Log.i(LOGTAG, "Got message: " + event);
try {
if (event.equals("Toast:Show")) {
final String msg = message.getString("message");
final String duration = message.getString("duration");
handleShowToast(msg, duration);
} else if (event.equals("DOMContentLoaded")) {
final int tabId = message.getInt("tabID");
final String backgroundColor = message.getString("bgColor");
handleContentLoaded(tabId);
Tab tab = Tabs.getInstance().getTab(tabId);
if (backgroundColor != null) {
tab.setCheckerboardColor(backgroundColor);
} else {
// Default to white if no color is given
tab.setCheckerboardColor(Color.WHITE);
}
// Sync up the layer view and the tab if the tab is
// currently displayed.
LayerView layerView = mLayerView;
if (layerView != null && Tabs.getInstance().isSelectedTab(tab)) {
layerView.setCheckerboardColor(tab.getCheckerboardColor());
}
} else if (event.equals("DOMTitleChanged")) {
final int tabId = message.getInt("tabID");
final String title = message.getString("title");
handleTitleChanged(tabId, title);
Log.i(LOGTAG, "title - " + title);
} else if (event.equals("DOMLinkAdded")) {
final int tabId = message.getInt("tabID");
final String rel = message.getString("rel");
final String href = message.getString("href");
final int size = message.getInt("size");
Log.i(LOGTAG, "link rel - " + rel + ", href - " + href + ", size - " + size);
handleLinkAdded(tabId, rel, href, size);
} else if (event.equals("DOMWindowClose")) {
final int tabId = message.getInt("tabID");
handleWindowClose(tabId);
} else if (event.equals("log")) {
// generic log listener
final String msg = message.getString("msg");
Log.i(LOGTAG, "Log: " + msg);
} else if (event.equals("Content:SecurityChange")) {
final int tabId = message.getInt("tabID");
final JSONObject identity = message.getJSONObject("identity");
Log.i(LOGTAG, "Security Mode - " + identity.getString("mode"));
handleSecurityChange(tabId, identity);
} else if (event.equals("Content:ReaderEnabled")) {
final int tabId = message.getInt("tabID");
handleReaderEnabled(tabId);
} else if (event.equals("Reader:FaviconRequest")) {
final String url = message.getString("url");
handleFaviconRequest(url);
} else if (event.equals("Reader:GoToReadingList")) {
showReadingList();
} else if (event.equals("Content:StateChange")) {
final int tabId = message.getInt("tabID");
final String uri = message.getString("uri");
final boolean success = message.getBoolean("success");
int state = message.getInt("state");
Log.i(LOGTAG, "State - " + state);
if ((state & GeckoAppShell.WPL_STATE_IS_NETWORK) != 0) {
if ((state & GeckoAppShell.WPL_STATE_START) != 0) {
Log.i(LOGTAG, "Got a document start");
final boolean showProgress = message.getBoolean("showProgress");
handleDocumentStart(tabId, showProgress, uri);
} else if ((state & GeckoAppShell.WPL_STATE_STOP) != 0) {
Log.i(LOGTAG, "Got a document stop");
handleDocumentStop(tabId, success);
}
}
} else if (event.equals("Content:LoadError")) {
final int tabId = message.getInt("tabID");
final String uri = message.getString("uri");
final String title = message.getString("title");
handleLoadError(tabId, uri, title);
} else if (event.equals("Content:PageShow")) {
final int tabId = message.getInt("tabID");
handlePageShow(tabId);
} else if (event.equals("Gecko:Ready")) {
sIsGeckoReady = true;
setLaunchState(GeckoApp.LaunchState.GeckoRunning);
GeckoAppShell.sendPendingEventsToGecko();
connectGeckoLayerClient();
} else if (event.equals("ToggleChrome:Hide")) {
toggleChrome(false);
} else if (event.equals("ToggleChrome:Show")) {
toggleChrome(true);
} else if (event.equals("ToggleChrome:Focus")) {
focusChrome();
} else if (event.equals("DOMFullScreen:Start")) {
mDOMFullScreen = true;
} else if (event.equals("DOMFullScreen:Stop")) {
mDOMFullScreen = false;
} else if (event.equals("Permissions:Data")) {
String host = message.getString("host");
JSONArray permissions = message.getJSONArray("permissions");
showSiteSettingsDialog(host, permissions);
} else if (event.equals("Tab:ViewportMetadata")) {
int tabId = message.getInt("tabID");
Tab tab = Tabs.getInstance().getTab(tabId);
if (tab == null)
return;
tab.setZoomConstraints(new ZoomConstraints(message));
// Sync up the layer view and the tab if the tab is currently displayed.
LayerView layerView = mLayerView;
if (layerView != null && Tabs.getInstance().isSelectedTab(tab)) {
layerView.setZoomConstraints(tab.getZoomConstraints());
}
} else if (event.equals("Tab:HasTouchListener")) {
int tabId = message.getInt("tabID");
final Tab tab = Tabs.getInstance().getTab(tabId);
tab.setHasTouchListeners(true);
mMainHandler.post(new Runnable() {
public void run() {
if (Tabs.getInstance().isSelectedTab(tab))
mLayerView.getTouchEventHandler().setWaitForTouchListeners(true);
}
});
} else if (event.equals("Session:StatePurged")) {
onStatePurged();
} else if (event.equals("Bookmark:Insert")) {
final String url = message.getString("url");
final String title = message.getString("title");
mMainHandler.post(new Runnable() {
public void run() {
Toast.makeText(GeckoApp.mAppContext, R.string.bookmark_added, Toast.LENGTH_SHORT).show();
GeckoAppShell.getHandler().post(new Runnable() {
public void run() {
BrowserDB.addBookmark(GeckoApp.mAppContext.getContentResolver(), title, url);
}
});
}
});
} else if (event.equals("Accessibility:Event")) {
GeckoAccessibility.sendAccessibilityEvent(message);
} else if (event.equals("Accessibility:Ready")) {
GeckoAccessibility.updateAccessibilitySettings();
} else if (event.equals("Shortcut:Remove")) {
final String url = message.getString("url");
final String origin = message.getString("origin");
final String title = message.getString("title");
final String type = message.getString("shortcutType");
GeckoAppShell.removeShortcut(title, url, origin, type);
} else if (event.equals("WebApps:Open")) {
String url = message.getString("uri");
String origin = message.getString("origin");
Intent intent = GeckoAppShell.getWebAppIntent(url, origin, "", null);
if (intent == null)
return;
Log.i(LOGTAG, "Open " + url + " (" + origin + ")");
startActivity(intent);
} else if (event.equals("WebApps:Install")) {
String name = message.getString("name");
String launchPath = message.getString("launchPath");
String iconURL = message.getString("iconURL");
String uniqueURI = message.getString("uniqueURI");
// installWebapp will return a File object pointing to the profile directory of the webapp
mCurrentResponse = GeckoAppShell.installWebApp(name, launchPath, uniqueURI, iconURL).toString();
} else if (event.equals("WebApps:Uninstall")) {
String uniqueURI = message.getString("uniqueURI");
GeckoAppShell.uninstallWebApp(uniqueURI);
} else if (event.equals("DesktopMode:Changed")) {
int tabId = message.getInt("tabId");
boolean desktopMode = message.getBoolean("desktopMode");
final Tab tab = Tabs.getInstance().getTab(tabId);
if (tab == null)
return;
tab.setDesktopMode(desktopMode);
mMainHandler.post(new Runnable() {
public void run() {
if (tab == Tabs.getInstance().getSelectedTab())
invalidateOptionsMenu();
}
});
} else if (event.equals("Share:Text")) {
String text = message.getString("text");
GeckoAppShell.openUriExternal(text, "text/plain", "", "", Intent.ACTION_SEND, "");