new size() parsing, change how P2D/P3D are handled, onward...

This commit is contained in:
benfry
2012-04-03 14:57:13 +00:00
parent 0a560a2226
commit f0c2ef79b6
14 changed files with 3201 additions and 2971 deletions

View File

@@ -87,13 +87,13 @@ public class Sketch {
// private ArrayList<Library> importedLibraries;
// //private ArrayList<File> importedLibraries;
/**
/**
* Most recent, default build path. This will contain the .java files that
* have been preprocessed, as well as any .class files that were compiled.
* have been preprocessed, as well as any .class files that were compiled.
*/
// private File buildFolder;
/**
* path is location of the main .pde file, because this is also
* simplest to use when opening the file from the finder/explorer.
@@ -134,7 +134,7 @@ public class Sketch {
load();
}
/**
* Build the list of files.
@@ -215,8 +215,8 @@ public class Sketch {
}
/**
* Reload the current sketch. Used to update the text area when
/**
* Reload the current sketch. Used to update the text area when
* an external editor is in use.
*/
public void reload() {
@@ -432,7 +432,7 @@ public class Sketch {
"\"" + newName + "\" already exists.", null);
return;
}
// renaming the containing sketch folder
boolean success = folder.renameTo(newFolder);
if (!success) {
@@ -632,7 +632,7 @@ public class Sketch {
public void setModified(boolean state) {
//System.out.println("setting modified to " + state);
//new Exception().printStackTrace(System.out);
if (current.isModified() != state) {
if (current.isModified() != state) {
current.setModified(state);
calcModified();
}
@@ -792,7 +792,7 @@ public class Sketch {
}
} catch (IOException e) { }
// if the new folder already exists, then first remove its contents before
// if the new folder already exists, then first remove its contents before
// copying everything over (user will have already been warned)
if (newFolder.exists()) {
Base.removeDir(newFolder);
@@ -828,7 +828,7 @@ public class Sketch {
return false;
}
}
// don't do screen captures, since there might be thousands. kind of
// don't do screen captures, since there might be thousands. kind of
// a hack, but seems harmless. hm, where have i heard that before...
if (name.startsWith("screen-")) {
return false;
@@ -839,7 +839,7 @@ public class Sketch {
// now copy over the items that make sense
for (File copyable : copyItems) {
if (copyable.isDirectory()) {
Base.copyDir(copyable, new File(newFolder, copyable.getName()));
Base.copyDir(copyable, new File(newFolder, copyable.getName()));
} else {
Base.copyFile(copyable, new File(newFolder, copyable.getName()));
}
@@ -863,19 +863,19 @@ public class Sketch {
// let Editor know that the save was successful
return true;
}
/**
/**
* Update internal state for new sketch name or folder location.
*/
protected void updateInternal(String sketchName, File sketchFolder) {
// reset all the state information for the sketch object
// reset all the state information for the sketch object
primaryFile = code[0].getFile();
name = sketchName;
folder = sketchFolder;
codeFolder = new File(folder, "code");
dataFolder = new File(folder, "data");
// set the main file to be the current tab
//setCurrentCode(0);
// nah, this might just annoy people
@@ -1067,7 +1067,7 @@ public class Sketch {
* </OL>
*/
public void setCurrentCode(int which) {
// // for the tab sizing
// // for the tab sizing
// if (current != null) {
// current.visited = System.currentTimeMillis();
// System.out.println(current.visited);
@@ -1110,7 +1110,7 @@ public class Sketch {
}
/**
/**
* Create a temporary folder that includes the sketch's name in its title.
*/
public File makeTempFolder() {
@@ -1120,11 +1120,11 @@ public class Sketch {
return buildFolder;
// } else {
// Base.showWarning("Build folder bad",
// Base.showWarning("Build folder bad",
// "Could not create a place to build the sketch.", null);
// }
} catch (IOException e) {
Base.showWarning("Build folder bad",
Base.showWarning("Build folder bad",
"Could not find a place to build the sketch.", e);
}
return null;
@@ -1281,7 +1281,7 @@ public class Sketch {
return dataFolder;
}
public boolean hasDataFolder() {
return dataFolder.exists();
}
@@ -1364,6 +1364,11 @@ public class Sketch {
}
public String getMainProgram() {
return getCode(0).getProgram();
}
public void setUntitled(boolean u) {
editor.untitled = u;
}
@@ -1448,8 +1453,8 @@ public class Sketch {
}
return buffer.toString();
}
public Mode getMode() {
return mode;
}

View File

@@ -120,9 +120,12 @@ class AndroidBuild extends JavaBuild {
// build the preproc and get to work
AndroidPreprocessor preproc = new AndroidPreprocessor(sketch, getPackageName());
if (!preproc.parseSketchSize()) {
throw new SketchException("Could not parse the size() command.");
}
// if (!preproc.parseSketchSize()) {
// String[] sizeInfo = PdePreprocessor.parseSketchSize(sketch.getMainProgram());
// if (sizeInfo == null) {
// throw new SketchException("Could not parse the size() command.");
// }
preproc.initSketchSize(sketch.getMainProgram());
sketchClassName = preprocess(srcFolder, manifest.getPackageName(), preproc);
if (sketchClassName != null) {
File tempManifest = new File(tmpFolder, "AndroidManifest.xml");

View File

@@ -26,10 +26,7 @@ import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import processing.app.Base;
import processing.app.Preferences;
import processing.app.Sketch;
import processing.app.SketchException;
import processing.app.*;
import processing.core.PApplet;
import processing.mode.java.preproc.PdePreprocessor;
import processing.mode.java.preproc.PreprocessorResult;
@@ -41,11 +38,6 @@ public class AndroidPreprocessor extends PdePreprocessor {
Sketch sketch;
String packageName;
String sizeStatement;
String sketchWidth;
String sketchHeight;
String sketchRenderer;
public AndroidPreprocessor(final Sketch sketch,
final String packageName) throws IOException {
@@ -55,8 +47,21 @@ public class AndroidPreprocessor extends PdePreprocessor {
}
// TODO this needs to be a generic function inside Sketch or elsewhere
public String[] initSketchSize(String code) throws SketchException {
String[] info = parseSketchSize(code, true);
if (info == null) {
System.err.println("More about the size() command on Android can be");
System.err.println("found here: http://wiki.processing.org/w/Android");
throw new SketchException("Could not parse the size() command.");
}
sizeStatement = info[0];
sketchWidth = info[1];
sketchHeight = info[2];
sketchRenderer = info[3];
return info;
}
/*
protected boolean parseSketchSize() {
// This matches against any uses of the size() function, whether numbers
// or variables or whatever. This way, no warning is shown if size() isn't
@@ -121,6 +126,7 @@ public class AndroidPreprocessor extends PdePreprocessor {
}
return true;
}
*/
public PreprocessorResult write(Writer out, String program, String[] codeFolderPackages)

View File

@@ -3,7 +3,7 @@
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-11 Ben Fry and Casey Reas
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
@@ -34,16 +34,6 @@ import processing.mode.java.preproc.*;
public class JavaBuild {
/**
* Regular expression for parsing the size() method. This should match
* against any uses of the size() function, whether numbers or variables
* or whatever. This way, no warning is shown if size() isn't actually used
* in the sketch, which is the case especially for anyone who is cutting
* and pasting from the reference.
*/
public static final String SIZE_REGEX =
"(?:^|\\s|;)size\\s*\\(\\s*([^\\s,]+)\\s*,\\s*([^\\s,\\)]+),?\\s*([^\\)]*)\\s*\\)\\s*\\;";
//"(?:^|\\s|;)size\\s*\\(\\s*(\\S+)\\s*,\\s*([^\\s,\\)]+),?\\s*([^\\)]*)\\s*\\)\\s*\\;";
public static final String PACKAGE_REGEX =
"(?:^|\\s|;)package\\s+(\\S+)\\;";
@@ -249,20 +239,24 @@ public class JavaBuild {
}
}
// Automatically insert the OpenGL import line if P3D is used. Do this by
// modifying the code here instead of
String scrubbed = scrubComments(sketch.getCode(0).getProgram());
String[] matches = PApplet.match(scrubbed, SIZE_REGEX);
String renderer = "";
if (matches != null) {
// Adding back the trim() for 0136 to handle Bug #769
if (matches.length == 4) renderer = matches[3].trim();
// Actually, matches.length should always be 4...
}
// OpenGL import time! Really, this is for P3D, but may as well do it
// for OpenGL as well.
if (renderer.equals("P3D") || renderer.equals("OPENGL")) {
bigCode.insert(0, "import processing.opengl.*; ");
// initSketchSize() sets the internal sketchWidth/Height/Renderer vars
// in the preprocessor. Those are used in preproc.write() so that they
// can be turned into sketchXxxx() methods.
// This also returns the size info as an array so that we can figure out
// if this fella is OpenGL, and if so, to add the import. It's messy and
// gross and someday we'll just always include OpenGL.
String[] sizeInfo =
preprocessor.initSketchSize(sketch.getMainProgram());
//PdePreprocessor.parseSketchSize(sketch.getMainProgram(), false);
if (sizeInfo != null) {
String sketchRenderer = sizeInfo[3];
if (sketchRenderer != null) {
if (sketchRenderer.equals("P2D") ||
sketchRenderer.equals("P3D") ||
sketchRenderer.equals("OPENGL")) {
bigCode.insert(0, "import processing.opengl.*; ");
}
}
}
PreprocessorResult result;
@@ -298,7 +292,7 @@ public class JavaBuild {
// System.out.println(errorLine + " " + errorFile + " " + code[errorFile].getPreprocOffset());
String msg = re.getMessage();
//System.out.println(java.getAbsolutePath());
System.out.println(bigCode);
@@ -313,7 +307,7 @@ public class JavaBuild {
"without a } to match it.",
errorFile, errorLine, re.getColumn(), false);
}
if (msg.contains("expecting LCURLY")) {
System.err.println(msg);
String suffix = ".";
@@ -321,7 +315,7 @@ public class JavaBuild {
if (m != null) {
suffix = ", not " + m[1] + ".";
}
throw new SketchException("Was expecting a { character" + suffix,
throw new SketchException("Was expecting a { character" + suffix,
errorFile, errorLine, re.getColumn(), false);
}
@@ -365,7 +359,7 @@ public class JavaBuild {
// TODO not tested since removing ORO matcher.. ^ could be a problem
String mess = "^line (\\d+):(\\d+):\\s";
matches = PApplet.match(tsre.toString(), mess);
String[] matches = PApplet.match(tsre.toString(), mess);
if (matches != null) {
int errorLine = Integer.parseInt(matches[1]) - 1;
int errorColumn = Integer.parseInt(matches[2]);
@@ -503,7 +497,7 @@ public class JavaBuild {
sc.addPreprocOffset(result.headerOffset);
}
}
foundMain = preprocessor.getFoundMain();
foundMain = preprocessor.hasMethod("main");
return result.className;
}
@@ -730,12 +724,57 @@ public class JavaBuild {
return false;
}
String[] sizeInfo =
PdePreprocessor.parseSketchSize(sketch.getMainProgram(), false);
int sketchWidth = PApplet.DEFAULT_WIDTH;
int sketchHeight = PApplet.DEFAULT_HEIGHT;
boolean openglApplet = false;
boolean foundSize = false;
if (sizeInfo != null) {
try {
if (sizeInfo[1] != null && sizeInfo[2] != null) {
sketchWidth = Integer.parseInt(sizeInfo[1]);
sketchHeight = Integer.parseInt(sizeInfo[2]);
foundSize = true;
}
} catch (Exception e) {
e.printStackTrace();
// parsing errors, whatever; ignored
}
String sketchRenderer = sizeInfo[3];
if (sketchRenderer != null) {
if (sketchRenderer.equals("P2D") ||
sketchRenderer.equals("P3D") ||
sketchRenderer.equals("OPENGL")) {
openglApplet = true;
}
}
}
if (!foundSize) {
final String message =
"The size of this applet could not automatically be\n" +
"determined from your code. You'll have to edit the\n" +
"HTML file to set the size of the applet.\n" +
"Use only numeric values (not variables) for the size()\n" +
"command. See the size() reference for an explanation.";
Base.showWarning("Could not find applet size", message, null);
}
// // If the renderer is set to the built-in OpenGL library,
// // then it's definitely an OpenGL applet.
// if (sketchRenderer.equals("P3D") || sketchRenderer.equals("OPENGL")) {
// openglApplet = true;
// }
/*
int wide = PApplet.DEFAULT_WIDTH;
int high = PApplet.DEFAULT_HEIGHT;
String renderer = "";
String scrubbed = scrubComments(sketch.getCode(0).getProgram());
String[] matches = PApplet.match(scrubbed, SIZE_REGEX);
String scrubbed = PdePreprocessor.scrubComments(sketch.getCode(0).getProgram());
String[] matches = PApplet.match(scrubbed, PdePreprocessor.SIZE_REGEX);
if (matches != null) {
try {
@@ -759,6 +798,7 @@ public class JavaBuild {
Base.showWarning("Could not find applet size", message, null);
}
} // else no size() command found
*/
// Grab the Javadoc-style description from the main code.
String description = "";
@@ -847,7 +887,7 @@ public class JavaBuild {
// File openglLibraryFolder =
// new File(editor.getMode().getLibrariesFolder(), "opengl/library");
// String openglLibraryPath = openglLibraryFolder.getAbsolutePath();
boolean openglApplet = false;
// boolean openglApplet = false;
HashMap<String,Object> zipFileContents = new HashMap<String,Object>();
@@ -942,11 +982,6 @@ public class JavaBuild {
// for (File libraryFolder : importedLibraries) {
// System.out.println(libraryFolder + " " + libraryFolder.getAbsolutePath());
// }
// If the renderer is set to the built-in OpenGL library,
// then it's definitely an OpenGL applet.
if (renderer.equals("P3D") || renderer.equals("OPENGL")) {
openglApplet = true;
}
if (is == null) {
if (openglApplet) {
is = mode.getContentStream("applet/template-opengl.html");
@@ -975,11 +1010,11 @@ public class JavaBuild {
}
while ((index = sb.indexOf("@@width@@")) != -1) {
sb.replace(index, index + "@@width@@".length(),
String.valueOf(wide));
String.valueOf(sketchWidth));
}
while ((index = sb.indexOf("@@height@@")) != -1) {
sb.replace(index, index + "@@height@@".length(),
String.valueOf(high));
String.valueOf(sketchHeight));
}
while ((index = sb.indexOf("@@description@@")) != -1) {
sb.replace(index, index + "@@description@@".length(),
@@ -998,58 +1033,6 @@ public class JavaBuild {
}
/**
* Replace all commented portions of a given String as spaces.
* Utility function used here and in the preprocessor.
*/
static public String scrubComments(String what) {
char p[] = what.toCharArray();
int index = 0;
while (index < p.length) {
// for any double slash comments, ignore until the end of the line
if ((p[index] == '/') &&
(index < p.length - 1) &&
(p[index+1] == '/')) {
p[index++] = ' ';
p[index++] = ' ';
while ((index < p.length) &&
(p[index] != '\n')) {
p[index++] = ' ';
}
// check to see if this is the start of a new multiline comment.
// if it is, then make sure it's actually terminated somewhere.
} else if ((p[index] == '/') &&
(index < p.length - 1) &&
(p[index+1] == '*')) {
p[index++] = ' ';
p[index++] = ' ';
boolean endOfRainbow = false;
while (index < p.length - 1) {
if ((p[index] == '*') && (p[index+1] == '/')) {
p[index++] = ' ';
p[index++] = ' ';
endOfRainbow = true;
break;
} else {
// continue blanking this area
p[index++] = ' ';
}
}
if (!endOfRainbow) {
throw new RuntimeException("Missing the */ from the end of a " +
"/* comment */");
}
} else { // any old character, move along
index++;
}
}
return new String(p);
}
/**
* Export to application via GUI.
*/

View File

@@ -24,7 +24,7 @@ import antlr.collections.AST;
* other than System.out, and then call print(), passing the
* AST. Typically, the AST node that you pass would be the root of a
* tree - the ROOT_ID node that represents a Java file.
*
*
* Modified March 2010 to support Java 5 type arguments and for loops by
* @author Jonathan Feinberg &lt;jdf@pobox.com&gt;
*/
@@ -239,10 +239,11 @@ public class PdeEmitter implements PdeTokenTypes {
type = modifiers.getNextSibling();
}
final AST methodName = type.getNextSibling();
if (methodName.getText().equals("main")) {
pdePreprocessor.setFoundMain(true);
}
printChildren(ast);
// if (methodName.getText().equals("main")) {
// pdePreprocessor.setFoundMain(true);
// }
pdePreprocessor.addMethod(methodName.getText());
printChildren(ast);
}
private void printIfThenElse(final AST literalIf) throws SketchException {
@@ -265,10 +266,10 @@ public class PdeEmitter implements PdeTokenTypes {
dumpHiddenBefore(bestPrintableNode);
final CommonHiddenStreamToken hiddenBefore =
((CommonASTWithHiddenTokens) elsePath).getHiddenBefore();
if (elsePath.getType() == PdeTokenTypes.SLIST && elsePath.getNumberOfChildren() == 0 &&
if (elsePath.getType() == PdeTokenTypes.SLIST && elsePath.getNumberOfChildren() == 0 &&
hiddenBefore == null) {
out.print("{");
final CommonHiddenStreamToken hiddenAfter =
final CommonHiddenStreamToken hiddenAfter =
((CommonASTWithHiddenTokens) elsePath).getHiddenAfter();
if (hiddenAfter == null) {
out.print("}");
@@ -742,11 +743,11 @@ public class PdeEmitter implements PdeTokenTypes {
out.print("@");
printChildren(ast);
break;
case ANNOTATION_ARRAY_INIT:
printChildren(ast);
break;
case ANNOTATION_MEMBER_VALUE_PAIR:
print(ast.getFirstChild());
out.print("=");

View File

@@ -4,7 +4,7 @@
PdePreprocessor - wrapper for default ANTLR-generated parser
Part of the Processing project - http://processing.org
Copyright (c) 2004-10 Ben Fry and Casey Reas
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
ANTLR-generated parser and several supporting classes written
@@ -30,6 +30,8 @@ package processing.mode.java.preproc;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
import processing.app.Base;
import processing.app.Preferences;
import processing.app.SketchException;
import processing.core.PApplet;
@@ -146,33 +148,33 @@ public class PdePreprocessor {
private TokenStreamCopyingHiddenTokenFilter filter;
private boolean foundMain;
public void setFoundMain(boolean foundMain) {
this.foundMain = foundMain;
}
public boolean getFoundMain() {
return foundMain;
}
// private boolean foundMain;
private String advClassName = "";
public void setAdvClassName(final String advClassName) {
this.advClassName = advClassName;
}
protected Mode mode;
HashMap<String, Object> foundMethods;
protected String sizeStatement;
protected String sketchWidth;
protected String sketchHeight;
protected String sketchRenderer;
/**
* Regular expression for parsing the size() method. This should match
* against any uses of the size() function, whether numbers or variables
* or whatever. This way, no warning is shown if size() isn't actually used
* in the sketch, which is the case especially for anyone who is cutting
* and pasting from the reference.
*/
public static final String SIZE_REGEX =
"(?:^|\\s|;)size\\s*\\(\\s*([^\\s,]+)\\s*,\\s*([^\\s,\\)]+),?\\s*([^\\)]*)\\s*\\)\\s*\\;";
//"(?:^|\\s|;)size\\s*\\(\\s*(\\S+)\\s*,\\s*([^\\s,\\)]+),?\\s*([^\\)]*)\\s*\\)\\s*\\;";
public void setMode(final Mode mode) {
// System.err.println("Setting mode to " + mode);
this.mode = mode;
}
public PdePreprocessor(final String sketchName) {
this(sketchName, Preferences.getInteger("editor.tabs.size"));
}
public PdePreprocessor(final String sketchName, final int tabSize) {
this.name = sketchName;
final char[] indentChars = new char[tabSize];
@@ -180,14 +182,176 @@ public class PdePreprocessor {
indent = new String(indentChars);
}
public String[] initSketchSize(String code) throws SketchException {
String[] info = parseSketchSize(code, true);
if (info != null) {
sizeStatement = info[0];
sketchWidth = info[1];
sketchHeight = info[2];
sketchRenderer = info[3];
}
return info;
}
/**
* Parse a chunk of code and extract the size() command and its contents.
* @param code Usually the code from the main tab in the sketch
* @param fussy true if it should show an error message if bad size()
* @return null if there was an error, otherwise an array (might contain some/all nulls)
*/
static public String[] parseSketchSize(String code, boolean fussy) {
// This matches against any uses of the size() function, whether numbers
// or variables or whatever. This way, no warning is shown if size() isn't
// actually used in the applet, which is the case especially for anyone
// who is cutting/pasting from the reference.
// String scrubbed = scrubComments(sketch.getCode(0).getProgram());
// String[] matches = PApplet.match(scrubbed, SIZE_REGEX);
String[] matches = PApplet.match(scrubComments(code), SIZE_REGEX);
if (matches != null) {
boolean badSize = false;
if (matches[1].equals("screenWidth") ||
matches[1].equals("screenHeight") ||
matches[2].equals("screenWidth") ||
matches[2].equals("screenHeight")) {
final String message =
"The screenWidth and screenHeight variables\n" +
"are named displayWidth and displayHeight\n" +
"in this release of Processing.";
Base.showWarning("Time for a quick update", message, null);
return null;
}
if (!matches[1].equals("displayWidth") &&
!matches[1].equals("displayHeight") &&
PApplet.parseInt(matches[1], -1) == -1) {
badSize = true;
}
if (!matches[2].equals("displayWidth") &&
!matches[2].equals("displayHeight") &&
PApplet.parseInt(matches[2], -1) == -1) {
badSize = true;
}
if (badSize && fussy) {
// found a reference to size, but it didn't seem to contain numbers
final String message =
"The size of this applet could not automatically\n" +
"be determined from your code. Use only numeric\n" +
"values (not variables) for the size() command.\n" +
"See the size() reference for an explanation.";
Base.showWarning("Could not find sketch size", message, null);
new Exception().printStackTrace(System.out);
return null;
}
// if the renderer entry is empty, set it to null
if (matches[3].trim().length() == 0) {
matches[3] = null;
}
return matches;
}
return new String[] { null, null, null, null }; // not an error, just empty
}
/**
* Replace all commented portions of a given String as spaces.
* Utility function used here and in the preprocessor.
*/
static public String scrubComments(String what) {
char p[] = what.toCharArray();
int index = 0;
while (index < p.length) {
// for any double slash comments, ignore until the end of the line
if ((p[index] == '/') &&
(index < p.length - 1) &&
(p[index+1] == '/')) {
p[index++] = ' ';
p[index++] = ' ';
while ((index < p.length) &&
(p[index] != '\n')) {
p[index++] = ' ';
}
// check to see if this is the start of a new multiline comment.
// if it is, then make sure it's actually terminated somewhere.
} else if ((p[index] == '/') &&
(index < p.length - 1) &&
(p[index+1] == '*')) {
p[index++] = ' ';
p[index++] = ' ';
boolean endOfRainbow = false;
while (index < p.length - 1) {
if ((p[index] == '*') && (p[index+1] == '/')) {
p[index++] = ' ';
p[index++] = ' ';
endOfRainbow = true;
break;
} else {
// continue blanking this area
p[index++] = ' ';
}
}
if (!endOfRainbow) {
throw new RuntimeException("Missing the */ from the end of a " +
"/* comment */");
}
} else { // any old character, move along
index++;
}
}
return new String(p);
}
public void addMethod(String methodName) {
foundMethods.put(methodName, new Object());
}
public boolean hasMethod(String methodName) {
return foundMethods.containsKey(methodName);
}
// public void setFoundMain(boolean foundMain) {
// this.foundMain = foundMain;
// }
// public boolean getFoundMain() {
// return foundMain;
// }
public void setAdvClassName(final String advClassName) {
this.advClassName = advClassName;
}
public void setMode(final Mode mode) {
// System.err.println("Setting mode to " + mode);
this.mode = mode;
}
CommonHiddenStreamToken getHiddenAfter(final CommonHiddenStreamToken t) {
return filter.getHiddenAfter(t);
}
CommonHiddenStreamToken getInitialHiddenToken() {
return filter.getInitialHiddenToken();
}
private static int countNewlines(final String s) {
int count = 0;
for (int pos = s.indexOf('\n', 0); pos >= 0; pos = s.indexOf('\n', pos + 1))
@@ -195,6 +359,7 @@ public class PdePreprocessor {
return count;
}
private static void checkForUnterminatedMultilineComment(final String program)
throws SketchException {
final int length = program.length();
@@ -291,11 +456,13 @@ public class PdePreprocessor {
}
}
public PreprocessorResult write(final Writer out, String program)
throws SketchException, RecognitionException, TokenStreamException {
return write(out, program, null);
}
public PreprocessorResult write(Writer out, String program,
String codeFolderPackages[])
throws SketchException, RecognitionException, TokenStreamException {
@@ -310,9 +477,10 @@ public class PdePreprocessor {
final ArrayList<String> codeFolderImports = new ArrayList<String>();
// need to reset whether or not this has a main()
foundMain = false;
// foundMain = false;
foundMethods = new HashMap<String, Object>();
// bug #5
// http://processing.org/bugs/bugzilla/5.html
if (!program.endsWith("\n"))
program += "\n";
@@ -663,7 +831,17 @@ public class PdePreprocessor {
}
if ((mode == Mode.STATIC) || (mode == Mode.ACTIVE)) {
if (!foundMain) {
if (sketchWidth != null && !hasMethod("sketchWidth")) {
out.println(indent + "public int sketchWidth() { return " + sketchWidth + "; }");
}
if (sketchHeight != null && !hasMethod("sketchHeight")) {
out.println(indent + "public int sketchHeight() { return " + sketchHeight + "; }");
}
if (sketchRenderer != null && !hasMethod("sketchRenderer")) {
out.println(indent + "public String sketchRenderer() { return " + sketchRenderer + "; }");
}
if (!hasMethod("main")) {
out.println(indent + "static public void main(String args[]) {");
out.print(indent + indent + "PApplet.main(new String[] { ");

View File

@@ -20,27 +20,27 @@ import processing.app.Library;
import processing.core.PApplet;
import processing.mode.java.JavaBuild;
import processing.mode.java.preproc.PdePreprocessor;
public class JavaScriptBuild
{
public final static String TEMPLATE_FOLDER_NAME = "template";
public final static String EXPORTED_FOLDER_NAME = "web-export";
public final static String TEMPLATE_FILE_NAME = "template.html";
public final static String IMPORT_REGEX =
public final static String IMPORT_REGEX =
"^[\\s]*import[\\s]+([^\\s]+)[\\s]*";
/**
* Answers with the first java doc style comment in the string,
* or an empty string if no such comment can be found.
*/
public static String getDocString ( String s )
public static String getDocString ( String s )
{
String[] javadoc = PApplet.match(s, "/\\*{2,}(.*?)\\*+/");
if (javadoc != null)
if (javadoc != null)
{
StringBuffer dbuffer = new StringBuffer();
String[] pieces = PApplet.split(javadoc[1], '\n');
@@ -56,21 +56,21 @@ public class JavaScriptBuild
return "";
}
/**
* Reads in a simple template file, with fields of the form '@@somekey@@'
* and replaces each field with the value in the map for 'somekey', writing
* the output to the output file.
*
*
* Keys not in the map will be replaced with empty strings.
*
*
* @param template File object mapping to the template
* @param output File object handle to the output
* @param args template keys, data values to replace them
* @throws IOException when there are problems writing to or from the files
*/
public static void writeTemplate ( File template, File output, Map<String, String> fields )
throws IOException
throws IOException
{
BufferedReader reader = PApplet.createReader(template);
PrintWriter writer = PApplet.createWriter(output);
@@ -97,11 +97,11 @@ public class JavaScriptBuild
}
writer.close();
}
// -----------------------------------------------------
/**
// -----------------------------------------------------
/**
* The sketch this builder is working on.
* <p>
* Each builder instance should only work on a single sketch, so if
@@ -110,16 +110,16 @@ public class JavaScriptBuild
protected Sketch sketch;
protected Mode mode;
protected File binFolder;
public JavaScriptBuild ( Sketch sketch )
public JavaScriptBuild ( Sketch sketch )
{
this.sketch = sketch;
this.mode = sketch.getMode();
}
/**
* Builds the sketch
* <p>
@@ -128,9 +128,9 @@ public class JavaScriptBuild
* 2. cat *.pde > bin/sketchname.pde
* 3. cp -r sketch/data/* bin/ (p.js doesn't recognize the data folder)
* 4. series of greps to find height, width, name, desc
* 5. cat template.html | sed 's/@@sketch@@/[name]/g' ... [many sed filters] > bin/index.html
* 5. cat template.html | sed 's/@@sketch@@/[name]/g' ... [many sed filters] > bin/index.html
* </p>
*
*
* @param bin the output folder for the built sketch
* @return boolean whether the build was successful
*/
@@ -138,38 +138,38 @@ public class JavaScriptBuild
{
// make sure the user isn't playing "hide-the-sketch-folder" again
sketch.ensureExistence();
this.binFolder = bin;
// we need these ..
// JavaScriptMode jsMode = (JavaScriptMode)mode;
// JavaScriptEditor jsEditor = (JavaScriptEditor)jsMode.getEditor();
// BasicServer jsServer = jsEditor.getServer();
if ( bin.exists() )
{
if ( bin.exists() )
{
Base.removeDescendants(bin);
} //else will be created during preprocesss
// pass through preprocessor to catch syntax errors
// .. exceptions bubble up.
preprocess(bin);
// move the data files, copies contents of sketch/data/ to web-export/
if (sketch.hasDataFolder())
if (sketch.hasDataFolder())
{
try {
Base.copyDir(sketch.getDataFolder(), bin);
} catch (IOException e) {
final String msg = "An exception occured while trying to copy the data folder. " +
final String msg = "An exception occured while trying to copy the data folder. " +
"You may have to manually move the contents of sketch/data to " +
"the web-export/ folder. Processing.js doesn't look for a data " +
"folder, so lump them together.";
Base.showWarning("Problem building the sketch", msg, e);
}
}
// as .js files are allowed now include these into the mix,
// first find 'em ..
String[] sketchFolderFilesRaw = sketch.getFolder().list();
@@ -198,18 +198,18 @@ public class JavaScriptBuild
}
// TODO
// Really scrub comments from code?
// Really scrub comments from code?
// Con: larger files, PJS needs to do it later
// Pro: being literate as we are in a script language.
String scrubbed = JavaBuild.scrubComments(sketch.getCode(0).getProgram());
String scrubbed = PdePreprocessor.scrubComments(sketch.getCode(0).getProgram());
// get width and height
int wide = PApplet.DEFAULT_WIDTH;
int high = PApplet.DEFAULT_HEIGHT;
String[] matches = PApplet.match(scrubbed, JavaBuild.SIZE_REGEX);
if (matches != null)
String[] matches = PApplet.match(scrubbed, PdePreprocessor.SIZE_REGEX);
if (matches != null)
{
try
try
{
wide = Integer.parseInt(matches[1]);
high = Integer.parseInt(matches[2]);
@@ -234,7 +234,7 @@ public class JavaScriptBuild
// try resolve imports
ArrayList<String> importPackages = new ArrayList<String>();
String[] lines = scrubbed.split( "\n" );
for ( String l : lines )
for ( String l : lines )
{
int iIndex = l.indexOf( "import" );
if ( iIndex != -1 )
@@ -247,7 +247,7 @@ public class JavaScriptBuild
{
String iPackage = matches[1];
iPackage = iPackage.trim();
if ( iPackage.indexOf(".*") != -1 ) {
// de.bezier.tutto.*
iPackage = iPackage.replace( ".*", "" );
@@ -273,10 +273,10 @@ public class JavaScriptBuild
return false;
}
}
for ( String pack : importPackages )
for ( String pack : importPackages )
{
Library lib = mode.getLibrary( pack );
if ( lib != null )
if ( lib != null )
{
String libPath = lib.getJarPath();
File libJar = new File( libPath );
@@ -284,20 +284,20 @@ public class JavaScriptBuild
{
File libJS = new File( libJar.getParent(), libJar.getName().replace(".jar",".js") );
//System.out.println( libJS.getPath() );
if ( libJS.exists() )
if ( libJS.exists() )
{
String libJSDest = "libs" + File.separator + libJS.getName();
File libJSDestFile = new File( bin, libJSDest );
if ( libJSDestFile.exists() )
if ( libJSDestFile.exists() )
{
System.out.println( "Duplicate import!" );
}
try
try
{
Base.copyFile( libJS,
Base.copyFile( libJS,
libJSDestFile );
jsImports.add( libJSDest );
} catch ( Exception se ) {
se.printStackTrace();
}
@@ -305,13 +305,13 @@ public class JavaScriptBuild
}
}
}
// final prep and write to template.
// getTemplateFile() is very important as it looks and preps
// any custom templates present in the sketch folder.
File templateFile = getTemplateFile();
File htmlOutputFile = new File(bin, "index.html");
Map<String, String> templateFields = new HashMap<String, String>();
templateFields.put( "width", String.valueOf(wide) );
templateFields.put( "height", String.valueOf(high) );
@@ -320,23 +320,23 @@ public class JavaScriptBuild
// generate an ID for the sketch to use with <canvas id="XXXX"></canvas>
String sketchID = sketch.getName().replaceAll("[^a-zA-Z0-9]+", "").replaceAll("^[^a-zA-Z]+","");
// add a handy method to read the generated sketchID
String scriptFiles = "<script type=\"text/javascript\">\n";
scriptFiles += "// convenience function to fetch ID of sketch html element\n" +
"function getProcessingSketchID () { return '"+sketchID+"'; }\n";
// ArrayList<String> addresses = jsServer.getInetAddresses();
// int port = jsServer.getPort();
// scriptFiles += "var getServerAddresses = function () {\nreturn [\n";
// for ( String addr : addresses )
// {
// scriptFiles += "\"http://" + addr + ":" + port + "/\", \n";
// }
// scriptFiles += "];\n}\n";
scriptFiles += "</script>\n";
// add imports if any ...
@@ -346,9 +346,9 @@ public class JavaScriptBuild
}
// main .pde file first
String sourceFiles = "<a href=\"" + sketch.getName() + ".pde\">" +
String sourceFiles = "<a href=\"" + sketch.getName() + ".pde\">" +
sketch.getName() + "</a> ";
// add all other files (both types: .pde and .js)
if ( sketchFolderFiles != null )
{
@@ -373,14 +373,14 @@ public class JavaScriptBuild
Base.showWarning("A problem occured during the build", msg, ioe);
return false;
}
// finally, add files processing.js
String[] defaultJSFiles = new String[]{
"processing.js" /*, "qrcode.js"*/
};
for ( String defaultJSFile : defaultJSFiles )
{
try
try
{
Base.copyFile( sketch.getMode().getContentFile(
TEMPLATE_FOLDER_NAME + File.separator + defaultJSFile
@@ -390,11 +390,11 @@ public class JavaScriptBuild
} catch (IOException ioe) {
final String msg = "There was a problem copying " +defaultJSFile+ " to the " +
"build folder. You will have to manually add " +
"build folder. You will have to manually add " +
defaultJSFile +" to the build folder before the sketch " +
"will run.";
Base.showWarning( "There was a problem writing to the build folder", msg, ioe);
//return false;
//return false;
}
}
@@ -411,21 +411,21 @@ public class JavaScriptBuild
{
File sketchFolder = sketch.getFolder();
File customTemplateFolder = new File( sketchFolder, TEMPLATE_FOLDER_NAME );
if ( customTemplateFolder.exists() &&
customTemplateFolder.isDirectory() &&
if ( customTemplateFolder.exists() &&
customTemplateFolder.isDirectory() &&
customTemplateFolder.canRead() )
{
File appletJsFolder = new File( sketchFolder, EXPORTED_FOLDER_NAME );
try {
//TODO: this is potentially dangerous as it might override files in "web-export"
//TODO: this is potentially dangerous as it might override files in "web-export"
Base.copyDir( customTemplateFolder, appletJsFolder );
if ( !(new File( appletJsFolder, TEMPLATE_FILE_NAME )).delete() )
{
// ignore?
}
return new File( customTemplateFolder, TEMPLATE_FILE_NAME );
} catch ( Exception e ) {
} catch ( Exception e ) {
String msg = "";
Base.showWarning("There was a problem copying your custom template folder", msg, e);
return sketch.getMode().getContentFile(
@@ -438,9 +438,9 @@ public class JavaScriptBuild
TEMPLATE_FOLDER_NAME + File.separator + TEMPLATE_FILE_NAME
);
}
/**
/**
* Collects the sketch code and runs it by the Java-mode preprocessor
* to fish for errors.
*
@@ -460,7 +460,7 @@ public class JavaScriptBuild
bigCode.append("\n");
}
}
if (!bin.exists()) {
bin.mkdirs();
}
@@ -475,8 +475,8 @@ public class JavaScriptBuild
PdePreprocessor preprocessor = new PdePreprocessor( sketch.getName() );
//PreprocessorResult result;
try
try
{
File outputFolder = sketch.makeTempFolder();
final File java = new File( outputFolder, sketch.getName() + ".java" );
@@ -596,12 +596,12 @@ public class JavaScriptBuild
* Copied from JavaBuild as it is protected there.
* @see processing.mode.java.JavaBuild#findErrorFile(int)
*/
protected int findErrorFile ( int errorLine )
protected int findErrorFile ( int errorLine )
{
for (int i = 1; i < sketch.getCodeCount(); i++)
for (int i = 1; i < sketch.getCodeCount(); i++)
{
SketchCode sc = sketch.getCode(i);
if (sc.isExtension("pde") && (sc.getPreprocOffset() < errorLine))
if (sc.isExtension("pde") && (sc.getPreprocOffset() < errorLine))
{
// keep looping until the errorLine is past the offset
return i;
@@ -609,9 +609,9 @@ public class JavaScriptBuild
}
return 0; // i give up
}
/**
* Parse the sketch to retrieve it's description. Answers with the first
* Parse the sketch to retrieve it's description. Answers with the first
* java doc style comment in the main sketch file, or an empty string if
* no such comment exists.
*/
@@ -623,10 +623,10 @@ public class JavaScriptBuild
// -----------------------------------------------------
// Export
/**
* Export the sketch to the default "web-export" folder.
* @return success of the operation
/**
* Export the sketch to the default "web-export" folder.
* @return success of the operation
*/
public boolean export() throws IOException, SketchException
{