-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
OFAndroid.java
1103 lines (936 loc) · 33.3 KB
/
OFAndroid.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 cc.openframeworks;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.opengl.GLSurfaceView;
import android.os.Environment;
import android.os.PowerManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class OFAndroid {
// List based on http://bit.ly/NpkL4Q
private final String[] mExternalStorageDirectories = new String[] {
"/mnt/sdcard-ext",
"/mnt/sdcard/external_sd",
"/sdcard/sd",
"/mnt/external_sd",
"/emmc",
"/mnt/sdcard/bpemmctest",
"/mnt/sdcard/_ExternalSD",
"/mnt/Removable/MicroSD",
"/Removable/MicroSD" };
private String getRealExternalStorageDirectory()
{
// Standard way to get the external storage directory
String externalPath = Environment.getExternalStorageDirectory().getAbsolutePath();
// This checks if any of the directories from mExternalStorageDirectories exist, if it does, it uses that one instead
for(int i = 0; i < mExternalStorageDirectories.length; i++)
{
//Log.i("OF", "Checking: " + mExternalStorageDirectories[i]);
File SDCardDir = new File(mExternalStorageDirectories[i]);
if(SDCardDir.exists() && SDCardDir.canWrite()) {
externalPath = mExternalStorageDirectories[i]; // Found writable location
break;
}
}
Log.i("OF", "Using storage location: " + externalPath);
return externalPath;
}
public OFAndroid(String packageName, Activity ofActivity){
ofActivity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
//Log.i("OF","external files dir: "+ ofActivity.getApplicationContext().getExternalFilesDir(null));
OFAndroid.packageName = packageName;
OFAndroidObject.setActivity(ofActivity);
try {
// try to find if R.raw class exists will throw
// an exception if not
Class<?> raw = Class.forName(packageName+".R$raw");
// if it exists copy all the raw resources
// to a folder in the sdcard
Field[] files = raw.getDeclaredFields();
boolean copydata = false;
SharedPreferences preferences = ofActivity.getPreferences(Context.MODE_PRIVATE);
long lastInstalled = preferences.getLong("installed", 0);
PackageManager pm = ofActivity.getPackageManager();
ApplicationInfo appInfo = pm.getApplicationInfo(packageName, 0);
String appFile = appInfo.sourceDir;
long installed = new File(appFile).lastModified();
if(installed>lastInstalled){
Editor editor = preferences.edit();
editor.putLong("installed", installed);
editor.commit();
copydata = true;
}
dataPath="";
try{
//dataPath = Environment.getExternalStorageDirectory().getAbsolutePath();
dataPath = getRealExternalStorageDirectory();
dataPath += "/"+packageName;
Log.i("OF","creating app directory: " + dataPath);
try{
File dir = new File(dataPath);
if(!dir.exists() && dir.mkdir()!=true)
throw new Exception();
}catch(Exception e){
Log.e("OF","error creating dir " + dataPath,e);
}
if(copydata){
for(int i=0; i<files.length; i++){
int fileId;
String fileName="";
InputStream from=null;
File toFile=null;
FileOutputStream to=null;
try {
fileId = files[i].getInt(null);
String resName = ofActivity.getResources().getText(fileId).toString();
fileName = resName.substring(resName.lastIndexOf("/"));
from = ofActivity.getResources().openRawResource(fileId);
//toFile = new File(Environment.getExternalStorageDirectory() + "/" + appName + "/" +fileName);
Log.i("OF","copying file " + fileName + " to " + dataPath);
toFile = new File(dataPath + "/" + fileName);
to = new FileOutputStream(toFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead); // write
} catch (Exception e) {
Log.e("OF","error copying file",e);
} finally {
if (from != null)
try {
from.close();
} catch (IOException e) { }
if (to != null)
try {
to.close();
} catch (IOException e) { }
}
}
}
}catch(Exception e){
Log.e("OF","couldn't move app resources to data directory " + dataPath);
e.printStackTrace();
}
String app_name="";
try {
int app_name_id = Class.forName(packageName+".R$string").getField("app_name").getInt(null);
app_name = ofActivity.getResources().getText(app_name_id).toString();
Log.i("OF","app name: " + app_name);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("OF","error retrieving app name",e);
}
OFAndroid.setAppDataDir(dataPath,app_name);
} catch (ClassNotFoundException e1) {
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OFAndroid.ofActivity = ofActivity;
gestureListener = new OFGestureListener(ofActivity);
try {
Log.v("OF","trying to find class: "+packageName+".R$layout");
Class<?> layout = Class.forName(packageName+".R$layout");
View view = ofActivity.getLayoutInflater().inflate(layout.getField("main_layout").getInt(null),null);
ofActivity.setContentView(view);
Class<?> id = Class.forName(packageName+".R$id");
mGLView = (OFGLSurfaceView)ofActivity.findViewById(id.getField("of_gl_surface").getInt(null));
enableTouchEvents();
} catch (Exception e) {
Log.e("OF", "couldn't create view from layout falling back to GL only",e);
mGLView = new OFGLSurfaceView(ofActivity);
ofActivity.setContentView(mGLView);
enableTouchEvents();
}
//android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
}
public void start(){
Log.i("OF","onStart");
enableTouchEvents();
}
public void restart(){
Log.i("OF","onRestart");
enableTouchEvents();
onRestart();
/*if(OFAndroidSoundStream.isInitialized() && OFAndroidSoundStream.wasStarted())
OFAndroidSoundStream.getInstance().start();*/
}
public void pause(){
Log.i("OF","onPause");
disableTouchEvents();
mGLView.onPause();
onPause();
for(OFAndroidObject object : OFAndroidObject.ofObjects){
object.onPause();
}
unlockScreenSleep();
}
public void resume(){
Log.i("OF","onResume");
enableTouchEvents();
mGLView.onResume();
for(OFAndroidObject object : OFAndroidObject.ofObjects){
object.onResume();
}
onResume();
if(OFAndroid::orientation!=-1) OFAndroid::setOrientation(OFAndroid::orientation)
if(wl!=null) lockScreenSleep();
}
public void stop(){
Log.i("OF","onStop");
disableTouchEvents();
onStop();
for(OFAndroidObject object : OFAndroidObject.ofObjects){
object.onStop();
}
unlockScreenSleep();
/*if(OFAndroidSoundStream.isInitialized())
OFAndroidSoundStream.getInstance().stop();*/
}
public void destroy(){
Log.i("OF","onDestroy");
onDestroy();
}
static public boolean menuItemSelected(int id){
try {
Class<?> menu_ids = Class.forName(packageName+".R$id");
Field[] fields = menu_ids.getFields();
for(Field field: fields){
Log.i("OF", "checking " + field.getName());
if(id == field.getInt(null)){
return onMenuItemSelected(field.getName());
}
}
} catch (Exception e) {
Log.w("OF","Trying to get menu items ", e);
}
return false;
}
static public boolean menuItemChecked(int id, boolean checked){
try {
Class<?> menu_ids = Class.forName(packageName+".R$id");
Field[] fields = menu_ids.getFields();
for(Field field: fields){
if(id == field.getInt(null)){
return onMenuItemChecked(field.getName(),checked);
}
}
} catch (Exception e) {
Log.w("OF","Trying to get menu items ", e);
}
return false;
}
static public void setMenuItemChecked(String idStr, boolean checked){
final String id = idStr;
ofActivity.runOnUiThread(new Runnable(){
public void run() {
try {
Class<?> menu_ids = Class.forName(packageName+".R$id");
Field field = menu_ids.getField(id);
//ofActivity.getMenuInflater().
} catch (Exception e) {
Log.w("OF","Trying to get menu items ", e);
}
}
});
}
static public void setViewItemChecked(String idStr, boolean checked){
final String id = idStr;
final boolean fchecked = checked;
ofActivity.runOnUiThread(new Runnable(){
public void run() {
try {
Class<?> menu_ids = Class.forName(packageName+".R$id");
Field field = menu_ids.getField(id);
CompoundButton checkbox = (CompoundButton) ofActivity.findViewById(field.getInt(null));
checkbox.setChecked(fchecked);
} catch (Exception e) {
Log.w("OF","Trying to get menu items ", e);
}
}
});
}
static public String getStringRes(String idStr){
Class<?> string_ids;
try {
string_ids = Class.forName(packageName+".R$string");
Field field = string_ids.getField(idStr);
int id = field.getInt(null);
return (String) ofActivity.getResources().getText(id);
} catch (Exception e) {
Log.e("OF","Couldn't get string resource",e);
}
return "";
}
static public boolean isOnline(){
try{
ConnectivityManager conMgr = (ConnectivityManager)ofActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
return conMgr!=null && ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
|| conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ) ;
}catch(Exception e){
return false;
}
}
static public boolean isWifiOnline(){
try{
ConnectivityManager conMgr = (ConnectivityManager)ofActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
return conMgr!=null && ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ) ;
}catch(Exception e){
return false;
}
}
static public boolean isMobileOnline(){
try{
ConnectivityManager conMgr = (ConnectivityManager)ofActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
return conMgr!=null && ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ) ;
}catch(Exception e){
return false;
}
}
static public void monitorNetworkState(){
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) return;
boolean noConnectivity =
intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
networkConnected(false);
} else {
networkConnected(true);
}
Log.w("Network Listener", "Network Type Changed");
}
};
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
ofActivity.registerReceiver(networkStateReceiver, filter);
networkConnected(isOnline());
}
static Map<Integer,ProgressDialog> progressDialogs = new HashMap<Integer, ProgressDialog>();
static int lastProgressID=0;
static public int progressBox(String msg){
final String finmsg = msg;
final int id = lastProgressID++;
ofActivity.runOnUiThread(new Runnable(){
public void run() {
ProgressDialog d = new ProgressDialog(ofActivity);
d.setMessage(finmsg);
d.setCancelable(false);
d.show();
progressDialogs.put(id,d);
}
});
return id;
}
static public void dismissProgressBox(int id){
final int dId = id;
final ProgressDialog d = progressDialogs.get(id);
if(d!=null){
ofActivity.runOnUiThread(new Runnable(){
public void run() {
d.dismiss();
progressDialogs.remove(dId);
}
});
}
}
static public boolean checkSDCardMounted(){
boolean canSaveExternal = false;
String storageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(storageState))
canSaveExternal = true;
else
canSaveExternal = false;
return canSaveExternal;
}
public static void onActivityResult(int requestCode, int resultCode,Intent intent){
for(OFAndroidObject object : OFAndroidObject.ofObjects){
object.onActivityResult(requestCode,resultCode,intent);
}
}
// native methods to call OF c++ callbacks
public static native void setAppDataDir(String data_dir,String app_name);
public static native void init();
public static native void onRestart();
public static native void onPause();
public static native void onResume();
public static native void onStop();
public static native void onDestroy();
public static native void onSurfaceCreated();
public static native void onSurfaceDestroyed();
public static native void setup(int w, int h);
public static native void resize(int w, int h);
public static native void render();
public static native void exit();
public static native void onTouchDown(int id,float x,float y,float pressure);
public static native void onTouchDoubleTap(int id,float x,float y,float pressure);
public static native void onTouchUp(int id,float x,float y,float pressure);
public static native void onTouchMoved(int id,float x,float y,float pressure);
public static native void onTouchCancelled(int id,float x,float y);
public static native void onSwipe(int id, int swipeDir);
public static native void onKeyDown(int keyCode);
public static native void onKeyUp(int keyCode);
public static native boolean onBackPressed();
public static native boolean onMenuItemSelected(String menu_id);
public static native boolean onMenuItemChecked(String menu_id, boolean checked);
public static native void okPressed();
public static native void cancelPressed();
public static native void networkConnected(boolean conected);
// static methods to be called from OF c++ code
public static void setFullscreen(boolean fs){
//ofActivity.requestWindowFeature(Window.FEATURE_NO_TITLE);
//ofActivity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
/* if(fs)
{
ofActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
ofActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
else
{
ofActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
ofActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}*/
//m_contentView.requestLayout();
//ofActivity.getWindow().setAttributes(attrs);
}
private static int orientation=-1;
public static void setScreenOrientation(int orientation){
OFAndroid::orientation = orientation;
switch(orientation){
case 0:
ofActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case 90:
ofActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case 270:
ofActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case 180:
ofActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case -1:
ofActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
break;
}
}
public static void pauseApp(){
ofActivity.moveTaskToBack(true);
}
public static void setupAccelerometer(){
if(accelerometer==null)
accelerometer = new OFAndroidAccelerometer((SensorManager)ofActivity.getSystemService(Context.SENSOR_SERVICE));
}
public static void setupGPS(){
if(gps==null)
gps = new OFAndroidGPS(ofActivity);
gps.startGPS();
}
public static void stopGPS(){
if(gps==null)
return;
gps.stopGPS();
}
public static void alertBox(String msg){
final String alertMsg = msg;
/*try{
Looper.prepare();
}catch(Exception e){
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message mesg) {
throw new RuntimeException();
}
};*/
ofActivity.runOnUiThread(new Runnable(){
public void run() {
new AlertDialog.Builder(ofActivity)
.setMessage(alertMsg)
.setTitle("")
.setCancelable(false)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
OFAndroid.okPressed();
//handler.sendMessage(handler.obtainMessage());
}
})
.show();
}
});
// loop till a runtime exception is triggered.
/*try { Looper.loop(); }
catch(RuntimeException e2) {}*/
//alert.dismiss();
}
static public void positiveNegativeBox(String msg,final int positiveButton, final int negativeButton){
final String alertMsg = msg;
/*try{
Looper.prepare();
}catch(Exception e){
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message mesg) {
throw new RuntimeException();
}
};*/
ofActivity.runOnUiThread(new Runnable(){
public void run() {
new AlertDialog.Builder(ofActivity)
.setMessage(alertMsg)
.setTitle("OF")
.setCancelable(false)
.setNeutralButton(positiveButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
OFAndroid.okPressed();
//handler.sendMessage(handler.obtainMessage());
}
})
.setNegativeButton(negativeButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
OFAndroid.cancelPressed();
//handler.sendMessage(handler.obtainMessage());
}
})
.show();
}
});
// loop till a runtime exception is triggered.
/*try { Looper.loop(); }
catch(RuntimeException e2) {}*/
}
public static void okCancelBox(String msg){
positiveNegativeBox(msg,android.R.string.ok,android.R.string.cancel);
}
public static void yesNoBox(String msg){
positiveNegativeBox(msg,android.R.string.yes,android.R.string.no);
}
private static String textBoxResult="";
public static void alertTextBox(String question, String text){
final String alertQuestion = question;
final String alertMsg = text;
/*try{
Looper.prepare();
}catch(Exception e){
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message mesg) {
throw new RuntimeException();
}
};*/
textBoxResult=text;
ofActivity.runOnUiThread(new Runnable(){
public void run() {
final EditText input = new EditText(ofActivity);
new AlertDialog.Builder(ofActivity)
.setMessage(alertMsg)
.setTitle(alertQuestion)
.setCancelable(false)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
textBoxResult = input.getText().toString();
OFAndroid.okPressed();
//handler.sendMessage(handler.obtainMessage());
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
OFAndroid.cancelPressed();
//handler.sendMessage(handler.obtainMessage());
}
})
.setView(input)
.show();
}
});
// loop till a runtime exception is triggered.
/*try { Looper.loop(); }
catch(RuntimeException e2) {}*/
//alert.dismiss();
}
public static String getLastTextBoxResult(){
return textBoxResult;
}
private static boolean alertListResult;
public static boolean alertListBox(String title, String[] list){
final String[] alertList = list;
final String alertTitle = title;
/*Looper.prepare();
final Handler handler = new Handler() {
@Override
public void handleMessage(Message mesg) {
throw new RuntimeException();
}
};*/
alertListResult=false;
ofActivity.runOnUiThread(new Runnable(){
public void run() {
final ListView listView = new ListView(ofActivity);
final ListAdapter adapter = new ArrayAdapter<String>(ofActivity, android.R.layout.simple_list_item_1, alertList);
listView.setAdapter(adapter);
new AlertDialog.Builder(ofActivity)
.setTitle(alertTitle)
.setCancelable(false)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
alertListResult = true;
//OFAndroid.okPressed();
//handler.sendMessage(handler.obtainMessage());
}
})
/*.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
alertListResult = false;
OFAndroid.cancelPressed();
//handler.sendMessage(handler.obtainMessage());
}
})*/
.setView(listView)
.show();
}
});
// loop till a runtime exception is triggered.
//try { Looper.loop(); }
//catch(RuntimeException e2) {}
return alertListResult;
}
public static void toast(String msg){
if(msg=="") return;
final String alertMsg = msg;
ofActivity.runOnUiThread(new Runnable(){
public void run() {
Toast toast = Toast.makeText(ofActivity, alertMsg, Toast.LENGTH_SHORT);
toast.show();
}
});
}
public static Context getContext(){
return ofActivity;
}
public static String toDataPath(String path){
return dataPath + "/" + path;
}
public static void lockScreenSleep(){
if(wl==null){
PowerManager pm = (PowerManager) ofActivity.getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "DoNotDimScreen");
}
wl.acquire();
}
public static void unlockScreenSleep(){
if(wl==null) return;
wl.release();
}
public static String getRandomUUID(){
return UUID.randomUUID().toString();
}
private static OFGLSurfaceView mGLView;
private static OFAndroidAccelerometer accelerometer;
private static OFAndroidGPS gps;
private static Activity ofActivity;
private OFGestureListener gestureListener;
private static String packageName;
private static String dataPath;
private static PowerManager.WakeLock wl;
public static native boolean hasNeon();
static {
try{
System.loadLibrary("neondetection");
if(hasNeon()){
Log.i("OF","loading neon optimized library");
System.loadLibrary("OFAndroidApp_neon");
}else{
Log.i("OF","loading not-neon optimized library");
System.loadLibrary("OFAndroidApp");
}
}catch(Throwable e){
Log.i("OF","failed neon detection, loading not-neon library",e);
System.loadLibrary("OFAndroidApp");
}
}
public static SurfaceView getGLContentView() {
return mGLView;
}
public void disableTouchEvents(){
mGLView.setOnClickListener(null);
mGLView.setOnTouchListener(null);
}
public void enableTouchEvents(){
mGLView.setOnClickListener(gestureListener);
mGLView.setOnTouchListener(gestureListener.touchListener);
}
/**
*
* @param keyCode
* @param event
* @return true to say we handled this, false to tell Android to handle it
*/
public static boolean keyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)) {
if( onBackPressed() ) {
return true;
} else {
// let the Android system handle the back button
return false;
}
}
if (KeyEvent.isModifierKey(keyCode)) {
/* Android sends a shift keycode (for instance),
then the key that goes with the shift. We don't need the first
keycode, that info is in event.getMetaState() anyway */
return false;
}
else
{
int unicodeChar = event.getUnicodeChar();
onKeyDown(unicodeChar);
// return false to let Android handle certain keys
// like the back and menu keys
return false;
}
}
/**
*
* @param keyCode
* @param event
* @return true to say we handled this, false to tell Android to handle it
*/
public static boolean keyUp(int keyCode, KeyEvent event) {
if (KeyEvent.isModifierKey(keyCode)) {
/* Android sends a shift keycode (for instance),
then the key that goes with the shift. We don't need the first
keycode, that info is in event.getMetaState() anyway */
return false;
}
else
{
int unicodeChar = event.getUnicodeChar();
onKeyUp(unicodeChar);
// return false to let Android handle certain keys
// like the back and menu keys
return false;
}
}
}
class OFGestureListener extends SimpleOnGestureListener implements OnClickListener {
OFGestureListener(Activity activity){
gestureDetector = new GestureDetector(activity,this);
touchListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction();
final int pointerIndex = (action & MotionEvent.ACTION_POINTER_ID_MASK)
>> MotionEvent.ACTION_POINTER_ID_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
switch((action & MotionEvent.ACTION_MASK)){
case MotionEvent.ACTION_MOVE:
{
for(int i=0; i<event.getHistorySize(); i++)
{
try{
for(int j=0; j<event.getPointerCount(); j++)
{
int ptr = event.getPointerId(j);
OFAndroid.onTouchMoved(ptr, event.getHistoricalX(ptr, i), event.getHistoricalY(ptr, i), event.getHistoricalPressure(ptr, i));
}
}catch(IllegalArgumentException e){}
}
for(int i=0; i<event.getPointerCount(); i++){
OFAndroid.onTouchMoved(event.getPointerId(i), event.getX(i), event.getY(i), event.getPressure(i));
}
}
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
OFAndroid.onTouchUp(pointerId, event.getX(pointerIndex), event.getY(pointerIndex), event.getPressure(pointerIndex));
break;
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_DOWN:
OFAndroid.onTouchDown(pointerId, event.getX(pointerIndex), event.getY(pointerIndex), event.getPressure(pointerIndex));
break;
case MotionEvent.ACTION_CANCEL:
OFAndroid.onTouchCancelled(pointerId,event.getX(),event.getY());
break;
}
return gestureDetector.onTouchEvent(event);
}
};
}
public void onClick(View view) {
}
@Override
public boolean onDoubleTap(MotionEvent event) {
final int action = event.getAction();
final int pointerIndex = (action & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
OFAndroid.onTouchDoubleTap(pointerId, event.getX(pointerIndex), event.getY(pointerIndex), event.getPressure(pointerIndex));
return true;
//return super.onDoubleTap(e);
}
@Override
public boolean onDoubleTapEvent(MotionEvent event) {
return super.onDoubleTapEvent(event);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
return super.onSingleTapConfirmed(event);
}
@Override
public boolean onDown(MotionEvent event) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
/*boolean res = super.onFling(e1, e2, velocityX, velocityY);
Log.i("OF","onFLing" + res);
return res;*/
final float xDistance = Math.abs(e1.getX() - e2.getX());
final float yDistance = Math.abs(e1.getY() - e2.getY());
if(xDistance > OFGestureListener.swipe_Max_Distance || yDistance > OFGestureListener.swipe_Max_Distance)
return false;
velocityX = Math.abs(velocityX);
velocityY = Math.abs(velocityY);
boolean result = false;
if(velocityX > OFGestureListener.swipe_Min_Velocity && xDistance > OFGestureListener.swipe_Min_Distance){
if(e1.getX() > e2.getX()) // right to left
OFAndroid.onSwipe(e1.getPointerId(0),SWIPE_LEFT);
else
OFAndroid.onSwipe(e1.getPointerId(0),SWIPE_RIGHT);
result = true;
}else if(velocityY > OFGestureListener.swipe_Min_Velocity && yDistance > OFGestureListener.swipe_Min_Distance){
if(e1.getY() > e2.getY()) // bottom to up
OFAndroid.onSwipe(e1.getPointerId(0),SWIPE_UP);
else
OFAndroid.onSwipe(e1.getPointerId(0),SWIPE_DOWN);