forked from arduino/Arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPApplet.java
9483 lines (7844 loc) · 302 KB
/
PApplet.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
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-10 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 as published by the Free Software Foundation, version 2.1.
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.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import java.util.zip.*;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import processing.core.PShape;
/**
* Base class for all sketches that use processing.core.
* <p/>
* Note that you should not use AWT or Swing components inside a Processing
* applet. The surface is made to automatically update itself, and will cause
* problems with redraw of components drawn above it. If you'd like to
* integrate other Java components, see below.
* <p/>
* As of release 0145, Processing uses active mode rendering in all cases.
* All animation tasks happen on the "Processing Animation Thread". The
* setup() and draw() methods are handled by that thread, and events (like
* mouse movement and key presses, which are fired by the event dispatch
* thread or EDT) are queued to be (safely) handled at the end of draw().
* For code that needs to run on the EDT, use SwingUtilities.invokeLater().
* When doing so, be careful to synchronize between that code (since
* invokeLater() will make your code run from the EDT) and the Processing
* animation thread. Use of a callback function or the registerXxx() methods
* in PApplet can help ensure that your code doesn't do something naughty.
* <p/>
* As of release 0136 of Processing, we have discontinued support for versions
* of Java prior to 1.5. We don't have enough people to support it, and for a
* project of our size, we should be focusing on the future, rather than
* working around legacy Java code. In addition, Java 1.5 gives us access to
* better timing facilities which will improve the steadiness of animation.
* <p/>
* This class extends Applet instead of JApplet because 1) historically,
* we supported Java 1.1, which does not include Swing (without an
* additional, sizable, download), and 2) Swing is a bloated piece of crap.
* A Processing applet is a heavyweight AWT component, and can be used the
* same as any other AWT component, with or without Swing.
* <p/>
* Similarly, Processing runs in a Frame and not a JFrame. However, there's
* nothing to prevent you from embedding a PApplet into a JFrame, it's just
* that the base version uses a regular AWT frame because there's simply
* no need for swing in that context. If people want to use Swing, they can
* embed themselves as they wish.
* <p/>
* It is possible to use PApplet, along with core.jar in other projects.
* In addition to enabling you to use Java 1.5+ features with your sketch,
* this also allows you to embed a Processing drawing area into another Java
* application. This means you can use standard GUI controls with a Processing
* sketch. Because AWT and Swing GUI components cannot be used on top of a
* PApplet, you can instead embed the PApplet inside another GUI the way you
* would any other Component.
* <p/>
* It is also possible to resize the Processing window by including
* <tt>frame.setResizable(true)</tt> inside your <tt>setup()</tt> method.
* Note that the Java method <tt>frame.setSize()</tt> will not work unless
* you first set the frame to be resizable.
* <p/>
* Because the default animation thread will run at 60 frames per second,
* an embedded PApplet can make the parent sluggish. You can use frameRate()
* to make it update less often, or you can use noLoop() and loop() to disable
* and then re-enable looping. If you want to only update the sketch
* intermittently, use noLoop() inside setup(), and redraw() whenever
* the screen needs to be updated once (or loop() to re-enable the animation
* thread). The following example embeds a sketch and also uses the noLoop()
* and redraw() methods. You need not use noLoop() and redraw() when embedding
* if you want your application to animate continuously.
* <PRE>
* public class ExampleFrame extends Frame {
*
* public ExampleFrame() {
* super("Embedded PApplet");
*
* setLayout(new BorderLayout());
* PApplet embed = new Embedded();
* add(embed, BorderLayout.CENTER);
*
* // important to call this whenever embedding a PApplet.
* // It ensures that the animation thread is started and
* // that other internal variables are properly set.
* embed.init();
* }
* }
*
* public class Embedded extends PApplet {
*
* public void setup() {
* // original setup code here ...
* size(400, 400);
*
* // prevent thread from starving everything else
* noLoop();
* }
*
* public void draw() {
* // drawing code goes here
* }
*
* public void mousePressed() {
* // do something based on mouse movement
*
* // update the screen (run draw once)
* redraw();
* }
* }
* </PRE>
*
* <H2>Processing on multiple displays</H2>
* <P>I was asked about Processing with multiple displays, and for lack of a
* better place to document it, things will go here.</P>
* <P>You can address both screens by making a window the width of both,
* and the height of the maximum of both screens. In this case, do not use
* present mode, because that's exclusive to one screen. Basically it'll
* give you a PApplet that spans both screens. If using one half to control
* and the other half for graphics, you'd just have to put the 'live' stuff
* on one half of the canvas, the control stuff on the other. This works
* better in windows because on the mac we can't get rid of the menu bar
* unless it's running in present mode.</P>
* <P>For more control, you need to write straight java code that uses p5.
* You can create two windows, that are shown on two separate screens,
* that have their own PApplet. this is just one of the tradeoffs of one of
* the things that we don't support in p5 from within the environment
* itself (we must draw the line somewhere), because of how messy it would
* get to start talking about multiple screens. It's also not that tough to
* do by hand w/ some Java code.</P>
* @usage Web & Application
*/
public class PApplet extends Applet
implements PConstants, Runnable,
MouseListener, MouseMotionListener, KeyListener, FocusListener
{
/**
* Full name of the Java version (i.e. 1.5.0_11).
* Prior to 0125, this was only the first three digits.
*/
public static final String javaVersionName =
System.getProperty("java.version");
/**
* Version of Java that's in use, whether 1.1 or 1.3 or whatever,
* stored as a float.
* <P>
* Note that because this is stored as a float, the values may
* not be <EM>exactly</EM> 1.3 or 1.4. Instead, make sure you're
* comparing against 1.3f or 1.4f, which will have the same amount
* of error (i.e. 1.40000001). This could just be a double, but
* since Processing only uses floats, it's safer for this to be a float
* because there's no good way to specify a double with the preproc.
*/
public static final float javaVersion =
new Float(javaVersionName.substring(0, 3)).floatValue();
/**
* Current platform in use.
* <P>
* Equivalent to System.getProperty("os.name"), just used internally.
*/
/**
* Current platform in use, one of the
* PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER.
*/
static public int platform;
/**
* Name associated with the current 'platform' (see PConstants.platformNames)
*/
//static public String platformName;
static {
String osname = System.getProperty("os.name");
if (osname.indexOf("Mac") != -1) {
platform = MACOSX;
} else if (osname.indexOf("Windows") != -1) {
platform = WINDOWS;
} else if (osname.equals("Linux")) { // true for the ibm vm
platform = LINUX;
} else {
platform = OTHER;
}
}
/**
* Modifier flags for the shortcut key used to trigger menus.
* (Cmd on Mac OS X, Ctrl on Linux and Windows)
*/
static public final int MENU_SHORTCUT =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** The PGraphics renderer associated with this PApplet */
public PGraphics g;
//protected Object glock = new Object(); // for sync
/** The frame containing this applet (if any) */
public Frame frame;
/**
* The screen size when the applet was started.
* <P>
* Access this via screen.width and screen.height. To make an applet
* run at full screen, use size(screen.width, screen.height).
* <P>
* If you have multiple displays, this will be the size of the main
* display. Running full screen across multiple displays isn't
* particularly supported, and requires more monkeying with the values.
* This probably can't/won't be fixed until/unless I get a dual head
* system.
* <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 future releases need to be better
* at handling multiple displays.
*/
public Dimension screen =
Toolkit.getDefaultToolkit().getScreenSize();
/**
* A leech graphics object that is echoing all events.
*/
public PGraphics recorder;
/**
* Command line options passed in from main().
* <P>
* This does not include the arguments passed in to PApplet itself.
*/
public String args[];
/** Path to sketch folder */
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 { }
/**
* 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;
/**
* Array containing the values for all the pixels in the display window. These values are of the color datatype. This array is the size of the display window. For example, if the image is 100x100 pixels, there will be 10000 values and if the window is 200x300 pixels, there will be 60000 values. The <b>index</b> value defines the position of a value within the array. For example, the statment <b>color b = pixels[230]</b> will set the variable <b>b</b> to be equal to the value at that location in the array. <br><br> Before accessing this array, the data must loaded with the <b>loadPixels()</b> function. After the array data has been modified, the <b>updatePixels()</b> function must be run to update the changes. Without <b>loadPixels()</b>, running the code may (or will in future releases) result in a NullPointerException.
* Pixel buffer from this applet's PGraphics.
* <P>
* When used with OpenGL or Java2D, this value will
* be null until loadPixels() has been called.
*
* @webref image:pixels
* @see processing.core.PApplet#loadPixels()
* @see processing.core.PApplet#updatePixels()
* @see processing.core.PApplet#get(int, int, int, int)
* @see processing.core.PApplet#set(int, int, int)
* @see processing.core.PImage
*/
public int pixels[];
/** width of this applet's associated PGraphics
* @webref environment
*/
public int width;
/** height of this applet's associated PGraphics
* @webref environment
* */
public int height;
/**
* The system variable <b>mouseX</b> always contains the current horizontal coordinate of the mouse.
* @webref input:mouse
* @see PApplet#mouseY
* @see PApplet#mousePressed
* @see PApplet#mousePressed()
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*
* */
public int mouseX;
/**
* The system variable <b>mouseY</b> always contains the current vertical coordinate of the mouse.
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mousePressed
* @see PApplet#mousePressed()
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
* */
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.
* @webref input:mouse
* @see PApplet#pmouseY
* @see PApplet#mouseX
* @see PApplet#mouseY
*/
public int pmouseX;
/**
* @webref input:mouse
* @see PApplet#pmouseX
* @see PApplet#mouseX
* @see PApplet#mouseY
*/
public int pmouseY;
/**
* 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;
/**
* pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc)
* these are different because mouse events are queued to the end of
* draw, so the previous position has to be updated on each event,
* as opposed to the pmouseX/Y that's used inside draw, which is expected
* to be updated once per trip through draw().
*/
protected int emouseX, emouseY;
/**
* Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used,
* otherwise pmouseX/Y are always zero, causing a nasty jump.
* <P>
* Just using (frameCount == 0) won't work since mouseXxxxx()
* may not be called until a couple frames into things.
*/
public boolean firstMouse;
/**
* Processing automatically tracks if the mouse button is pressed and which button is pressed.
* The value of the system variable <b>mouseButton</b> is either <b>LEFT</b>, <b>RIGHT</b>, or <b>CENTER</b> depending on which button is pressed.
* <h3>Advanced:</h3>
* If running on Mac OS, a ctrl-click will be interpreted as
* the righthand mouse button (unlike Java, which reports it as
* the left mouse).
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mouseY
* @see PApplet#mousePressed()
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*/
public int mouseButton;
/**
* Variable storing if a mouse button is pressed. The value of the system variable <b>mousePressed</b> is true if a mouse button is pressed and false if a button is not pressed.
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mouseY
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*/
public boolean mousePressed;
public MouseEvent mouseEvent;
/**
* The system variable <b>key</b> always contains the value of the most recent key on the keyboard that was used (either pressed or released). <br><br>
* For non-ASCII keys, use the <b>keyCode</b> variable.
* The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the <b>key</b> variable instead of <b>keyCode</b>
* If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh.
* Check for both ENTER and RETURN to make sure your program will work for all platforms.
* =advanced
*
* 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).
* @webref input:keyboard
* @see PApplet#keyCode
* @see PApplet#keyPressed
* @see PApplet#keyPressed()
* @see PApplet#keyReleased()
*/
public char key;
/**
* The variable <b>keyCode</b> is used to detect special keys such as the UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT.
* When checking for these keys, it's first necessary to check and see if the key is coded. This is done with the conditional "if (key == CODED)" as shown in the example.
* <br><br>The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and DELETE) do not require checking to see if they key is coded, and you should simply use the <b>key</b> variable instead of <b>keyCode</b>
* If you're making cross-platform projects, note that the ENTER key is commonly used on PCs and Unix and the RETURN key is used instead on Macintosh.
* Check for both ENTER and RETURN to make sure your program will work for all platforms.
* <br><br>For users familiar with Java, the values for UP and DOWN are simply shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN.
* Other keyCode values can be found in the Java <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/KeyEvent.html">KeyEvent</a> reference.
*
* =advanced
* 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.
* @webref input:keyboard
* @see PApplet#key
* @see PApplet#keyPressed
* @see PApplet#keyPressed()
* @see PApplet#keyReleased()
*/
public int keyCode;
/**
* The boolean system variable <b>keyPressed</b> is <b>true</b> if any key is pressed and <b>false</b> if no keys are pressed.
* @webref input:keyboard
* @see PApplet#key
* @see PApplet#keyCode
* @see PApplet#keyPressed()
* @see PApplet#keyReleased()
*/
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.
* @webref environment
*/
public boolean focused = 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).
* @webref environment
*/
public boolean online = false;
/**
* Time in milliseconds when the applet was started.
* <P>
* Used by the millis() function.
*/
long millisOffset;
/**
* 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;
/**
* true if exit() has been called so that things shut down
* once the main thread kicks off.
*/
protected boolean exitCalled;
Thread thread;
protected RegisteredMethods sizeMethods;
protected RegisteredMethods preMethods, drawMethods, postMethods;
protected RegisteredMethods mouseEventMethods, keyEventMethods;
protected RegisteredMethods disposeMethods;
// 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.";
// during rev 0100 dev cycle, working on new threading model,
// but need to disable and go conservative with changes in order
// to get pdf and audio working properly first.
// for 0116, the CRUSTY_THREADS are being disabled to fix lots of bugs.
//static final boolean CRUSTY_THREADS = false; //true;
public void init() {
// println("Calling init()");
// send tab keys through to the PApplet
setFocusTraversalKeysEnabled(false);
millisOffset = System.currentTimeMillis();
finished = false; // just for clarity
// this will be cleared by draw() if it is not overridden
looping = true;
redraw = true; // draw this guy once
firstMouse = true;
// these need to be inited before setup
sizeMethods = new RegisteredMethods();
preMethods = new RegisteredMethods();
drawMethods = new RegisteredMethods();
postMethods = new RegisteredMethods();
mouseEventMethods = new RegisteredMethods();
keyEventMethods = new RegisteredMethods();
disposeMethods = new RegisteredMethods();
try {
getAppletContext();
online = true;
} catch (NullPointerException e) {
online = false;
}
try {
if (sketchPath == null) {
sketchPath = System.getProperty("user.dir");
}
} catch (Exception e) { } // may be a security problem
Dimension size = getSize();
if ((size.width != 0) && (size.height != 0)) {
// When this PApplet is embedded inside a Java application with other
// Component objects, its size() may already be set externally (perhaps
// by a LayoutManager). In this case, honor that size as the default.
// Size of the component is set, just create a renderer.
g = makeGraphics(size.width, size.height, getSketchRenderer(), null, true);
// This doesn't call setSize() or setPreferredSize() because the fact
// that a size was already set means that someone is already doing it.
} else {
// Set the default size, until the user specifies otherwise
this.defaultSize = true;
int w = getSketchWidth();
int h = getSketchHeight();
g = makeGraphics(w, h, getSketchRenderer(), null, true);
// Fire component resize event
setSize(w, h);
setPreferredSize(new Dimension(w, h));
}
width = g.width;
height = g.height;
addListeners();
// this is automatically called in applets
// though it's here for applications anyway
start();
}
public int getSketchWidth() {
return DEFAULT_WIDTH;
}
public int getSketchHeight() {
return DEFAULT_HEIGHT;
}
public String getSketchRenderer() {
return JAVA2D;
}
/**
* 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() {
// When running inside a browser, start() will be called when someone
// returns to a page containing this applet.
// http://dev.processing.org/bugs/show_bug.cgi?id=581
finished = false;
if (thread != null) return;
thread = new Thread(this, "Animation Thread");
thread.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() {
// bringing this back for 0111, hoping it'll help opengl shutdown
finished = true; // why did i comment this out?
// don't run stop and disposers twice
if (thread == null) return;
thread = null;
// call to shut down renderer, in case it needs it (pdf does)
if (g != null) g.dispose();
// maybe this should be done earlier? might help ensure it gets called
// before the vm just craps out since 1.5 craps out so aggressively.
disposeMethods.handle();
}
/**
* Called by the browser or applet viewer to inform this applet
* that it is being reclaimed and that it should destroy
* any resources that it has allocated.
* <p/>
* This also attempts to call PApplet.stop(), in case there
* was an inadvertent override of the stop() function by a user.
* <p/>
* destroy() supposedly gets called as the applet viewer
* is shutting down the applet. stop() is called
* first, and then destroy() to really get rid of things.
* no guarantees on when they're run (on browser quit, or
* when moving between pages), though.
*/
public void destroy() {
((PApplet)this).stop();
}
/**
* This returns the last width and height specified by the user
* via the size() command.
*/
// public Dimension getPreferredSize() {
// return new Dimension(width, height);
// }
// public void addNotify() {
// super.addNotify();
// println("addNotify()");
// }
//////////////////////////////////////////////////////////////
public class RegisteredMethods {
int count;
Object objects[];
Method methods[];
// convenience version for no args
public void handle() {
handle(new Object[] { });
}
public void handle(Object oargs[]) {
for (int i = 0; i < count; i++) {
try {
//System.out.println(objects[i] + " " + args);
methods[i].invoke(objects[i], oargs);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void add(Object object, Method method) {
if (objects == null) {
objects = new Object[5];
methods = new Method[5];
}
if (count == objects.length) {
objects = (Object[]) PApplet.expand(objects);
methods = (Method[]) PApplet.expand(methods);
// Object otemp[] = new Object[count << 1];
// System.arraycopy(objects, 0, otemp, 0, count);
// objects = otemp;
// Method mtemp[] = new Method[count << 1];
// System.arraycopy(methods, 0, mtemp, 0, count);
// methods = mtemp;
}
objects[count] = object;
methods[count] = method;
count++;
}
/**
* 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);
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) {
for (int i = 0; i < count; i++) {
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;
}
}
return -1;
}
}
public void registerSize(Object o) {
Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE };
registerWithArgs(sizeMethods, "size", o, methodArgs);
}
public void registerPre(Object o) {
registerNoArgs(preMethods, "pre", o);
}
public void registerDraw(Object o) {
registerNoArgs(drawMethods, "draw", o);
}
public void registerPost(Object o) {
registerNoArgs(postMethods, "post", o);
}
public void registerMouseEvent(Object o) {
Class<?> methodArgs[] = new Class[] { MouseEvent.class };
registerWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs);
}
public void registerKeyEvent(Object o) {
Class<?> methodArgs[] = new Class[] { KeyEvent.class };
registerWithArgs(keyEventMethods, "keyEvent", o, methodArgs);
}
public void registerDispose(Object o) {
registerNoArgs(disposeMethods, "dispose", o);
}
protected void registerNoArgs(RegisteredMethods meth,
String name, Object o) {
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, new Class[] {});
meth.add(o, method);
} catch (NoSuchMethodException nsme) {
die("There is no public " + name + "() method in the class " +
o.getClass().getName());
} catch (Exception e) {
die("Could not register " + name + " + () for " + o, e);
}
}
protected void registerWithArgs(RegisteredMethods meth,
String name, Object o, Class<?> cargs[]) {
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, cargs);
meth.add(o, method);
} catch (NoSuchMethodException nsme) {
die("There is no public " + name + "() method in the class " +
o.getClass().getName());
} catch (Exception e) {
die("Could not register " + name + " + () for " + o, e);
}
}
public void unregisterSize(Object o) {
Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE };
unregisterWithArgs(sizeMethods, "size", o, methodArgs);
}
public void unregisterPre(Object o) {
unregisterNoArgs(preMethods, "pre", o);
}
public void unregisterDraw(Object o) {
unregisterNoArgs(drawMethods, "draw", o);
}
public void unregisterPost(Object o) {
unregisterNoArgs(postMethods, "post", o);
}
public void unregisterMouseEvent(Object o) {
Class<?> methodArgs[] = new Class[] { MouseEvent.class };
unregisterWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs);
}
public void unregisterKeyEvent(Object o) {
Class<?> methodArgs[] = new Class[] { KeyEvent.class };
unregisterWithArgs(keyEventMethods, "keyEvent", o, methodArgs);
}
public void unregisterDispose(Object o) {
unregisterNoArgs(disposeMethods, "dispose", o);
}
protected void unregisterNoArgs(RegisteredMethods meth,
String name, Object o) {
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, new Class[] {});
meth.remove(o, method);
} catch (Exception e) {
die("Could not unregister " + name + "() for " + o, e);
}
}
protected void unregisterWithArgs(RegisteredMethods meth,
String name, Object o, Class<?> cargs[]) {
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, cargs);
meth.remove(o, method);
} catch (Exception e) {
die("Could not unregister " + name + "() for " + o, e);