forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
GeckoAppShell.java
2218 lines (1906 loc) · 85.5 KB
/
GeckoAppShell.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.gfx.BitmapUtils;
import org.mozilla.gecko.gfx.GeckoLayerClient;
import org.mozilla.gecko.gfx.GfxInfoThread;
import org.mozilla.gecko.gfx.LayerView;
import org.mozilla.gecko.gfx.PanZoomController;
import org.mozilla.gecko.mozglue.GeckoLoader;
import org.mozilla.gecko.util.EventDispatcher;
import org.mozilla.gecko.util.GeckoEventListener;
import org.mozilla.gecko.util.ThreadUtils;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.os.Vibrator;
import android.provider.Settings;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.HapticFeedbackConstants;
import android.view.Surface;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.concurrent.SynchronousQueue;
import java.net.ProxySelector;
import java.net.Proxy;
import java.net.URI;
public class GeckoAppShell
{
private static final String LOGTAG = "GeckoAppShell";
// static members only
private GeckoAppShell() { }
static private LinkedList<GeckoEvent> gPendingEvents =
new LinkedList<GeckoEvent>();
static private boolean gRestartScheduled = false;
static private GeckoEditableListener mEditableListener = null;
static private final HashMap<String, String>
mAlertCookies = new HashMap<String, String>();
/* Keep in sync with constants found here:
http://mxr.mozilla.org/mozilla-central/source/uriloader/base/nsIWebProgressListener.idl
*/
static public final int WPL_STATE_START = 0x00000001;
static public final int WPL_STATE_STOP = 0x00000010;
static public final int WPL_STATE_IS_DOCUMENT = 0x00020000;
static public final int WPL_STATE_IS_NETWORK = 0x00040000;
public static final String SHORTCUT_TYPE_WEBAPP = "webapp";
public static final String SHORTCUT_TYPE_BOOKMARK = "bookmark";
static private final boolean LOGGING = false;
static private int sDensityDpi = 0;
private static final EventDispatcher sEventDispatcher = new EventDispatcher();
/* Default colors. */
private static final float[] DEFAULT_LAUNCHER_ICON_HSV = { 32.0f, 1.0f, 1.0f };
/* Is the value in sVibrationEndTime valid? */
private static boolean sVibrationMaybePlaying = false;
/* Time (in System.nanoTime() units) when the currently-playing vibration
* is scheduled to end. This value is valid only when
* sVibrationMaybePlaying is true. */
private static long sVibrationEndTime = 0;
/* Default value of how fast we should hint the Android sensors. */
private static int sDefaultSensorHint = 100;
private static Sensor gAccelerometerSensor = null;
private static Sensor gLinearAccelerometerSensor = null;
private static Sensor gGyroscopeSensor = null;
private static Sensor gOrientationSensor = null;
private static Sensor gProximitySensor = null;
private static Sensor gLightSensor = null;
private static boolean mLocationHighAccuracy = false;
public static ActivityHandlerHelper sActivityHelper = new ActivityHandlerHelper();
static NotificationClient sNotificationClient;
/* The Android-side API: API methods that Android calls */
// Initialization methods
public static native void nativeInit();
// helper methods
// public static native void setSurfaceView(GeckoSurfaceView sv);
public static native void setLayerClient(GeckoLayerClient client);
public static native void onResume();
public static native void onLowMemory();
public static native void callObserver(String observerKey, String topic, String data);
public static native void removeObserver(String observerKey);
public static native void onChangeNetworkLinkStatus(String status);
public static native Message getNextMessageFromQueue(MessageQueue queue);
public static native void onSurfaceTextureFrameAvailable(Object surfaceTexture, int id);
public static void registerGlobalExceptionHandler() {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable e) {
Log.e(LOGTAG, ">>> REPORTING UNCAUGHT EXCEPTION FROM THREAD "
+ thread.getId() + " (\"" + thread.getName() + "\")", e);
// If the uncaught exception was rethrown, walk the exception `cause` chain to find
// the original exception so Socorro can correctly collate related crash reports.
Throwable cause;
while ((cause = e.getCause()) != null) {
e = cause;
}
if (e instanceof java.lang.OutOfMemoryError) {
SharedPreferences prefs =
GeckoApp.mAppContext.getSharedPreferences(GeckoApp.PREFS_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(GeckoApp.PREFS_OOM_EXCEPTION, true);
editor.commit();
}
reportJavaCrash(getStackTraceString(e));
}
});
}
private static String getStackTraceString(Throwable e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
return sw.toString();
}
private static native void reportJavaCrash(String stackTrace);
public static void notifyUriVisited(String uri) {
sendEventToGecko(GeckoEvent.createVisitedEvent(uri));
}
public static native void processNextNativeEvent();
public static native void notifyBatteryChange(double aLevel, boolean aCharging, double aRemainingTime);
public static native void scheduleComposite();
// Resuming the compositor is a synchronous request, so be
// careful of possible deadlock. Resuming the compositor will also cause
// a composition, so there is no need to schedule a composition after
// resuming.
public static native void scheduleResumeComposition(int width, int height);
public static native float computeRenderIntegrity();
public static native SurfaceBits getSurfaceBits(Surface surface);
public static native void onFullScreenPluginHidden(View view);
private static final class GeckoMediaScannerClient implements MediaScannerConnectionClient {
private final String mFile;
private final String mMimeType;
private MediaScannerConnection mScanner;
public static void startScan(Context context, String file, String mimeType) {
new GeckoMediaScannerClient(context, file, mimeType);
}
private GeckoMediaScannerClient(Context context, String file, String mimeType) {
mFile = file;
mMimeType = mimeType;
mScanner = new MediaScannerConnection(context, this);
mScanner.connect();
}
@Override
public void onMediaScannerConnected() {
mScanner.scanFile(mFile, mMimeType);
}
@Override
public void onScanCompleted(String path, Uri uri) {
if(path.equals(mFile)) {
mScanner.disconnect();
mScanner = null;
}
}
}
public static void runGecko(String apkPath, String args, String url, String type) {
Looper.prepare();
// run gecko -- it will spawn its own thread
GeckoAppShell.nativeInit();
// Tell Gecko where the target byte buffer is for rendering
GeckoAppShell.setLayerClient(GeckoApp.mAppContext.getLayerView().getLayerClient());
// First argument is the .apk path
String combinedArgs = apkPath + " -greomni " + apkPath;
if (args != null)
combinedArgs += " " + args;
if (url != null)
combinedArgs += " -url " + url;
if (type != null)
combinedArgs += " " + type;
DisplayMetrics metrics = GeckoApp.mAppContext.getResources().getDisplayMetrics();
combinedArgs += " -width " + metrics.widthPixels + " -height " + metrics.heightPixels;
GeckoApp.mAppContext.runOnUiThread(new Runnable() {
@Override
public void run() {
geckoLoaded();
}
});
// and go
GeckoLoader.nativeRun(combinedArgs);
}
// Called on the UI thread after Gecko loads.
private static void geckoLoaded() {
GeckoEditable editable = new GeckoEditable();
// install the gecko => editable listener
mEditableListener = editable;
}
static void sendPendingEventsToGecko() {
try {
while (!gPendingEvents.isEmpty()) {
GeckoEvent e = gPendingEvents.removeFirst();
notifyGeckoOfEvent(e);
}
} catch (NoSuchElementException e) {}
}
/* This method is referenced by Robocop via reflection. */
public static void sendEventToGecko(GeckoEvent e) {
if (GeckoThread.checkLaunchState(GeckoThread.LaunchState.GeckoRunning)) {
notifyGeckoOfEvent(e);
} else {
gPendingEvents.addLast(e);
}
}
// Tell the Gecko event loop that an event is available.
public static native void notifyGeckoOfEvent(GeckoEvent event);
/*
* The Gecko-side API: API methods that Gecko calls
*/
public static void notifyIME(int type) {
if (mEditableListener != null) {
mEditableListener.notifyIME(type);
}
}
public static void notifyIMEContext(int state, String typeHint,
String modeHint, String actionHint) {
if (mEditableListener != null) {
mEditableListener.notifyIMEContext(state, typeHint,
modeHint, actionHint);
}
}
public static void notifyIMEChange(String text, int start, int end, int newEnd) {
if (newEnd < 0) { // Selection change
mEditableListener.onSelectionChange(start, end);
} else { // Text change
mEditableListener.onTextChange(text, start, end, newEnd);
}
}
private static final Object sEventAckLock = new Object();
private static boolean sWaitingForEventAck;
// Block the current thread until the Gecko event loop is caught up
public static void sendEventToGeckoSync(GeckoEvent e) {
e.setAckNeeded(true);
long time = SystemClock.uptimeMillis();
boolean isUiThread = ThreadUtils.isOnUiThread();
synchronized (sEventAckLock) {
if (sWaitingForEventAck) {
// should never happen since we always leave it as false when we exit this function.
Log.e(LOGTAG, "geckoEventSync() may have been called twice concurrently!", new Exception());
// fall through for graceful handling
}
sendEventToGecko(e);
sWaitingForEventAck = true;
while (true) {
try {
sEventAckLock.wait(100);
} catch (InterruptedException ie) {
}
if (!sWaitingForEventAck) {
// response received
break;
}
long waited = SystemClock.uptimeMillis() - time;
Log.d(LOGTAG, "Gecko event sync taking too long: " + waited + "ms");
if (isUiThread && waited >= 4000) {
Log.w(LOGTAG, "Gecko event sync took too long, aborting!", new Exception());
sWaitingForEventAck = false;
break;
}
}
}
}
// Signal the Java thread that it's time to wake up
public static void acknowledgeEvent() {
synchronized (sEventAckLock) {
sWaitingForEventAck = false;
sEventAckLock.notifyAll();
}
}
public static void enableLocation(final boolean enable) {
ThreadUtils.postToUiThread(new Runnable() {
@Override
public void run() {
LocationManager lm = (LocationManager)
GeckoApp.mAppContext.getSystemService(Context.LOCATION_SERVICE);
if (enable) {
Criteria criteria = new Criteria();
criteria.setSpeedRequired(false);
criteria.setBearingRequired(false);
criteria.setAltitudeRequired(false);
if (mLocationHighAccuracy) {
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
} else {
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
}
String provider = lm.getBestProvider(criteria, true);
if (provider == null)
return;
Looper l = Looper.getMainLooper();
Location loc = lm.getLastKnownLocation(provider);
if (loc != null) {
GeckoApp.mAppContext.onLocationChanged(loc);
}
lm.requestLocationUpdates(provider, 100, (float).5, GeckoApp.mAppContext, l);
} else {
lm.removeUpdates(GeckoApp.mAppContext);
}
}
});
}
public static void enableLocationHighAccuracy(final boolean enable) {
mLocationHighAccuracy = enable;
}
public static void enableSensor(int aSensortype) {
SensorManager sm = (SensorManager)
GeckoApp.mAppContext.getSystemService(Context.SENSOR_SERVICE);
switch(aSensortype) {
case GeckoHalDefines.SENSOR_ORIENTATION:
if(gOrientationSensor == null)
gOrientationSensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
if (gOrientationSensor != null)
sm.registerListener(GeckoApp.mAppContext, gOrientationSensor, sDefaultSensorHint);
break;
case GeckoHalDefines.SENSOR_ACCELERATION:
if(gAccelerometerSensor == null)
gAccelerometerSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (gAccelerometerSensor != null)
sm.registerListener(GeckoApp.mAppContext, gAccelerometerSensor, sDefaultSensorHint);
break;
case GeckoHalDefines.SENSOR_PROXIMITY:
if(gProximitySensor == null)
gProximitySensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
if (gProximitySensor != null)
sm.registerListener(GeckoApp.mAppContext, gProximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
break;
case GeckoHalDefines.SENSOR_LIGHT:
if(gLightSensor == null)
gLightSensor = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
if (gLightSensor != null)
sm.registerListener(GeckoApp.mAppContext, gLightSensor, SensorManager.SENSOR_DELAY_NORMAL);
break;
case GeckoHalDefines.SENSOR_LINEAR_ACCELERATION:
if(gLinearAccelerometerSensor == null)
gLinearAccelerometerSensor = sm.getDefaultSensor(10 /* API Level 9 - TYPE_LINEAR_ACCELERATION */);
if (gLinearAccelerometerSensor != null)
sm.registerListener(GeckoApp.mAppContext, gLinearAccelerometerSensor, sDefaultSensorHint);
break;
case GeckoHalDefines.SENSOR_GYROSCOPE:
if(gGyroscopeSensor == null)
gGyroscopeSensor = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (gGyroscopeSensor != null)
sm.registerListener(GeckoApp.mAppContext, gGyroscopeSensor, sDefaultSensorHint);
break;
default:
Log.w(LOGTAG, "Error! Can't enable unknown SENSOR type " + aSensortype);
}
}
public static void disableSensor(int aSensortype) {
SensorManager sm = (SensorManager)
GeckoApp.mAppContext.getSystemService(Context.SENSOR_SERVICE);
switch (aSensortype) {
case GeckoHalDefines.SENSOR_ORIENTATION:
if (gOrientationSensor != null)
sm.unregisterListener(GeckoApp.mAppContext, gOrientationSensor);
break;
case GeckoHalDefines.SENSOR_ACCELERATION:
if (gAccelerometerSensor != null)
sm.unregisterListener(GeckoApp.mAppContext, gAccelerometerSensor);
break;
case GeckoHalDefines.SENSOR_PROXIMITY:
if (gProximitySensor != null)
sm.unregisterListener(GeckoApp.mAppContext, gProximitySensor);
break;
case GeckoHalDefines.SENSOR_LIGHT:
if (gLightSensor != null)
sm.unregisterListener(GeckoApp.mAppContext, gLightSensor);
break;
case GeckoHalDefines.SENSOR_LINEAR_ACCELERATION:
if (gLinearAccelerometerSensor != null)
sm.unregisterListener(GeckoApp.mAppContext, gLinearAccelerometerSensor);
break;
case GeckoHalDefines.SENSOR_GYROSCOPE:
if (gGyroscopeSensor != null)
sm.unregisterListener(GeckoApp.mAppContext, gGyroscopeSensor);
break;
default:
Log.w(LOGTAG, "Error! Can't disable unknown SENSOR type " + aSensortype);
}
}
public static void moveTaskToBack() {
GeckoApp.mAppContext.moveTaskToBack(true);
}
public static void returnIMEQueryResult(String result, int selectionStart, int selectionLength) {
// This method may be called from JNI to report Gecko's current selection indexes, but
// Native Fennec doesn't care because the Java code already knows the selection indexes.
}
static void onXreExit() {
// The launch state can only be Launched or GeckoRunning at this point
GeckoThread.setLaunchState(GeckoThread.LaunchState.GeckoExiting);
if (gRestartScheduled) {
GeckoApp.mAppContext.doRestart();
} else {
GeckoApp.mAppContext.finish();
}
Log.d(LOGTAG, "Killing via System.exit()");
System.exit(0);
}
static void scheduleRestart() {
gRestartScheduled = true;
}
public static File preInstallWebApp(String aTitle, String aURI, String aUniqueURI) {
int index = WebAppAllocator.getInstance(GeckoApp.mAppContext).findAndAllocateIndex(aUniqueURI, aTitle, (String) null);
GeckoProfile profile = GeckoProfile.get(GeckoApp.mAppContext, "webapp" + index);
return profile.getDir();
}
public static void postInstallWebApp(String aTitle, String aURI, String aUniqueURI, String aIconURL) {
WebAppAllocator allocator = WebAppAllocator.getInstance(GeckoApp.mAppContext);
int index = allocator.getIndexForApp(aUniqueURI);
assert index != -1 && aIconURL != null;
allocator.updateAppAllocation(aUniqueURI, index, BitmapUtils.getBitmapFromDataURI(aIconURL));
createShortcut(aTitle, aURI, aUniqueURI, aIconURL, "webapp");
}
public static Intent getWebAppIntent(String aURI, String aUniqueURI, String aTitle, Bitmap aIcon) {
int index;
if (aIcon != null && !TextUtils.isEmpty(aTitle))
index = WebAppAllocator.getInstance(GeckoApp.mAppContext).findAndAllocateIndex(aUniqueURI, aTitle, aIcon);
else
index = WebAppAllocator.getInstance(GeckoApp.mAppContext).getIndexForApp(aUniqueURI);
if (index == -1)
return null;
return getWebAppIntent(index, aURI);
}
public static Intent getWebAppIntent(int aIndex, String aURI) {
Intent intent = new Intent();
intent.setAction(GeckoApp.ACTION_WEBAPP_PREFIX + aIndex);
intent.setData(Uri.parse(aURI));
intent.setClassName(GeckoApp.mAppContext, GeckoApp.mAppContext.getPackageName() + ".WebApps$WebApp" + aIndex);
return intent;
}
// "Installs" an application by creating a shortcut
// This is the entry point from AndroidBridge.h
static void createShortcut(String aTitle, String aURI, String aIconData, String aType) {
if ("webapp".equals(aType)) {
Log.w(LOGTAG, "createShortcut with no unique URI should not be used for aType = webapp!");
}
createShortcut(aTitle, aURI, aURI, aIconData, aType);
}
// internal, for non-webapps
static void createShortcut(String aTitle, String aURI, Bitmap aBitmap, String aType) {
createShortcut(aTitle, aURI, aURI, aBitmap, aType);
}
// internal, for webapps
static void createShortcut(String aTitle, String aURI, String aUniqueURI, String aIconData, String aType) {
createShortcut(aTitle, aURI, aUniqueURI, BitmapUtils.getBitmapFromDataURI(aIconData), aType);
}
public static void createShortcut(final String aTitle, final String aURI, final String aUniqueURI,
final Bitmap aIcon, final String aType)
{
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
// the intent to be launched by the shortcut
Intent shortcutIntent;
if (aType.equalsIgnoreCase(SHORTCUT_TYPE_WEBAPP)) {
shortcutIntent = getWebAppIntent(aURI, aUniqueURI, aTitle, aIcon);
} else {
shortcutIntent = new Intent();
shortcutIntent.setAction(GeckoApp.ACTION_BOOKMARK);
shortcutIntent.setData(Uri.parse(aURI));
shortcutIntent.setClassName(GeckoApp.mAppContext,
GeckoApp.mAppContext.getPackageName() + ".App");
}
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
if (aTitle != null)
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, aTitle);
else
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, aURI);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, getLauncherIcon(aIcon, aType));
// Do not allow duplicate items
intent.putExtra("duplicate", false);
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
GeckoApp.mAppContext.sendBroadcast(intent);
}
});
}
public static void removeShortcut(final String aTitle, final String aURI, final String aType) {
removeShortcut(aTitle, aURI, null, aType);
}
public static void removeShortcut(final String aTitle, final String aURI, final String aUniqueURI, final String aType) {
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
// the intent to be launched by the shortcut
Intent shortcutIntent;
if (aType.equalsIgnoreCase(SHORTCUT_TYPE_WEBAPP)) {
int index = WebAppAllocator.getInstance(GeckoApp.mAppContext).getIndexForApp(aUniqueURI);
shortcutIntent = getWebAppIntent(aURI, aUniqueURI, "", null);
if (shortcutIntent == null)
return;
} else {
shortcutIntent = new Intent();
shortcutIntent.setAction(GeckoApp.ACTION_BOOKMARK);
shortcutIntent.setClassName(GeckoApp.mAppContext,
GeckoApp.mAppContext.getPackageName() + ".App");
shortcutIntent.setData(Uri.parse(aURI));
}
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
if (aTitle != null)
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, aTitle);
else
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, aURI);
intent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
GeckoApp.mAppContext.sendBroadcast(intent);
}
});
}
public static void uninstallWebApp(final String uniqueURI) {
// On uninstall, we need to do a couple of things:
// 1. nuke the running app process.
// 2. nuke the profile that was assigned to that webapp
ThreadUtils.postToBackgroundThread(new Runnable() {
@Override
public void run() {
int index = WebAppAllocator.getInstance(GeckoApp.mAppContext).releaseIndexForApp(uniqueURI);
// if -1, nothing to do; we didn't think it was installed anyway
if (index == -1)
return;
// kill the app if it's running
String targetProcessName = GeckoApp.mAppContext.getPackageName();
targetProcessName = targetProcessName + ":" + targetProcessName + ".WebApp" + index;
ActivityManager am = (ActivityManager) GeckoApp.mAppContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> procs = am.getRunningAppProcesses();
if (procs != null) {
for (ActivityManager.RunningAppProcessInfo proc : procs) {
if (proc.processName.equals(targetProcessName)) {
android.os.Process.killProcess(proc.pid);
break;
}
}
}
// then nuke the profile
GeckoProfile.removeProfile(GeckoApp.mAppContext, "webapp" + index);
}
});
}
static public int getPreferredIconSize() {
if (android.os.Build.VERSION.SDK_INT >= 11) {
ActivityManager am = (ActivityManager)GeckoApp.mAppContext.getSystemService(Context.ACTIVITY_SERVICE);
return am.getLauncherLargeIconSize();
} else {
switch (getDpi()) {
case DisplayMetrics.DENSITY_MEDIUM:
return 48;
case DisplayMetrics.DENSITY_XHIGH:
return 96;
case DisplayMetrics.DENSITY_HIGH:
default:
return 72;
}
}
}
static private Bitmap getLauncherIcon(Bitmap aSource, String aType) {
final int kOffset = 6;
final int kRadius = 5;
int size = getPreferredIconSize();
int insetSize = aSource != null ? size * 2 / 3 : size;
Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
if (aType.equalsIgnoreCase(SHORTCUT_TYPE_WEBAPP)) {
Rect iconBounds = new Rect(0, 0, size, size);
canvas.drawBitmap(aSource, null, iconBounds, null);
return bitmap;
}
// draw a base color
Paint paint = new Paint();
if (aSource == null) {
// If we aren't drawing a favicon, just use an orange color.
paint.setColor(Color.HSVToColor(DEFAULT_LAUNCHER_ICON_HSV));
canvas.drawRoundRect(new RectF(kOffset, kOffset, size - kOffset, size - kOffset), kRadius, kRadius, paint);
} else {
// otherwise use the dominant color from the icon + a layer of transparent white to lighten it somewhat
int color = BitmapUtils.getDominantColor(aSource);
paint.setColor(color);
canvas.drawRoundRect(new RectF(kOffset, kOffset, size - kOffset, size - kOffset), kRadius, kRadius, paint);
paint.setColor(Color.argb(100, 255, 255, 255));
canvas.drawRoundRect(new RectF(kOffset, kOffset, size - kOffset, size - kOffset), kRadius, kRadius, paint);
}
// draw the overlay
Bitmap overlay = BitmapUtils.decodeResource(GeckoApp.mAppContext, R.drawable.home_bg);
canvas.drawBitmap(overlay, null, new Rect(0, 0, size, size), null);
// draw the favicon
if (aSource == null)
aSource = BitmapUtils.decodeResource(GeckoApp.mAppContext, R.drawable.home_star);
// by default, we scale the icon to this size
int sWidth = insetSize / 2;
int sHeight = sWidth;
if (aSource.getWidth() > insetSize || aSource.getHeight() > insetSize) {
// however, if the icon is larger than our minimum, we allow it to be drawn slightly larger
// (but not necessarily at its full resolution)
sWidth = Math.min(size / 3, aSource.getWidth() / 2);
sHeight = Math.min(size / 3, aSource.getHeight() / 2);
}
int halfSize = size / 2;
canvas.drawBitmap(aSource,
null,
new Rect(halfSize - sWidth,
halfSize - sHeight,
halfSize + sWidth,
halfSize + sHeight),
null);
return bitmap;
}
static String[] getHandlersForMimeType(String aMimeType, String aAction) {
Intent intent = getIntentForActionString(aAction);
if (aMimeType != null && aMimeType.length() > 0)
intent.setType(aMimeType);
return getHandlersForIntent(intent);
}
static String[] getHandlersForURL(String aURL, String aAction) {
// aURL may contain the whole URL or just the protocol
Uri uri = aURL.indexOf(':') >= 0 ? Uri.parse(aURL) : new Uri.Builder().scheme(aURL).build();
Intent intent = getIntentForActionString(aAction);
intent.setData(uri);
return getHandlersForIntent(intent);
}
static String[] getHandlersForIntent(Intent intent) {
PackageManager pm = GeckoApp.mAppContext.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
int numAttr = 4;
String[] ret = new String[list.size() * numAttr];
for (int i = 0; i < list.size(); i++) {
ResolveInfo resolveInfo = list.get(i);
ret[i * numAttr] = resolveInfo.loadLabel(pm).toString();
if (resolveInfo.isDefault)
ret[i * numAttr + 1] = "default";
else
ret[i * numAttr + 1] = "";
ret[i * numAttr + 2] = resolveInfo.activityInfo.applicationInfo.packageName;
ret[i * numAttr + 3] = resolveInfo.activityInfo.name;
}
return ret;
}
static Intent getIntentForActionString(String aAction) {
// Default to the view action if no other action as been specified.
if (aAction != null && aAction.length() > 0)
return new Intent(aAction);
else
return new Intent(Intent.ACTION_VIEW);
}
static String getExtensionFromMimeType(String aMimeType) {
return MimeTypeMap.getSingleton().getExtensionFromMimeType(aMimeType);
}
static String getMimeTypeFromExtensions(String aFileExt) {
MimeTypeMap mtm = MimeTypeMap.getSingleton();
StringTokenizer st = new StringTokenizer(aFileExt, ".,; ");
String type = null;
String subType = null;
while (st.hasMoreElements()) {
String ext = st.nextToken();
String mt = mtm.getMimeTypeFromExtension(ext);
if (mt == null)
continue;
int slash = mt.indexOf('/');
String tmpType = mt.substring(0, slash);
if (!tmpType.equalsIgnoreCase(type))
type = type == null ? tmpType : "*";
String tmpSubType = mt.substring(slash + 1);
if (!tmpSubType.equalsIgnoreCase(subType))
subType = subType == null ? tmpSubType : "*";
}
if (type == null)
type = "*";
if (subType == null)
subType = "*";
return type + "/" + subType;
}
static void safeStreamClose(Closeable stream) {
try {
if (stream != null)
stream.close();
} catch (IOException e) {}
}
static void shareImage(String aSrc, String aType) {
Intent intent = new Intent(Intent.ACTION_SEND);
boolean isDataURI = aSrc.startsWith("data:");
OutputStream os = null;
File dir = GeckoApp.getTempDirectory();
if (dir == null) {
showImageShareFailureToast();
return;
}
GeckoApp.deleteTempFiles();
try {
// Create a temporary file for the image
File imageFile = File.createTempFile("image",
"." + aType.replace("image/",""),
dir);
os = new FileOutputStream(imageFile);
if (isDataURI) {
// We are dealing with a Data URI
int dataStart = aSrc.indexOf(',');
byte[] buf = Base64.decode(aSrc.substring(dataStart+1), Base64.DEFAULT);
os.write(buf);
} else {
// We are dealing with a URL
InputStream is = null;
try {
URL url = new URL(aSrc);
is = url.openStream();
byte[] buf = new byte[2048];
int length;
while ((length = is.read(buf)) != -1) {
os.write(buf, 0, length);
}
} finally {
safeStreamClose(is);
}
}
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
// If we were able to determine the image type, send that in the intent. Otherwise,
// use a generic type.
if (aType.startsWith("image/")) {
intent.setType(aType);
} else {
intent.setType("image/*");
}
} catch (IOException e) {
if (!isDataURI) {
// If we failed, at least send through the URL link
intent.putExtra(Intent.EXTRA_TEXT, aSrc);
intent.setType("text/plain");
} else {
showImageShareFailureToast();
return;
}
} finally {
safeStreamClose(os);
}
GeckoApp.mAppContext.startActivity(Intent.createChooser(intent,
GeckoApp.mAppContext.getResources().getString(R.string.share_title)));
}
// Don't fail silently, tell the user that we weren't able to share the image
private static final void showImageShareFailureToast() {
Toast toast = Toast.makeText(GeckoApp.mAppContext,
GeckoApp.mAppContext.getResources().getString(R.string.share_image_failed),
Toast.LENGTH_SHORT);
toast.show();
}
static boolean isUriSafeForScheme(Uri aUri) {
// Bug 794034 - We don't want to pass MWI or USSD codes to the
// dialer, and ensure the Uri class doesn't parse a URI
// containing a fragment ('#')
final String scheme = aUri.getScheme();
if ("tel".equals(scheme) || "sms".equals(scheme)) {
final String number = aUri.getSchemeSpecificPart();
if (number.contains("#") || number.contains("*") || aUri.getFragment() != null) {
return false;
}
}
return true;
}
/**
* Given the inputs to <code>getOpenURIIntent</code>, plus an optional
* package name and class name, create and fire an intent to open the
* provided URI.
*
* @param targetURI the string spec of the URI to open.
* @param mimeType an optional MIME type string.
* @param action an Android action specifier, such as
* <code>Intent.ACTION_SEND</code>.
* @param title the title to use in <code>ACTION_SEND</code> intents.
* @return true if the activity started successfully; false otherwise.
*/
static boolean openUriExternal(String targetURI,
String mimeType,
String packageName,
String className,
String action,
String title) {
final Context context = GeckoApp.mAppContext;
final Intent intent = getOpenURIIntent(context, targetURI,
mimeType, action, title);
if (intent == null) {
return false;
}
if (packageName.length() > 0 && className.length() > 0) {
intent.setClassName(packageName, className);
}
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
context.startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
/**
* Return a <code>Uri</code> instance which is equivalent to <code>u</code>,
* but with a guaranteed-lowercase scheme as if the API level 16 method
* <code>u.normalizeScheme</code> had been called.
*
* @param u the <code>Uri</code> to normalize.
* @return a <code>Uri</code>, which might be <code>u</code>.