This repository was archived by the owner on May 11, 2025. It is now read-only.
forked from processing/processing-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPApplet.java
More file actions
10033 lines (8078 loc) · 276 KB
/
PApplet.java
File metadata and controls
10033 lines (8078 loc) · 276 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-17 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 2.1 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.*;
import java.util.zip.*;
import android.view.inputmethod.InputMethodManager;
import android.app.Activity;
import android.content.*;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.*;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.LayoutRes;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import processing.a2d.PGraphicsAndroid2D;
import processing.android.ActivityAPI;
import processing.android.AppComponent;
import processing.android.CompatUtils;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
public class PApplet extends Object implements ActivityAPI, PConstants {
static final public boolean DEBUG = false;
// static final public boolean DEBUG = true;
// Convenience public constant holding the SDK version, akin to platform in Java mode
static final public int SDK = Build.VERSION.SDK_INT;
//static final public int SDK = Build.VERSION_CODES.ICE_CREAM_SANDWICH; // Forcing older SDK for testing
/**
* The surface this sketch draws to.
*/
protected PSurface surface;
/**
* The view group containing the surface view of the PApplet.
*/
public @LayoutRes int parentLayout = -1;
/** The PGraphics renderer associated with this PApplet */
public PGraphics g;
/**
* The screen size when the sketch was started. This is initialized inside
* onCreate().
* <p>
* Note that this won't update if you change the resolution
* of your screen once the the applet is running.
* <p>
* This variable is not static because in the desktop version of Processing,
* not all instances of PApplet will necessarily be started on a screen of
* the same size.
*/
public int displayWidth, displayHeight;
/**
* Command line options passed in from main().
* <P>
* This does not include the arguments passed in to PApplet itself.
*/
// public String[] args;
/**
* Path to where sketch can read/write files (read-only).
* Android: This is the writable area for the Activity, which is correct
* for purposes of how sketchPath is used in practice from a sketch,
* even though it's technically different than the desktop version.
*/
public String sketchPath; //folder;
/** When debugging headaches */
// static final boolean THREAD_DEBUG = false;
/** Default width and height for applet when not specified */
static public final int DEFAULT_WIDTH = -1;
static public final int DEFAULT_HEIGHT = -1;
/**
* Set true when the surface dimensions have changed, so that the PGraphics
* object can be resized on the next trip through handleDraw().
*/
protected boolean surfaceChanged;
/**
* Pixel buffer from this applet's PGraphics.
* <P>
* When used with OpenGL or Java2D, this value will
* be null until loadPixels() has been called.
*/
public int[] pixels;
/** width of this applet's associated PGraphics */
public int width = DEFAULT_WIDTH;
/** height of this applet's associated PGraphics */
public int height = DEFAULT_HEIGHT;
/** The logical density of the display from getDisplayMetrics().density
* According to Android's documentation:
* This is a scaling factor for the Density Independent Pixel unit,
* where one DIP is one pixel on an approximately 160 dpi screen
* (for example a 240x320, 1.5"x2" screen), providing the baseline of the
* system's display. Thus on a 160dpi screen this density value will be 1;
* on a 120 dpi screen it would be .75; etc.
*/
public float displayDensity = 1;
// For future use
public int pixelDensity = 1;
public int pixelWidth;
public int pixelHeight;
///////////////////////////////////////////////////////////////
// Mouse events
/** absolute x position of input on screen */
public int mouseX;
/** absolute x position of input on screen */
public int mouseY;
/**
* Previous x/y position of the mouse. This will be a different value
* when inside a mouse handler (like the mouseMoved() method) versus
* when inside draw(). Inside draw(), pmouseX is updated once each
* frame, but inside mousePressed() and friends, it's updated each time
* an event comes through. Be sure to use only one or the other type of
* means for tracking pmouseX and pmouseY within your sketch, otherwise
* you're gonna run into trouble.
*/
public int pmouseX, pmouseY;
public boolean mousePressed;
public boolean touchIsStarted;
public TouchEvent.Pointer[] touches = new TouchEvent.Pointer[0];
/**
* previous mouseX/Y for the draw loop, separated out because this is
* separate from the pmouseX/Y when inside the mouse event handlers.
*/
protected int dmouseX, dmouseY;
/**
* pmotionX/Y for the event handlers (motionPressed(), motionDragged() etc)
* these are different because motion events are queued to the end of
* draw, so the previous position has to be updated on each event,
* as opposed to the pmotionX/Y that's used inside draw, which is expected
* to be updated once per trip through draw().
*/
protected int emouseX, emouseY;
/**
* ID of the pointer tracked for mouse events.
*/
protected int mousePointerId;
/**
* ID of the most recently touch pointer gone up or down.
*/
protected int touchPointerId;
///////////////////////////////////////////////////////////////
// Key events
/**
* Last key pressed.
* <P>
* If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT,
* this will be set to CODED (0xffff or 65535).
*/
public char key;
/**
* When "key" is set to CODED, this will contain a Java key code.
* <P>
* For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT.
* Also available are ALT, CONTROL and SHIFT. A full set of constants
* can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables.
*/
public int keyCode;
/**
* true if the mouse is currently pressed.
*/
public boolean keyPressed;
/**
* the last KeyEvent object passed into a mouse function.
*/
// public KeyEvent keyEvent;
/**
* Gets set to true/false as the applet gains/loses focus.
*/
public boolean focused = false;
/**
* Keeps track of ENABLE_KEY_REPEAT hint
*/
protected boolean keyRepeatEnabled = false;
/**
* Set to open when openKeyboard() is called, and used to close the keyboard when the sketch is
* paused, otherwise it remains visible.
*/
boolean keyboardIsOpen = false;
/**
* Flag to determine if the user handled the back press.
*/
public boolean handledBackPressed = true;
///////////////////////////////////////////////////////////////
// Permission handling
/**
* Callback methods to handle permission requests
*/
protected HashMap<String, String> permissionMethods = new HashMap<String, String>();
/**
* Permissions requested during one frame
*/
protected ArrayList<String> reqPermissions = new ArrayList<String>();
///////////////////////////////////////////////////////////////
// Rendering/timing
/**
* Time in milliseconds when the applet was started.
* <P>
* Used by the millis() function.
*/
long millisOffset = System.currentTimeMillis();
protected boolean insideDraw;
/** Last time in nanoseconds that frameRate was checked */
protected long frameRateLastNanos = 0;
/**
* The current value of frames per second.
* <P>
* The initial value will be 10 fps, and will be updated with each
* frame thereafter. The value is not instantaneous (since that
* wouldn't be very useful since it would jump around so much),
* but is instead averaged (integrated) over several frames.
* As such, this value won't be valid until after 5-10 frames.
*/
public float frameRate = 10;
protected boolean looping;
/** flag set to true when a redraw is asked for by the user */
protected boolean redraw;
/**
* How many frames have been displayed since the applet started.
* <P>
* This value is read-only <EM>do not</EM> attempt to set it,
* otherwise bad things will happen.
* <P>
* Inside setup(), frameCount is 0.
* For the first iteration of draw(), frameCount will equal 1.
*/
public int frameCount;
/**
* true if this applet has had it.
*/
public boolean finished;
/**
* true if exit() has been called so that things shut down
* once the main thread kicks off.
*/
protected boolean exitCalled;
boolean insideSettings;
String renderer = JAVA2D;
int smooth = 1; // default smoothing (whatever that means for the renderer)
boolean fullScreen = false;
int display = -1; // use default
// Background default needs to be different from the default value in
// PGraphics.backgroundColor, otherwise size(100, 100) bg spills over.
// https://github.com/processing/processing/issues/2297
int windowColor = 0xffDDDDDD;
///////////////////////////////////////////////////////////////
// Error messages
static final String ERROR_MIN_MAX =
"Cannot use min() or max() on an empty array.";
///////////////////////////////////////////////////////////////
// Command line options
/**
* Position of the upper-lefthand corner of the editor window
* that launched this applet.
*/
static public final String ARGS_EDITOR_LOCATION = "--editor-location";
/**
* Location for where to position the applet window on screen.
* <P>
* This is used by the editor to when saving the previous applet
* location, or could be used by other classes to launch at a
* specific position on-screen.
*/
static public final String ARGS_EXTERNAL = "--external";
static public final String ARGS_LOCATION = "--location";
static public final String ARGS_DISPLAY = "--display";
static public final String ARGS_BGCOLOR = "--bgcolor";
static public final String ARGS_PRESENT = "--present";
static public final String ARGS_EXCLUSIVE = "--exclusive";
static public final String ARGS_STOP_COLOR = "--stop-color";
static public final String ARGS_HIDE_STOP = "--hide-stop";
/**
* Allows the user or PdeEditor to set a specific sketch folder path.
* <P>
* Used by PdeEditor to pass in the location where saveFrame()
* and all that stuff should write things.
*/
static public final String ARGS_SKETCH_FOLDER = "--sketch-path";
/**
* When run externally to a PdeEditor,
* this is sent by the applet when it quits.
*/
//static public final String EXTERNAL_QUIT = "__QUIT__";
static public final String EXTERNAL_STOP = "__STOP__";
/**
* When run externally to a PDE Editor, this is sent by the applet
* whenever the window is moved.
* <P>
* This is used so that the editor can re-open the sketch window
* in the same position as the user last left it.
*/
static public final String EXTERNAL_MOVE = "__MOVE__";
/** true if this sketch is being run by the PDE */
boolean external = false;
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
/**
* Required empty constructor.
*/
public PApplet() {
}
public PSurface getSurface() {
return surface;
}
public Context getContext() {
return surface.getContext();
}
public Activity getActivity() {
return surface.getActivity();
}
public void initSurface(AppComponent component, SurfaceHolder holder) {
parentLayout = -1;
initSurface(null, null, null, component, holder);
}
public void initSurface(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState,
AppComponent component, SurfaceHolder holder) {
if (DEBUG) println("initSurface() happening here: " + Thread.currentThread().getName());
component.initDimensions();
displayWidth = component.getDisplayWidth();
displayHeight = component.getDisplayHeight();
displayDensity = component.getDisplayDensity();
handleSettings();
boolean parentSize = false;
if (parentLayout == -1) {
if (fullScreen || width == -1 || height == -1) {
// Either sketch explicitly set to full-screen mode, or not
// size/fullScreen provided, so sketch uses the entire display
width = displayWidth;
height = displayHeight;
}
} else {
if (fullScreen || width == -1 || height == -1) {
// Dummy weight and height to initialize the PGraphics, will be resized
// when the view associated to the parent layout is created
width = 100;
height = 100;
parentSize = true;
}
}
pixelWidth = width * pixelDensity;
pixelHeight = height * pixelDensity;
String rendererName = sketchRenderer();
if (DEBUG) println("Renderer " + rendererName);
g = makeGraphics(width, height, rendererName, true);
if (DEBUG) println("Created renderer");
surface = g.createSurface(component, holder, false);
if (DEBUG) println("Created surface");
if (parentLayout == -1) {
setFullScreenVisibility();
surface.initView(width, height);
} else {
surface.initView(width, height, parentSize,
inflater, container, savedInstanceState);
}
finished = false; // just for clarity
// this will be cleared by draw() if it is not overridden
looping = true;
redraw = true; // draw this guy once
sketchPath = surface.getFilesDir().getAbsolutePath();
surface.startThread();
if (DEBUG) println("Done with init surface");
}
private void setFullScreenVisibility() {
if (fullScreen) {
runOnUiThread(new Runnable() {
@Override
public void run() {
int visibility;
if (SDK < 19) {
// Pre-4.4
visibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
} else {
// 4.4 and higher. Integer instead of constants defined in View so it can
// build with SDK < 4.4
visibility = 256 | // View.SYSTEM_UI_FLAG_LAYOUT_STABLE
512 | // View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
1024 | // View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4 | // View.SYSTEM_UI_FLAG_FULLSCREEN
4096; // View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
// However, this visibility does not fix a bug where the navigation area
// turns black after resuming the app:
// https://code.google.com/p/android/issues/detail?id=170752
}
surface.setSystemUiVisibility(visibility);
}
});
}
}
public void onResume() {
if (DEBUG) System.out.println("PApplet.onResume() called");
if (parentLayout == -1) {
setFullScreenVisibility();
}
if (g != null) {
g.restoreState();
}
handleMethods("resume");
if (0 < frameCount) {
// Don't call resume() when the app is starting and setup() has not been
// called yet
// https://github.com/processing/processing-android/issues/274
// Also, no need to call resume() from anywhere else (for example, from
// onStart) since onResume() is always called in the activity lifecyle:
// https://developer.android.com/guide/components/activities/activity-lifecycle.html
resume();
}
// Set the default to true to handle the situation where a fragment is popping back
// after pressing back (app does not exit)
handledBackPressed = true;
surface.resumeThread();
}
public void onPause() {
surface.pauseThread();
// Make sure that the keyboard is not left open after leaving the app
closeKeyboard();
if (g != null) {
g.saveState();
}
handleMethods("pause");
pause(); // handler for others to write
}
public void onStart() {
start();
}
public void onStop() {
stop();
}
public void onCreate(Bundle savedInstanceState) {
create();
}
public void onDestroy() {
handleMethods("onDestroy");
dispose();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
handleMethods("onActivityResult", new Object[] { requestCode, resultCode, data });
}
public void onNewIntent(Intent intent) {
handleMethods("onNewIntent", new Object[] { intent });
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
}
public boolean onContextItemSelected(MenuItem item) {
return false;
}
public void setHasOptionsMenu(boolean hasMenu) {
surface.setHasOptionsMenu(hasMenu);
}
public void onBackPressed() {
handledBackPressed = false;
}
public void startActivity(Intent intent) {
surface.startActivity(intent);
}
public void runOnUiThread(Runnable action) {
surface.runOnUiThread(action);
}
public boolean hasPermission(String permission) {
return surface.hasPermission(permission);
}
public void requestPermission(String permission) {
if (!hasPermission(permission)) {
reqPermissions.add(permission);
}
}
public void requestPermission(String permission, String callback) {
requestPermission(permission, callback, this);
}
public void requestPermission(String permission, String callback, Object target) {
registerWithArgs(callback, target, new Class[] { boolean.class });
if (hasPermission(permission)) {
// If the app already has permission, still call the handle method as it
// may be doing some initialization
handleMethods(callback, new Object[] { true });
} else {
permissionMethods.put(permission, callback);
// Accumulating permissions so they requested all at once at the end
// of draw.
reqPermissions.add(permission);
}
}
public void onRequestPermissionsResult(int requestCode,
String permissions[],
int[] grantResults) {
if (requestCode == PSurface.REQUEST_PERMISSIONS) {
for (int i = 0; i < grantResults.length; i++) {
boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
handlePermissionsResult(permissions[i], granted);
}
}
}
private void handlePermissionsResult(String permission, final boolean granted) {
String methodName = permissionMethods.get(permission);
final RegisteredMethods meth = registerMap.get(methodName);
if (meth != null) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
meth.handle(new Object[] { granted });
}
});
}
}
private void handlePermissions() {
if (0 < reqPermissions.size()) {
String[] req = reqPermissions.toArray(new String[reqPermissions.size()]);
surface.requestPermissions(req);
reqPermissions.clear();
}
}
/**
* @param method "size" or "fullScreen"
* @param args parameters passed to the function so we can show the user
* @return true if safely inside the settings() method
*/
boolean insideSettings(String method, Object... args) {
if (insideSettings) {
return true;
}
final String url = "https://processing.org/reference/" + method + "_.html";
if (!external) { // post a warning for users of Eclipse and other IDEs
StringList argList = new StringList(args);
System.err.println("When not using the PDE, " + method + "() can only be used inside settings().");
System.err.println("Remove the " + method + "() method from setup(), and add the following:");
System.err.println("public void settings() {");
System.err.println(" " + method + "(" + argList.join(", ") + ");");
System.err.println("}");
}
throw new IllegalStateException(method + "() cannot be used here, see " + url);
}
void handleSettings() {
insideSettings = true;
//Do stuff
settings();
insideSettings = false;
}
public void settings() {
//It'll be empty. Will be overridden by user's sketch class.
}
final public int sketchWidth() {
return width;
}
final public int sketchHeight() {
return height;
}
final public String sketchRenderer() {
return renderer;
}
public int sketchSmooth() {
return smooth;
}
final public boolean sketchFullScreen() {
return fullScreen;
}
final public int sketchDisplay() {
return display;
}
final public String sketchOutputPath() {
return null;
}
final public OutputStream sketchOutputStream() {
return null;
}
final public int sketchWindowColor() {
return windowColor;
}
final public int sketchPixelDensity() {
return pixelDensity;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public void surfaceChanged() {
surfaceChanged = true;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Called by the sketch surface view, thought it could conceivably be called
* by Android as well.
*/
public void surfaceWindowFocusChanged(boolean hasFocus) {
focused = hasFocus;
if (focused) {
focusGained();
} else {
focusLost();
}
}
/**
* If you override this function without calling super.onTouchEvent(),
* then motionX, motionY, motionPressed, and motionEvent will not be set.
*/
public boolean surfaceTouchEvent(MotionEvent event) {
nativeMotionEvent(event);
return true;
}
public void surfaceKeyDown(int code, android.view.KeyEvent event) {
nativeKeyEvent(event);
}
public void surfaceKeyUp(int code, android.view.KeyEvent event) {
nativeKeyEvent(event);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Called by the browser or applet viewer to inform this applet that it
* should start its execution. It is called after the init method and
* each time the applet is revisited in a Web page.
* <p/>
* Called explicitly via the first call to PApplet.paint(), because
* PAppletGL needs to have a usable screen before getting things rolling.
*/
public void start() {
}
/**
* Called by the browser or applet viewer to inform
* this applet that it should stop its execution.
* <p/>
* Unfortunately, there are no guarantees from the Java spec
* when or if stop() will be called (i.e. on browser quit,
* or when moving between web pages), and it's not always called.
*/
public void stop() {
}
/**
* Developers can override here to save state. The 'paused' variable will be
* set before this function is called.
*/
public void pause() {
}
/**
* Developers can override here to restore state. The 'paused' variable
* will be cleared before this function is called.
*/
public void resume() {
}
//////////////////////////////////////////////////////////////
/** Map of registered methods, stored by name. */
HashMap<String, RegisteredMethods> registerMap =
new HashMap<String, PApplet.RegisteredMethods>();
class RegisteredMethods {
int count;
Object[] objects;
// Because the Method comes from the class being called,
// it will be unique for most, if not all, objects.
Method[] methods;
Object[] emptyArgs = new Object[] { };
void handle() {
handle(emptyArgs);
}
void handle(Object[] args) {
for (int i = 0; i < count; i++) {
try {
methods[i].invoke(objects[i], args);
} catch (Exception e) {
// check for wrapped exception, get root exception
Throwable t;
if (e instanceof InvocationTargetException) {
InvocationTargetException ite = (InvocationTargetException) e;
t = ite.getCause();
} else {
t = e;
}
// check for RuntimeException, and allow to bubble up
if (t instanceof RuntimeException) {
// re-throw exception
throw (RuntimeException) t;
} else {
// trap and print as usual
t.printStackTrace();
}
}
}
}
void add(Object object, Method method) {
if (findIndex(object) == -1) {
if (objects == null) {
objects = new Object[5];
methods = new Method[5];
} else if (count == objects.length) {
objects = (Object[]) PApplet.expand(objects);
methods = (Method[]) PApplet.expand(methods);
}
objects[count] = object;
methods[count] = method;
count++;
} else {
die(method.getName() + "() already added for this instance of " +
object.getClass().getName());
}
}
/**
* Removes first object/method pair matched (and only the first,
* must be called multiple times if object is registered multiple times).
* Does not shrink array afterwards, silently returns if method not found.
*/
// public void remove(Object object, Method method) {
// int index = findIndex(object, method);
public void remove(Object object) {
int index = findIndex(object);
if (index != -1) {
// shift remaining methods by one to preserve ordering
count--;
for (int i = index; i < count; i++) {
objects[i] = objects[i+1];
methods[i] = methods[i+1];
}
// clean things out for the gc's sake
objects[count] = null;
methods[count] = null;
}
}
// protected int findIndex(Object object, Method method) {
protected int findIndex(Object object) {
for (int i = 0; i < count; i++) {
if (objects[i] == object) {
// if (objects[i] == object && methods[i].equals(method)) {
//objects[i].equals() might be overridden, so use == for safety
// since here we do care about actual object identity
//methods[i]==method is never true even for same method, so must use
// equals(), this should be safe because of object identity
return i;
}
}