-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathRLangPApplet.java
More file actions
538 lines (482 loc) · 15.5 KB
/
Copy pathRLangPApplet.java
File metadata and controls
538 lines (482 loc) · 15.5 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
package rprocessing;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.script.ScriptException;
import org.renjin.parser.RParser;
import org.renjin.sexp.Closure;
import org.renjin.sexp.ExpressionVector;
import org.renjin.sexp.FunctionCall;
import org.renjin.sexp.SEXP;
import org.renjin.sexp.Symbol;
import com.jogamp.newt.opengl.GLWindow;
import processing.awt.PSurfaceAWT;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PSurface;
import processing.event.KeyEvent;
import processing.event.MouseEvent;
import processing.javafx.PSurfaceFX;
import processing.opengl.PSurfaceJOGL;
import rprocessing.applet.BuiltinApplet;
import rprocessing.exception.NotFoundException;
import rprocessing.exception.RSketchError;
import rprocessing.util.Constant;
import rprocessing.util.Printer;
import rprocessing.util.RScriptReader;
/**
* RlangPApplet PApplet for R language, powered by Renjin.
*
* @author github.com/gaocegege
*/
public class RLangPApplet extends BuiltinApplet {
private static final boolean VERBOSE = Boolean.parseBoolean(System.getenv("VERBOSE_RLANG_MODE"));
// 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;
/** Program code */
private final String programText;
private ExpressionVector expressionVector;
private static final String CORE_TEXT =
RScriptReader.readResourceAsText(Runner.class, "r/core.R");
private final Printer stdout;
private final CountDownLatch finishedLatch = new CountDownLatch(1);
private Field frameField;
private RSketchError terminalException = null;
private boolean hasSize = false;
private SEXP sizeFunction = null;
/**
* Mode for Processing.
*
* @author github.com/gaocegege
*/
private enum Mode {
STATIC, ACTIVE, MIXED
}
private static void log(String msg) {
if (!VERBOSE) {
return;
}
System.err.println(RLangPApplet.class.getSimpleName() + ": " + msg);
}
public RLangPApplet(final String programText, final Printer stdout) throws NotFoundException {
this.programText = programText;
this.stdout = stdout;
this.prePassCode();
// Detect the mode after pre-pass program code.
this.mode = this.detectMode();
}
public void evaluateCoreCode() throws RSketchError {
try {
this.renjinEngine.eval(CORE_TEXT);
} catch (final ScriptException se) {
throw RSketchError.toSketchException(se);
}
}
/**
* Evaluate all the function calls.
*/
public void prePassCode() {
SEXP source = RParser.parseSource(this.programText + "\n", "inline-string");
if (isSameClass(source, ExpressionVector.class)) {
ExpressionVector ev = (ExpressionVector) source;
// Stores the expressions except size().
List<SEXP> sexps = new ArrayList<>();
for (int i = ev.length() - 1; i >= 0; --i) {
if (isSameClass(ev.get(i), FunctionCall.class)
&& isSameClass(((FunctionCall) ev.get(i)).getFunction(), Symbol.class)) {
if (((Symbol) ((FunctionCall) ev.get(i)).getFunction()).getPrintName().equals("<-")) {
this.renjinEngine.getTopLevelContext().evaluate(ev.get(i),
this.renjinEngine.getTopLevelContext().getEnvironment());
sexps.add(ev.get(i));
} else if (((Symbol) ((FunctionCall) ev.get(i)).getFunction()).getPrintName()
.equals(Constant.SIZE_NAME)) {
// size function is defined in global namespace.
log("size function is defined in global namespace.");
hasSize = true;
sizeFunction = ev.get(i);
} else {
sexps.add(ev.get(i));
}
}
}
expressionVector = new ExpressionVector(sexps);
}
}
/**
* Detect the mode. After: prePassCode()
*/
private Mode detectMode() {
if (isActiveMode()) {
if (isMixMode()) {
return Mode.MIXED;
}
return Mode.ACTIVE;
}
return Mode.STATIC;
}
/**
* Add PApplet instance to R top context Notice: DO NOT do it in constructor.
*/
public void addPAppletToRContext() {
this.renjinEngine.put(Constant.PROCESSING_VAR_NAME, this);
// This is a trick to be deprecated. It is used to print
// messages in Processing app console by stdout$print(msg).
this.renjinEngine.put("stdout", stdout);
this.renjinEngine.put("key", "0");
this.renjinEngine.put("keyCode", 0);
}
public void runBlock(final String[] arguments) throws RSketchError {
log("runBlock");
PApplet.runSketch(arguments, this);
try {
finishedLatch.await();
log("RunSketch done.");
} catch (final InterruptedException interrupted) {
// Treat an interruption as a request to the applet to terminate.
exit();
try {
finishedLatch.await();
log("RunSketch interrupted.");
} catch (final InterruptedException exception) {
log(exception.toString());
}
} finally {
Thread.setDefaultUncaughtExceptionHandler(null);
if (PApplet.platform == PConstants.MACOSX
&& Arrays.asList(arguments).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.)
log("Disabling fullscreen.");
if (frameField != null) {
try {
Frame frame = (Frame) frameField.get(this);
// This is probably a holdover from Processing 2.x
// and likely shouldn't be used anymore. [fry 210703]
macosxFullScreenToggle(frame);
} catch (Exception e) {
// safe enough to ignore; this was a workaround
}
}
}
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.
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);
}
}
// log(terminalException.toString());
if (terminalException != null) {
log("Throw the exception to PDE.");
throw terminalException;
}
}
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);
} catch (final ClassNotFoundException cnfe) {
// ignored
} catch (final Exception exception) {
exception.printStackTrace();
}
}
// 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;
}
/**
*
* @see processing.core.PApplet#initSurface()
*/
@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) {
log("initSurface");
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) {
log("initSurface");
finishedLatch.countDown();
}
});
} else if (s instanceof PSurfaceFX) {
System.err.println("I don't know how to watch FX2D windows for close.");
}
return s;
}
@Override
public void exitActual() {
log("exitActual");
finishedLatch.countDown();
}
/**
* @see processing.core.PApplet#start()
*/
@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 = RSketchError.toSketchException(e);
try {
log("There is an unexpected exception.");
handleMethods("dispose");
} catch (final Exception noop) {
// give up
}
finishedLatch.countDown();
}
});
super.start();
}
/**
* @see processing.core.PApplet#settings()
*/
@Override
public void settings() {
if (mode == Mode.MIXED || mode == Mode.STATIC) {
this.renjinEngine.getTopLevelContext().evaluate(this.sizeFunction,
this.renjinEngine.getTopLevelContext().getEnvironment());
}
applyFunction(Constant.SETTINGS_NAME);
}
/**
* Evaluate the program code.
*
* @see processing.core.PApplet#setup()
*/
@Override
public void setup() {
// I don't know why I put it there. Now I think it should be in constructor.
// But I ...
wrapProcessingVariables();
if (this.mode == Mode.STATIC) {
try {
log("The mode is static, run the program directly.");
// The code includes size function but it would not raise a error, I don't know what happens
// although it works well.
this.renjinEngine.eval(this.programText);
log("Evaluate the code in static mode.");
} catch (final Exception exception) {
log("There is exception when evaluate the code in static mode.");
log(exception.toString());
terminalException = RSketchError.toSketchException(exception);
exitActual();
}
} else if (this.mode == Mode.ACTIVE) {
Object obj = this.renjinEngine.get(Constant.SETUP_NAME);
if (obj.getClass().equals(Closure.class)) {
((Closure) obj).doApply(this.renjinEngine.getTopLevelContext());
}
} else {
System.out.println("The program is in mix mode now.");
applyFunction(Constant.SETUP_NAME);
}
log("Setup done");
}
@Override
public void handleDraw() {
super.handleDraw();
this.wrapFrameVariables();
}
/**
* Call the draw function in R script.
*
* @see processing.core.PApplet#draw()
*/
@Override
public void draw() {
applyFunction(Constant.DRAW_NAME);
}
/*
* Helper functions
*/
/**
* Detect whether the program is in active mode.
*
* @return
*/
@SuppressWarnings("rawtypes")
private boolean isActiveMode() {
Class closureClass = Closure.class;
return isSameClass(this.renjinEngine.get(Constant.SETTINGS_NAME), closureClass)
|| isSameClass(this.renjinEngine.get(Constant.SETUP_NAME), closureClass)
|| isSameClass(this.renjinEngine.get(Constant.DRAW_NAME), closureClass);
}
/**
* Detect whether the program is in mix mode. After: isActiveMode()
*
* @return
*/
private boolean isMixMode() {
return hasSize;
}
protected void wrapFrameVariables() {
this.renjinEngine.put("frameRateVar", frameRate);
this.renjinEngine.put("frameCount", frameCount);
}
/**
* Set Environment variables in R top context.
*/
protected void wrapProcessingVariables() {
log("Wrap Processing built-in variables into R top context.");
this.wrapMouseVariables();
this.wrapKeyVariables();
this.renjinEngine.put("width", width);
this.renjinEngine.put("height", height);
this.renjinEngine.put("displayWidth", displayWidth);
this.renjinEngine.put("displayHeight", displayHeight);
this.renjinEngine.put("focused", focused);
this.renjinEngine.put("pixelWidth", pixelWidth);
this.renjinEngine.put("pixelHeight", pixelHeight);
}
@Override
protected void handleMouseEvent(MouseEvent event) {
super.handleMouseEvent(event);
wrapMouseVariables();
}
@Override
public void mouseClicked() {
wrapMouseVariables();
applyFunction(Constant.MOUSECLICKED_NAME);
}
@Override
public void mouseMoved() {
wrapMouseVariables();
applyFunction(Constant.MOUSEMOVED_NAME);
}
@Override
public void mousePressed() {
wrapMouseVariables();
applyFunction(Constant.MOUSEPRESSED_NAME);
}
@Override
public void mouseReleased() {
wrapMouseVariables();
applyFunction(Constant.MOUSERELEASED_NAME);
}
@Override
public void mouseDragged() {
wrapMouseVariables();
applyFunction(Constant.MOUSEDRAGGED_NAME);
}
/**
*
* @see processing.core.PApplet#focusGained()
*/
@Override
public void focusGained() {
super.focusGained();
this.renjinEngine.put("focused", super.focused);
}
/**
*
* @see processing.core.PApplet#focusLost()
*/
@Override
public void focusLost() {
super.focusLost();
this.renjinEngine.put("focused", super.focused);
}
private void wrapMouseVariables() {
this.renjinEngine.put("mouseX", mouseX);
this.renjinEngine.put("mouseY", mouseY);
this.renjinEngine.put("pmouseX", pmouseX);
this.renjinEngine.put("pmouseY", pmouseY);
this.renjinEngine.put("mouseButtonVar", mouseButton);
this.renjinEngine.put("mousePressedVar", mousePressed);
}
private void applyFunction(String name) {
Object obj = this.renjinEngine.get(name);
if (obj.getClass().equals(Closure.class)) {
((Closure) obj).doApply(this.renjinEngine.getTopLevelContext());
}
}
@Override
protected void handleKeyEvent(KeyEvent event) {
super.handleKeyEvent(event);
wrapKeyVariables();
}
@Override
public void keyPressed() {
wrapKeyVariables();
applyFunction(Constant.KEYPRESSED_NAME);
}
@Override
public void keyReleased() {
wrapKeyVariables();
applyFunction(Constant.KEYRELEASED_NAME);
}
@Override
public void keyTyped() {
wrapKeyVariables();
applyFunction(Constant.KEYTYPED_NAME);
}
protected void wrapKeyVariables() {
this.renjinEngine.put("key", String.valueOf(key));
this.renjinEngine.put("keyCode", keyCode);
this.renjinEngine.put("keyPressedVar", keyPressed);
}
/**
* Return whether the object has same class with clazz.
*
* @param obj
* @param clazz
* @return
*/
@SuppressWarnings("rawtypes")
private static boolean isSameClass(Object obj, Class clazz) {
return obj.getClass().equals(clazz);
}
}