/
NativeToJavaBridge.java
3236 lines (2807 loc) · 112 KB
/
NativeToJavaBridge.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
//////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
package com.ansca.corona;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.net.URL;
import java.net.MalformedURLException;
import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.media.MediaScannerConnection;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Environment;
import android.location.Location;
import android.util.Base64;
import android.util.Log;
import android.view.DisplayCutout;
import dalvik.system.DexClassLoader;
import com.ansca.corona.AudioRecorder.AudioByteBufferHolder;
import com.ansca.corona.listeners.CoronaSplashScreenApiListener;
import com.ansca.corona.listeners.CoronaStatusBarApiListener;
import com.ansca.corona.listeners.CoronaStoreApiListener;
import com.ansca.corona.listeners.CoronaSystemApiListener;
import com.ansca.corona.maps.MapType;
import com.ansca.corona.permissions.PermissionsSettings;
import com.ansca.corona.permissions.PermissionsServices;
import com.ansca.corona.permissions.PermissionState;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.entity.BufferedHttpEntity;
import org.json.JSONArray;
import org.json.JSONObject;
import com.naef.jnlua.JavaFunction;
import com.naef.jnlua.LuaState;
public class NativeToJavaBridge {
private android.content.Context myContext;
NativeToJavaBridge( android.content.Context context )
{
myContext = context;
}
protected static boolean callRequestSystem(
CoronaRuntime runtime, long luaStateMemoryAddress, String actionName, int luaStackIndex)
{
CoronaSystemApiListener listener = runtime.getController().getCoronaSystemApiListener();
if (listener != null) {
return listener.requestSystem(runtime, actionName, luaStateMemoryAddress, luaStackIndex);
}
return false;
}
/**
* A test routine, to see if the bridge can be crossed.
*/
protected static void ping()
{
System.out.println( "NativeToJavaBridge.ping()" );
}
private static HashMap< String, JavaFunction > sPluginCache = new HashMap< String, JavaFunction >();
protected static int instantiateClass( LuaState L, CoronaRuntime runtime, Class<?> c ) {
int result = 0;
try {
if ( JavaFunction.class.isAssignableFrom( c ) ) {
JavaFunction f = sPluginCache.get( c.getName() );
// Cache miss
if ( null == f ) {
Object o = c.newInstance();
if ( CoronaRuntimeListener.class.isAssignableFrom( c ) ) {
CoronaRuntimeListener listener = (CoronaRuntimeListener)o;
CoronaEnvironment.addRuntimeListener( listener );
listener.onLoaded( runtime );
}
f = (JavaFunction)o;
// Cache the plugin
sPluginCache.put( c.getName(), f );
}
L.pushJavaFunction( f );
result = 1;
}
} catch ( Exception ex ) {
Log.i( "Corona", "ERROR: Could not instantiate class (" + c.getName() + "): " + ex.getLocalizedMessage() );
ex.printStackTrace();
}
return result;
}
private static DexClassLoader sClassLoader = null;
protected static int callLoadClass(
CoronaRuntime runtime, long luaStateMemoryAddress, String libName, String className )
{
int result = 0;
StringBuilder err = new StringBuilder();
if (runtime != null) {
// Fetch the runtime's Lua state.
// TODO: We need to account for coroutines.
LuaState L = runtime.getLuaState();
if ( null == L ) {
L = new com.naef.jnlua.LuaState(luaStateMemoryAddress);
}
// DEBUG: Temporarily set to 'true' for helpful logging messages
final boolean verbose = true;
// Look for the class via reflection.
final String classPath = libName + "." + className;
try {
if ( verbose ) { Log.v( "Corona", "> Class.forName: " + classPath ); }
Class<?> c = Class.forName( classPath );
if ( verbose ) { Log.v( "Corona", "< Class.forName: " + classPath ); }
result = instantiateClass( L, runtime, c );
if ( verbose ) { Log.v( "Corona", "Loading via reflection: " + classPath ); }
}
catch ( Exception ex ) {
err.append("\n\tno Java class '").append(classPath).append("'");
}
catch ( Throwable ex ) {
ex.printStackTrace();
err.append("\n\terror loading class '").append(classPath).append("': ").append(ex);
}
if(result == 0) {
L.pushString(err.toString());
result = 1;
}
}
return result;
}
/**
* This function is used by Corona Kit to load a file when you require("something"). In Corona the file is loaded
* automatically from the archive. There is no archive file in Corona Kit.
*/
protected static int callLoadFile(CoronaRuntime runtime, long luaStateMemoryAddress, String fileName)
{
int result = 0;
android.content.Context context = CoronaEnvironment.getApplicationContext();
if (context == null) {
return result;
}
if (runtime != null) {
com.ansca.corona.storage.FileServices fileServices;
fileServices = new com.ansca.corona.storage.FileServices(context);
fileName = fileName.replace('.', '/');
// Needs to append the file extension because you call require("something") with out the extension
// but to load the file you need the full name of the file
String filePath = runtime.getPath() + fileName + ".lua";
java.io.File pathToOpen = new File(filePath);
if(!fileServices.doesAssetFileExist(filePath)) {
return result;
}
LuaState L = runtime.getLuaState();
if ( null == L ) {
L = new com.naef.jnlua.LuaState(luaStateMemoryAddress);
}
java.io.InputStream inputStream = null;
try {
inputStream = fileServices.openFile(pathToOpen);
L.load(inputStream, fileName);
result = 1;
} catch (Exception e) {
Log.i( "Corona", "WARNING: Could not load '" + fileName + "'" );
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {}
}
}
}
return result;
}
protected static String callGetExceptionStackTraceFrom(Throwable ex)
{
// Validate.
if (ex == null) {
return null;
}
// Return the given exception's message and stack trace as a single string.
com.naef.jnlua.LuaError luaError = new com.naef.jnlua.LuaError(null, ex);
return luaError.toString();
}
protected static String getAudioOutputSettings()
{
if (android.os.Build.VERSION.SDK_INT >= 17) // getProperty
{
android.content.Context context = CoronaEnvironment.getApplicationContext();
if (context != null)
{
AudioManager am = (AudioManager) context.getSystemService(android.content.Context.AUDIO_SERVICE);
if (am != null)
{
String sampleRate = am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
String framesPerBuffer = am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
return sampleRate + "," + framesPerBuffer;
}
}
}
return "";
}
protected static void callOnRuntimeLoaded(long luaStateMemoryAddress, CoronaRuntime runtime)
{
if (runtime != null) {
runtime.onLoaded(luaStateMemoryAddress);
}
}
protected static void callOnRuntimeWillLoadMain(CoronaRuntime runtime)
{
if (runtime != null) {
runtime.onWillLoadMain();
}
}
protected static void callOnRuntimeStarted(CoronaRuntime runtime)
{
if (runtime != null) {
runtime.onStarted();
}
}
protected static void callOnRuntimeSuspended(CoronaRuntime runtime)
{
if (runtime != null) {
runtime.onSuspended();
}
}
protected static void callOnRuntimeResumed(CoronaRuntime runtime)
{
if (runtime != null) {
runtime.onResumed();
}
}
protected static void callOnAudioEnabled() {
MediaManager.onUsingAudio();
}
protected static int callInvokeLuaErrorHandler(long luaStateMemoryAddress)
{
return CoronaEnvironment.invokeLuaErrorHandler(luaStateMemoryAddress);
}
protected static void callPushLaunchArgumentsToLuaTable(CoronaRuntime runtime, long luaStateMemoryAddress)
{
CoronaSystemApiListener listener = runtime.getController().getCoronaSystemApiListener();
if (listener != null) {
pushArgumentsToLuaTable(runtime, luaStateMemoryAddress, listener.getInitialIntent());
}
}
protected static void callPushApplicationOpenArgumentsToLuaTable(CoronaRuntime runtime, long luaStateMemoryAddress)
{
CoronaSystemApiListener listener = runtime.getController().getCoronaSystemApiListener();
if (listener != null) {
pushArgumentsToLuaTable(runtime, luaStateMemoryAddress, listener.getIntent());
}
}
private static void pushArgumentsToLuaTable(CoronaRuntime runtime, long luaStateMemoryAddress, android.content.Intent intent)
{
// Validate arguments.
if ((luaStateMemoryAddress == 0) || (intent == null)) {
return;
}
// Fetch a Lua state object for the given memory address.
com.naef.jnlua.LuaState luaState = null;
if (runtime != null) {
luaState = runtime.getLuaState();
}
// Using coroutines will give a different lua state than what the runtime has so this is to verify its the same one
if (luaState == null || CoronaRuntimeProvider.getLuaStateMemoryAddress(luaState) != luaStateMemoryAddress) {
luaState = new com.naef.jnlua.LuaState(luaStateMemoryAddress);
}
// Do not continue if there is no Lua table at the top of the Lua stack.
int rootLuaTableStackIndex = luaState.getTop();
if (luaState.isTable(rootLuaTableStackIndex) == false) {
return;
}
// Push the intent's URL to the Lua table.
android.net.Uri uri = intent.getData();
luaState.pushString(((uri != null) ? uri.toString() : ""));
luaState.setField(rootLuaTableStackIndex, "url");
// Push an "androidIntent" Lua table to the given Lua table.
luaState.newTable();
{
// Get the index to the intent Lua table.
int intentLuaTableStackIndex = luaState.getTop();
// Push the intent's URL to the Lua table.
luaState.pushString(((uri != null) ? uri.toString() : ""));
luaState.setField(intentLuaTableStackIndex, "url");
// Push the intent's action string to the Lua table.
String action = intent.getAction();
luaState.pushString(((action != null) ? action : ""));
luaState.setField(intentLuaTableStackIndex, "action");
// Push the intent's category strings to the Lua table.
boolean wasPushed = pushToLua(luaState, intent.getCategories());
if (wasPushed == false) {
luaState.newTable();
}
luaState.setField(intentLuaTableStackIndex, "categories");
// Push the intent's extras to the Lua table.
luaState.newTable();
{
int extrasLuaTableStackIndex = luaState.getTop();
android.os.Bundle bundle = intent.getExtras();
if ((bundle != null) && (bundle.size() > 0)) {
for (String key : bundle.keySet()) {
wasPushed = pushToLua(luaState, bundle.get(key));
if (wasPushed) {
luaState.setField(extrasLuaTableStackIndex, key);
}
}
}
}
luaState.setField(intentLuaTableStackIndex, "extras");
}
luaState.setField(rootLuaTableStackIndex, "androidIntent");
// If there is a notification bundle in the intent, then push it to the root Lua table.
// This is to be consistent with how Corona for iOS provides notification data.
String notificationEventName = com.ansca.corona.events.NotificationReceivedTask.NAME;
boolean wasPushed = pushToLua(luaState, intent.getBundleExtra(notificationEventName));
if (wasPushed) {
luaState.setField(rootLuaTableStackIndex, notificationEventName);
}
}
private static boolean pushToLua(com.naef.jnlua.LuaState luaState, Object value)
{
// Validate arguments.
if ((luaState == null) || (value == null)) {
return false;
}
// Convert the given Java object to its equivalent Lua type and push it to the Lua stack.
if (value instanceof Boolean) {
luaState.pushBoolean(((Boolean)value).booleanValue());
}
else if ((value instanceof Float) || (value instanceof Double)) {
luaState.pushNumber(((Number)value).doubleValue());
}
else if (value instanceof Number) {
luaState.pushInteger(((Number)value).intValue());
}
else if (value instanceof Character) {
luaState.pushString(value.toString());
}
else if (value instanceof String) {
luaState.pushString((String)value);
}
else if (value instanceof java.io.File) {
luaState.pushString(((java.io.File)value).getAbsolutePath());
}
else if (value instanceof android.net.Uri) {
luaState.pushString(value.toString());
}
else if (value instanceof CoronaData) {
((CoronaData)value).pushTo(luaState);
}
else if (value instanceof android.os.Bundle) {
android.os.Bundle bundle = (android.os.Bundle)value;
if (bundle.size() > 0) {
luaState.newTable(0, bundle.size());
int luaTableStackIndex = luaState.getTop();
for (String key : bundle.keySet()) {
boolean wasPushed = pushToLua(luaState, bundle.get(key));
if (wasPushed) {
luaState.setField(luaTableStackIndex, key);
}
}
}
else {
luaState.newTable();
}
}
else if (value.getClass().isArray()) {
int arrayLength = java.lang.reflect.Array.getLength(value);
if (arrayLength > 0) {
luaState.newTable(arrayLength, 0);
int luaTableStackIndex = luaState.getTop();
for (int arrayIndex = 0; arrayIndex < arrayLength; arrayIndex++) {
boolean wasPushed = pushToLua(luaState, java.lang.reflect.Array.get(value, arrayIndex));
if (wasPushed) {
luaState.rawSet(luaTableStackIndex, arrayIndex + 1);
}
}
}
else {
luaState.newTable();
}
}
else if (value instanceof java.util.Map) {
java.util.Map map = (java.util.Map)value;
if (map.size() > 0) {
luaState.newTable(0, map.size());
int luaTableStackIndex = luaState.getTop();
for (java.util.Map.Entry entry : (java.util.Set<java.util.Map.Entry>)map.entrySet()) {
if ((entry.getKey() instanceof String) || (entry.getKey() instanceof Number)) {
boolean wasPushed = pushToLua(luaState, entry.getValue());
if (wasPushed) {
luaState.setField(luaTableStackIndex, entry.getKey().toString());
}
}
}
}
else {
luaState.newTable();
}
}
else if (value instanceof Iterable) {
luaState.newTable();
int luaTableStackIndex = luaState.getTop();
int arrayIndex = 0;
for (Object collectionValue : (Iterable)value) {
boolean wasPushed = pushToLua(luaState, collectionValue);
if (wasPushed) {
luaState.rawSet(luaTableStackIndex, arrayIndex + 1);
}
arrayIndex++;
}
}
else {
return false;
}
// Return true to indicate that we successfully pushed the value into Lua.
return true;
}
/**
* Test to see if the named asset exists
*
* @param assetName Asset to find
* @return True if it exists, false otherwise
*/
private boolean getRawAssetExists( String assetName )
{
// Validate.
if ((assetName == null) || (assetName.length() <= 0)) {
return false;
}
// Attempt to fetch the given asset name's URL scheme, if it has one.
android.net.Uri uri = android.net.Uri.parse(android.net.Uri.encode(assetName, ":/\\."));
String scheme = uri.getScheme();
if (scheme == null) {
scheme = "";
}
scheme = scheme.toLowerCase();
// Determine if the given asset name exists.
boolean wasAssetFound = false;
if (scheme.equals("android.app.icon")) {
// The asset is an application icon.
try {
String packageName = uri.getHost();
if ((packageName == null) || (packageName.length() <= 0)) {
wasAssetFound = true;
}
else {
android.content.pm.PackageInfo packageInfo =
CoronaEnvironment.getApplicationContext().getPackageManager().getPackageInfo(packageName, 0);
wasAssetFound = (packageInfo != null);
}
}
catch (Exception ex) { }
}
else {
// The asset is likely a file within the APK or Google Play expansion file.
android.content.Context context = CoronaEnvironment.getApplicationContext();
if (context != null) {
com.ansca.corona.storage.FileServices fileServices;
fileServices = new com.ansca.corona.storage.FileServices(context);
wasAssetFound = fileServices.doesAssetFileExist(assetName);
}
// It doesn't make sense to issue a log message when testing for existence (not existing
// may be ok in the context of the caller)
// Log a warning if the asset was not found.
// if (wasAssetFound == false) {
// Log.i("Corona", "WARNING: Asset file \"" + assetName + "\" does not exist.");
// }
}
// Return the result.
return wasAssetFound;
}
protected static boolean callGetRawAssetExists( CoronaRuntime runtime, String assetName )
{
return runtime.getController().getBridge().getRawAssetExists(runtime.getPath() + assetName);
}
protected static boolean callGetCoronaResourceFileExists( CoronaRuntime runtime, String assetName )
{
boolean exists = false;
android.content.Context context = CoronaEnvironment.getApplicationContext();
if (context != null) {
java.io.File destinationFile =
new java.io.File(context.getFileStreamPath("coronaResources"), runtime.getPath() + assetName);
exists = destinationFile.exists();
}
return exists;
}
protected static boolean callGetAssetFileLocation(String filePath, long zipFileEntryMemoryAddress) {
// Fetch the application context.
android.content.Context context = CoronaEnvironment.getApplicationContext();
if (context == null) {
return false;
}
// Fetch the asset's location.
com.ansca.corona.storage.FileServices fileServices;
com.ansca.corona.storage.AssetFileLocationInfo assetFileLocationInfo;
fileServices = new com.ansca.corona.storage.FileServices(context);
assetFileLocationInfo = fileServices.getAssetFileLocation(filePath);
if (assetFileLocationInfo == null) {
return false;
}
// Write the asset's location info to the struct referenced by the given memory address.
JavaToNativeShim.setZipFileEntryInfo(zipFileEntryMemoryAddress, assetFileLocationInfo);
// Return true to indicate that the asset was found.
return true;
}
protected static byte[] callGetBytesFromFile( String filePathName ) {
// Fetch the application context.
android.content.Context context = CoronaEnvironment.getApplicationContext();
if (context == null) {
return null;
}
// Extract all bytes from the given file and return them.
com.ansca.corona.storage.FileServices fileServices;
fileServices = new com.ansca.corona.storage.FileServices(context);
return fileServices.getBytesFromFile(filePathName);
}
protected static String callExternalizeResource( String assetName, CoronaRuntime runtime ) {
// Fetch the application context.
android.content.Context context = CoronaEnvironment.getApplicationContext();
if (context == null) {
return null;
}
// Extract the given asset file.
com.ansca.corona.storage.FileServices fileServices = new com.ansca.corona.storage.FileServices(context);
java.io.File destinationFile = fileServices.extractAssetFile(runtime.getPath() + assetName);
if (destinationFile == null) {
return null;
}
// Return the path to where the extracted file was written to.
return destinationFile.getAbsolutePath();
}
/**
* Fetches the given image file's dimensions and mime type without loading the file.
* @param imageFileName The path\file name of the image to fetch information from.
* @return Returns an object providing image information via parameters: outWidth, outHeight, outMimeType
* Returns null if failed to load the given image file.
*/
private android.graphics.BitmapFactory.Options getBitmapFileInfo(String imageFileName) {
BitmapFactory.Options options = null;
// Validate.
if ((imageFileName == null) || (imageFileName.length() <= 0)) {
return null;
}
// Attempt to fetch the given image file's information.
InputStream stream = null;
try {
// Get a stream to the given file. A path that does not start with a '/' is assumed to be an asset file.
com.ansca.corona.storage.FileServices fileServices;
fileServices = new com.ansca.corona.storage.FileServices(myContext);
stream = fileServices.openFile(imageFileName);
if (stream != null) {
// Fetch the image file's information.
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(stream, null, options);
// The option object's dimensions will be -1 if we have failed to load the file.
// In this case, we want to return null from this function.
if (options.outWidth < 0) {
options = null;
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (stream != null) {
try { stream.close(); }
catch (Exception ex) { }
}
}
// Return the result. Will be null if failed to load the image.
return options;
}
private int getImageExifRotationInDegreesFrom(String imageFileName) {
// Validate argument.
if ((imageFileName == null) || (imageFileName.length() <= 0)) {
return 0;
}
// Do not continue if the given file is an asset.
// The ExifReader class cannot access an asset within a file.
com.ansca.corona.storage.FileServices fileServices;
fileServices = new com.ansca.corona.storage.FileServices(CoronaEnvironment.getApplicationContext());
if (fileServices.isAssetFile(imageFileName)) {
return 0;
}
// Attempt to fetch the EXIF orientation from the given image file.
int rotationInDegrees = 0;
try {
android.media.ExifInterface exifReader = new android.media.ExifInterface(imageFileName);
int exifOrientation = exifReader.getAttributeInt(
android.media.ExifInterface.TAG_ORIENTATION,
android.media.ExifInterface.ORIENTATION_NORMAL);
switch (exifOrientation) {
case android.media.ExifInterface.ORIENTATION_ROTATE_90:
rotationInDegrees = 90;
break;
case android.media.ExifInterface.ORIENTATION_ROTATE_180:
rotationInDegrees = 180;
break;
case android.media.ExifInterface.ORIENTATION_ROTATE_270:
rotationInDegrees = 270;
break;
}
}
catch (Exception ex) { }
return rotationInDegrees;
}
/**
* Instances of this class are returned from the loadBitmap() method to indicate if it successfully
* loaded a bitmap, and if so, provide information about that loaded bitmap.
*/
private static class LoadBitmapResult {
private Bitmap fBitmap;
private int fWidth;
private int fHeight;
private float fScaleFactor;
private int fRotationInDegrees;
public LoadBitmapResult(Bitmap bitmap, float scaleFactor, int rotationInDegrees) {
fBitmap = bitmap;
fWidth = 0;
fHeight = 0;
fScaleFactor = scaleFactor;
fRotationInDegrees = rotationInDegrees;
}
public LoadBitmapResult(int width, int height, float scaleFactor, int rotationInDegrees) {
fBitmap = null;
fWidth = width;
fHeight = height;
fScaleFactor = scaleFactor;
fRotationInDegrees = rotationInDegrees;
}
public boolean wasSuccessful() {
return (fBitmap != null);
}
public Bitmap getBitmap() {
return fBitmap;
}
public int getWidth() {
if (fBitmap != null) {
return fBitmap.getWidth();
}
return fWidth;
}
public int getHeight() {
if (fBitmap != null) {
return fBitmap.getHeight();
}
return fHeight;
}
public float getScaleFactor() {
return fScaleFactor;
}
public int getRotationInDegrees() {
return fRotationInDegrees;
}
}
private LoadBitmapResult loadBitmap(String filePath, int maxWidth, int maxHeight, boolean loadImageInfoOnly) {
Bitmap result = null;
// Attempt to fetch the image file's dimensions first.
BitmapFactory.Options options = getBitmapFileInfo(filePath);
if (options == null) {
// File not found. Do not continue.
return null;
}
int originalWidth = options.outWidth;
int originalHeight = options.outHeight;
// Get a stream to the given file.
// A path that does not start with a '/' is assumed to be an asset file.
com.ansca.corona.storage.FileServices fileServices;
fileServices = new com.ansca.corona.storage.FileServices(myContext);
boolean isAssetFile = fileServices.isAssetFile(filePath);
InputStream stream = fileServices.openFile(filePath);
if (stream == null) {
return null;
}
// Fetch the image file's EXIF orientation, if available.
// Skip asset files since the ExifInterface class can only open external files.
// Note: EXIF is optional metadata assigned to image files. It is commonly set by cameras.
int rotationInDegrees = 0;
if (!isAssetFile) {
rotationInDegrees = getImageExifRotationInDegreesFrom(filePath);
}
// If a maximum pixel width and height has been provided (ie: a max value greater than zero),
// then use the smallest of the maximum lengths to downsample the image with below.
int maxImageLength = 0;
if ((maxWidth > 0) && (maxHeight > 0)) {
maxImageLength = (maxWidth < maxHeight) ? maxWidth : maxHeight;
}
else if (maxWidth > 0) {
maxImageLength = maxWidth;
}
else if (maxHeight > 0) {
maxImageLength = maxHeight;
}
// Downsample the image if it is larger than the provided maximum size provided.
// Note: Downsampling involves skipping every other decoded pixel, which downscales
// the image in powers of 2 in a fast and memory efficient manner.
options = new BitmapFactory.Options();
options.inSampleSize = 1;
if (maxImageLength > 0) {
float percentLength = (float)java.lang.Math.max(originalWidth, originalHeight) / (float)maxImageLength;
while (percentLength > 1.0f) {
options.inSampleSize *= 2;
percentLength /= 2.0f;
}
if (options.inSampleSize > 1) {
Log.v("Corona", "Downsampling image file '" + filePath +
"' to fit max pixel size of " + Integer.toString(maxImageLength) + ".");
}
}
// Check if we have enough memory to load the image at full 32-bit color quality.
// If we don't have enough memory, then load the image at 16-bit quality.
// Note: We can't determine the memory usage of this app, so we have to guess based on the max JVM heap size.
long imagePixelCount = (originalWidth * originalHeight) / options.inSampleSize;
long memoryUsage = imagePixelCount * 4; // Calculate the image memory size of at a 32-bit color quality.
memoryUsage += 2000000; // Add about 2 MB for other things this app may be using memory for.
// Note: This is a guess. We don't know how much memory the app is using.
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
if (memoryUsage > Runtime.getRuntime().maxMemory()) {
Log.v("Corona", "Not enough memory to load file '" + filePath +
"' as a 32-bit image. Reducing the image quality to 16-bit.");
options.inPreferredConfig = Bitmap.Config.RGB_565;
}
// Do not continue if the caller only wants image information and not the decoded pixels.
if (loadImageInfoOnly) {
// Predict what the downsampled width, height, and scale will be if applicable.
int expectedWidth = originalWidth;
int expectedHeight = originalHeight;
float expectedScale = 1.0f;
if (options.inSampleSize > 1) {
expectedWidth = originalWidth / options.inSampleSize;
if ((originalWidth % options.inSampleSize) > 0) {
expectedWidth++;
}
expectedHeight = originalHeight / options.inSampleSize;
if ((originalHeight % options.inSampleSize) > 0) {
expectedHeight++;
}
expectedScale = (float)expectedWidth / (float)originalWidth;
}
// Return the image file's information.
return new LoadBitmapResult(expectedWidth, expectedHeight, expectedScale, rotationInDegrees);
}
// Load the image file to an uncompressed bitmap in memory.
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(stream, null, options);
}
catch (OutOfMemoryError memoryException) {
try {
// There was not enough memory to load the image file. If we were loading it as a 32-bit color bitmap,
// then attempt to load the image again with a lower 16-bit color quality.
if (options.inPreferredConfig == Bitmap.Config.ARGB_8888) {
Log.v("Corona", "Failed to load file '" + filePath +
"' as a 32-bit image. Reducing the image quality to 16-bit.");
System.gc();
options.inPreferredConfig = Bitmap.Config.RGB_565;
bitmap = BitmapFactory.decodeStream(stream, null, options);
}
else {
throw memoryException;
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
try { stream.close(); }
catch (Exception ex) {
ex.printStackTrace();
}
if (bitmap == null) {
Log.v("Corona", "Unable to decode file '" + filePath + "'");
return null;
}
// If the image was downsampled, then calculate the scaling factor.
float downsampleScale = 1.0f;
if (bitmap.getWidth() != originalWidth) {
downsampleScale = (float)bitmap.getWidth() / (float)originalWidth;
}
// Image file was loaded successfully. Return the bitmap in a result object.
return new LoadBitmapResult(bitmap, downsampleScale, rotationInDegrees);
}
private static boolean callLoadBitmap(
CoronaRuntime runtime, String filePath, long nativeImageMemoryAddress, boolean convertToGrayscale,
int maxWidth, int maxHeight, boolean loadImageInfoOnly)
{
// Validate.
if ((filePath == null) || (filePath.length() <= 0) || (nativeImageMemoryAddress == 0 || runtime == null)) {
return false;
}
// When display.newImage is called with an image in the temp directory then an absolute path is passed in
// when the image is in the resource path its not an absolute path and should be relative to the asset path
// This assumes that if the files exists then its an absolute path
File f = new File(filePath);
if (!f.exists()) {
filePath = runtime.getPath() + filePath;
}
// Attempt to fetch the given path's URL scheme, if it has one.
android.net.Uri uri = android.net.Uri.parse(android.net.Uri.encode(filePath, ":/\\."));
String scheme = uri.getScheme();
if (scheme == null) {
scheme = "";
}
scheme = scheme.toLowerCase();
// Load the specified image file.
LoadBitmapResult result = null;
// boolean canRecycleBitmap = false;
if (scheme.equals("android.app.icon")) {
// Fetch the application icon's bitmap.
try {
android.content.Context context = CoronaEnvironment.getApplicationContext();
android.content.pm.ApplicationInfo applicationInfo = context.getApplicationInfo();
android.content.pm.PackageManager packageManager = context.getPackageManager();
String packageName = uri.getHost();
if ((packageName == null) || (packageName.length() <= 0)) {
packageName = applicationInfo.packageName;
}
android.graphics.drawable.Drawable drawable = packageManager.getApplicationIcon(packageName);
if (drawable instanceof android.graphics.drawable.BitmapDrawable) {
android.graphics.drawable.BitmapDrawable bitmapDrawable;
bitmapDrawable = (android.graphics.drawable.BitmapDrawable)drawable;
if (bitmapDrawable.getBitmap() != null) {
if (loadImageInfoOnly) {
result = new LoadBitmapResult(
bitmapDrawable.getBitmap().getWidth(),
bitmapDrawable.getBitmap().getHeight(),
1.0f, 0);
}
else {
result = new LoadBitmapResult(bitmapDrawable.getBitmap(), 1.0f, 0);
}
}
// canRecycleBitmap = false;
}
if (result == null) {
int w = Math.max(drawable.getIntrinsicWidth(), 1);
int h = Math.max(drawable.getIntrinsicHeight(), 1);
if (loadImageInfoOnly) {
result = new LoadBitmapResult(w, h, 1.0f, 0);
} else {
final Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bmp);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
result = new LoadBitmapResult(bmp, 1.0f, 0);
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
else {
// Fetch the bitmap from file.
result = runtime.getController().getBridge().loadBitmap(filePath, maxWidth, maxHeight, loadImageInfoOnly);
// canRecycleBitmap = true;
}