-
Notifications
You must be signed in to change notification settings - Fork 184
/
WikitudePlugin.java
1311 lines (1112 loc) · 56.3 KB
/
WikitudePlugin.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
package com.wikitude.phonegap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.engine.SystemWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.Settings;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.wikitude.architect.ArchitectJavaScriptInterfaceListener;
import com.wikitude.architect.ArchitectView;
import com.wikitude.architect.ArchitectView.ArchitectWorldLoadedListener;
import com.wikitude.architect.ArchitectView.CaptureScreenCallback;
import com.wikitude.architect.ArchitectStartupConfiguration;
import com.wikitude.common.camera.CameraSettings;
import com.wikitude.tools.device.features.MissingDeviceFeatures;
/**
* Basic PhoneGap Wikitude ARchitect Plugin
*
* You must add "<plugin name="wikitudeplugin" value="com.wikitude.phonegap.wikitudeplugin"/>"
* in config.xml to enable this plug-in in your project
*
* Also ensure to have wikitudesdk.jar in your libs folder
*
* Note:
* This plug-in is written under Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0.html
*/
public class WikitudePlugin extends CordovaPlugin implements ArchitectJavaScriptInterfaceListener, ArchitectWorldLoadedListener {
/** PhoneGap-root to Android-app-assets folder ; e.g. use "assets/foo.html" as source if you want to load foo.html from your android-project's assets-folder */
private static final String LOCAL_ASSETS_PATH_ROOT = "assets/";
/* static action strings */
/**
* opens architect-view (add to view stack)
*/
private static final String ACTION_OPEN = "open";
/**
* closes architect-view (remove view stack)
*/
private static final String ACTION_CLOSE = "close";
/**
* set visibility of architectView to visible (of present)
*/
private static final String ACTION_SHOW = "show";
/**
* set visibility of architectView to invisible (of present)
*/
private static final String ACTION_HIDE = "hide";
/**
* inject location information
*/
private static final String ACTION_SET_LOCATION = "setLocation";
/**
* inject location information
*/
private static final String ACTION_CAPTURE_SCREEN = "captureScreen";
/**
* callback for uri-invocations
*/
private static final String ACTION_ON_URLINVOKE = "onUrlInvoke";
/**
* callback for AR.platform.sendJSONObject
*/
private static final String ACTION_ON_JSON_RECEIVED = "onJSONObjectReceived";
/**
* life-cycle notification for resume
*/
private static final String ACTION_ON_RESUME = "onResume";
/**
* life-cycle notification for pause
*/
private static final String ACTION_ON_PAUSE = "onPause";
/**
* check if view is on view-stack (no matter if visible or not)
*/
private static final String ACTION_STATE_ISOPEN = "isOpen";
/**
* opens architect-view (add to view stack)
*/
private static final String ACTION_IS_DEVICE_SUPPORTED = "isDeviceSupported";
private static final String ACTION_REQUEST_ACCESS = "requestAccess";
private static final String ACTION_OPEN_APP_SETTINGS = "openAppSettings";
private static final String ACTION_SHOW_ALERT = "showAlert";
/**
* check if view is on view-stack (no matter if visible or not)
*/
private static final String ACTION_CALL_JAVASCRIPT = "callJavascript";
/**
* Used to set a custom callback that is called once the back button is clicked.
*/
private static final String ACTION_SET_BACK_BUTTON_CALLBACK = "setBackButtonCallback";
/**
* Used as key to see if a local path prefix is given in the strings.xml file or not.
* If the key is given, it's value will be appended before the `www` substring in the Architect world url.
*/
private static final String LOCAL_PATH_PREFIX_KEY = "WikitudeCordovaPluginLocalPathPrefix";
private static final String GET_SDK_BUILD_INFORMATION = "getSDKBuildInformation";
private static final String GET_SDK_VERSION = "getSDKVersion";
private static final int CAMERA_PERMISSION_REQUEST_CODE = 1;
private static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
private static final int REQUEST_ACCESS_REQUEST_CODE = 3;
/**
* the Wikitude ARchitectview
*/
private ArchitectViewPhoneGap architectView;
/**
* callback-Id of sendJSONObject method
*/
private CallbackContext urlInvokeCallback = null;
/**
* callback-Id of sendJSONObject method
*/
private CallbackContext jsonObjectReceivedCallback = null;
/**
* callback-id of "open"-action method
*/
private CallbackContext openCallback = null;
/**
* The custom back button callback id
*/
private CallbackContext onBackButtonCallback = null;
private CallbackContext requestAccessCallback = null;
/**
* last known location of the user, used internally for content-loading after user location was fetched
*/
protected Location lastKnownLocaton;
/**
* sample location strategy
*/
protected ILocationProvider locationProvider;
/**
* location listener receives location updates and must forward them to the architectView
*/
protected LocationListener locationListener;
private boolean useCustomLocation = false;
private boolean _locationPermissionRequired = false;
private boolean _cameraPermissionGranted = false;
private boolean _locationPermissionRequestRequired = false;
private JSONArray openArgs;
private String action;
private JSONArray _savedCaptureScreenArgs;
private CallbackContext _savedCaptureScreenCallbackContext;
@Override
public boolean execute( final String action, final JSONArray args, final CallbackContext callContext ) {
this.action = action;
/* hide architect-view -> destroy and remove from activity */
if ( WikitudePlugin.ACTION_CLOSE.equals( action ) ) {
if ( this.architectView != null ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
if (WikitudePlugin.this.locationProvider != null) {
WikitudePlugin.this.locationProvider.onPause();
}
removeArchitectView();
}
} );
callContext.success( action + ": architectView is present" );
}
else {
callContext.error( action + ": architectView is not present" );
}
return true;
}
/* return success only if view is opened (no matter if visible or not) */
if ( WikitudePlugin.ACTION_STATE_ISOPEN.equals( action ) ) {
if ( this.architectView != null ) {
callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
return true;
}
/* return success only if view is opened (no matter if visible or not) */
if ( WikitudePlugin.ACTION_IS_DEVICE_SUPPORTED.equals( action ) ) {
JSONArray jsonArray = null;
try {
jsonArray = args.getJSONArray( 0 );
} catch (JSONException e) {
}
int featuresBitMap = convertArFeatures(jsonArray);
MissingDeviceFeatures missingDeviceFeatues = ArchitectView.isDeviceSupported( this.cordova.getActivity(), featuresBitMap );
if (missingDeviceFeatues.areFeaturesMissing()) {
callContext.error(missingDeviceFeatues.getMissingFeatureMessage());
} else {
callContext.success("This device is supported" );
}
return true;
}
if (WikitudePlugin.ACTION_CAPTURE_SCREEN.equals(action) )
{
if (!this.cordova.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
_savedCaptureScreenArgs = args;
_savedCaptureScreenCallbackContext = callContext;
this.cordova.requestPermissions(this, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE});
}
else
{
captureScreen(args, callContext);
}
return true;
}
/* life-cycle's RESUME */
if ( WikitudePlugin.ACTION_ON_RESUME.equals( action ) ) {
if ( this.architectView != null ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
WikitudePlugin.this.architectView.onResume();
callContext.success( action + ": architectView is present" );
if (locationProvider != null) {
locationProvider.onResume();
}
}
} );
// callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
return true;
}
/* life-cycle's PAUSE */
if ( WikitudePlugin.ACTION_ON_PAUSE.equals( action ) ) {
if ( architectView != null ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
WikitudePlugin.this.architectView.onPause();
if (locationProvider != null) {
locationProvider.onPause();
}
}
} );
callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
return true;
}
/* set visibility to "visible", return error if view is null */
if ( WikitudePlugin.ACTION_SHOW.equals( action ) ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
if ( architectView != null ) {
architectView.setVisibility( View.VISIBLE );
callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
}
} );
return true;
}
/* set visibility to "invisible", return error if view is null */
if ( WikitudePlugin.ACTION_HIDE.equals( action ) ) {
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
if ( architectView != null ) {
architectView.setVisibility( View.INVISIBLE );
callContext.success( action + ": architectView is present" );
} else {
callContext.error( action + ": architectView is not present" );
}
}
} );
return true;
}
/* set a custom callback that is called when our plugin internally */
if ( WikitudePlugin.ACTION_SET_BACK_BUTTON_CALLBACK.equals( action ) ) {
this.onBackButtonCallback = callContext;
final PluginResult result = new PluginResult( PluginResult.Status.NO_RESULT, action + ": registered back button callback");
result.setKeepCallback(true);
callContext.sendPluginResult( result );
return true;
}
/* define call-back for url-invocations */
if ( WikitudePlugin.ACTION_ON_URLINVOKE.equals( action ) ) {
this.urlInvokeCallback = callContext;
final PluginResult result = new PluginResult( PluginResult.Status.NO_RESULT, action + ": registered callback" );
result.setKeepCallback( true );
callContext.sendPluginResult( result );
return true;
}
/* define call-back for AR.platform.sendJSONObject */
if ( WikitudePlugin.ACTION_ON_JSON_RECEIVED.equals( action ) ) {
this.jsonObjectReceivedCallback = callContext;
final PluginResult result = new PluginResult( PluginResult.Status.NO_RESULT, action + ": registered callback" );
result.setKeepCallback( true );
callContext.sendPluginResult( result );
return true;
}
/* location update */
if ( WikitudePlugin.ACTION_SET_LOCATION.equals( action ) ) {
try {
final double lat = args.getDouble( 0 );
final double lon = args.getDouble( 1 );
float alt = Float.MIN_VALUE;
try {
alt = (float)args.getDouble( 2 );
} catch ( Exception e ) {
// invalid altitude -> ignore it
}
final float altitude = alt;
Double acc = null;
try {
acc = args.getDouble( 3 );
} catch ( Exception e ) {
// invalid accuracy -> ignore it
}
final Double accuracy = acc;
if ( this.cordova != null && this.cordova.getActivity() != null ) {
this.useCustomLocation = true;
cordova.getActivity().runOnUiThread(
// this.cordova.getThreadPool().execute(
new Runnable() {
@Override
public void run() {
if ( WikitudePlugin.this.architectView != null ) {
if ( accuracy != null ) {
WikitudePlugin.this.architectView.setLocation( lat, lon, altitude, accuracy.floatValue() );
} else {
WikitudePlugin.this.architectView.setLocation( lat, lon, altitude );
}
callContext.success( action + ": updated location" );
} else {
/* return error if there is no architect-view active*/
callContext.error( action + ": architectView is not present" );
}
}
} );
}
} catch ( Exception e ) {
callContext.error( action + ": exception thrown, " + e != null ? e.getMessage() : "(exception is NULL)" );
return true;
}
return true;
}
if ( WikitudePlugin.ACTION_CALL_JAVASCRIPT.equals( action ) ) {
String logMsg = null;
try {
final String callJS = args.getString( 0 );
logMsg = callJS;
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
if ( architectView != null ) {
WikitudePlugin.this.architectView.callJavascript( callJS );
} else {
callContext.error( action + ": architectView is not present" );
}
}
} );
} catch ( JSONException je ) {
callContext.error( action + ": exception thrown, " + je != null ? je.getMessage() : "(exception is NULL)" );
return true;
}
callContext.success( action + ": called js, '" + logMsg + "'" );
return true;
}
if ( WikitudePlugin.ACTION_REQUEST_ACCESS.equals( action ) ) {
requestAccessCallback = callContext;
JSONArray jsonArray = null;
try {
jsonArray = args.getJSONArray( 0 );
} catch (JSONException e) {
}
int features = convertArFeatures(jsonArray);
boolean cameraPermissionRequestRequired = !cordova.hasPermission(Manifest.permission.CAMERA);
_locationPermissionRequestRequired = !cordova.hasPermission(Manifest.permission.ACCESS_FINE_LOCATION) && !cordova.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
_locationPermissionRequired = (ArchitectStartupConfiguration.Features.Geo & features) == ArchitectStartupConfiguration.Features.Geo;
if(cameraPermissionRequestRequired && (_locationPermissionRequestRequired && _locationPermissionRequired)) {
_cameraPermissionGranted = false;
this.cordova.requestPermissions(this, REQUEST_ACCESS_REQUEST_CODE, new String[] { Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
} else if (cameraPermissionRequestRequired) {
this.cordova.requestPermission(this, REQUEST_ACCESS_REQUEST_CODE, Manifest.permission.CAMERA);
} else if (_locationPermissionRequestRequired && _locationPermissionRequired) {
_cameraPermissionGranted = true;
this.cordova.requestPermissions(this, REQUEST_ACCESS_REQUEST_CODE, new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
} else {
callContext.success();
}
return true;
}
/* initial set-up, show ArchitectView full-screen in current screen/activity */
if ( WikitudePlugin.ACTION_OPEN.equals( action ) ) {
this.openCallback = callContext;
this.openArgs = args;
int features = 0;
try {
final JSONObject params = this.openArgs.getJSONObject( 0 );
final JSONArray jsonArray = params.getJSONArray("RequiredFeatures");
features = convertArFeatures(jsonArray);
} catch (JSONException e) {
features = ArchitectStartupConfiguration.Features.Geo | ArchitectStartupConfiguration.Features.ImageTracking | ArchitectStartupConfiguration.Features.InstantTracking;
}
boolean cameraPermissionRequestRequired = !cordova.hasPermission(Manifest.permission.CAMERA);
_locationPermissionRequestRequired = !cordova.hasPermission(Manifest.permission.ACCESS_FINE_LOCATION) && !cordova.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
_locationPermissionRequired = (ArchitectStartupConfiguration.Features.Geo & features) == ArchitectStartupConfiguration.Features.Geo;
if(cameraPermissionRequestRequired && (_locationPermissionRequestRequired && _locationPermissionRequired)) {
_cameraPermissionGranted = false;
this.cordova.requestPermissions(this, CAMERA_PERMISSION_REQUEST_CODE, new String[] { Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
} else if (cameraPermissionRequestRequired) {
this.cordova.requestPermission(this, CAMERA_PERMISSION_REQUEST_CODE, Manifest.permission.CAMERA);
} else if (_locationPermissionRequestRequired && _locationPermissionRequired) {
_cameraPermissionGranted = true;
this.cordova.requestPermissions(this, CAMERA_PERMISSION_REQUEST_CODE, new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
} else {
loadArchitectWorld();
}
return true;
}
if ( WikitudePlugin.GET_SDK_BUILD_INFORMATION.equals( action ) ) {
callContext.success(ArchitectView.getSDKBuildInformation().toJSONString());
return true;
}
if ( WikitudePlugin.GET_SDK_VERSION.equals( action ) ) {
callContext.success(ArchitectView.getSDKVersion());
return true;
}
if ( WikitudePlugin.ACTION_OPEN_APP_SETTINGS.equals( action ) ) {
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + cordova.getActivity().getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
cordova.getActivity().startActivity(i);
return true;
}
if ( WikitudePlugin.ACTION_SHOW_ALERT.equals( action ) ) {
try {
final String alertString = args.getString( 0 );
AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getActivity());
builder.setMessage(alertString)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
} catch (JSONException e) {
callContext.error( action + ": exception thrown, " + e != null ? e.getMessage() : "(exception is NULL)" );
return true;
}
return true;
}
/* fall-back return value */
callContext.sendPluginResult( new PluginResult( PluginResult.Status.ERROR, "no such action: " + action ) );
return false;
}
private void loadArchitectWorld() {
PluginResult result = null;
try {
final JSONObject params = this.openArgs.getJSONObject(0);
final String apiKey = params.getString("SDKKey");
String tempFilePath = params.getString("ARchitectWorldURL");
String stringResourceClassName = cordova.getActivity().getPackageName() + ".R$string";
Class<?> c = Class.forName(stringResourceClassName);
Field[] fields = c.getFields();
int stringPrefixIndex = -1;
for (Field field: fields) {
if (field.getName().equals(LOCAL_PATH_PREFIX_KEY)) {
stringPrefixIndex = field.getInt(null);
}
}
if ( stringPrefixIndex != -1 ) {
String stringPrefix = this.cordova.getActivity().getResources().getString(stringPrefixIndex);
if ( stringPrefix.length() > 0 ) {
int wwwIndex = tempFilePath.indexOf("www");
if ( wwwIndex > 0 ) {
tempFilePath= new StringBuffer(tempFilePath).insert(wwwIndex, stringPrefix+"/").toString();
}
}
}
final String filePath = tempFilePath;
int featuresTemp = 0;
try {
final JSONArray jsonArray = params.getJSONArray( "RequiredFeatures" );
featuresTemp = convertArFeatures(jsonArray);
} catch (JSONException e) {
featuresTemp = ArchitectStartupConfiguration.Features.Geo | ArchitectStartupConfiguration.Features.ImageTracking | ArchitectStartupConfiguration.Features.InstantTracking;
}
final int features = featuresTemp;
JSONObject startupConfigurationTmp;
try {
startupConfigurationTmp = params.getJSONObject( "StartupConfiguration" );
} catch (Exception e) {
startupConfigurationTmp = null;
}
final JSONObject startupConfiguration = startupConfigurationTmp;
this.cordova.getActivity().runOnUiThread( new Runnable() {
@Override
public void run() {
try {
WikitudePlugin.this.addArchitectView( apiKey, filePath, features, startupConfiguration );
} catch ( Exception e ) {
/* in case "addArchitectView" threw an exception -> notify callback method asynchronously */
openCallback.error( e != null ? e.getMessage() : "Exception is 'null'" );
}
}
} );
} catch ( Exception e ) {
result = new PluginResult( PluginResult.Status.ERROR, action + ": exception thown, " + e != null ? e.getMessage() : "(exception is NULL)" );
result.setKeepCallback( false );
this.openCallback.sendPluginResult(result);
}
/* adding architect-view is done in separate thread, ensure to setKeepCallback so one can call success-method properly later on */
result = new PluginResult( PluginResult.Status.NO_RESULT, action + ": no result required, just registered callback-method" );
result.setKeepCallback( true );
this.openCallback.sendPluginResult(result);
}
/**
* Triggered when AR.platform.sendJSONObject is called. (e.g. AR.platform.sendJSONObject({foo:"bar"}))
* @param jsonObject the sent jsonObject
*/
@Override
public void onJSONObjectReceived(JSONObject jsonObject) {
/* call callback-method if set*/
if ( this.jsonObjectReceivedCallback != null ) {
/* pass called url as String to callback-method */
final PluginResult res = new PluginResult( PluginResult.Status.OK, jsonObject );
res.setKeepCallback( true );
this.jsonObjectReceivedCallback.sendPluginResult( res );
}
}
@Override
public void worldWasLoaded(String url) {
if ( this.openCallback != null ) {
try {
if ( !url.startsWith("data:text") ) {
final PluginResult res = new PluginResult( PluginResult.Status.OK, url );
res.setKeepCallback( true );
this.openCallback.sendPluginResult( res );
}
} catch ( Exception e ) { }
}
}
@Override
public void worldLoadFailed(int errorCode, String description, String failingUrl) {
if ( this.openCallback != null ) {
try {
this.openCallback.error( "Failed to load Architect World. " + description + ". Url: " + failingUrl );
} catch ( Exception e ) { }
}
}
/**
* hides/removes ARchitect-View completely
* @return true if successful, false otherwise
*/
private boolean removeArchitectView() {
if ( this.architectView != null ) {
/* fake life-cycle calls, because activity is already up and running */
this.architectView.onPause();
this.architectView.onDestroy();
// clean-up used temp-directory
try {
WikitudePlugin.clearCacheFolder( new File( ArchitectView.getCacheDirectoryAbsoluteFilePath( this.cordova.getActivity() ) ), 0 );
} catch ( Exception e ) {
// had troubles in clearing files from cache
e.printStackTrace();
}
this.architectView.setVisibility( View.GONE );
((ViewManager)this.architectView.getParent()).removeView( this.architectView );
this.architectView = null;
WikitudePlugin.handleResumeInCordovaWebView(cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content));
WikitudePlugin.releaseFocusInCordovaWebView(cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content));
return true;
}
return false;
}
private static int clearCacheFolder( final File dir, final int numDays ) {
int deletedFiles = 0;
if ( dir != null && dir.isDirectory() ) {
try {
for ( File child : dir.listFiles() ) {
//first delete subdirectories recursively
if ( child.isDirectory() ) {
deletedFiles += clearCacheFolder( child, numDays );
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if ( child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS ) {
if ( child.delete() ) {
deletedFiles++;
}
}
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
return deletedFiles;
}
private int convertArFeatures(JSONArray jsonArray) {
int featuresBitMap = 0;
for (int i = 0; i < jsonArray.length(); i++) {
String feature = "";
try {
feature = (String) jsonArray.get(i);
} catch (JSONException e) {
}
if (feature.equalsIgnoreCase("image_tracking")) {
featuresBitMap = featuresBitMap | ArchitectStartupConfiguration.Features.ImageTracking;
} else if (feature.equalsIgnoreCase("geo")) {
featuresBitMap = featuresBitMap | ArchitectStartupConfiguration.Features.Geo;
} else if (feature.equalsIgnoreCase("instant_tracking")) {
featuresBitMap = featuresBitMap | ArchitectStartupConfiguration.Features.InstantTracking;
} else if (feature.equalsIgnoreCase("object_tracking")) {
featuresBitMap = featuresBitMap | ArchitectStartupConfiguration.Features.ObjectTracking;
}
}
if (featuresBitMap == 0) {
featuresBitMap = ArchitectStartupConfiguration.Features.ImageTracking | ArchitectStartupConfiguration.Features.Geo | ArchitectStartupConfiguration.Features.InstantTracking | ArchitectStartupConfiguration.Features.ObjectTracking;
}
return featuresBitMap;
}
/**
* Architect-Configuration required for proper set-up
* @param apiKey
* @param features
* @return
*/
protected ArchitectStartupConfiguration getStartupConfiguration( final String apiKey, int features, JSONObject startupConfiguration ) {
ArchitectStartupConfiguration config = new ArchitectStartupConfiguration();
config.setLicenseKey(apiKey);
config.setFeatures(features);
config.setOrigin( ArchitectStartupConfiguration.ORIGIN_PHONEGAP );
if (startupConfiguration != null) {
try {
if (startupConfiguration.getString("camera_position").compareToIgnoreCase("front") == 0) {
config.setCameraPosition(CameraSettings.CameraPosition.FRONT);
} else if (startupConfiguration.getString("camera_position").compareToIgnoreCase("back") == 0) {
config.setCameraPosition(CameraSettings.CameraPosition.BACK);
}
} catch (JSONException e) {
}
try {
if (startupConfiguration.getString("camera_focus_mode").compareToIgnoreCase("once") == 0) {
config.setCameraFocusMode(CameraSettings.CameraFocusMode.ONCE);
} else if (startupConfiguration.getString("camera_focus_mode").compareToIgnoreCase("continuous") == 0) {
config.setCameraFocusMode(CameraSettings.CameraFocusMode.CONTINUOUS);
} else if (startupConfiguration.getString("camera_focus_mode").compareToIgnoreCase("off") == 0) {
config.setCameraFocusMode(CameraSettings.CameraFocusMode.OFF);
}
} catch (JSONException e) {
}
try {
config.setCameraManualFocusDistance((float)startupConfiguration.getDouble("camera_manual_focus_distance"));
} catch (JSONException e) {
}
try {
String cameraResolution;
if (null != (cameraResolution = startupConfiguration.getString("camera_resolution"))) {
cameraResolution = cameraResolution.toLowerCase();
CameraSettings.CameraResolution cameraResolutionMode;
if ("sd_640x480".equals(cameraResolution) || "640x480".equals(cameraResolution) || "sd".equals(cameraResolution)) {
cameraResolutionMode = CameraSettings.CameraResolution.SD_640x480;
} else if ("hd_1280x720".equals(cameraResolution) || "1280x720".equals(cameraResolution) || "hd".equals(cameraResolution)) {
cameraResolutionMode = CameraSettings.CameraResolution.HD_1280x720;
} else if ("full_hd_1920x1080".equals(cameraResolution) || "1920x1080".equals(cameraResolution) || "full_hd".equals(cameraResolution)) {
cameraResolutionMode = CameraSettings.CameraResolution.FULL_HD_1920x1080;
} else if ("auto".equals(cameraResolution)) {
cameraResolutionMode = CameraSettings.CameraResolution.AUTO;
} else {
cameraResolutionMode = CameraSettings.CameraResolution.SD_640x480;
}
config.setCameraResolution(cameraResolutionMode);
}
} catch (JSONException e) {
}
try {
config.setCamera2Enabled(startupConfiguration.getBoolean("camera2_enabled"));
} catch (JSONException e) {
}
}
return config;
}
/**
* add architectView to current screen
* @param apiKey developers's api key to use (hides watermarking/intro-animation if it matches your package-name)
* @param filePath the url (starting with http:// for online use; starting with LOCAL_ASSETS_PATH_ROOT if oyu want to load assets within your app-assets folder)
* @param features Augmented Reality mode ()
* @throws IOException might be thrown from ARchitect-SDK
*/
private void addArchitectView( final String apiKey, String filePath, int features, JSONObject startupConfiguration) throws IOException {
if ( this.architectView == null ) {
WikitudePlugin.releaseFocusInCordovaWebView(cordova.getActivity().getWindow().getDecorView().findViewById(android.R.id.content));
this.architectView = new ArchitectViewPhoneGap( this.cordova.getActivity() , new ArchitectViewPhoneGap.OnKeyUpDownListener() {
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (architectView!=null && keyCode == KeyEvent.KEYCODE_BACK) {
if ( WikitudePlugin.this.onBackButtonCallback != null ) {
try {
/* pass called url as String to callback-method */
final PluginResult res = new PluginResult( PluginResult.Status.OK);
res.setKeepCallback(true);
WikitudePlugin.this.onBackButtonCallback.sendPluginResult( res );
} catch ( Exception e ) {
WikitudePlugin.this.onBackButtonCallback.error( "onBackButton result could not be send." );
}
}
return true;
} else {
return false;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return architectView!=null && keyCode == KeyEvent.KEYCODE_BACK;
}
});
this.architectView.setFocusableInTouchMode(true);
this.architectView.requestFocus();
this.locationListener = new LocationListener() {
@Override
public void onStatusChanged( String provider, int status, Bundle extras ) {
}
@Override
public void onProviderEnabled( String provider ) {
}
@Override
public void onProviderDisabled( String provider ) {
}
@Override
public void onLocationChanged( final Location location ) {
if (location!=null && !WikitudePlugin.this.useCustomLocation) {
WikitudePlugin.this.lastKnownLocaton = location;
if ( WikitudePlugin.this.architectView != null ) {
if ( location.hasAltitude() ) {
WikitudePlugin.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy() );
} else {
WikitudePlugin.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.getAccuracy() );
}
}
}
}
};
/* add content view and fake initial life-cycle */
(this.cordova.getActivity()).addContentView( this.architectView, new ViewGroup.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) );
(this.cordova.getActivity()).setVolumeControlStream( AudioManager.STREAM_MUSIC );
/* fake life-cycle calls, because activity is already up and running */
this.architectView.onCreate( getStartupConfiguration( apiKey, features, startupConfiguration ) );
this.architectView.onPostCreate();
/* add self as js interface listener to forward AR.platform to Cordova. */
this.architectView.addArchitectJavaScriptInterfaceListener( WikitudePlugin.this );
this.architectView.registerWorldLoadedListener( WikitudePlugin.this );
/* load asset from local directory if prefix is used */
if ( filePath.startsWith( WikitudePlugin.LOCAL_ASSETS_PATH_ROOT ) ) {
filePath = filePath.substring( WikitudePlugin.LOCAL_ASSETS_PATH_ROOT.length() );
}
this.architectView.load( filePath );
/* also a fake-life-cycle call (the last one before it is really shown in UI */
this.architectView.onResume();
if ((features & ArchitectStartupConfiguration.Features.Geo) == ArchitectStartupConfiguration.Features.Geo) {
this.locationProvider = new LocationProvider( this.cordova.getActivity(), this.locationListener );
this.locationProvider.onResume();
}
}
// hide keyboard when adding AR view on top of views
InputMethodManager inputManager = (InputMethodManager)
(this.cordova.getActivity()).getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow((this.cordova.getActivity()).getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private static void releaseFocusInCordovaWebView(View rootView) {
if (rootView instanceof SystemWebView) {
((SystemWebView) rootView).getCordovaWebView().getView().clearFocus();
} else if (rootView instanceof ViewGroup) {
final int childCount = ((ViewGroup)rootView).getChildCount();
for (int i=0; i< childCount; i++) {
WikitudePlugin.releaseFocusInCordovaWebView(((ViewGroup)rootView).getChildAt(i));
}
}
}
/**
* To avoid JavaScript in Cordova staying paused after CordovaWebView lost focus call "handleResume" of the CordovaView in current Activity
* @param rootView the root view to search recursively for a CordovaWebView
*/
private static void handleResumeInCordovaWebView(final View rootView) {
if (rootView instanceof SystemWebView) {
((SystemWebView) rootView).getCordovaWebView().handleResume(true);
}
else if (rootView instanceof ViewGroup) {
final int childCount = ((ViewGroup)rootView).getChildCount();
for (int i=0; i< childCount; i++) {
WikitudePlugin.handleResumeInCordovaWebView(((ViewGroup)rootView).getChildAt(i));
}
}
}
protected static class ArchitectViewPhoneGap extends ArchitectView {
public static interface OnKeyUpDownListener {
public boolean onKeyDown(int keyCode, KeyEvent event);
public boolean onKeyUp(int keyCode, KeyEvent event);
}
private final OnKeyUpDownListener onKeyUpDownListener;
@Deprecated
public ArchitectViewPhoneGap(Context context) {
super(context);
this.onKeyUpDownListener = null;
}
public ArchitectViewPhoneGap(Context context, OnKeyUpDownListener onKeyUpDownListener) {
super(context);
this.onKeyUpDownListener = onKeyUpDownListener;
}