-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathPAppletJythonDriver.java
More file actions
executable file
·1761 lines (1603 loc) · 55.1 KB
/
PAppletJythonDriver.java
File metadata and controls
executable file
·1761 lines (1603 loc) · 55.1 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
/*
* Copyright 2010 Jonathan Feinberg
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package jycessing;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sound.midi.MidiMessage;
import org.python.core.CompileMode;
import org.python.core.CompilerFlags;
import org.python.core.JyAttribute;
import org.python.core.Py;
import org.python.core.PyBaseCode;
import org.python.core.PyBoolean;
import org.python.core.PyCode;
import org.python.core.PyException;
import org.python.core.PyFloat;
import org.python.core.PyFunction;
import org.python.core.PyIndentationError;
import org.python.core.PyInteger;
import org.python.core.PyJavaType;
import org.python.core.PyObject;
import org.python.core.PyObjectDerived;
import org.python.core.PySet;
import org.python.core.PyString;
import org.python.core.PyStringMap;
import org.python.core.PySyntaxError;
import org.python.core.PyTuple;
import org.python.core.PyType;
import org.python.core.PyUnicode;
import org.python.util.InteractiveConsole;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.jogamp.newt.opengl.GLWindow;
import jycessing.IOUtil.ResourceReader;
import jycessing.jni.OSX;
import jycessing.mode.run.WrappedPrintStream;
import jycessing.mode.run.WrappedPrintStream.PushedOut;
import processing.awt.PSurfaceAWT;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PImage;
import processing.core.PSurface;
import processing.event.KeyEvent;
import processing.event.MouseEvent;
import processing.javafx.PSurfaceFX;
import processing.opengl.PGraphicsOpenGL;
import processing.opengl.PShader;
import processing.opengl.PSurfaceJOGL;
@SuppressWarnings("serial")
public class PAppletJythonDriver extends PApplet {
public static final String C_LIKE_LOGICAL_AND_ERROR_MESSAGE =
"Did you maybe use \"&&\" instead of \"and\"?";
public static final String C_LIKE_LOGICAL_OR_ERROR_MESSAGE =
"Did you maybe use \"||\" instead of \"or\"?";
private static final ResourceReader resourceReader =
new ResourceReader(PAppletJythonDriver.class);
private static final String GET_SETTINGS_SCRIPT = resourceReader.readText("get_settings.py");
private static final String DETECT_MODE_SCRIPT = resourceReader.readText("detect_sketch_mode.py");
private static final String PREPROCESS_SCRIPT = resourceReader.readText("pyde_preprocessor.py");
static {
// There's some bug that I don't understand yet that causes the native file
// select box to fire twice, skipping confirmation the first time.
useNativeSelect = false;
}
private Field frameField;
private PythonSketchError terminalException = null;
protected final PyStringMap builtins;
protected final InteractiveConsole interp;
private final Path pySketchPath;
private final String programText;
private final WrappedPrintStream wrappedStdout;
private final CountDownLatch finishedLatch = new CountDownLatch(1);
private enum Mode {
STATIC,
ACTIVE,
MIXED
}
// A static-mode sketch must be interpreted from within the setup() method.
// All others are interpreted during construction in order to harvest method
// definitions, which we then invoke during the run loop.
private final Mode mode;
private int detectedWidth, detectedHeight, detectedPixelDensity;
private String detectedRenderer;
private boolean detectedSmooth, detectedNoSmooth, detectedFullScreen;
private PyObject processedStaticSketch;
private static int argCount(final PyObject func) {
if (!(func instanceof PyFunction)) {
return -1;
}
return ((PyBaseCode) ((PyFunction) func).__code__).co_argcount;
}
/**
* The Processing event handling functions can take 0 or 1 argument. This class represents such a
* function.
*
* <p>If the user did not implement the variant that takes an event, then we have to pass through
* to the super implementation, or else the zero-arg version won't get called.
*/
private abstract class EventFunction<T> {
private final PyFunction func;
private final int argCount;
protected abstract void callSuper(T event);
public EventFunction(final String funcName) {
func = (PyFunction) interp.get(funcName);
argCount = argCount(func);
}
public void invoke() {
if (func != null && argCount == 0) {
func.__call__();
}
}
public void invoke(final T event) {
if (func != null && argCount == 1) {
func.__call__(Py.java2py(event));
} else {
callSuper(event);
}
}
}
/**
* We maintain a map from function name to function in order to implement {@link
* PApplet#method(String)}.
*/
private final Map<String, PyFunction> allFunctionsByName = new HashMap<>();
// These are all of the methods that PApplet might call in your sketch. If
// you have implemented a method, we save it and call it.
private PyObject setupMeth, settingsMeth, drawMeth, pauseMeth, resumeMeth;
// For compatibility, we look for definitions of both stop() and dispose()
// in the user's sketch, and call whatever's defined of those two when the sketch
// is dispose()d. If you define both, they'll both be called.
private PyObject stopMeth, disposeMeth;
private EventFunction<KeyEvent> keyPressedFunc, keyReleasedFunc, keyTypedFunc;
private EventFunction<MouseEvent> mousePressedFunc,
mouseClickedFunc,
mouseMovedFunc,
mouseReleasedFunc,
mouseDraggedFunc;
private PyObject mouseWheelMeth; // Can only be called with a MouseEvent; no need for shenanigans
// Implement the Video library's callbacks.
private PyObject captureEventMeth, movieEventMeth;
// Implement the Serial library's callback.
private PyObject serialEventMeth;
// Implement the net library's callbacks.
private PyObject clientEventMeth, disconnectEventMeth, serverEventMeth;
// Implement the oscP5 library's callback.
private PyObject oscEventMeth;
// Implement themidibus callbacks.
private PyObject noteOn3Meth,
noteOff3Meth,
controllerChange3Meth,
rawMidi1Meth,
midiMessage1Meth,
noteOn5Meth,
noteOff5Meth,
controllerChange5Meth,
rawMidi3Meth,
midiMessage3Meth;
// Implement processing_websockets callbacks.
private PyObject webSocketEventMeth, webSocketServerEventMeth;
private SketchPositionListener sketchPositionListener;
private void processSketch(final String scriptSource) throws PythonSketchError {
try {
interp.set("__processing_source__", programText);
final PyCode code =
Py.compile_flags(
scriptSource, pySketchPath.toString(), CompileMode.exec, new CompilerFlags());
try (PushedOut out = wrappedStdout.pushStdout()) {
interp.exec(code);
}
Py.flushLine();
} catch (Throwable t) {
while (t.getCause() != null) {
t = t.getCause();
}
throw toSketchException(t);
}
}
/**
* Handy method for raising a Python exception in the current interpreter frame.
*
* @param msg TypeError message.
*/
private PyObject raiseTypeError(final String msg) {
interp.exec(String.format("raise TypeError('%s')", msg.replace("'", "\\'")));
return Py.None;
}
private static PythonSketchError toSketchException(Throwable t) {
if (t instanceof RuntimeException && t.getCause() != null) {
t = t.getCause();
}
if (t instanceof PythonSketchError) {
return (PythonSketchError) t;
}
if (t instanceof PySyntaxError) {
final PySyntaxError e = (PySyntaxError) t;
return extractSketchErrorFromPyExceptionValue((PyTuple) e.value);
}
if (t instanceof PyIndentationError) {
final PyIndentationError e = (PyIndentationError) t;
return extractSketchErrorFromPyExceptionValue((PyTuple) e.value);
}
if (t instanceof PyException) {
final PyException e = (PyException) t;
final Pattern tbParse =
Pattern.compile("^\\s*File \"([^\"]+)\", line (\\d+)", Pattern.MULTILINE);
final Matcher m = tbParse.matcher(e.toString());
String file = null;
int line = -1;
while (m.find()) {
final String fileName = m.group(1);
// Ignore stack elements that come from exec()ing code in the interpreter from Java.
if (fileName.equals("<string>")) {
continue;
}
file = fileName;
// Throw away the path.
if (new File(file).exists()) {
file = new File(file).getName();
}
line = Integer.parseInt(m.group(2)) - 1;
}
if (((PyType) e.type).getName().equals("ImportError")) {
final Pattern importStar = Pattern.compile("import\\s+\\*");
if (importStar.matcher(e.toString()).find()) {
return new PythonSketchError("import * does not work in this environment.", file, line);
}
}
return new PythonSketchError(Py.formatException(e.type, e.value), file, line);
}
final StringWriter stackTrace = new StringWriter();
t.printStackTrace(new PrintWriter(stackTrace));
return new PythonSketchError(stackTrace.toString());
}
private static PythonSketchError extractSketchErrorFromPyExceptionValue(final PyTuple tup) {
final String pyMessage = (String) tup.get(0);
final String message = maybeMakeFriendlyMessage(pyMessage);
final PyTuple context = (PyTuple) tup.get(1);
final File file = new File((String) context.get(0));
final String fileName = file.getName();
final int lineNumber = ((Integer) context.get(1)).intValue() - 1;
final int column = ((Integer) context.get(2)).intValue();
if (pyMessage.startsWith("no viable alternative")) {
return noViableAlternative(file, lineNumber, column, pyMessage);
}
return new PythonSketchError(message, fileName, lineNumber, column);
}
private static final Pattern NAKED_COLOR = Pattern.compile("[(,]\\s*#([0-9a-fA-F]{6})\\b");
/**
* The message "no viable alternative" is a strong indication that there's an unclosed paren
* somewhere before the triggering line. Maybe the user tried to specify a color as in Java
* Processing, like <code>fill(#FFAA55)</code>, which Python sees as an open paren followed by a
* comment.
*
* <p>This function takes a stab at finding such a thing, and reporting it. Otherwise, it throws a
* slightly less cryptic error message.
*
* @param file
* @param line
* @param column
* @return
*/
private static PythonSketchError noViableAlternative(
final File file, final int lineNo, final int column, final String message) {
if (message.equals("no viable alternative at input '&'")) {
return new PythonSketchError(
C_LIKE_LOGICAL_AND_ERROR_MESSAGE, file.getName(), lineNo, column);
}
if (message.equals("no viable alternative at input '|'")) {
return new PythonSketchError(C_LIKE_LOGICAL_OR_ERROR_MESSAGE, file.getName(), lineNo, column);
}
final PythonSketchError defaultException =
new PythonSketchError(
"Maybe there's an unclosed paren or quote mark somewhere before this line?",
file.getName(),
lineNo,
column);
try {
int lineIndex = 0;
for (final String line : Files.readLines(file, Charsets.UTF_8)) {
final Matcher m = NAKED_COLOR.matcher(line);
if (m.find()) {
final String color = m.group(1);
return new PythonSketchError(
"Did you try to name a color here? "
+ "Colors in Python mode are either strings, like '#"
+ color
+ "', or "
+ "large hex integers, like 0xFF"
+ color.toUpperCase()
+ ".",
file.getName(),
lineIndex,
m.start(1));
}
lineIndex++;
}
} catch (final IOException e) {
System.err.println("While trying to read " + file + ": " + e.getMessage());
return defaultException;
}
return defaultException;
}
private static String maybeMakeFriendlyMessage(final String message) {
if (message.contains("expecting INDENT")) {
return "This line probably needs to be indented.";
}
if (message.contains("mismatched input '//'")) {
return "Did you mean to make a comment? "
+ "Comments in Python use the # character, not the double-slash.";
}
return message;
}
@Override
public void frameMoved(final int x, final int y) {
if (sketchPositionListener != null) {
sketchPositionListener.sketchMoved(new Point(x, y));
}
}
public PAppletJythonDriver(
final InteractiveConsole interp,
final String pySketchPath,
final String programText,
final Printer stdout)
throws PythonSketchError {
this.wrappedStdout =
new WrappedPrintStream(System.out) {
@Override
public void doPrint(final String s) {
stdout.print(s);
}
};
this.programText = programText;
this.pySketchPath = Paths.get(pySketchPath);
this.interp = interp;
this.builtins = (PyStringMap) interp.getSystemState().getBuiltins();
interp.set("__file__", Py.newStringUTF8(new File(pySketchPath).getName()));
processSketch(DETECT_MODE_SCRIPT);
this.mode = Mode.valueOf(interp.get("__mode__").asString());
Runner.log("Mode: ", mode.name());
if (mode == Mode.MIXED) {
throw interp.get("__error__", MixedModeError.class);
}
if (mode == Mode.STATIC) {
processSketch(GET_SETTINGS_SCRIPT);
detectedWidth = interp.get("__width__").asInt();
detectedHeight = interp.get("__height__").asInt();
detectedPixelDensity = interp.get("__pixelDensity__").asInt();
detectedSmooth = interp.get("__smooth__").asInt() != 0;
detectedNoSmooth = interp.get("__noSmooth__").asInt() != 0;
final String r = interp.get("__renderer__").asString();
if (r.equals("JAVA2D")) {
detectedRenderer = JAVA2D;
} else if (r.equals("P2D")) {
detectedRenderer = P2D;
} else if (r.equals("P3D")) {
detectedRenderer = P3D;
} else if (r.equals("OPENGL")) {
detectedRenderer = P3D;
} else if (r.equals("FX2D")) {
detectedRenderer = FX2D;
} else if (r.equals("PDF")) {
detectedRenderer = PDF;
} else if (r.equals("SVG")) {
detectedRenderer = SVG;
} else if (r.equals("DXF")) {
detectedRenderer = DXF;
} else {
detectedRenderer = r;
}
processedStaticSketch = interp.get("__cleaned_sketch__");
}
initializeStatics(builtins);
setFilter();
setMap();
setSet();
setColorMethods();
setText();
// Make sure key and keyCode are defined.
builtins.__setitem__("key", Py.newUnicode((char) 0));
builtins.__setitem__("keyCode", pyint(0));
}
// method to find the frame field, rather than relying on an Exception
private Field getFrameField() {
for (Field field : getClass().getFields()) {
if (field.getName().equals("frame")) {
return field;
}
}
return null;
}
@Override
protected PSurface initSurface() {
final PSurface s = super.initSurface();
frameField = getFrameField();
if (frameField != null) {
try {
// eliminate a memory leak from 2.x compat hack
frameField.set(this, null);
} catch (Exception e) {
// safe enough to ignore; this was a workaround
}
}
s.setTitle(pySketchPath.getFileName().toString().replaceAll("\\..*$", ""));
if (s instanceof PSurfaceAWT) {
final PSurfaceAWT surf = (PSurfaceAWT) s;
final Component c = (Component) surf.getNative();
c.addComponentListener(
new ComponentAdapter() {
@Override
public void componentHidden(final ComponentEvent e) {
finishedLatch.countDown();
}
});
} else if (s instanceof PSurfaceJOGL) {
final PSurfaceJOGL surf = (PSurfaceJOGL) s;
final GLWindow win = (GLWindow) surf.getNative();
win.addWindowListener(
new com.jogamp.newt.event.WindowAdapter() {
@Override
public void windowDestroyed(final com.jogamp.newt.event.WindowEvent arg0) {
finishedLatch.countDown();
}
});
} else if (s instanceof PSurfaceFX) {
System.err.println("I don't know how to watch FX2D windows for close.");
}
final PyObject pyG;
if (g instanceof PGraphicsOpenGL) {
/*
* The name "camera" in PGraphicsOpenGL can refer to either a PMatrix3D field
* or a couple of functions of that name. Unfortunately, Python only has one namespace,
* not separate namespaces for functions and fields. So here we create new attributes
* on the "g" object that are aliases to the matrix fields. It's only necessary to
* do this for "camera" itself, but, for the sake of consistency, we do it for
* all of them.
*
* So, in Python Mode:
*
* def setup():
* size(300, 300, P3D)
*
* def mousePressed():
* # do something silly to the PGraphics camera
* g.camera(1, 2, 3, 4, 5, 6, 7, 8, 9)
*
* # read back what we did
* print g.cameraMatrix.m02
*/
final PGraphicsOpenGL glGraphics = (PGraphicsOpenGL) g;
final PyObject cameraMatrix = Py.java2py(glGraphics.camera);
final PyObject cameraInvMatrix = Py.java2py(glGraphics.cameraInv);
final PyObject modelviewMatrix = Py.java2py(glGraphics.modelview);
final PyObject modelviewInvMatrix = Py.java2py(glGraphics.modelviewInv);
final PyObject projmodelviewMatrix = Py.java2py(glGraphics.projmodelview);
pyG =
new PyObjectDerived(PyType.fromClass(g.getClass(), false)) {
@Override
public PyObject __findattr_ex__(final String name) {
if (name == "cameraMatrix") { // name is interned
return cameraMatrix;
}
if (name == "cameraInvMatrix") {
return cameraInvMatrix;
}
if (name == "modelviewMatrix") {
return modelviewMatrix;
}
if (name == "modelviewInvMatrix") {
return modelviewInvMatrix;
}
if (name == "projmodelviewMatrix") {
return projmodelviewMatrix;
}
return super.__findattr_ex__(name);
}
};
JyAttribute.setAttr(pyG, JyAttribute.JAVA_PROXY_ATTR, g);
} else {
pyG = Py.java2py(g);
}
// We want the builtin "g" object to behave just like PGraphics instances
// created with createGraphics(), so that its beginPGL can be used in a with
// statement, etc.
interp.set("__original_g__", pyG);
final PyObject wrappedG = interp.eval("PGraphicsPythonModeWrapper(__original_g__)");
builtins.__setitem__("g", wrappedG);
return s;
}
@Override
public void exitActual() {
finishedLatch.countDown();
}
/** Call the user-defined Python function with the given name. */
@Override
public void method(final String name) {
final PyFunction f = allFunctionsByName.get(name);
if (f != null) {
f.__call__();
} else {
super.method(name);
}
}
/**
* Python Mode's {@link PApplet#thread(String)} can take a {@link String} (like Java mode) or a
* function object.
*
* @param obj either a {@link PyString} or a {@link PyFunction} to run in a thread.
*/
public void thread(final Object obj) {
if (obj instanceof String) {
super.thread((String) obj);
} else if (obj instanceof PyFunction) {
new Thread() {
@Override
public void run() {
((PyFunction) obj).__call__();
}
}.start();
}
}
public void findSketchMethods() throws PythonSketchError {
if (mode == Mode.ACTIVE) {
// Executing the sketch will bind method names ("draw") to PyCode
// objects (the sketch's draw method), which can then be invoked
// during the run loop
processSketch(PREPROCESS_SCRIPT);
}
for (final Object local : ((PyStringMap) interp.getLocals()).items()) {
final PyTuple t = (PyTuple) local;
final String k = t.get(0).toString();
final Object v = t.get(1);
if (v instanceof PyFunction) {
allFunctionsByName.put(k, (PyFunction) v);
}
}
// Find and cache any PApplet callbacks defined in the Python sketch
drawMeth = interp.get("draw");
setupMeth = interp.get("setup");
mousePressedFunc =
new EventFunction<MouseEvent>("mousePressed") {
@Override
protected void callSuper(final MouseEvent event) {
PAppletJythonDriver.super.mousePressed(event);
}
};
mouseClickedFunc =
new EventFunction<MouseEvent>("mouseClicked") {
@Override
protected void callSuper(final MouseEvent event) {
PAppletJythonDriver.super.mouseClicked(event);
}
};
mouseMovedFunc =
new EventFunction<MouseEvent>("mouseMoved") {
@Override
protected void callSuper(final MouseEvent event) {
PAppletJythonDriver.super.mouseMoved(event);
}
};
mouseReleasedFunc =
new EventFunction<MouseEvent>("mouseReleased") {
@Override
protected void callSuper(final MouseEvent event) {
PAppletJythonDriver.super.mouseReleased(event);
}
};
mouseDraggedFunc =
new EventFunction<MouseEvent>("mouseDragged") {
@Override
protected void callSuper(final MouseEvent event) {
PAppletJythonDriver.super.mouseDragged(event);
}
};
// keyPressed is renamed to __keyPressed__ by the preprocessor.
keyPressedFunc =
new EventFunction<KeyEvent>("__keyPressed__") {
@Override
protected void callSuper(final KeyEvent event) {
PAppletJythonDriver.super.keyPressed(event);
}
};
keyReleasedFunc =
new EventFunction<KeyEvent>("keyReleased") {
@Override
protected void callSuper(final KeyEvent event) {
PAppletJythonDriver.super.keyReleased(event);
}
};
keyTypedFunc =
new EventFunction<KeyEvent>("keyTyped") {
@Override
protected void callSuper(final KeyEvent event) {
PAppletJythonDriver.super.keyTyped(event);
}
};
settingsMeth = interp.get("settings");
stopMeth = interp.get("stop");
disposeMeth = interp.get("dispose");
pauseMeth = interp.get("pause");
resumeMeth = interp.get("resume");
mouseWheelMeth = interp.get("mouseWheel");
if (mousePressedFunc.func != null) {
// The user defined a mousePressed() method, which will hide the magical
// Processing variable boolean mousePressed. We have to do some magic.
interp
.getLocals()
.__setitem__(
"mousePressed",
new PyBoolean(false) {
@Override
public boolean getBooleanValue() {
return mousePressed;
}
@Override
public PyObject __call__(final PyObject[] args, final String[] kws) {
return mousePressedFunc.func.__call__(args, kws);
}
});
}
// Video library callbacks.
captureEventMeth = interp.get("captureEvent");
movieEventMeth = interp.get("movieEvent");
// Serial library callback.
serialEventMeth = interp.get("serialEvent");
// Net library callbacks.
clientEventMeth = interp.get("clientEvent");
disconnectEventMeth = interp.get("disconnectEvent");
serverEventMeth = interp.get("serverEvent");
// oscP5 library callback.
oscEventMeth = interp.get("oscEvent");
// themidibus callbacks
PyObject meth;
if ((meth = interp.get("noteOn")) != null) {
switch (argCount(meth)) {
default:
throw new RuntimeException(
"only noteOn(channel, pitch, velocity) or "
+ "noteOn(channel, pitch, velocity, timestamp, bus_name) "
+ "are supported by Python Mode");
case 3:
noteOn3Meth = meth;
break;
case 5:
noteOn5Meth = meth;
}
}
if ((meth = interp.get("noteOff")) != null) {
switch (argCount(meth)) {
case 1:
throw new RuntimeException(
"only noteOff(channel, pitch, velocity) or "
+ "noteOff(channel, pitch, velocity, timestamp, bus_name) "
+ "are supported by Python Mode");
case 3:
noteOff3Meth = meth;
break;
case 5:
noteOff5Meth = meth;
}
}
if ((meth = interp.get("controllerChange")) != null) {
switch (argCount(meth)) {
case 1:
throw new RuntimeException(
"only controllerChange(channel, pitch, velocity) or "
+ "controllerChange(channel, pitch, velocity, timestamp, bus_name) "
+ "are supported by Python Mode");
case 3:
controllerChange3Meth = meth;
break;
case 5:
controllerChange5Meth = meth;
}
}
if ((meth = interp.get("rawMidi")) != null) {
switch (argCount(meth)) {
case 1:
rawMidi1Meth = meth;
break;
case 3:
rawMidi3Meth = meth;
}
}
if ((meth = interp.get("midiMessage")) != null) {
switch (argCount(meth)) {
case 1:
midiMessage1Meth = meth;
break;
case 3:
midiMessage3Meth = meth;
}
}
// processing_websockets callbacks.
webSocketEventMeth = interp.get("webSocketEvent");
webSocketServerEventMeth = interp.get("webSocketServerEvent");
}
/*
* Most of the time we're wrapping small, positive integers (like the mouse
* position, the keyCode, and the frameCount). So we pre-allocate a bunch of
* them to avoid garbage collection.
*/
private static final PyInteger[] CHEAP_INTS = new PyInteger[20000];
static {
for (int i = 0; i < CHEAP_INTS.length; i++) {
CHEAP_INTS[i] = Py.newInteger(i);
}
}
private static PyInteger pyint(final int i) {
return i >= 0 && i < CHEAP_INTS.length ? CHEAP_INTS[i] : Py.newInteger(i);
}
@Override
public void focusGained() {
super.focusGained();
builtins.__setitem__("focused", Py.newBoolean(focused));
}
@Override
public void focusLost() {
super.focusLost();
builtins.__setitem__("focused", Py.newBoolean(focused));
}
protected void wrapProcessingVariables() {
wrapMouseVariables();
wrapKeyVariables();
builtins.__setitem__("width", pyint(width));
builtins.__setitem__("height", pyint(height));
builtins.__setitem__("displayWidth", pyint(displayWidth));
builtins.__setitem__("displayHeight", pyint(displayHeight));
builtins.__setitem__("focused", Py.newBoolean(focused));
builtins.__setitem__("keyPressed", Py.newBoolean(keyPressed));
builtins.__setitem__("frameCount", pyint(frameCount));
builtins.__setitem__(
"frameRate",
new PyFloat(frameRate) {
@Override
public PyObject __call__(final PyObject[] args, final String[] kws) {
switch (args.length) {
default:
return raiseTypeError(
"Can't call \"frameRate\" with " + args.length + " parameters.");
case 1:
frameRate((float) args[0].asDouble());
return Py.None;
}
}
});
}
// We only change the "key" variable as necessary to avoid generating
// lots of PyUnicode garbage.
private char lastKey = Character.MIN_VALUE;
private void wrapKeyVariables() {
if (lastKey != key) {
lastKey = key;
/*
* If key is "CODED", i.e., an arrow key or other non-printable, pass that
* value through as-is. If it's printable, convert it to a unicode string,
* so that the user can compare key == 'x' instead of key == ord('x').
*/
final PyObject pyKey = key == CODED ? pyint(key) : Py.newUnicode(key);
builtins.__setitem__("key", pyKey);
}
builtins.__setitem__("keyCode", pyint(keyCode));
}
private void wrapMouseVariables() {
builtins.__setitem__("mouseX", pyint(mouseX));
builtins.__setitem__("mouseY", pyint(mouseY));
builtins.__setitem__("pmouseX", pyint(pmouseX));
builtins.__setitem__("pmouseY", pyint(pmouseY));
builtins.__setitem__("mouseButton", pyint(mouseButton));
if (mousePressedFunc.func == null) {
builtins.__setitem__("mousePressed", Py.newBoolean(mousePressed));
}
}
@Override
public void start() {
// I want to quit on runtime exceptions.
// Processing just sits there by default.
Thread.setDefaultUncaughtExceptionHandler(
new UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
terminalException = toSketchException(e);
try {
handleMethods("dispose");
} catch (final Exception noop) {
// give up
}
finishedLatch.countDown();
}
});
super.start();
}
private void bringToFront() {
if (PApplet.platform == PConstants.MACOSX) {
OSX.bringToFront();
}
}
public void runAndBlock(final String[] args) throws PythonSketchError {
PApplet.runSketch(args, this);
bringToFront();
try {
finishedLatch.await();
} catch (final InterruptedException interrupted) {
// Treat an interruption as a request to the applet to terminate.
exit();
try {
finishedLatch.await();
} catch (final InterruptedException e) {
// fallthrough
}
} finally {
try {
if (stopMeth != null) {
stopMeth.__call__();
}
if (disposeMeth != null) {
disposeMeth.__call__();
}
} catch (Throwable t) {
System.err.println("while disposing: " + t);
}
maybeShutdownSoundEngine();
Thread.setDefaultUncaughtExceptionHandler(null);
if (PApplet.platform == PConstants.MACOSX && Arrays.asList(args).contains("fullScreen")) {
// Frame should be OS-X fullscreen, and it won't stop being that unless the jvm
// exits or we explicitly tell it to minimize.
// (If it's disposed, it'll leave a gray blank window behind it.)
Runner.log("Disabling fullscreen.");
if (frameField != null) {
try {
Frame frameObj = (Frame) frameField.get(this);
macosxFullScreenToggle(frameObj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (surface instanceof PSurfaceFX) {
// Sadly, JavaFX is an abomination, and there's no way to run an FX sketch more than once,
// so we must actually exit.
Runner.log("JavaFX requires SketchRunner to terminate. Farewell!");
System.exit(0);
}
final Object nativeWindow = surface.getNative();
if (nativeWindow instanceof com.jogamp.newt.Window) {
((com.jogamp.newt.Window) nativeWindow).destroy();
} else {
surface.setVisible(false);
}
}
if (terminalException != null) {
throw terminalException;
}
}
/**
* The sound library is designed to depend on exiting the VM when the sketch
* exits, or rather, it's not designed to work if startup up with one
* PApplet, but then attempted to be used with another. This hack nukes
* the Engine singleton so that it has to be re-instantiated on the next
* run.
*/
private void maybeShutdownSoundEngine() {
try {
final Class<?> appClass = Class.forName("processing.sound.Engine");
final Field singleton = appClass.getDeclaredField("singleton");
singleton.setAccessible(true);
singleton.set(null, null);
} catch (final ClassNotFoundException cnfe) {
// ignored
} catch (final Exception e) {
e.printStackTrace();
}
}
/**
* Use reflection to call <code>
* com.apple.eawt.Application.getApplication().requestToggleFullScreen(window);</code>
*/
private static void macosxFullScreenToggle(final Window window) {
try {
final Class<?> appClass = Class.forName("com.apple.eawt.Application");
final Method getAppMethod = appClass.getMethod("getApplication");
final Object app = getAppMethod.invoke(null);
final Method requestMethod = appClass.getMethod("requestToggleFullScreen", Window.class);
requestMethod.invoke(app, window);