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
9975 lines (8057 loc) · 279 KB
/
Copy pathPApplet.java
File metadata and controls
9975 lines (8057 loc) · 279 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) 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.app.*;
import android.content.*;
import android.content.pm.ActivityInfo;
import android.content.pm.ConfigurationInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.*;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Time;
import android.util.*;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.*;
import android.app.Fragment;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
public class PApplet extends Fragment implements PConstants, Runnable {
/**
* The activity which holds this fragment.
*/
private Activity activity;
/** The PGraphics renderer associated with this PApplet */
public PGraphics g;
// static final public boolean DEBUG = true;
static final public boolean DEBUG = false;
/** The frame containing this applet (if any) */
// public Frame frame;
/**
* 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 = 100;
// static public final int DEFAULT_HEIGHT = 100;
/**
* Minimum dimensions for the window holding an applet.
* This varies between platforms, Mac OS X 10.3 can do any height
* but requires at least 128 pixels width. Windows XP has another
* set of limitations. And for all I know, Linux probably lets you
* make windows with negative sizes.
*/
// static public final int MIN_WINDOW_WIDTH = 128;
// static public final int MIN_WINDOW_HEIGHT = 128;
/**
* Exception thrown when size() is called the first time.
* <P>
* This is used internally so that setup() is forced to run twice
* when the renderer is changed. This is the only way for us to handle
* invoking the new renderer while also in the midst of rendering.
*/
static public class RendererChangeException extends RuntimeException { }
protected boolean surfaceReady;
/**
* 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;
/**
* true if no size() command has been executed. This is used to wait until
* a size has been set before placing in the window and showing it.
*/
// public boolean defaultSize;
// volatile boolean resizeRequest;
// volatile int resizeWidth;
// volatile int resizeHeight;
/**
* 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;
/** height of this applet's associated PGraphics */
public int height;
// can't call this because causes an ex, but could set elsewhere
//final float screenDensity = getResources().getDisplayMetrics().density;
/** absolute x position of input on screen */
public int mouseX;
/** absolute x position of input on screen */
public int mouseY;
// /** current x position of motion (relative to start of motion) */
// public float motionX;
//
// /** current y position of the mouse (relative to start of motion) */
// public float motionY;
//
// /** Last reported pressure of the current motion event */
// public float motionPressure;
//
// /** Last reported positions and pressures for all pointers */
// protected int numPointers;
// protected int pnumPointers;
//
// protected float[] ppointersX = {0};
// protected float[] ppointersY = {0};
// protected float[] ppointersPressure = {0};
//
// protected float[] pointersX = {0};
// protected float[] pointersY = {0};
// protected float[] pointersPressure = {0};
//
// protected int downMillis;
// protected float downX, downY;
// protected boolean onePointerGesture = false;
// protected boolean twoPointerGesture = true;
//
// protected final int MIN_SWIPE_LENGTH = 150; // Minimum length (in pixels) of a swipe event
// protected final int MAX_SWIPE_DURATION = 2000; // Maximum duration (in millis) of a swipe event
// protected final int MAX_TAP_DISP = 20; // Maximum displacement (in pixels) during a tap event
// protected final int MAX_TAP_DURATION = 1000; // Maximum duration (in millis) of a tap event
/**
* 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 float pmotionX, pmotionY;
/**
* 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;
// protected float dmotionX, dmotionY;
/**
* 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;
// protected float emotionX, emotionY;
// /**
// * Used to set pmotionX/Y to motionX/Y the first time motionX/Y are used,
// * otherwise pmotionX/Y are always zero, causing a nasty jump.
// * <P>
// * Just using (frameCount == 0) won't work since motionXxxxx()
// * may not be called until a couple frames into things.
// */
// public boolean firstMotion;
// public int mouseButton;
public boolean mousePressed;
// public MouseEvent mouseEvent;
// public MotionEvent motionEvent;
/** Post events to the main thread that created the Activity */
Handler handler;
/**
* 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;
protected boolean windowFocused = false;
protected boolean viewFocused = false;
/**
* true if the applet is online.
* <P>
* This can be used to test how the applet should behave
* since online situations are different (no file writing, etc).
*/
// public boolean online = false;
/**
* Time in milliseconds when the applet was started.
* <P>
* Used by the millis() function.
*/
long millisOffset = System.currentTimeMillis();
/**
* 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;
/** Last time in nanoseconds that frameRate was checked */
protected long frameRateLastNanos = 0;
/** As of release 0116, frameRate(60) is called as a default */
protected float frameRateTarget = 60;
protected long frameRatePeriod = 1000000000L / 60L;
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;
/**
* For Android, true if the activity has been paused.
*/
protected boolean paused;
protected SurfaceView surfaceView;
/**
* The Window object for Android.
*/
// protected Window window;
/**
* true if exit() has been called so that things shut down
* once the main thread kicks off.
*/
protected boolean exitCalled;
Thread thread;
// messages to send if attached as an external vm
/**
* 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;
static final String ERROR_MIN_MAX =
"Cannot use min() or max() on an empty array.";
boolean insideSettings;
String renderer = JAVA2D;
int smooth = 1; // default smoothing (whatever that means for the renderer)
boolean fullScreen = false;
// 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;
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
/**
* Required empty constructor.
*/
public PApplet() {}
/** Called with the activity is first created. */
@SuppressWarnings("unchecked")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (DEBUG) println("onCreateView() happening here: " + Thread.currentThread().getName());
activity = getActivity();
View rootView;
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
displayWidth = dm.widthPixels;
displayHeight = dm.heightPixels;
//Setting the default height and width to be fullscreen
width = displayWidth;
height = displayHeight;
// println("density is " + dm.density);
// println("densityDpi is " + dm.densityDpi);
if (DEBUG) println("display metrics: " + dm);
//println("screen size is " + screenWidth + "x" + screenHeight);
// LinearLayout layout = new LinearLayout(this);
// layout.setOrientation(LinearLayout.VERTICAL | LinearLayout.HORIZONTAL);
// viewGroup = new ViewGroup();
// surfaceView.setLayoutParams();
// viewGroup.setLayoutParams(LayoutParams.)
// RelativeLayout layout = new RelativeLayout(this);
// RelativeLayout overallLayout = new RelativeLayout(this);
// RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
//lp.addRule(RelativeLayout.RIGHT_OF, tv1.getId());
// layout.setGravity(RelativeLayout.CENTER_IN_PARENT);
handleSettings();
int sw = sketchWidth();
int sh = sketchHeight();
// Get renderer name and class
String rendererName = sketchRenderer();
Class<?> rendererClass = null;
try {
rendererClass = Class.forName(rendererName);
} catch (ClassNotFoundException exception) {
String message = String.format(
"Error: Could not resolve renderer class name: %s", rendererName);
throw new RuntimeException(message, exception);
}
if (rendererName.equals(JAVA2D)) {
// JAVA2D renderer
surfaceView = new SketchSurfaceView(activity, sw, sh,
(Class<? extends PGraphicsAndroid2D>) rendererClass);
} else if (PGraphicsOpenGL.class.isAssignableFrom(rendererClass)) {
// P2D, P3D, and any other PGraphicsOpenGL-based renderer
surfaceView = new SketchSurfaceViewGL(activity, sw, sh,
(Class<? extends PGraphicsOpenGL>) rendererClass);
} else {
// Anything else
String message = String.format(
"Error: Unsupported renderer class: %s", rendererName);
throw new RuntimeException(message);
}
//set smooth level
if (smooth == 0) {
g.noSmooth();
} else {
g.smooth(smooth);
}
// g = ((SketchSurfaceView) surfaceView).getGraphics();
// surfaceView.setLayoutParams(new LayoutParams(sketchWidth(), sketchHeight()));
// layout.addView(surfaceView);
// surfaceView.setVisibility(1);
// println("visibility " + surfaceView.getVisibility() + " " + SurfaceView.VISIBLE);
// layout.addView(surfaceView);
// AttributeSet as = new AttributeSet();
// RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(layout, as);
// lp.addRule(android.R.styleable.ViewGroup_Layout_layout_height,
// layout.add
//lp.addRule(, arg1)
//layout.addView(surfaceView, sketchWidth(), sketchHeight());
// new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
// RelativeLayout.LayoutParams.FILL_PARENT);
if (sw == displayWidth && sh == displayHeight) {
// If using the full screen, don't embed inside other layouts
// window.setContentView(surfaceView);
rootView = surfaceView;
} else {
// If not using full screen, setup awkward view-inside-a-view so that
// the sketch can be centered on screen. (If anyone has a more efficient
// way to do this, please file an issue on Google Code, otherwise you
// can keep your "talentless hack" comments to yourself. Ahem.)
RelativeLayout overallLayout = new RelativeLayout(activity);
RelativeLayout.LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
LinearLayout layout = new LinearLayout(activity);
layout.addView(surfaceView, sketchWidth(), sketchHeight());
overallLayout.addView(layout, lp);
// window.setContentView(overallLayout);
rootView = overallLayout;
}
/*
// Here we use Honeycomb API (11+) to hide (in reality, just make the status icons into small dots)
// the status bar. Since the core is still built against API 7 (2.1), we use introspection to get
// the setSystemUiVisibility() method from the view class.
Method visibilityMethod = null;
try {
visibilityMethod = surfaceView.getClass().getMethod("setSystemUiVisibility", new Class[] { int.class});
} catch (NoSuchMethodException e) {
// Nothing to do. This means that we are running with a version of Android previous to Honeycomb.
}
if (visibilityMethod != null) {
try {
// This is equivalent to calling:
//surfaceView.setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
// The value of View.STATUS_BAR_HIDDEN is 1.
visibilityMethod.invoke(surfaceView, new Object[] { 1 });
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
}
}
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
*/
// layout.addView(surfaceView, lp);
// surfaceView.setLayoutParams(new LayoutParams(sketchWidth(), sketchHeight()));
// RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams()
// layout.addView(surfaceView, new LayoutParams(arg0)
// TODO probably don't want to set these here, can't we wait for surfaceChanged()?
// removing this in 0187
// width = screenWidth;
// height = screenHeight;
// int left = (screenWidth - iwidth) / 2;
// int right = screenWidth - (left + iwidth);
// int top = (screenHeight - iheight) / 2;
// int bottom = screenHeight - (top + iheight);
// surfaceView.setPadding(left, top, right, bottom);
// android:layout_width
// window.setContentView(surfaceView); // set full screen
// code below here formerly from init()
//millisOffset = System.currentTimeMillis(); // moved to the variable declaration
finished = false; // just for clarity
// this will be cleared by draw() if it is not overridden
looping = true;
redraw = true; // draw this guy once
// firstMotion = true;
sketchPath = activity.getFilesDir().getAbsolutePath();
// Looper.prepare();
handler = new Handler();
// println("calling loop()");
// Looper.loop();
// println("done with loop() call, will continue...");
start();
return rootView;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (DEBUG) System.out.println("configuration changed: " + newConfig);
super.onConfigurationChanged(newConfig);
}
@Override
public void onResume() {
super.onResume();
// TODO need to bring back app state here!
// surfaceView.onResume();
if (DEBUG) System.out.println("PApplet.onResume() called");
paused = false;
handleMethods("resume");
//start(); // kick the thread back on
resume();
// surfaceView.onResume();
}
@Override
public void onPause() {
super.onPause();
// TODO need to save all application state here!
// System.out.println("PApplet.onPause() called");
paused = true;
handleMethods("pause");
pause(); // handler for others to write
// synchronized (this) {
// paused = true;
//}
// surfaceView.onPause();
}
/**
* @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.
}
/**
* 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() {
}
@Override
public void onDestroy() {
// stop();
dispose();
if (PApplet.DEBUG) {
System.out.println("PApplet.onDestroy() called");
}
super.onDestroy();
//finish();
}
//////////////////////////////////////////////////////////////
// ANDROID SURFACE VIEW
// TODO this is only used by A2D, when finishing up a draw. but if the
// surfaceview has changed, then it might belong to an a3d surfaceview. hrm.
public SurfaceHolder getSurfaceHolder() {
return surfaceView.getHolder();
// return surfaceHolder;
}
/** Not official API, not guaranteed to work in the future. */
public SurfaceView getSurfaceView() {
return surfaceView;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// public interface SketchSurfaceView {
// public PGraphics getGraphics();
// }
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public class SketchSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
PGraphicsAndroid2D g2;
SurfaceHolder surfaceHolder;
public SketchSurfaceView(Context context, int wide, int high,
Class<? extends PGraphicsAndroid2D> clazz) {
super(context);
// println("surface holder");
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); // no longer needed.
// println("creating graphics");
if (clazz.equals(PGraphicsAndroid2D.class)) {
g2 = new PGraphicsAndroid2D();
} else {
try {
Constructor<? extends PGraphicsAndroid2D> constructor =
clazz.getConstructor();
g2 = constructor.newInstance();
} catch (Exception exception) {
throw new RuntimeException(
"Error: Failed to initialize custom Android2D renderer",
exception);
}
}
// Set semi-arbitrary size; will be set properly when surfaceChanged() called
g2.setSize(wide, high);
// newGraphics.setSize(getWidth(), getHeight());
g2.setParent(PApplet.this);
g2.setPrimary(true);
// Set the value for 'g' once everything is ready (otherwise rendering
// may attempt before setSize(), setParent() etc)
// g = newGraphics;
g = g2; // assign the g object for the PApplet
// println("setting focusable, requesting focus");
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
// println("done making surface view");
}
// public PGraphics getGraphics() {
// return g2;
// }
// part of SurfaceHolder.Callback
public void surfaceCreated(SurfaceHolder holder) {
}
// part of SurfaceHolder.Callback
public void surfaceDestroyed(SurfaceHolder holder) {
//g2.dispose();
}
// part of SurfaceHolder.Callback
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (DEBUG) {
System.out.println("SketchSurfaceView2D.surfaceChanged() " + w + " " + h);
}
surfaceChanged = true;
// width = w;
// height = h;
//
// g.setSize(w, h);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
surfaceWindowFocusChanged(hasFocus);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return surfaceTouchEvent(event);
}
@Override
public boolean onKeyDown(int code, android.view.KeyEvent event) {
surfaceKeyDown(code, event);
return super.onKeyDown(code, event);
}
@Override
public boolean onKeyUp(int code, android.view.KeyEvent event) {
surfaceKeyUp(code, event);
return super.onKeyUp(code, event);
}
// don't think i want to call stop() from here, since it might be swapping renderers
// @Override
// protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// stop();
// }
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public class SketchSurfaceViewGL extends GLSurfaceView {
PGraphicsOpenGL g3;
SurfaceHolder surfaceHolder;
@SuppressWarnings("deprecation")
public SketchSurfaceViewGL(Context context, int wide, int high,
Class<? extends PGraphicsOpenGL> clazz) {
super(context);
// Check if the system supports OpenGL ES 2.0.
final ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
final boolean supportsGLES2 = configurationInfo.reqGlEsVersion >= 0x20000;
if (!supportsGLES2) {
throw new RuntimeException("OpenGL ES 2.0 is not supported by this device.");
}
surfaceHolder = getHolder();
// are these two needed?
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
// The PGraphics object needs to be created here so the renderer is not
// null. This is required because PApplet.onResume events (which call
// this.onResume() and thus require a valid renderer) are triggered
// before surfaceChanged() is ever called.
if (clazz.equals(PGraphics2D.class)) { // P2D
g3 = new PGraphics2D();
} else if (clazz.equals(PGraphics3D.class)) { // P3D
g3 = new PGraphics3D();
} else { // something that extends P2D, P3D, or PGraphicsOpenGL
try {
Constructor<? extends PGraphicsOpenGL> constructor =
clazz.getConstructor();
g3 = constructor.newInstance();
} catch (Exception exception) {
throw new RuntimeException(
"Error: Failed to initialize custom OpenGL renderer",
exception);
}
}
//set it up
g3.setParent(PApplet.this);
g3.setPrimary(true);
// Set semi-arbitrary size; will be set properly when surfaceChanged() called
g3.setSize(wide, high);
// Tells the default EGLContextFactory and EGLConfigChooser to create an GLES2 context.
setEGLContextClientVersion(2);
int quality = sketchQuality();
if (1 < quality) {
setEGLConfigChooser(((PGLES)g3.pgl).getConfigChooser(quality));
}
// The renderer can be set only once.
setRenderer(((PGLES)g3.pgl).getRenderer());
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
// assign this g to the PApplet
g = g3;
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
}
public PGraphics getGraphics() {
return g3;
}
// part of SurfaceHolder.Callback
@Override
public void surfaceCreated(SurfaceHolder holder) {
super.surfaceCreated(holder);
if (DEBUG) {
System.out.println("surfaceCreated()");
}
}
// part of SurfaceHolder.Callback
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
super.surfaceDestroyed(holder);
if (DEBUG) {
System.out.println("surfaceDestroyed()");
}
/*
// TODO: Check how to make sure of calling g3.dispose() when this call to
// surfaceDestoryed corresponds to the sketch being shut down instead of just
// taken to the background.
// For instance, something like this would be ok?
// The sketch is being stopped, so we dispose the resources.
if (!paused) {
g3.dispose();
}
*/
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
super.surfaceChanged(holder, format, w, h);
if (DEBUG) {
System.out.println("SketchSurfaceView3D.surfaceChanged() " + w + " " + h);
}
surfaceChanged = true;
// width = w;
// height = h;