diff --git a/mobile/app/PdeCompiler.java b/mobile/app/Compiler.java similarity index 83% rename from mobile/app/PdeCompiler.java rename to mobile/app/Compiler.java index a02716278..a6c89ee26 100755 --- a/mobile/app/PdeCompiler.java +++ b/mobile/app/Compiler.java @@ -1,12 +1,11 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* - PdeCompiler - default compiler class that connects to jikes + Compiler - default compiler class that connects to jikes Part of the Processing project - http://processing.org - Copyright (c) 2001-03 - Ben Fry, Massachusetts Institute of Technology and - Casey Reas, Interaction Design Institute Ivrea + Copyright (c) 2004-05 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 it under the terms of the GNU General Public License as published by @@ -18,11 +17,13 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +package processing.app; + import processing.core.*; import java.io.*; @@ -30,24 +31,24 @@ import java.util.*; import java.util.zip.*; import javax.swing.*; -public class PdeCompiler implements PdeMessageConsumer { - static final String BUGS_URL = +public class Compiler implements MessageConsumer { + static final String BUGS_URL = "http://processing.org/bugs/"; - static final String SUPER_BADNESS = + static final String SUPER_BADNESS = "Compiler error, please submit this code to " + BUGS_URL; - PdeSketch sketch; + Sketch sketch; String buildPath; //String buildPath; //String className; //File includeFolder; - PdeException exception; - //PdeEditor editor; + RunnerException exception; + //Editor editor; /* - public PdeCompiler(String buildPath, String className, - File includeFolder, PdeEditor editor) { + public Compiler(String buildPath, String className, + File includeFolder, Editor editor) { this.buildPath = buildPath; this.includeFolder = includeFolder; this.className = className; @@ -58,29 +59,29 @@ public class PdeCompiler implements PdeMessageConsumer { public boolean compile(PrintStream leechErr) { */ - public PdeCompiler() { } // consider this a warning, you werkin soon. + public Compiler() { } // consider this a warning, you werkin soon. - public boolean compile(PdeSketch sketch, String buildPath, String bootClassPath) - throws PdeException { + public boolean compile(Sketch sketch, String buildPath, String bootClassPath) + throws RunnerException { this.sketch = sketch; this.buildPath = buildPath; - + // the pms object isn't used for anything but storage - PdeMessageStream pms = new PdeMessageStream(this); + MessageStream pms = new MessageStream(this); String baseCommand[] = new String[] { // user.dir is folder containing P5 (and therefore jikes) // macosx needs the extra path info. linux doesn't like it, though // windows doesn't seem to care. write once, headache anywhere. - ((PdeBase.platform != PdeBase.MACOSX) ? "jikes" : + ((!Base.isMacOS()) ? "jikes" : System.getProperty("user.dir") + File.separator + "jikes"), // this doesn't help much.. also java 1.4 seems to not support // -source 1.1 for javac, and jikes seems to also have dropped it. // for versions of jikes that don't complain, "final int" inside - // a function doesn't throw an error, so it could just be a + // a function doesn't throw an error, so it could just be a // ms jvm error that this sort of thing doesn't work. blech. //"-source", //"1.1", @@ -88,7 +89,7 @@ public class PdeCompiler implements PdeMessageConsumer { // necessary to make output classes compatible with 1.1 // i.e. so that exported applets can work with ms jvm on the web "-target", - PdePreferences.get("preproc.jdk_version"), //"1.1", + Preferences.get("preproc.jdk_version"), //"1.1", // let the incompatability headache begin // used when run without a vm ("expert" mode) @@ -120,39 +121,38 @@ public class PdeCompiler implements PdeMessageConsumer { System.arraycopy(baseCommand, 0, command, 0, baseCommand.length); // append each of the files to the command string for (int i = 0; i < preprocCount; i++) { - command[baseCommand.length + i] = + command[baseCommand.length + i] = buildPath + File.separator + preprocNames[i]; } + //PApplet.printarr(command); /* String command[] = new String[baseCommand.length + sketch.codeCount]; System.arraycopy(baseCommand, 0, command, 0, baseCommand.length); // append each of the files to the command string for (int i = 0; i < sketch.codeCount; i++) { - command[baseCommand.length + i] = + command[baseCommand.length + i] = buildPath + File.separator + sketch.code[i].preprocName; } */ -/* - for (int i = 0; i < command.length; i++) { - System.out.println("cmd " + i + ": " + command[i]); - } - */ + + //for (int i = 0; i < command.length; i++) { + //System.out.println("cmd " + i + " " + command[i]); + //} firstErrorFound = false; // haven't found any errors yet secondErrorFound = false; int result = 0; // pre-initialized to quiet a bogus warning from jikes - try { - // execute the compiler, and create threads to deal + try { + // execute the compiler, and create threads to deal // with the input and error streams // Process process = Runtime.getRuntime().exec(command); - - PdeMessageSiphon errSiphon = new PdeMessageSiphon(process.getErrorStream(), this); - PdeMessageSiphon inSiphon = new PdeMessageSiphon(process.getInputStream(), this); - - // wait for the process to finish. if interrupted + new MessageSiphon(process.getInputStream(), this); + new MessageSiphon(process.getErrorStream(), this); + + // wait for the process to finish. if interrupted // before waitFor returns, continue waiting // boolean compiling = true; @@ -161,15 +161,14 @@ public class PdeCompiler implements PdeMessageConsumer { result = process.waitFor(); //System.out.println("result is " + result); compiling = false; - } catch (InterruptedException ignored) { - } + } catch (InterruptedException ignored) { } } } catch (Exception e) { String msg = e.getMessage(); if ((msg != null) && (msg.indexOf("jikes: not found") != -1)) { //System.err.println("jikes is missing"); - PdeBase.showWarning("Compiler error", + Base.showWarning("Compiler error", "Could not find the compiler.\n" + "jikes is missing from your PATH,\n" + "see readme.txt for help.", null); @@ -182,21 +181,21 @@ public class PdeCompiler implements PdeMessageConsumer { } // an error was queued up by message(), barf this back to build() - // which will barf it back to PdeEditor. if you're having trouble + // which will barf it back to Editor. if you're having trouble // discerning the imagery, consider how cows regurgitate their food // to digest it, and the fact that they have five stomaches. // //System.out.println("throwing up " + exception); - if (exception != null) throw exception; + if (exception != null) throw exception; // if the result isn't a known, expected value it means that something // is fairly wrong, one possibility is that jikes has crashed. // if (result != 0 && result != 1 ) { - //exception = new PdeException(SUPER_BADNESS); + //exception = new RunnerException(SUPER_BADNESS); //editor.error(exception); // this will instead be thrown - PdeBase.openURL(BUGS_URL); - throw new PdeException(SUPER_BADNESS); + Base.openURL(BUGS_URL); + throw new RunnerException(SUPER_BADNESS); } // success would mean that 'result' is set to zero @@ -209,21 +208,21 @@ public class PdeCompiler implements PdeMessageConsumer { boolean secondErrorFound; /** - * Part of the PdeMessageConsumer interface, this is called - * whenever a piece (usually a line) of error message is spewed + * Part of the MessageConsumer interface, this is called + * whenever a piece (usually a line) of error message is spewed * out from the compiler. The errors are parsed for their contents - * and line number, which is then reported back to PdeEditor. + * and line number, which is then reported back to Editor. */ public void message(String s) { - // This receives messages as full lines, so a newline needs + // This receives messages as full lines, so a newline needs // to be added as they're printed to the console. //// MOBILE: moving to end due to wierd jikes output - //System.err.println(s); - + //System.err.println(s); + // ignore cautions if (s.indexOf("Caution") != -1) return; - // jikes always uses a forward slash character as its separator, + // jikes always uses a forward slash character as its separator, // so replace any platform-specific separator characters before // attemping to compare // @@ -254,7 +253,7 @@ public class PdeCompiler implements PdeMessageConsumer { // skip past the path and parse the int after the first colon // - String s1 = s.substring(partialStartIndex + + String s1 = s.substring(partialStartIndex + partialTempPath.length() + 1); int colon = s1.indexOf(':'); int lineNumber = Integer.parseInt(s1.substring(0, colon)); @@ -262,7 +261,7 @@ public class PdeCompiler implements PdeMessageConsumer { if (fileIndex == 0) { // main class, figure out which tab for (int i = 1; i < sketch.codeCount; i++) { - if (sketch.code[i].flavor == PdeSketch.PDE) { + if (sketch.code[i].flavor == Sketch.PDE) { if (sketch.code[i].lineOffset < lineNumber) { fileIndex = i; //System.out.println("i'm thinkin file " + i); @@ -287,20 +286,19 @@ public class PdeCompiler implements PdeMessageConsumer { } // if executing at this point, this is *at least* the first error - /// MOBILE: moving to end due to wierd jikes output firstErrorFound = true; //err += "error:".length(); String description = s1.substring(err + "Error:".length()); description = description.trim(); - + String hasLoop = "The method \"void loop();\" with default access"; if (description.indexOf(hasLoop) != -1) { - description = + description = "Rename loop() to draw() in Processing 0070 and higher"; } - String constructorProblem = + String constructorProblem = "No applicable overload was found for a constructor of type"; if (description.indexOf(constructorProblem) != -1) { //"simong.particles.ParticleSystem". Perhaps you wanted the overloaded version "ParticleSystem();" instead? @@ -319,23 +317,23 @@ public class PdeCompiler implements PdeMessageConsumer { if (description.indexOf(classpathProblem) != -1) { if (description.indexOf("quicktime/std") != -1) { // special case for the quicktime libraries - description = + description = "To run sketches that use the Processing video library, " + "you must first install QuickTime for Java."; } else { int nextSentence = description.indexOf(". Package") + 2; - description = - description.substring(nextSentence, description.indexOf(':')) + + description = + description.substring(nextSentence, description.indexOf(':')) + " the code folder or in any libraries."; } - } + } //// MOBILE: ignore wierd jikes errors that get output even though it compiles fine - if (description.indexOf("Type java.io.Serializable was not found.") != -1) { + if (description.indexOf("Type \"java.io.Serializable\" was not found.") != -1) { return; } - if (description.indexOf("Type java.lang.Cloneable was not found.") != -1) { + if (description.indexOf("Type \"java.lang.Cloneable\" was not found.") != -1) { return; } if (description.indexOf("A non-standard version of the type \"java.lang.StringBuffer\" was found.") != -1) { @@ -343,12 +341,11 @@ public class PdeCompiler implements PdeMessageConsumer { } //// MOBILE: moving to end due to wierd jikes output - firstErrorFound = true; System.err.println(s); //System.out.println("description = " + description); //System.out.println("creating exception " + exception); - exception = new PdeException(description, fileIndex, lineNumber-1, -1); + exception = new RunnerException(description, fileIndex, lineNumber-1, -1); // NOTE!! major change here, this exception will be queued // here to be thrown by the compile() function @@ -362,9 +359,9 @@ public class PdeCompiler implements PdeMessageConsumer { // this isn't the start of an error line, so don't attempt to parse // a line number out of it. - // if the second error hasn't been discovered yet, these lines - // are probably associated with the first error message, - // which is already in the status bar, and are likely to be + // if the second error hasn't been discovered yet, these lines + // are probably associated with the first error message, + // which is already in the status bar, and are likely to be // of interest to the user, so spit them to the console. // if (!secondErrorFound) { @@ -379,8 +376,8 @@ public class PdeCompiler implements PdeMessageConsumer { static public String calcBootClassPath() { if (bootClassPath == null) { String additional = ""; - if (PdeBase.platform == PdeBase.MACOSX) { - additional = + if (Base.isMacOS()) { + additional = contentsToClassPath(new File("/System/Library/Java/Extensions/")); } bootClassPath = System.getProperty("sun.boot.class.path") + additional; @@ -389,16 +386,16 @@ public class PdeCompiler implements PdeMessageConsumer { } - /// + /// /** - * Return the path for a folder, with appended paths to + * Return the path for a folder, with appended paths to * any .jar or .zip files inside that folder. * This will prepend a colon (or whatever the path separator is) * so that it can be directly appended to another path string. * - * This will always add the root folder as well, and doesn't bother + * This will always add the root folder as well, and doesn't bother * checking to see if there are any .class files in the folder or * within a subfolder. */ @@ -428,7 +425,7 @@ public class PdeCompiler implements PdeMessageConsumer { abuffer.append(list[i]); } } - } catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); // this would be odd } //System.out.println("included path is " + abuffer.toString()); @@ -447,14 +444,14 @@ public class PdeCompiler implements PdeMessageConsumer { */ static public String[] packageListFromClassPath(String path) { Hashtable table = new Hashtable(); - String pieces[] = + String pieces[] = PApplet.split(path, File.pathSeparatorChar); for (int i = 0; i < pieces.length; i++) { //System.out.println("checking piece '" + pieces[i] + "'"); if (pieces[i].length() == 0) continue; - if (pieces[i].toLowerCase().endsWith(".jar") || + if (pieces[i].toLowerCase().endsWith(".jar") || pieces[i].toLowerCase().endsWith(".zip")) { packageListFromZip(pieces[i], table); @@ -462,8 +459,8 @@ public class PdeCompiler implements PdeMessageConsumer { File dir = new File(pieces[i]); if (dir.exists() && dir.isDirectory()) { packageListFromFolder(dir, null, table); - //importCount = magicImportsRecursive(dir, null, - // table); + //importCount = magicImportsRecursive(dir, null, + // table); //imports, importCount); } } @@ -476,6 +473,7 @@ public class PdeCompiler implements PdeMessageConsumer { output[index++] = ((String) e.nextElement()).replace('/', '.'); } //System.arraycopy(imports, 0, output, 0, importCount); + //PApplet.printarr(output); return output; } @@ -492,7 +490,7 @@ public class PdeCompiler implements PdeMessageConsumer { if (name.endsWith(".class")) { int slash = name.lastIndexOf('/'); - if (slash == -1) continue; + if (slash == -1) continue; String pname = name.substring(0, slash); if (table.get(pname) == null) { @@ -510,13 +508,13 @@ public class PdeCompiler implements PdeMessageConsumer { /** * Make list of package names by traversing a directory hierarchy. - * Each time a class is found in a folder, add its containing set - * of folders to the package list. If another folder is found, + * Each time a class is found in a folder, add its containing set + * of folders to the package list. If another folder is found, * walk down into that folder and continue. */ - static private void packageListFromFolder(File dir, String sofar, + static private void packageListFromFolder(File dir, String sofar, Hashtable table) { - //String imports[], + //String imports[], //int importCount) { //System.err.println("checking dir '" + dir + "'"); boolean foundClass = false; @@ -527,12 +525,12 @@ public class PdeCompiler implements PdeMessageConsumer { File sub = new File(dir, files[i]); if (sub.isDirectory()) { - String nowfar = + String nowfar = (sofar == null) ? files[i] : (sofar + "." + files[i]); packageListFromFolder(sub, nowfar, table); //System.out.println(nowfar); //imports[importCount++] = nowfar; - //importCount = magicImportsRecursive(sub, nowfar, + //importCount = magicImportsRecursive(sub, nowfar, // imports, importCount); } else if (!foundClass) { // if no classes found in this folder yet if (files[i].endsWith(".class")) { @@ -546,9 +544,9 @@ public class PdeCompiler implements PdeMessageConsumer { } /* - static public int magicImportsRecursive(File dir, String sofar, + static public int magicImportsRecursive(File dir, String sofar, Hashtable table) { - //String imports[], + //String imports[], //int importCount) { System.err.println("checking dir '" + dir + "'"); String files[] = dir.list(); @@ -557,12 +555,12 @@ public class PdeCompiler implements PdeMessageConsumer { File sub = new File(dir, files[i]); if (sub.isDirectory()) { - String nowfar = (sofar == null) ? + String nowfar = (sofar == null) ? files[i] : (sofar + "." + files[i]); //System.out.println(nowfar); imports[importCount++] = nowfar; - importCount = magicImportsRecursive(sub, nowfar, + importCount = magicImportsRecursive(sub, nowfar, imports, importCount); } } diff --git a/mobile/app/PdeEditor.java b/mobile/app/Editor.java similarity index 78% rename from mobile/app/PdeEditor.java rename to mobile/app/Editor.java index 1ffbab006..b45f8f1c9 100755 --- a/mobile/app/PdeEditor.java +++ b/mobile/app/Editor.java @@ -1,10 +1,10 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* - PdeEditor - main editor panel for the processing development environment + Editor - main editor panel for the processing development environment Part of the Processing project - http://processing.org - Except where noted, code is written by Ben Fry and + Copyright (c) 2004-05 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 @@ -22,6 +22,11 @@ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +package processing.app; + +import processing.app.syntax.*; +import processing.app.tools.*; + import java.awt.*; import java.awt.event.*; import java.io.*; @@ -41,22 +46,26 @@ import com.oroinc.text.regex.*; import com.apple.mrj.*; -public class PdeEditor extends JFrame -implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler +public class Editor extends JFrame + implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler, + MRJOpenDocumentHandler //, MRJOpenApplicationHandler { // yeah - static final String WINDOW_TITLE = "Processing Mobile"; + static final String WINDOW_TITLE = "Processing Mobile" + " - " + Base.VERSION_NAME; // p5 icon for the window Image icon; // otherwise, if the window is resized with the message label // set to blank, it's preferredSize() will be fukered - static final String EMPTY = + static public final String EMPTY = " " + " " + " "; + static public final KeyStroke WINDOW_CLOSE_KEYSTROKE = + KeyStroke.getKeyStroke('W', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); + static final int HANDLE_NEW = 1; static final int HANDLE_OPEN = 2; static final int HANDLE_QUIT = 3; @@ -64,38 +73,35 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler String handleOpenPath; boolean handleNewShift; boolean handleNewLibrary; - //String handleSaveAsPath; - //String openingName; - PdeEditorButtons buttons; - PdeEditorHeader header; - PdeEditorStatus status; - PdeEditorConsole console; + EditorButtons buttons; + EditorHeader header; + EditorStatus status; + EditorConsole console; JSplitPane splitPane; JPanel consolePanel; + JLabel lineNumberComponent; + // currently opened program - public PdeSketch sketch; + public Sketch sketch; + + EditorLineStatus lineStatus; public JEditTextArea textarea; - PdeEditorListener listener; + EditorListener listener; // runtime information and window placement Point appletLocation; - Point presentLocation; - Window presentationWindow; + //Point presentLocation; + //Window presentationWindow; RunButtonWatcher watcher; - PdeRuntime runtime; - - //boolean externalRuntime; - //String externalPaths; - //File externalCode; + Runner runtime; JMenuItem exportAppItem; JMenuItem saveMenuItem; JMenuItem saveAsMenuItem; - //JMenuItem beautifyMenuItem; // @@ -110,27 +116,29 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler // - //PdeHistory history; // TODO re-enable history - PdeSketchbook sketchbook; - PdePreferences preferences; - PdeEditorFind find; + //SketchHistory history; // TODO re-enable history + Sketchbook sketchbook; + //Preferences preferences; + FindReplace find; //static Properties keywords; // keyword -> reference html lookup - public PdeEditor() { - super(WINDOW_TITLE + " - " + PdeBase.VERSION); - // this is needed by just about everything else - preferences = new PdePreferences(); + public Editor() { + super(WINDOW_TITLE); // #@$*(@#$ apple.. always gotta think different MRJApplicationUtils.registerAboutHandler(this); MRJApplicationUtils.registerPrefsHandler(this); MRJApplicationUtils.registerQuitHandler(this); + MRJApplicationUtils.registerOpenDocumentHandler(this); + + // run static initialization that grabs all the prefs + Preferences.init(); // set the window icon try { - icon = PdeBase.getImage("icon.gif", this); + icon = Base.getImage("icon.gif", this); setIconImage(icon); } catch (Exception e) { } // fail silently, no big whup @@ -143,174 +151,88 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler }); PdeKeywords keywords = new PdeKeywords(); - // TODO re-enable history - //history = new PdeHistory(this); - sketchbook = new PdeSketchbook(this); + sketchbook = new Sketchbook(this); JMenuBar menubar = new JMenuBar(); menubar.add(buildFileMenu()); menubar.add(buildEditMenu()); menubar.add(buildSketchMenu()); menubar.add(buildToolsMenu()); - // what platform has their help menu way on the right? - //if ((PdeBase.platform == PdeBase.WINDOWS) || + // what platform has their help menu way on the right? motif? //menubar.add(Box.createHorizontalGlue()); menubar.add(buildHelpMenu()); setJMenuBar(menubar); // doesn't matter when this is created, just make it happen at some point - find = new PdeEditorFind(PdeEditor.this); + find = new FindReplace(Editor.this); Container pain = getContentPane(); pain.setLayout(new BorderLayout()); - buttons = new PdeEditorButtons(this); - pain.add("West", buttons); + Box box = Box.createVerticalBox(); + Box upper = Box.createVerticalBox(); - JPanel rightPanel = new JPanel(); - rightPanel.setLayout(new BorderLayout()); + buttons = new EditorButtons(this); + upper.add(buttons); - header = new PdeEditorHeader(this); - rightPanel.add(header, BorderLayout.NORTH); + header = new EditorHeader(this); + //header.setBorder(null); + upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); textarea.setTokenMarker(new PdeKeywords()); - - textarea.setHorizontalOffset(5); - //textarea.setBorder(new EmptyBorder(0, 20, 0, 0)); - //textarea.setBackground(Color.white); + textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); - //System.out.println(consolePanel.getInsets()); consolePanel.setLayout(new BorderLayout()); - status = new PdeEditorStatus(this); + status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); - console = new PdeEditorConsole(this); + console = new EditorConsole(this); + // windows puts an ugly border on this guy + console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); + lineStatus = new EditorLineStatus(textarea); + consolePanel.add(lineStatus, BorderLayout.SOUTH); + + upper.add(textarea); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, - textarea, consolePanel); + upper, consolePanel); + //textarea, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); - // if window increases in size, give all of increase to textarea (top pane) + // if window increases in size, give all of increase to + // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. - if (PdeBase.platform == PdeBase.MACOSX) { - splitPane.setBorder(null); - } + splitPane.setBorder(null); // the default size on windows is too small and kinda ugly - int dividerSize = PdePreferences.getInteger("editor.divider.size"); + int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } - rightPanel.add(splitPane, BorderLayout.CENTER); - - pain.add("Center", rightPanel); + splitPane.setMinimumSize(new Dimension(600, 600)); + box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) - listener = new PdeEditorListener(this, textarea); - textarea.pdeEditorListener = listener; + listener = new EditorListener(this, textarea); + pain.add(box); // set the undo stuff for this feller Document document = textarea.getDocument(); document.addUndoableEditListener(new PdeUndoableEditListener()); - - Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); - if ((PdeBase.platform == PdeBase.MACOSX) || - (PdeBase.platform == PdeBase.MACOS9)) { - presentationWindow = new Frame(); - - // mrj is still (with version 2.2.x) a piece of shit, - // and doesn't return valid insets for frames - //presentationWindow.pack(); // make a peer so insets are valid - //Insets insets = presentationWindow.getInsets(); - // the extra +20 is because the resize boxes intrude - Insets insets = new Insets(21, 5, 5 + 20, 5); - - presentationWindow.setBounds(-insets.left, -insets.top, - screen.width + insets.left + insets.right, - screen.height + insets.top + insets.bottom); - } else { - presentationWindow = new Frame(); - //((Frame)presentationWindow).setUndecorated(true); - try { - Method undecoratedMethod = - Frame.class.getMethod("setUndecorated", - new Class[] { Boolean.TYPE }); - undecoratedMethod.invoke(presentationWindow, - new Object[] { Boolean.TRUE }); - } catch (Exception e) { } - //} catch (NoSuchMethodException e) { } - //} catch (NoSuchMethodError e) { } - - presentationWindow.setBounds(0, 0, screen.width, screen.height); - } - - Label label = new Label("stop"); - label.addMouseListener(new MouseAdapter() { - public void mousePressed(MouseEvent e) { - setVisible(true); - doClose(); - }}); - - Dimension labelSize = new Dimension(60, 20); - presentationWindow.setLayout(null); - presentationWindow.add(label); - label.setBounds(5, screen.height - 5 - labelSize.height, - labelSize.width, labelSize.height); - - Color presentationBgColor = - PdePreferences.getColor("run.present.bgcolor"); - presentationWindow.setBackground(presentationBgColor); - - textarea.addFocusListener(new FocusAdapter() { - public void focusGained(FocusEvent e) { - if (presenting == true) { - try { - presentationWindow.toFront(); - runtime.applet.requestFocus(); - } catch (Exception ex) { } - } - } - }); - - this.addFocusListener(new FocusAdapter() { - public void focusGained(FocusEvent e) { - if (presenting == true) { - try { - presentationWindow.toFront(); - runtime.applet.requestFocus(); - } catch (Exception ex) { } - } - } - }); - - // moved from the PdeRuntime window to the main presentation window - // [toxi 030903] - presentationWindow.addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - //System.out.println("window got " + e); - if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { - runtime.stop(); - doClose(); - } else { - // pass on the event to the applet [toxi 030903] - runtime.applet.keyPressed(e); - } - } - }); } @@ -318,7 +240,8 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler * Hack for #@#)$(* Mac OS X. */ public Dimension getMinimumSize() { - return new Dimension(500, 500); + System.out.println("getting minimum size"); + return new Dimension(500, 550); } @@ -335,57 +258,69 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); - boolean windowPositionInvalid = false; + boolean windowPositionValid = true; - if (PdePreferences.get("last.screen.height") != null) { + if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical - int screenW = PdePreferences.getInteger("last.screen.width"); - int screenH = PdePreferences.getInteger("last.screen.height"); + int screenW = Preferences.getInteger("last.screen.width"); + int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { - windowPositionInvalid = true; + windowPositionValid = false; } + int windowX = Preferences.getInteger("last.window.x"); + int windowY = Preferences.getInteger("last.window.y"); + if ((windowX < 0) || (windowY < 0) || + (windowX > screenW) || (windowY > screenH)) { + windowPositionValid = false; + } + } else { - windowPositionInvalid = true; + windowPositionValid = false; } - if (windowPositionInvalid) { + if (!windowPositionValid) { //System.out.println("using default size"); - int windowH = PdePreferences.getInteger("default.window.height"); - int windowW = PdePreferences.getInteger("default.window.width"); + int windowH = Preferences.getInteger("default.window.height"); + int windowW = Preferences.getInteger("default.window.width"); setBounds((screen.width - windowW) / 2, (screen.height - windowH) / 2, windowW, windowH); // this will be invalid as well, so grab the new value - PdePreferences.setInteger("last.divider.location", + Preferences.setInteger("last.divider.location", splitPane.getDividerLocation()); } else { - setBounds(PdePreferences.getInteger("last.window.x"), - PdePreferences.getInteger("last.window.y"), - PdePreferences.getInteger("last.window.width"), - PdePreferences.getInteger("last.window.height")); + setBounds(Preferences.getInteger("last.window.x"), + Preferences.getInteger("last.window.y"), + Preferences.getInteger("last.window.width"), + Preferences.getInteger("last.window.height")); } - // last sketch that was in use + // last sketch that was in use, or used to launch the app - //String sketchName = PdePreferences.get("last.sketch.name"); - String sketchPath = PdePreferences.get("last.sketch.path"); - //PdeSketch sketchTemp = new PdeSketch(sketchPath); - - if ((sketchPath != null) && (new File(sketchPath)).exists()) { - // don't check modified because nothing is open yet - handleOpen2(sketchPath); + if (Base.openedAtStartup != null) { + handleOpen2(Base.openedAtStartup); } else { - handleNew2(true); + //String sketchName = Preferences.get("last.sketch.name"); + String sketchPath = Preferences.get("last.sketch.path"); + //Sketch sketchTemp = new Sketch(sketchPath); + + if ((sketchPath != null) && (new File(sketchPath)).exists()) { + // don't check modified because nothing is open yet + handleOpen2(sketchPath); + + } else { + handleNew2(true); + } } // location for the console/editor area divider - int location = PdePreferences.getInteger("last.divider.location"); + int location = Preferences.getInteger("last.divider.location"); splitPane.setDividerLocation(location); @@ -403,7 +338,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler public void applyPreferences() { // apply the setting for 'use external editor' - boolean external = PdePreferences.getBoolean("editor.external"); + boolean external = Preferences.getBoolean("editor.external"); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); @@ -413,19 +348,25 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler TextAreaPainter painter = textarea.getPainter(); if (external) { // disable line highlight and turn off the caret when disabling - Color color = PdePreferences.getColor("editor.external.bgcolor"); + Color color = Preferences.getColor("editor.external.bgcolor"); painter.setBackground(color); - painter.lineHighlight = false; + painter.setLineHighlightEnabled(false); textarea.setCaretVisible(false); } else { - Color color = PdePreferences.getColor("editor.bgcolor"); + Color color = Preferences.getColor("editor.bgcolor"); painter.setBackground(color); - painter.lineHighlight = - PdePreferences.getBoolean("editor.linehighlight"); + boolean highlight = Preferences.getBoolean("editor.linehighlight"); + painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); } + // apply changes to the font size for the editor + //TextAreaPainter painter = textarea.getPainter(); + painter.setFont(Preferences.getFont("editor.font")); + //Font font = painter.getFont(); + //textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); + // in case tab expansion stuff has changed listener.applyPreferences(); @@ -443,23 +384,23 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler // window location information Rectangle bounds = getBounds(); - PdePreferences.setInteger("last.window.x", bounds.x); - PdePreferences.setInteger("last.window.y", bounds.y); - PdePreferences.setInteger("last.window.width", bounds.width); - PdePreferences.setInteger("last.window.height", bounds.height); + Preferences.setInteger("last.window.x", bounds.x); + Preferences.setInteger("last.window.y", bounds.y); + Preferences.setInteger("last.window.width", bounds.width); + Preferences.setInteger("last.window.height", bounds.height); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); - PdePreferences.setInteger("last.screen.width", screen.width); - PdePreferences.setInteger("last.screen.height", screen.height); + Preferences.setInteger("last.screen.width", screen.width); + Preferences.setInteger("last.screen.height", screen.height); // last sketch that was in use - //PdePreferences.set("last.sketch.name", sketchName); - //PdePreferences.set("last.sketch.name", sketch.name); - PdePreferences.set("last.sketch.path", sketch.getMainFilePath()); + //Preferences.set("last.sketch.name", sketchName); + //Preferences.set("last.sketch.name", sketch.name); + Preferences.set("last.sketch.path", sketch.getMainFilePath()); // location for the console/editor area divider int location = splitPane.getDividerLocation(); - PdePreferences.setInteger("last.divider.location", location); + Preferences.setInteger("last.divider.location", location); } @@ -470,7 +411,16 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler JMenuItem item; JMenu menu = new JMenu("File"); - if (!PdePreferences.getBoolean("export.library")) { + /* + menu.add(item = new JMenuItem("do the editor thing")); + item.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); + } + }); + */ + + if (!Preferences.getBoolean("export.library")) { item = newJMenuItem("New", 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { @@ -496,28 +446,6 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler }); menu.add(item); } - - /* - item = newJMenuItem("New code", 'N', true); - item.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - handleNewCode(); - } - }); - menu.add(item); - */ - - /* - item = newJMenuItem("Open", 'O'); - item.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - handleOpen(null); - } - }); - menu.add(item); - menu.add(sketchbook.rebuildMenu()); - menu.add(sketchbook.getExamplesMenu()); - */ menu.add(sketchbook.getOpenMenu()); saveMenuItem = newJMenuItem("Save", 'S'); @@ -575,10 +503,10 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler menu.add(item); // macosx already has its own preferences and quit menu - if (PdeBase.platform != PdeBase.MACOSX) { + if (!Base.isMacOS()) { menu.addSeparator(); - item = new JMenuItem("Preferences"); + item = newJMenuItem("Preferences", ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrefs(); @@ -631,16 +559,15 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler }); menu.add(item); - //menu.add(newJMenuItem("Stop", 'T')); - menu.add(new JMenuItem("Stop")); + item = new JMenuItem("Stop"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleStop(); } }); - menu.addSeparator(); + menu.add(item); - // + menu.addSeparator(); item = new JMenuItem("Add File..."); item.addActionListener(new ActionListener() { @@ -652,15 +579,14 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler menu.add(sketchbook.getImportMenu()); - if ((PdeBase.platform == PdeBase.WINDOWS) || - (PdeBase.platform == PdeBase.MACOSX)) { + if (Base.isWindows() || Base.isMacOS()) { // no way to do an 'open in file browser' on other platforms // since there isn't any sort of standard item = new JMenuItem("Show Sketch Folder"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - //PdeBase.openFolder(sketchDir); - PdeBase.openFolder(sketch.folder); + //Base.openFolder(sketchDir); + Base.openFolder(sketch.folder); } }); menu.add(item); @@ -679,6 +605,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler item = new JMenuItem("Auto Format"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { + //new AutoFormat(Editor.this).show(); handleBeautify(); } }); @@ -687,7 +614,8 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler item = new JMenuItem("Create Font..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - new PdeFontBuilder().show(sketch.dataFolder); + //new CreateFont().show(sketch.dataFolder); + new CreateFont(Editor.this).show(); } }); menu.add(item); @@ -695,10 +623,10 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler item = new JMenuItem("Archive Sketch"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - //new PdeFontBuilder().show(sketch.dataFolder); - Archiver archiver = new Archiver(); - archiver.setup(PdeEditor.this); - archiver.show(); + new Archiver(Editor.this).show(); + //Archiver archiver = new Archiver(); + //archiver.setup(Editor.this); + //archiver.show(); } }); menu.add(item); @@ -714,7 +642,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler item = new JMenuItem("Environment"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - PdeBase.openURL(System.getProperty("user.dir") + File.separator + + Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "environment" + File.separator + "index.html"); } @@ -724,7 +652,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler item = new JMenuItem("Reference"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - PdeBase.openURL(System.getProperty("user.dir") + File.separator + + Base.openURL(System.getProperty("user.dir") + File.separator + "reference" + File.separator + "index.html"); } }); @@ -743,7 +671,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler if (referenceFile == null) { message("No reference available for \"" + text + "\""); } else { - PdeBase.showReference(referenceFile); + Base.showReference(referenceFile); } } } @@ -754,13 +682,13 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler item = newJMenuItem("Visit Processing.org", '5'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - PdeBase.openURL("http://processing.org/"); + Base.openURL("http://processing.org/"); } }); menu.add(item); // macosx already has its own about menu - if (PdeBase.platform != PdeBase.MACOSX) { + if (!Base.isMacOS()) { menu.addSeparator(); item = new JMenuItem("About Processing"); item.addActionListener(new ActionListener() { @@ -850,8 +778,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler /** - * Convenience method for the antidote to overthought - * swing api mess for setting accelerators. + * Convenience method, see below. */ static public JMenuItem newJMenuItem(String title, int what) { return newJMenuItem(title, what, false); @@ -860,9 +787,9 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler /** * A software engineer, somewhere, needs to have his abstraction - * taken away. I hear they jail people in third world countries for - * writing the sort of crappy api that would require a four line - * helpher function to *set the command key* for a menu item. + * taken away. In some countries they jail people for writing the + * sort of crappy api that would require a four line helper function + * to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what, boolean shift) { @@ -957,24 +884,20 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler // so used internally for everything else public void handleAbout() { - //System.out.println("the about box will now be shown"); - final Image image = PdeBase.getImage("about.jpg", this); + final Image image = Base.getImage("about.jpg", this); int w = image.getWidth(this); int h = image.getHeight(this); final Window window = new Window(this) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); - /* - // does nothing.. Graphics2D g2 = (Graphics2D) g; - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_OFF); - */ + g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); - g.drawString(PdeBase.VERSION, 50, 30); + g.drawString(Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { @@ -989,12 +912,15 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler /** - * Show the (already created on app init) preferences window. + * Show the preferences window. */ public void handlePrefs() { + Preferences preferences = new Preferences(); + preferences.showFrame(this); + // since this can't actually block, it'll hide // the editor window while the prefs are open - preferences.showFrame(this); + //preferences.showFrame(this); // and then call applyPreferences if 'ok' is hit // and then unhide @@ -1010,7 +936,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler /** - * Get the contents of the current buffer. Used by the PdeSketch class. + * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); @@ -1018,7 +944,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler /** - * Called by PdeEditorHeader when the tab is changed + * Called by EditorHeader when the tab is changed * (or a new set of files are opened). * @param discardUndo true if undo info to this point should be ignored */ @@ -1041,35 +967,61 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to - //if (PdeBase.getBoolean("console.auto_clear", true)) { - //if (PdePreferences.getBoolean("console.auto_clear", true)) { - if (PdePreferences.getBoolean("console.auto_clear")) { + //if (Base.getBoolean("console.auto_clear", true)) { + //if (Preferences.getBoolean("console.auto_clear", true)) { + if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } presenting = present; + /* if (presenting) { // wipe everything out with a bulbous screen-covering window presentationWindow.show(); presentationWindow.toFront(); } + */ try { if (!sketch.handleRun()) return; - runtime = new PdeRuntime(sketch, this); - runtime.start(presenting ? presentLocation : appletLocation); + runtime = new Runner(sketch, Editor.this); + runtime.start(appletLocation); watcher = new RunButtonWatcher(); - } catch (PdeException e) { + } catch (RunnerException e) { error(e); } catch (Exception e) { e.printStackTrace(); } + + // this doesn't seem to help much or at all + /* + final SwingWorker worker = new SwingWorker() { + public Object construct() { + try { + if (!sketch.handleRun()) return null; + + runtime = new Runner(sketch, Editor.this); + runtime.start(presenting ? presentLocation : appletLocation); + watcher = new RunButtonWatcher(); + + } catch (RunnerException e) { + error(e); + + } catch (Exception e) { + e.printStackTrace(); + } + return null; // needn't return anything + } + }; + worker.start(); + */ //sketch.cleanup(); // where does this go? } + class RunButtonWatcher implements Runnable { Thread thread; @@ -1099,6 +1051,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler } catch (InterruptedException ie) { } + } else { stop(); } @@ -1147,20 +1100,19 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler * mode, this will always be called instead of doStop(). */ public void doClose() { - if (presenting) { - presentationWindow.hide(); - - } else { - try { - // the window will also be null the process was running - // externally. so don't even try setting if window is null - // since PdeRuntime will set the appletLocation when an - // external process is in use. - if (runtime.window != null) { - appletLocation = runtime.window.getLocation(); - } - } catch (NullPointerException e) { } - } + //if (presenting) { + //presentationWindow.hide(); + //} else { + try { + // the window will also be null the process was running + // externally. so don't even try setting if window is null + // since Runner will set the appletLocation when an + // external process is in use. + if (runtime.window != null) { + appletLocation = runtime.window.getLocation(); + } + } catch (NullPointerException e) { } + //} //if (running) doStop(); doStop(); // need to stop if runtime error @@ -1240,7 +1192,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler /** - * Called by PdeEditorStatus to complete the job. + * Called by EditorStatus to complete the job. */ public void checkModified2() { switch (checkModifiedMode) { @@ -1267,6 +1219,19 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler } + /** + * Extra public method so that Sketch can call + * this when a sketch is selected to be deleted, + * and it won't prompt for save as. + */ + public void handleNew() { + doStop(); + handleNewShift = false; + handleNewLibrary = false; + handleNew2(true); + } + + /** * User selected "New Library", this will act just like handleNew * but internally set a flag that the new guy is a library, @@ -1283,25 +1248,36 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler /** * Does all the plumbing to create a new project * then calls handleOpen to load it up. - * @param startup true if the app is starting (auto-create a sketch) + * + * @param noPrompt true if the app is starting (auto-create a sketch) */ - protected void handleNew2(boolean startup) { + protected void handleNew2(boolean noPrompt) { try { String pdePath = - sketchbook.handleNew(startup, handleNewShift, handleNewLibrary); + sketchbook.handleNew(noPrompt, handleNewShift, handleNewLibrary); if (pdePath != null) handleOpen2(pdePath); } catch (IOException e) { // not sure why this would happen, but since there's no way to // recover (outside of creating another new setkch, which might // just cause more trouble), then they've gotta quit. - PdeBase.showError("Problem creating a new sketch", + Base.showError("Problem creating a new sketch", "An error occurred while creating\n" + "a new sketch. Processing must now quit.", e); } } + /** + * This is the implementation of the MRJ open document event, + * and the Windows XP open document will be routed through this too. + */ + public void handleOpenFile(File file) { + //System.out.println("handling open file: " + file); + handleOpen(file.getAbsolutePath()); + } + + /** * Open a sketch given the full path to the .pde file. * Pass in 'null' to prompt the user for the name of the sketch. @@ -1323,6 +1299,18 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler * need to be saved. */ protected void handleOpen2(String path) { + if (sketch != null) { + // if leaving an empty sketch (i.e. the default) do an + // auto-clean right away + if (Base.calcFolderSize(sketch.folder) == 0) { + //System.err.println("removing empty poopster"); + Base.removeDir(sketch.folder); + sketchbook.rebuildMenus(); + } + //} else { + //System.err.println("sketch was null"); + } + try { // check to make sure that this .pde file is // in a folder of the same name @@ -1346,7 +1334,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler //System.out.println("found alt file in same folder"); } else if (!path.endsWith(".pde")) { - PdeBase.showWarning("Bad file selected", + Base.showWarning("Bad file selected", "Processing can only open its own sketches\n" + "and other files ending in .pde", null); return; @@ -1374,7 +1362,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler // create properly named folder File properFolder = new File(file.getParent(), properParent); if (properFolder.exists()) { - PdeBase.showWarning("Error", + Base.showWarning("Error", "A folder named \"" + properParent + "\" " + "already exists. Can't open sketch.", null); return; @@ -1385,7 +1373,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler // copy the sketch inside File properPdeFile = new File(properFolder, file.getName()); File origPdeFile = new File(path); - PdeBase.copyFile(origPdeFile, properPdeFile); + Base.copyFile(origPdeFile, properPdeFile); // remove the original file, so user doesn't get confused origPdeFile.delete(); @@ -1398,13 +1386,13 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler } } - sketch = new PdeSketch(this, path); + sketch = new Sketch(this, path); // TODO re-enable this once export application works //// mobile: exportAppItem removed from mobile //exportAppItem.setEnabled(false && !sketch.isLibrary()); buttons.disableRun(sketch.isLibrary()); header.rebuild(); - if (PdePreferences.getBoolean("console.auto_clear")) { + if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } @@ -1501,10 +1489,10 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler } - /** + /** * Quit, but first ask user if it's ok. Also store preferences * to disk just in case they want to quit. Final exit() happens - * in PdeEditor since it has the callback from PdeEditorStatus. + * in Editor since it has the callback from EditorStatus. */ public void handleQuit() { // stop isn't sufficient with external vm & quit @@ -1523,7 +1511,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler */ protected void handleQuit2() { storePreferences(); - preferences.save(); + Preferences.save(); sketchbook.clean(); @@ -1549,9 +1537,9 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler String prog = textarea.getText(); // TODO re-enable history - //history.record(prog, PdeHistory.BEAUTIFY); + //history.record(prog, SketchHistory.BEAUTIFY); - int tabSize = PdePreferences.getInteger("editor.tabs.size"); + int tabSize = Preferences.getInteger("editor.tabs.size"); char program[] = prog.toCharArray(); StringBuffer buffer = new StringBuffer(); @@ -1698,16 +1686,40 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler public void error(Exception e) { - status.error(e.getMessage()); + //System.out.println("ERORROOROROR 1"); + //status.error(e.getMessage()); + + // not sure if any RuntimeExceptions will actually arrive + // through here, but gonna check for em just in case. + String mess = e.getMessage(); + //System.out.println("MESSY: " + mess); + String rxString = "RuntimeException: "; + if (mess.indexOf(rxString) == 0) { + mess = mess.substring(rxString.length()); + //System.out.println("MESS2: " + mess); + } + status.error(mess); + e.printStackTrace(); } - public void error(PdeException e) { + public void error(RunnerException e) { + //System.out.println("ERORROOROROR 2"); if (e.file >= 0) sketch.setCurrent(e.file); if (e.line >= 0) highlightLine(e.line); - status.error(e.getMessage()); + // remove the RuntimeException: message since it's not + // really all that useful to the user + //status.error(e.getMessage()); + String mess = e.getMessage(); + String rxString = "RuntimeException: "; + if (mess.indexOf(rxString) == 0) { + mess = mess.substring(rxString.length()); + //System.out.println("MESS3: " + mess); + } + status.error(mess); + buttons.clearRun(); } @@ -1788,7 +1800,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler referenceItem = new JMenuItem("Find in Reference"); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - PdeBase.showReference(referenceFile); + Base.showReference(referenceFile); } }); this.add(referenceItem); @@ -1812,7 +1824,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler super.show(component, x, y); } } - + //// mobile: exports MIDlet and executes emulator public void handleRunEmulator() { doClose(); @@ -1825,14 +1837,14 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler // clear the console on each run, unless the user doesn't want to //if (PdeBase.getBoolean("console.auto_clear", true)) { //if (PdePreferences.getBoolean("console.auto_clear", true)) { - if (PdePreferences.getBoolean("console.auto_clear")) { + if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } try { if (!sketch.exportMIDlet()) return; - runtime = new PdeEmulator(sketch, this); + runtime = new Emulator(sketch, this); runtime.start(null); watcher = new RunButtonWatcher(); @@ -1848,7 +1860,7 @@ implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler if (sketch.exportMIDlet()) { message("Done exporting."); File midletDir = new File(sketch.folder, "midlet"); - PdeBase.openFolder(midletDir); + Base.openFolder(midletDir); } else { // error message will already be visible } diff --git a/mobile/app/PdeEditorButtons.java b/mobile/app/EditorButtons.java similarity index 67% rename from mobile/app/PdeEditorButtons.java rename to mobile/app/EditorButtons.java index 7b38adbe7..4e2a0fcd5 100755 --- a/mobile/app/PdeEditorButtons.java +++ b/mobile/app/EditorButtons.java @@ -1,13 +1,10 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* - PdeEditorButtons - run/stop/etc buttons for the ide Part of the Processing project - http://processing.org - Copyright (c) 2004 Ben Fry and the Processing project. - - The original rendition of this code was written by Ben Fry and - Copyright (c) 2001-03 Massachusetts Institute of Technology + Copyright (c) 2004-05 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 it under the terms of the GNU General Public License as published by @@ -19,11 +16,13 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +package processing.app; + import java.awt.*; import java.awt.event.*; import java.awt.font.*; @@ -32,30 +31,33 @@ import javax.swing.*; import javax.swing.event.*; -public class PdeEditorButtons extends JComponent implements MouseInputListener { +/** + * run/stop/etc buttons for the ide + */ +public class EditorButtons extends JComponent implements MouseInputListener { static final String title[] = { - "", "run", "stop", "new", "open", "save", "export" + "Run", "Stop", "New", "Open", "Save", "Export" }; static final int BUTTON_COUNT = title.length; - static final int BUTTON_WIDTH = PdePreferences.GRID_SIZE; - static final int BUTTON_HEIGHT = PdePreferences.GRID_SIZE; + static final int BUTTON_WIDTH = 27; //Preferences.GRID_SIZE; + static final int BUTTON_HEIGHT = 32; //Preferences.GRID_SIZE; + static final int BUTTON_GAP = 15; //BUTTON_WIDTH / 2; - static final int NOTHING = 0; - static final int RUN = 1; - static final int STOP = 2; + static final int RUN = 0; + static final int STOP = 1; - static final int NEW = 3; - static final int OPEN = 4; - static final int SAVE = 5; - static final int EXPORT = 6; + static final int NEW = 2; + static final int OPEN = 3; + static final int SAVE = 4; + static final int EXPORT = 5; static final int INACTIVE = 0; static final int ROLLOVER = 1; static final int ACTIVE = 2; - PdeEditor editor; + Editor editor; boolean disableRun; //Label status; @@ -78,23 +80,23 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { Image stateImage[]; int which[]; // mapping indices to implementation - int x1, x2; - int y1[], y2[]; + int x1[], x2[]; + int y1, y2; String status; Font statusFont; Color statusColor; - int statusY; + //int statusY; - public PdeEditorButtons(PdeEditor editor) { + public EditorButtons(Editor editor) { this.editor = editor; - buttons = PdeBase.getImage("buttons.gif", this); + buttons = Base.getImage("buttons.gif", this); buttonCount = 0; which = new int[BUTTON_COUNT]; - which[buttonCount++] = NOTHING; + //which[buttonCount++] = NOTHING; which[buttonCount++] = RUN; which[buttonCount++] = STOP; which[buttonCount++] = NEW; @@ -104,61 +106,40 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { currentRollover = -1; - bgcolor = PdePreferences.getColor("buttons.bgcolor"); + bgcolor = Preferences.getColor("buttons.bgcolor"); status = ""; - //setLayout(null); - //status = new JLabel(); - statusFont = PdePreferences.getFont("buttons.status.font"); - statusColor = PdePreferences.getColor("buttons.status.color"); - //add(status); + statusFont = Preferences.getFont("buttons.status.font"); + statusColor = Preferences.getColor("buttons.status.color"); - //status.setBounds(-5, BUTTON_COUNT * BUTTON_HEIGHT, - // BUTTON_WIDTH + 15, BUTTON_HEIGHT); - //status.setAlignment(Label.CENTER); - statusY = (BUTTON_COUNT + 1) * BUTTON_HEIGHT; + //statusY = (BUTTON_COUNT + 1) * BUTTON_HEIGHT; addMouseListener(this); addMouseMotionListener(this); } - /* - public void update() { - paint(this.getGraphics()); - } - - public void update(Graphics g) { - paint(g); - } - */ - - //public void paintComponent(Graphics g) { - //super.paintComponent(g); - //} - - public void paintComponent(Graphics screen) { if (inactive == null) { inactive = new Image[BUTTON_COUNT]; rollover = new Image[BUTTON_COUNT]; active = new Image[BUTTON_COUNT]; - //state = new int[BUTTON_COUNT]; + int IMAGE_SIZE = 33; for (int i = 0; i < BUTTON_COUNT; i++) { inactive[i] = createImage(BUTTON_WIDTH, BUTTON_HEIGHT); Graphics g = inactive[i].getGraphics(); - g.drawImage(buttons, -(i*BUTTON_WIDTH), -2*BUTTON_HEIGHT, null); + g.drawImage(buttons, -(i*IMAGE_SIZE) - 3, -2*IMAGE_SIZE, null); rollover[i] = createImage(BUTTON_WIDTH, BUTTON_HEIGHT); g = rollover[i].getGraphics(); - g.drawImage(buttons, -(i*BUTTON_WIDTH), -1*BUTTON_HEIGHT, null); + g.drawImage(buttons, -(i*IMAGE_SIZE) - 3, -1*IMAGE_SIZE, null); active[i] = createImage(BUTTON_WIDTH, BUTTON_HEIGHT); g = active[i].getGraphics(); - g.drawImage(buttons, -(i*BUTTON_WIDTH), -0*BUTTON_HEIGHT, null); + g.drawImage(buttons, -(i*IMAGE_SIZE) - 3, -0*IMAGE_SIZE, null); } state = new int[buttonCount]; @@ -168,23 +149,24 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { } } Dimension size = size(); - if ((offscreen == null) || + if ((offscreen == null) || (size.width != width) || (size.height != height)) { offscreen = createImage(size.width, size.height); width = size.width; height = size.height; - x1 = 0; - x2 = BUTTON_WIDTH; + y1 = 0; + y2 = BUTTON_HEIGHT; - y1 = new int[buttonCount]; - y2 = new int[buttonCount]; + x1 = new int[buttonCount]; + x2 = new int[buttonCount]; - int offsetY = 0; + int offsetX = 3; for (int i = 0; i < buttonCount; i++) { - y1[i] = offsetY; - y2[i] = offsetY + BUTTON_HEIGHT; - offsetY = y2[i]; + x1[i] = offsetX; + if (i == 2) x1[i] += BUTTON_GAP; + x2[i] = x1[i] + BUTTON_WIDTH; + offsetX = x2[i]; } } Graphics g = offscreen.getGraphics(); @@ -192,31 +174,31 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { g.fillRect(0, 0, width, height); for (int i = 0; i < buttonCount; i++) { - //g.drawImage(stateImage[i], x1[i], y1, null); - g.drawImage(stateImage[i], x1, y1[i], null); + g.drawImage(stateImage[i], x1[i], y1, null); } g.setColor(statusColor); g.setFont(statusFont); - // if i ever find the guy who wrote the java2d api, - // i will hurt him. or just laugh in his face. or pity him. + /* + // if i ever find the guy who wrote the java2d api, i will hurt him. Graphics2D g2 = (Graphics2D) g; FontRenderContext frc = g2.getFontRenderContext(); float statusW = (float) statusFont.getStringBounds(status, frc).getWidth(); float statusX = (getSize().width - statusW) / 2; - - //int statusWidth = g.getFontMetrics().stringWidth(status); - //int statusX = (getSize().width - statusWidth) / 2; - g2.drawString(status, statusX, statusY); + */ + //int statusY = (BUTTON_HEIGHT + statusFont.getAscent()) / 2; + int statusY = (BUTTON_HEIGHT + g.getFontMetrics().getAscent()) / 2; + g.drawString(status, buttonCount * BUTTON_WIDTH + 2 * BUTTON_GAP, statusY); + screen.drawImage(offscreen, 0, 0, null); } public void mouseMoved(MouseEvent e) { // mouse events before paint(); - if (state == null) return; + if (state == null) return; if (state[OPEN] != INACTIVE) { // avoid flicker, since there will probably be an update event @@ -233,8 +215,8 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { public void handleMouse(int x, int y) { if (currentRollover != -1) { - if ((y > y1[currentRollover]) && (x > x1) && - (y < y2[currentRollover]) && (x < x2)) { + if ((x > x1[currentRollover]) && (y > y1) && + (x < x2[currentRollover]) && (y < y2)) { return; } else { @@ -256,15 +238,14 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { private int findSelection(int x, int y) { - // if app loads slowly and cursor is near the buttons + // if app loads slowly and cursor is near the buttons // when it comes up, the app may not have time to load - if ((y1 == null) || (y2 == null)) return -1; + if ((x1 == null) || (x2 == null)) return -1; for (int i = 0; i < buttonCount; i++) { - if ((x > x1) && (y > y1[i]) && - (x < x2) && (y < y2[i])) { - //if ((x > x1[i]) && (y > y1) && - //(x < x2[i]) && (y < y2)) { + if ((y > y1) && (x > x1[i]) && + (y < y2) && (x < x2[i])) { + //System.out.println("sel is " + i); return i; } } @@ -277,13 +258,13 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { state[slot] = newState; switch (newState) { case INACTIVE: - stateImage[slot] = inactive[which[slot]]; + stateImage[slot] = inactive[which[slot]]; break; - case ACTIVE: - stateImage[slot] = active[which[slot]]; + case ACTIVE: + stateImage[slot] = active[which[slot]]; break; - case ROLLOVER: - stateImage[slot] = rollover[which[slot]]; + case ROLLOVER: + stateImage[slot] = rollover[which[slot]]; message(title[which[slot]]); break; } @@ -301,13 +282,7 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { if (state[OPEN] != INACTIVE) { setState(OPEN, INACTIVE, true); } - - // kludge - //for (int i = 0; i < BUTTON_COUNT; i++) { - //messageClear(title[i]); - //} status = ""; - //mouseMove(e); handleMouse(e.getX(), e.getY()); } @@ -317,7 +292,7 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); - + int sel = findSelection(x, y); ///if (sel == -1) return false; if (sel == -1) return; @@ -344,16 +319,16 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { public void mouseReleased(MouseEvent e) { switch (currentSelection) { - case RUN: + case RUN: if (!disableRun) { - editor.handleRunEmulator();//(e.isShiftDown()); + editor.handleRunEmulator();//(e.isShiftDown()); } break; - case STOP: + case STOP: if (!disableRun) { - setState(RUN, INACTIVE, true); - editor.handleStop(); + setState(RUN, INACTIVE, true); + editor.handleStop(); } break; @@ -405,13 +380,25 @@ public class PdeEditorButtons extends JComponent implements MouseInputListener { status = msg; } + public void messageClear(String msg) { - //if (status.getText().equals(msg + " ")) status.setText(PdeEditor.EMPTY); + //if (status.getText().equals(msg + " ")) status.setText(Editor.EMPTY); if (status.equals(msg)) status = ""; } public Dimension getPreferredSize() { - return new Dimension(BUTTON_WIDTH, (BUTTON_COUNT + 1)*BUTTON_HEIGHT); + return new Dimension((BUTTON_COUNT + 1)*BUTTON_WIDTH, BUTTON_HEIGHT); + //return new Dimension(BUTTON_WIDTH, (BUTTON_COUNT + 1)*BUTTON_HEIGHT); + } + + + public Dimension getMinimumSize() { + return getPreferredSize(); + } + + + public Dimension getMaximumSize() { + return new Dimension(3000, BUTTON_HEIGHT); } } diff --git a/mobile/app/PdeEmulator.java b/mobile/app/Emulator.java similarity index 71% rename from mobile/app/PdeEmulator.java rename to mobile/app/Emulator.java index 23819b35f..aa9812c2f 100755 --- a/mobile/app/PdeEmulator.java +++ b/mobile/app/Emulator.java @@ -1,3 +1,5 @@ +package processing.app; + import java.awt.Point; import java.io.*; @@ -5,16 +7,16 @@ import java.io.*; * * @author Francis Li */ -public class PdeEmulator extends PdeRuntime { +public class Emulator extends Runner { - /** Creates a new instance of PdeEmulator */ - public PdeEmulator(PdeSketch sketch, PdeEditor editor) { + /** Creates a new instance of Emulator */ + public Emulator(Sketch sketch, Editor editor) { super(sketch, editor); } - public void start(Point windowLocation) throws PdeException { + public void start(Point windowLocation) throws RunnerException { try{ - String wtkBinPath = PdePreferences.get("wtk.path") + File.separator + "bin"; + String wtkBinPath = Preferences.get("wtk.path") + File.separator + "bin"; StringBuffer command = new StringBuffer(); command.append(wtkBinPath); @@ -29,7 +31,7 @@ public class PdeEmulator extends PdeRuntime { process = Runtime.getRuntime().exec(command.toString(), null, new File(wtkBinPath)); processInput = new SystemOutSiphon(process.getInputStream()); - processError = new PdeMessageSiphon(process.getErrorStream(), this); + processError = new MessageSiphon(process.getErrorStream(), this); processOutput = process.getOutputStream(); } catch (Exception e) { e.printStackTrace(); diff --git a/mobile/app/PdePreverifier.java b/mobile/app/Preverifier.java similarity index 83% rename from mobile/app/PdePreverifier.java rename to mobile/app/Preverifier.java index 36f678fae..d352fa459 100755 --- a/mobile/app/PdePreverifier.java +++ b/mobile/app/Preverifier.java @@ -1,12 +1,14 @@ +package processing.app; + import java.io.*; -public class PdePreverifier implements PdeMessageConsumer { +public class Preverifier implements MessageConsumer { - public PdePreverifier() { + public Preverifier() { } public boolean preverify(File source, File output) { - String wtkPath = PdePreferences.get("wtk.path"); + String wtkPath = Preferences.get("wtk.path"); String wtkBinPath = wtkPath + File.separator + "bin" + File.separator; String wtkLibPath = wtkPath + File.separator + "lib" + File.separator; @@ -32,8 +34,8 @@ public class PdePreverifier implements PdeMessageConsumer { while (running) { try { result = p.waitFor(); - new PdeMessageSiphon(p.getInputStream(), this); - new PdeMessageSiphon(p.getErrorStream(), this); + new MessageSiphon(p.getInputStream(), this); + new MessageSiphon(p.getErrorStream(), this); running = false; } catch (InterruptedException ie) { diff --git a/mobile/app/PdeSketch.java b/mobile/app/Sketch.java similarity index 76% rename from mobile/app/PdeSketch.java rename to mobile/app/Sketch.java index 079b1210a..a3059a97e 100755 --- a/mobile/app/PdeSketch.java +++ b/mobile/app/Sketch.java @@ -1,10 +1,9 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* - PdeSketch - stores information about files in the current sketch Part of the Processing project - http://processing.org - Except where noted, code is written by Ben Fry + Copyright (c) 2004-05 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 @@ -22,6 +21,9 @@ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +package processing.app; + +import processing.app.preproc.*; import processing.core.*; import java.awt.FileDialog; @@ -35,11 +37,14 @@ import javax.swing.JOptionPane; import com.oroinc.text.regex.*; -public class PdeSketch { - static String TEMP_BUILD_PATH = "lib" + File.separator + "build"; +/** + * Stores information about files in the current sketch + */ +public class Sketch { + //static String TEMP_BUILD_PATH = "lib" + File.separator + "build"; static File tempBuildFolder; - PdeEditor editor; + Editor editor; // name of sketch, which is the name of main file // (without .pde or .java extension) @@ -55,18 +60,20 @@ public class PdeSketch { boolean library; // true if it's a library public File folder; //sketchFolder; - File dataFolder; - File codeFolder; + public File dataFolder; + public File codeFolder; static final int PDE = 0; static final int JAVA = 1; - PdeCode current; + public SketchCode current; int codeCount; - PdeCode code[]; + SketchCode code[]; int hiddenCount; - PdeCode hidden[]; + SketchCode hidden[]; + + Hashtable zipFileContents; // all these set each time build() is called String mainClassName; @@ -79,7 +86,7 @@ public class PdeSketch { * path is location of the main .pde file, because this is also * simplest to use when opening the file from the finder/explorer. */ - public PdeSketch(PdeEditor editor, String path) throws IOException { + public Sketch(Editor editor, String path) throws IOException { this.editor = editor; File mainFile = new File(path); @@ -99,29 +106,25 @@ public class PdeSketch { // lib/build must exist when the application is started // it is added to the CLASSPATH by default, but if it doesn't // exist when the application is started, then java will remove - // the entry from the CLASSPATH, causing PdeRuntime to fail. + // the entry from the CLASSPATH, causing Runner to fail. // + /* tempBuildFolder = new File(TEMP_BUILD_PATH); if (!tempBuildFolder.exists()) { tempBuildFolder.mkdirs(); - PdeBase.showError("Required folder missing", + Base.showError("Required folder missing", "A required folder was missing from \n" + "from your installation of Processing.\n" + "It has now been replaced, please restart \n" + "the application to complete the repair.", null); } + */ + tempBuildFolder = Base.getBuildFolder(); + //Base.addBuildFolderToClassPath(); folder = new File(new File(path).getParent()); //System.out.println("sketch dir is " + folder); - codeFolder = new File(folder, "code"); - dataFolder = new File(folder, "data"); - - File libraryFolder = new File(folder, "library"); - if (libraryFolder.exists()) { - library = true; - } - load(); } @@ -134,10 +137,21 @@ public class PdeSketch { * a nightmare to keep track of what files went where, because * not all the data will be saved to disk. * - * The exception is when an external editor is in use, + * This also gets called when the main sketch file is renamed, + * because the sketch has to be reloaded from a different folder. + * + * Another exception is when an external editor is in use, * in which case the load happens each time "run" is hit. */ public void load() { + codeFolder = new File(folder, "code"); + dataFolder = new File(folder, "data"); + + File libraryFolder = new File(folder, "library"); + if (libraryFolder.exists()) { + library = true; + } + // get list of files in the sketch folder String list[] = folder.list(); @@ -148,8 +162,8 @@ public class PdeSketch { else if (list[i].endsWith(".java.x")) hiddenCount++; } - code = new PdeCode[codeCount]; - hidden = new PdeCode[hiddenCount]; + code = new SketchCode[codeCount]; + hidden = new SketchCode[hiddenCount]; int codeCounter = 0; int hiddenCounter = 0; @@ -157,25 +171,25 @@ public class PdeSketch { for (int i = 0; i < list.length; i++) { if (list[i].endsWith(".pde")) { code[codeCounter++] = - new PdeCode(list[i].substring(0, list[i].length() - 4), + new SketchCode(list[i].substring(0, list[i].length() - 4), new File(folder, list[i]), PDE); } else if (list[i].endsWith(".java")) { code[codeCounter++] = - new PdeCode(list[i].substring(0, list[i].length() - 5), + new SketchCode(list[i].substring(0, list[i].length() - 5), new File(folder, list[i]), JAVA); } else if (list[i].endsWith(".pde.x")) { hidden[hiddenCounter++] = - new PdeCode(list[i].substring(0, list[i].length() - 6), + new SketchCode(list[i].substring(0, list[i].length() - 6), new File(folder, list[i]), PDE); } else if (list[i].endsWith(".java.x")) { hidden[hiddenCounter++] = - new PdeCode(list[i].substring(0, list[i].length() - 7), + new SketchCode(list[i].substring(0, list[i].length() - 7), new File(folder, list[i]), JAVA); } @@ -185,7 +199,10 @@ public class PdeSketch { // remove any entries that didn't load properly int index = 0; while (index < codeCount) { - if (code[index].program == null) { + //System.out.println("code is " + code); + //System.out.println(index + " " + code[index]); + if ((code[index] == null) || + (code[index].program == null)) { //hide(index); // although will this file be hidable? for (int i = index+1; i < codeCount; i++) { code[i-1] = code[i]; @@ -204,7 +221,7 @@ public class PdeSketch { for (int i = 1; i < codeCount; i++) { if (code[i].file.getName().equals(mainFilename)) { //System.out.println("found main code at slot " + i); - PdeCode temp = code[0]; + SketchCode temp = code[0]; code[0] = code[i]; code[i] = temp; break; @@ -220,10 +237,13 @@ public class PdeSketch { } - protected void insertCode(PdeCode newCode) { + protected void insertCode(SketchCode newCode) { + // make sure the user didn't hide the sketch folder + ensureExistence(); + // add file to the code/codeCount list, resort the list if (codeCount == code.length) { - PdeCode temp[] = new PdeCode[codeCount+1]; + SketchCode temp[] = new SketchCode[codeCount+1]; System.arraycopy(code, 0, temp, 0, codeCount); code = temp; } @@ -242,7 +262,7 @@ public class PdeSketch { } } if (who != i) { // swap with someone if changes made - PdeCode temp = code[who]; + SketchCode temp = code[who]; code[who] = code[i]; code[i] = temp; } @@ -253,6 +273,9 @@ public class PdeSketch { public void newCode() { + // make sure the user didn't hide the sketch folder + ensureExistence(); + //System.out.println("new code"); // ask for name of new file // maybe just popup a text area? @@ -262,8 +285,11 @@ public class PdeSketch { public void renameCode() { + // make sure the user didn't hide the sketch folder + ensureExistence(); + // don't allow rename of the main code - if (current == code[0]) return; + //if (current == code[0]) return; // TODO maybe gray out the menu on setCurrent(0) // ask for new name of file (internal to window) @@ -281,6 +307,9 @@ public class PdeSketch { * where they diverge. */ public void nameCode(String newName) { + // make sure the user didn't hide the sketch folder + ensureExistence(); + // if renaming to the same thing as before, just ignore. // also ignoring case here, because i don't want to write // a bunch of special stuff for each platform @@ -292,6 +321,11 @@ public class PdeSketch { return; } + if (newName.trim().equals("")) { + // don't allow blank names + return; + } + String newFilename = null; int newFlavor = 0; @@ -302,6 +336,14 @@ public class PdeSketch { newFlavor = PDE; } else if (newName.endsWith(".java")) { + if (code[0] == current) { + Base.showWarning("Problem with rename", + "The main .pde file cannot be .java file.\n" + + "(It may be time for your to graduate to a\n" + + "\"real\" programming environment)", null); + return; + } + newFilename = newName; newName = newName.substring(0, newName.length() - 5); newFlavor = JAVA; @@ -315,40 +357,69 @@ public class PdeSketch { // so make sure the user didn't name things poo.time.pde // or something like that (nothing against poo time) if (newName.indexOf('.') != -1) { - newName = PdeSketchbook.sanitizedName(newName); + newName = Sketchbook.sanitizedName(newName); newFilename = newName + ((newFlavor == PDE) ? ".pde" : ".java"); } - // create the new file, new PdeCode object and load it + // create the new file, new SketchCode object and load it File newFile = new File(folder, newFilename); if (newFile.exists()) { // yay! users will try anything - PdeBase.showMessage("Nope", - "A file named \"" + newFile + "\" already exists\n" + - "in \"" + folder.getAbsolutePath() + "\""); + Base.showMessage("Nope", + "A file named \"" + newFile + "\" already exists\n" + + "in \"" + folder.getAbsolutePath() + "\""); return; } if (renamingCode) { if (!current.file.renameTo(newFile)) { - PdeBase.showWarning("Error", - "Could not rename \"" + current.file.getName() + - "\" to \"" + newFile.getName() + "\"", null); + Base.showWarning("Error", + "Could not rename \"" + current.file.getName() + + "\" to \"" + newFile.getName() + "\"", null); return; } - current.file = newFile; - current.name = newName; - current.flavor = newFlavor; + + if (current == code[0]) { + // if renaming the main class, now rename the folder and re-open + File newFolder = new File(folder.getParentFile(), newName); + boolean success = folder.renameTo(newFolder); + if (!success) { + Base.showWarning("Error", + "Could not rename the sketch.", null); + return; + } + // if successful, set base properties for the sketch + folder = newFolder; + File mainFile = new File(newFolder, newName + ".pde"); + mainFilename = mainFile.getAbsolutePath(); + + // set the sketch name... used by the pde and whatnot. + // the name is only set in the sketch constructor, + // so it's important here + name = newName; + + // get the changes into the sketchbook menu + editor.sketchbook.rebuildMenus(); + + // reload the sketch + load(); + + } else { + // just reopen the class itself + current.file = newFile; + current.name = newName; + current.flavor = newFlavor; + } } else { // creating a new file try { newFile.createNewFile(); // TODO returns a boolean } catch (IOException e) { - PdeBase.showWarning("Error", - "Could not create the file \"" + newFile + "\"\n" + - "in \"" + folder.getAbsolutePath() + "\"", e); + Base.showWarning("Error", + "Could not create the file \"" + newFile + "\"\n" + + "in \"" + folder.getAbsolutePath() + "\"", e); return; } - PdeCode newCode = new PdeCode(newName, newFile, newFlavor); + SketchCode newCode = new SketchCode(newName, newFile, newFlavor); insertCode(newCode); } @@ -367,18 +438,24 @@ public class PdeSketch { * Remove a piece of code from the sketch and from the disk. */ public void deleteCode() { + // make sure the user didn't hide the sketch folder + ensureExistence(); + // don't allow delete of the main code // TODO maybe gray out the menu on setCurrent(0) + /* if (current == code[0]) { - PdeBase.showMessage("Can't do that", + Base.showMessage("Can't do that", "You cannot delete the main " + ".pde file from a sketch\n"); return; } + */ // confirm deletion with user, yes/no Object[] options = { "OK", "Cancel" }; - String prompt = + String prompt = (current == code[0]) ? + "Are you sure you want to delete this sketch?" : "Are you sure you want to delete \"" + current.name + "\"?"; int result = JOptionPane.showOptionDialog(editor, prompt, @@ -389,26 +466,38 @@ public class PdeSketch { options, options[0]); if (result == JOptionPane.YES_OPTION) { - // delete the file - if (!current.file.delete()) { - PdeBase.showMessage("Couldn't do it", - "Could not delete \"" + current.name + "\"."); - return; + if (current == code[0]) { + // delete the entire sketch + Base.removeDir(folder); + + // get the changes into the sketchbook menu + //sketchbook.rebuildMenus(); + + // make a new sketch, and i think this will rebuild the sketch menu + editor.handleNew(); + + } else { + // delete the file + if (!current.file.delete()) { + Base.showMessage("Couldn't do it", + "Could not delete \"" + current.name + "\"."); + return; + } + + // remove code from the list + removeCode(current); + + // just set current tab to the main tab + setCurrent(0); + + // update the tabs + editor.header.repaint(); } - - // remove code from the list - removeCode(current); - - // just set current tab to the main tab - setCurrent(0); - - // update the tabs - editor.header.repaint(); } } - protected void removeCode(PdeCode which) { + protected void removeCode(SketchCode which) { // remove it from the internal list of files // resort internal list of files for (int i = 0; i < codeCount; i++) { @@ -428,25 +517,25 @@ public class PdeSketch { // don't allow hide of the main code // TODO maybe gray out the menu on setCurrent(0) if (current == code[0]) { - PdeBase.showMessage("Can't do that", - "You cannot hide the main " + - ".pde file from a sketch\n"); + Base.showMessage("Can't do that", + "You cannot hide the main " + + ".pde file from a sketch\n"); return; } // rename the file File newFile = new File(current.file.getAbsolutePath() + ".x"); if (!current.file.renameTo(newFile)) { - PdeBase.showWarning("Error", - "Could not hide " + - "\"" + current.file.getName() + "\".", null); + Base.showWarning("Error", + "Could not hide " + + "\"" + current.file.getName() + "\".", null); return; } current.file = newFile; // move it to the hidden list if (hiddenCount == hidden.length) { - PdeCode temp[] = new PdeCode[hiddenCount+1]; + SketchCode temp[] = new SketchCode[hiddenCount+1]; System.arraycopy(hidden, 0, temp, 0, hiddenCount); hidden = temp; } @@ -463,10 +552,13 @@ public class PdeSketch { public void unhideCode(String what) { //System.out.println("unhide " + e); - int unhideIndex = -1; + //int unhideIndex = -1; + SketchCode unhideCode = null; + for (int i = 0; i < hiddenCount; i++) { if (hidden[i].name.equals(what)) { - unhideIndex = i; + //unhideIndex = i; + unhideCode = hidden[i]; // remove from the 'hidden' list for (int j = i; j < hiddenCount-1; j++) { @@ -476,14 +568,14 @@ public class PdeSketch { break; } } - if (unhideIndex == -1) { + //if (unhideIndex == -1) { + if (unhideCode == null) { System.err.println("internal error: could find " + what + " to unhide."); return; } - PdeCode unhideCode = hidden[unhideIndex]; if (!unhideCode.file.exists()) { - PdeBase.showMessage("Can't unhide", - "The file \"" + what + "\" no longer exists."); + Base.showMessage("Can't unhide", + "The file \"" + what + "\" no longer exists."); //System.out.println(unhideCode.file); return; } @@ -492,9 +584,9 @@ public class PdeSketch { new File(unhidePath.substring(0, unhidePath.length() - 2)); if (!unhideCode.file.renameTo(unhideFile)) { - PdeBase.showMessage("Can't unhide", - "The file \"" + what + "\" could not be" + - "renamed and unhidden."); + Base.showMessage("Can't unhide", + "The file \"" + what + "\" could not be" + + "renamed and unhidden."); return; } unhideCode.file = unhideFile; @@ -534,24 +626,58 @@ public class PdeSketch { } + /** + * Make sure the sketch hasn't been moved or deleted by some + * nefarious user. If they did, try to re-create it and save. + */ + protected void ensureExistence() { + if (folder.exists()) return; + + Base.showWarning("Sketch disappeared", + "The sketch folder has disappeared (did you " + + "delete it? Are you trying to f-- with me?)\n" + + "Will attempt to re-save in the same location," + + "but anything besides the code will be lost.", null); + try { + folder.mkdirs(); + modified = true; + + for (int i = 0; i < codeCount; i++) { + //code[i].modified = true; // make sure it gets re-saved + code[i].save(); + } + calcModified(); + + } catch (Exception e) { + Base.showWarning("Could not re-save sketch", + "Could not properly re-save the sketch. " + + "You may be in trouble at this point,\n" + + "and it might be time to copy and paste " + + "your code to another text editor.", e); + } + } + + /** * Save all code in the current sketch. */ public boolean save() throws IOException { + // make sure the user didn't hide the sketch folder + ensureExistence(); + // first get the contents of the editor text area if (current.modified) { current.program = editor.getText(); } - // see if actually modified + // don't do anything if not actually modified if (!modified) return false; - // check if the files are read-only. - // if so, need to first do a "save as". if (isReadOnly()) { - PdeBase.showMessage("Sketch is read-only", - "Some files are marked \"read-only\", so you'll\n" + - "need to re-save this sketch to another location."); + // if the files are read-only, need to first do a "save as". + Base.showMessage("Sketch is read-only", + "Some files are marked \"read-only\", so you'll\n" + + "need to re-save this sketch to another location."); // if the user cancels, give up on the save() if (!saveAs()) return false; } @@ -571,12 +697,13 @@ public class PdeSketch { /** - * handles 'save as' for a sketch.. essentially duplicates - * the current sketch folder to a new location, and then calls - * 'save'. (needs to take the current state of the open files - * and save them to the new folder.. but not save over the old - * versions for the old sketch..) - * + * Handles 'save as' for a sketch. + *

+ * This basically just duplicates the current sketch folder to + * a new location, and then calls 'Save'. (needs to take the current + * state of the open files and save them to the new folder.. + * but not save over the old versions for the old sketch..) + *

* also removes the previously-generated .class and .jar files, * because they can cause trouble. */ @@ -585,14 +712,13 @@ public class PdeSketch { FileDialog fd = new FileDialog(editor, //new Frame(), "Save sketch folder as...", FileDialog.SAVE); - // always default to the sketchbook folder.. - //fd.setDirectory(PdePreferences.get("sketchbook.path")); - fd.setDirectory(folder.getParent()); + if (isReadOnly()) { + // default to the sketchbook folder + fd.setDirectory(Preferences.get("sketchbook.path")); + } else { + fd.setDirectory(folder.getParent()); + } fd.setFile(folder.getName()); - //System.out.println("setting to " + folder.getParent()); - - // TODO or maybe this should default to the - // parent dir of the old folder? fd.show(); String newParentDir = fd.getDirectory(); @@ -600,16 +726,16 @@ public class PdeSketch { // user cancelled selection if (newName == null) return false; - newName = PdeSketchbook.sanitizeName(newName); + newName = Sketchbook.sanitizeName(newName); // new sketch folder File newFolder = new File(newParentDir, newName); // make sure the paths aren't the same if (newFolder.equals(folder)) { - PdeBase.showWarning("You can't fool me", - "The new sketch name and location are the same\n" + - "as the old. I ain't not doin nuthin'.", null); + Base.showWarning("You can't fool me", + "The new sketch name and location are the same as\n" + + "the old. I ain't not doin nuthin' not now.", null); return false; } @@ -622,17 +748,26 @@ public class PdeSketch { //System.out.println(oldPath); if (newPath.indexOf(oldPath) == 0) { - PdeBase.showWarning("How very Borges of you", - "You cannot save the sketch into a folder\n" + - "inside itself. This would go on forever.", null); + Base.showWarning("How very Borges of you", + "You cannot save the sketch into a folder\n" + + "inside itself. This would go on forever.", null); return false; } } catch (IOException e) { } - // copy the entire contents of the sketch folder - PdeBase.copyDir(folder, newFolder); + // if the new folder already exists, then need to remove + // its contents before copying everything over + // (user will have already been warned) + if (newFolder.exists()) { + Base.removeDir(newFolder); + } + // in fact, you can't do this on windows because it tries + // to go into the same folder, but it happens on osx a lot. - // change the references to the dir location in PdeCode files + // copy the entire contents of the sketch folder + Base.copyDir(folder, newFolder); + + // change the references to the dir location in SketchCode files for (int i = 0; i < codeCount; i++) { code[i].file = new File(newFolder, code[i].file.getName()); } @@ -647,7 +782,9 @@ public class PdeSketch { code[0].name = newName; // write the contents to the renamed file // (this may be resaved if the code is modified) - code[0].save(); + code[0].modified = true; + //code[0].save(); + //System.out.println("modified is " + modified); // change the other paths String oldName = name; @@ -660,9 +797,9 @@ public class PdeSketch { // remove the 'applet', 'application', 'library' folders // from the copied version. // otherwise their .class and .jar files can cause conflicts. - PdeBase.removeDir(new File(folder, "applet")); - PdeBase.removeDir(new File(folder, "application")); - PdeBase.removeDir(new File(folder, "library")); + Base.removeDir(new File(folder, "applet")); + Base.removeDir(new File(folder, "application")); + Base.removeDir(new File(folder, "library")); // do a "save" // this will take care of the unsaved changes in each of the tabs @@ -670,12 +807,12 @@ public class PdeSketch { // get the changes into the sketchbook menu //sketchbook.rebuildMenu(); - // done inside PdeEditor instead + // done inside Editor instead // update the tabs for the name change editor.header.repaint(); - // let PdeEditor know that the save was successful + // let Editor know that the save was successful return true; } @@ -729,7 +866,7 @@ public class PdeSketch { // make sure they aren't the same file if (!addingCode && sourceFile.equals(destFile)) { - PdeBase.showWarning("You can't fool me", + Base.showWarning("You can't fool me", "This file has already been copied to the\n" + "location where you're trying to add it.\n" + "I ain't not doin nuthin'.", null); @@ -740,9 +877,9 @@ public class PdeSketch { // to update the sketch's tabs if (!sourceFile.equals(destFile)) { try { - PdeBase.copyFile(sourceFile, destFile); + Base.copyFile(sourceFile, destFile); } catch (IOException e) { - PdeBase.showWarning("Error adding file", + Base.showWarning("Error adding file", "Could not add '" + filename + "' to the sketch.", e); } @@ -761,7 +898,7 @@ public class PdeSketch { } // see also "nameCode" for identical situation - PdeCode newCode = new PdeCode(newName, destFile, newFlavor); + SketchCode newCode = new SketchCode(newName, destFile, newFlavor); insertCode(newCode); sortCode(); setCurrent(newName); @@ -771,7 +908,10 @@ public class PdeSketch { public void addLibrary(String jarPath) { - String list[] = PdeCompiler.packageListFromClassPath(jarPath); + // make sure the user didn't hide the sketch folder + ensureExistence(); + + String list[] = Compiler.packageListFromClassPath(jarPath); // import statements into the main sketch file (code[0]) // if the current code is a .java file, insert into current @@ -796,9 +936,11 @@ public class PdeSketch { /** * Change what file is currently being edited. - * 1. store the String for the text of the current file. - * 2. retrieve the String for the text of the new file. - * 3. change the text that's visible in the text area + *

    + *
  1. store the String for the text of the current file. + *
  2. retrieve the String for the text of the new file. + *
  3. change the text that's visible in the text area + *
*/ public void setCurrent(int which) { // get the text currently being edited @@ -845,13 +987,13 @@ public class PdeSketch { System.gc(); // note that we can't remove the builddir itself, otherwise - // the next time we start up, internal runs using PdeRuntime won't + // the next time we start up, internal runs using Runner won't // work because the build dir won't exist at startup, so the classloader // will ignore the fact that that dir is in the CLASSPATH in run.sh // //File dirObject = new File(TEMP_BUILD_PATH); - //PdeBase.removeDescendants(dirObject); - PdeBase.removeDescendants(tempBuildFolder); + //Base.removeDescendants(dirObject); + Base.removeDescendants(tempBuildFolder); } @@ -881,16 +1023,19 @@ public class PdeSketch { * * X. afterwards, some of these steps need a cleanup function */ - //public void run() throws PdeException { - public boolean handleRun() throws PdeException { + //public void run() throws RunnerException { + public boolean handleRun() throws RunnerException { + // make sure the user didn't hide the sketch folder + ensureExistence(); + current.program = editor.getText(); // TODO record history here - //current.history.record(program, PdeHistory.RUN); + //current.history.record(program, SketchHistory.RUN); // if an external editor is being used, need to grab the // latest version of the code from the file. - if (PdePreferences.getBoolean("editor.external")) { + if (Preferences.getBoolean("editor.external")) { // history gets screwed by the open.. //String historySaved = history.lastRecorded; //handleOpen(sketch); @@ -913,20 +1058,22 @@ public class PdeSketch { "_" + String.valueOf((int) (Math.random() * 10000))); // handle preprocessing the main file's code - mainClassName = build(TEMP_BUILD_PATH, suggestedClassName); + //mainClassName = build(TEMP_BUILD_PATH, suggestedClassName); + mainClassName = + build(tempBuildFolder.getAbsolutePath(), suggestedClassName); // externalPaths is magically set by build() if (!externalRuntime) { // only if not running externally already // copy contents of data dir into lib/build if (dataFolder.exists()) { // just drop the files in the build folder (pre-68) - //PdeBase.copyDir(dataDir, buildDir); + //Base.copyDir(dataDir, buildDir); // drop the files into a 'data' subfolder of the build dir try { - PdeBase.copyDir(dataFolder, new File(tempBuildFolder, "data")); + Base.copyDir(dataFolder, new File(tempBuildFolder, "data")); } catch (IOException e) { e.printStackTrace(); - throw new PdeException("Problem copying files from data folder"); + throw new RunnerException("Problem copying files from data folder"); } } } @@ -937,12 +1084,12 @@ public class PdeSketch { /* if (externalPaths == null) { externalPaths = - PdeCompiler.calcClassPath(null) + File.pathSeparator + + Compiler.calcClassPath(null) + File.pathSeparator + tempBuildPath; } else { externalPaths = tempBuildPath + File.pathSeparator + - PdeCompiler.calcClassPath(null) + File.pathSeparator + + Compiler.calcClassPath(null) + File.pathSeparator + externalPaths; } */ @@ -957,7 +1104,7 @@ public class PdeSketch { */ // create a runtime object -// runtime = new PdeRuntime(this, editor); +// runtime = new Runner(this, editor); // if programType is ADVANCED // or the code/ folder is not empty -> or just exists (simpler) @@ -968,7 +1115,7 @@ public class PdeSketch { // use the runtime object to consume the errors now // no need to bother recycling the old guy - //PdeMessageStream messageStream = new PdeMessageStream(runtime); + //MessageStream messageStream = new MessageStream(runtime); // start the applet // runtime.start(presenting ? presentLocation : appletLocation); //, @@ -1001,71 +1148,96 @@ public class PdeSketch { * * In an advanced program, the returned classname could be different, * which is why the className is set based on the return value. - * A compilation error will burp up a PdeException. + * A compilation error will burp up a RunnerException. * * @return null if compilation failed, main class name if not */ protected String build(String buildPath, String suggestedClassName) - throws PdeException { - //String importPackageList[] = null; + throws RunnerException { +/* + // make sure the user didn't hide the sketch folder + ensureExistence(); + + String codeFolderPackages[] = null; +*/ String javaClassPath = System.getProperty("java.class.path"); // remove quotes if any.. this is an annoying thing on windows if (javaClassPath.startsWith("\"") && javaClassPath.endsWith("\"")) { javaClassPath = javaClassPath.substring(1, javaClassPath.length() - 1); } - javaClassPath = PdeSketchbook.librariesClassPath + File.pathSeparator + + + javaClassPath = Sketchbook.librariesClassPath + File.pathSeparator + javaClassPath; return build(buildPath, suggestedClassName, null, null, - PdeCompiler.calcBootClassPath(), javaClassPath); + Compiler.calcBootClassPath(), javaClassPath); } protected String build(String buildPath, String suggestedClassName, String baseClass, String[] baseImports, String bootClassPath, String additionalClassPath) - throws PdeException { + throws RunnerException { + // make sure the user didn't hide the sketch folder + ensureExistence(); String codeFolderPackages[] = null; - + classPath = buildPath; if (additionalClassPath != null) { classPath += File.pathSeparator + additionalClassPath; } +/* + classPath = buildPath + + File.pathSeparator + Sketchbook.librariesClassPath + + File.pathSeparator + javaClassPath; + */ + //System.out.println("cp = " + classPath); // figure out the contents of the code folder to see if there // are files that need to be added to the imports //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { externalRuntime = true; - classPath += File.pathSeparator + - PdeCompiler.contentsToClassPath(codeFolder); - //importPackageList = PdeCompiler.packageListFromClassPath(classPath); + + //classPath += File.pathSeparator + + //Compiler.contentsToClassPath(codeFolder); + classPath = + Compiler.contentsToClassPath(codeFolder) + + File.pathSeparator + classPath; + + //codeFolderPackages = Compiler.packageListFromClassPath(classPath); + //codeFolderPackages = Compiler.packageListFromClassPath(codeFolder); libraryPath = codeFolder.getAbsolutePath(); - + // get a list of .jar files in the "code" folder // (class files in subfolders should also be picked up) String codeFolderClassPath = - PdeCompiler.contentsToClassPath(codeFolder); + Compiler.contentsToClassPath(codeFolder); // get list of packages found in those jars codeFolderPackages = - PdeCompiler.packageListFromClassPath(codeFolderClassPath); + Compiler.packageListFromClassPath(codeFolderClassPath); //PApplet.println(libraryPath); //PApplet.println("packages:"); //PApplet.printarr(codeFolderPackages); + } else { + /* // check to see if multiple files that include a .java file externalRuntime = false; for (int i = 0; i < codeCount; i++) { if (code[i].flavor == JAVA) externalRuntime = true; } - //externalRuntime = (codeCount > 1); // may still be set true later - //importPackageList = null; + */ + // since using the special classloader, + // run externally whenever there are extra classes defined + externalRuntime = (codeCount > 1); + //codeFolderPackages = null; libraryPath = ""; } // if 'data' folder is large, set to external runtime if (dataFolder.exists() && - PdeBase.calcFolderSize(dataFolder) > 768 * 1024) { // if > 768k + Base.calcFolderSize(dataFolder) > 768 * 1024) { // if > 768k externalRuntime = true; } @@ -1086,6 +1258,17 @@ public class PdeSketch { } } + // since using the special classloader, + // run externally whenever there are extra classes defined + if ((bigCode.indexOf(" class ") != -1) || + (bigCode.indexOf("\nclass ") != -1)) { + externalRuntime = true; + } + + // if running in opengl mode, this is gonna be external + //if (Preferences.get("renderer").equals("opengl")) { + //externalRuntime = true; + //} // 2. run preproc on that code using the sugg class name // to create a single .java file and write to buildpath @@ -1094,18 +1277,16 @@ public class PdeSketch { PdePreprocessor preprocessor = new PdePreprocessor(); try { - // if (i != 0) preproc will fail if a pde file is not - // java mode, since that's required preprocessor.setBaseClass(baseClass); preprocessor.setBaseImports(baseImports); + // if (i != 0) preproc will fail if a pde file is not + // java mode, since that's required String className = preprocessor.write(bigCode.toString(), buildPath, suggestedClassName, codeFolderPackages); - //preprocessor.write(bigCode.toString(), buildPath, - // suggestedClassName, importPackageList); if (className == null) { - throw new PdeException("Could not find main class"); + throw new RunnerException("Could not find main class"); // this situation might be perfectly fine, // (i.e. if the file is empty) //System.out.println("No class found in " + code[i].name); @@ -1138,7 +1319,7 @@ public class PdeSketch { } errorLine -= code[errorFile].lineOffset; - throw new PdeException(re.getMessage(), errorFile, + throw new RunnerException(re.getMessage(), errorFile, errorLine, re.getColumn()); } catch (antlr.TokenStreamRecognitionException tsre) { @@ -1154,7 +1335,7 @@ public class PdeSketch { try { pattern = compiler.compile(mess); } catch (MalformedPatternException e) { - PdeBase.showWarning("Internal Problem", + Base.showWarning("Internal Problem", "An internal error occurred while trying\n" + "to compile the sketch. Please report\n" + "this online at http://processing.org/bugs", e); @@ -1176,16 +1357,16 @@ public class PdeSketch { } errorLine -= code[errorFile].lineOffset; - throw new PdeException(tsre.getMessage(), + throw new RunnerException(tsre.getMessage(), errorFile, errorLine, errorColumn); } else { // this is bad, defaults to the main class.. hrm. - throw new PdeException(tsre.toString(), 0, -1, -1); + throw new RunnerException(tsre.toString(), 0, -1, -1); } - } catch (PdeException pe) { - // PdeExceptions are caught here and re-thrown, so that they don't + } catch (RunnerException pe) { + // RunnerExceptions are caught here and re-thrown, so that they don't // get lost in the more general "Exception" handler below. throw pe; @@ -1193,7 +1374,7 @@ public class PdeSketch { // TODO better method for handling this? System.err.println("Uncaught exception type:" + ex.getClass()); ex.printStackTrace(); - throw new PdeException(ex.toString()); + throw new RunnerException(ex.toString()); } // grab the imports from the code just preproc'd @@ -1204,15 +1385,29 @@ public class PdeSketch { // remove things up to the last dot String entry = imports[i].substring(0, imports[i].lastIndexOf('.')); //System.out.println("found package " + entry); - File libFolder = (File) PdeSketchbook.importToLibraryTable.get(entry); + File libFolder = (File) Sketchbook.importToLibraryTable.get(entry); + if (libFolder == null) { - //throw new PdeException("Could not find library for " + entry); + //throw new RunnerException("Could not find library for " + entry); continue; } - //System.out.println(" found lib folder " + libFolder); - importedLibraries.add(libFolder); + importedLibraries.add(libFolder); libraryPath += File.pathSeparator + libFolder.getAbsolutePath(); + + /* + String list[] = libFolder.list(); + if (list != null) { + for (int j = 0; j < list.length; j++) { + // this might have a dll/jnilib/so packed, + // so add it to the library path + if (list[j].toLowerCase().endsWith(".jar")) { + libraryPath += File.pathSeparator + + libFolder.getAbsolutePath() + File.separator + list[j]; + } + } + } + */ } @@ -1226,20 +1421,20 @@ public class PdeSketch { // shtuff so that unicode bunk is properly handled String filename = code[i].name + ".java"; try { - PdeBase.saveFile(code[i].program, new File(buildPath, filename)); + Base.saveFile(code[i].program, new File(buildPath, filename)); } catch (IOException e) { e.printStackTrace(); - throw new PdeException("Problem moving " + filename + + throw new RunnerException("Problem moving " + filename + " to the build folder"); } code[i].preprocName = filename; } } - - // compile the program. errors will happen as a PdeException + + // compile the program. errors will happen as a RunnerException // that will bubble up to whomever called build(). // - PdeCompiler compiler = new PdeCompiler(); + Compiler compiler = new Compiler(); boolean success = compiler.compile(this, buildPath, bootClassPath); //System.out.println("success = " + success + " ... " + primaryClassName); return success ? primaryClassName : null; @@ -1257,7 +1452,7 @@ public class PdeSketch { /** - * Called by PdeEditor to handle someone having selected 'export'. + * Called by Editor to handle someone having selected 'export'. * Pops up a dialog box for export options, and then calls the * necessary function with the parameters from the window. * @@ -1342,6 +1537,11 @@ public class PdeSketch { public boolean exportApplet(/*boolean replaceHtml*/) throws Exception { + // make sure the user didn't hide the sketch folder + ensureExistence(); + + zipFileContents = new Hashtable(); + boolean replaceHtml = true; //File appletDir, String exportSketchName, File dataDir) { //String program = textarea.getText(); @@ -1370,7 +1570,7 @@ public class PdeSketch { // if name != exportSketchName, then that's weirdness // BUG unfortunately, that can also be a bug in the preproc :( if (!name.equals(foundName)) { - PdeBase.showWarning("Error during export", + Base.showWarning("Error during export", "Sketch name is " + name + " but the sketch\n" + "name in the code was " + foundName, null); return false; @@ -1380,7 +1580,6 @@ public class PdeSketch { int wide = PApplet.DEFAULT_WIDTH; int high = PApplet.DEFAULT_HEIGHT; - //try { PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); @@ -1389,8 +1588,10 @@ public class PdeSketch { // this way, no warning is shown if size() isn't actually // used in the applet, which is the case especially for // beginners that are cutting/pasting from the reference. + // modified for 83 to match size(XXX, ddd String sizing = - "[\\s\\;]size\\s*\\(\\s*(\\S+)\\s*,\\s*(\\S+)\\s*\\);"; + "[\\s\\;]size\\s*\\(\\s*(\\S+)\\s*,\\s*(\\d+)"; + //"[\\s\\;]size\\s*\\(\\s*(\\S+)\\s*,\\s*(\\S+)\\s*\\);"; Pattern pattern = compiler.compile(sizing); // adds a space at the beginning, in case size() is the very @@ -1412,17 +1613,41 @@ public class PdeSketch { "determined from your code. You'll have to edit the\n" + "HTML file to set the size of the applet."; - PdeBase.showWarning("Could not find applet size", message, null); + Base.showWarning("Could not find applet size", message, null); } } // else no size() command found - // handle this in editor instead, rare or nonexistant - //} catch (MalformedPatternException e) { - //PdeBase.showWarning("Internal Problem", - // "An internal error occurred while trying\n" + - // "to export the sketch. Please report this.", e); - //return false; - //} + // originally tried to grab this with a regexp matcher, + // but it wouldn't span over multiple lines for the match. + // this could prolly be forced, but since that's the case + // better just to parse by hand. + StringBuffer dbuffer = new StringBuffer(); + String lines[] = PApplet.split(code[0].program, '\n'); + for (int i = 0; i < lines.length; i++) { + if (lines[i].trim().startsWith("/**")) { // this is our comment + // some smartass put the whole thing on the same line + //if (lines[j].indexOf("*/") != -1) break; + + for (int j = i+1; j < lines.length; j++) { + if (lines[j].trim().endsWith("*/")) { + // remove the */ from the end, and any extra *s + // in case there's also content on this line + // nah, don't bother.. make them use the three lines + break; + } + + int offset = 0; + while ((offset < lines[j].length()) && + ((lines[j].charAt(offset) == '*') || + (lines[j].charAt(offset) == ' '))) { + offset++; + } + // insert the return into the html to help w/ line breaks + dbuffer.append(lines[j].substring(offset) + "\n"); + } + } + } + String description = dbuffer.toString(); StringBuffer sources = new StringBuffer(); for (int i = 0; i < codeCount; i++) { @@ -1435,6 +1660,7 @@ public class PdeSketch { PrintStream ps = new PrintStream(fos); // @@sketch@@, @@width@@, @@height@@, @@archive@@, @@source@@ + // and now @@description@@ InputStream is = null; // if there is an applet.html file in the sketch folder, use that @@ -1443,7 +1669,7 @@ public class PdeSketch { is = new FileInputStream(customHtml); } if (is == null) { - is = PdeBase.getStream("applet.html"); + is = Base.getStream("applet.html"); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); @@ -1472,6 +1698,10 @@ public class PdeSketch { sb.replace(index, index + "@@height@@".length(), String.valueOf(high)); } + while ((index = sb.indexOf("@@description@@")) != -1) { + sb.replace(index, index + "@@description@@".length(), + description); + } line = sb.toString(); } ps.println(line); @@ -1486,7 +1716,7 @@ public class PdeSketch { // to encourage people to share their code for (int i = 0; i < codeCount; i++) { try { - PdeBase.copyFile(code[i].file, + Base.copyFile(code[i].file, new File(appletDir, code[i].file.getName())); } catch (IOException e) { @@ -1503,7 +1733,7 @@ public class PdeSketch { // unpacks all jar files //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { - String includes = PdeCompiler.contentsToClassPath(codeFolder); + String includes = Compiler.contentsToClassPath(codeFolder); packClassPathIntoZipFile(includes, zos); } @@ -1511,17 +1741,16 @@ public class PdeSketch { // if a file called 'export.txt' is in there, it contains // a list of the files that should be exported. // otherwise, all files are exported. - Enumeration enum = importedLibraries.elements(); - while (enum.hasMoreElements()) { + Enumeration en = importedLibraries.elements(); + while (en.hasMoreElements()) { // in the list is a File object that points the // library sketch's "library" folder - File libraryFolder = (File)enum.nextElement(); + File libraryFolder = (File)en.nextElement(); //System.out.println("exporting files from " + libFolder); File exportSettings = new File(libraryFolder, "export.txt"); String exportList[] = null; if (exportSettings.exists()) { - //exportList = PApplet.loadStrings(exportSettings); - String info[] = PApplet.loadStrings(exportSettings); + String info[] = Base.loadStrings(exportSettings); for (int i = 0; i < info.length; i++) { if (info[i].startsWith("applet")) { int idx = info[i].indexOf('='); // get applet= or applet = @@ -1548,10 +1777,12 @@ public class PdeSketch { } else if (exportFile.getName().toLowerCase().endsWith(".zip") || exportFile.getName().toLowerCase().endsWith(".jar")) { + //System.out.println("adding zip file " + + // exportFile.getAbsolutePath()); packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos); } else { // just copy the file over.. prolly a .dll or something - PdeBase.copyFile(exportFile, + Base.copyFile(exportFile, new File(appletDir, exportFile.getName())); } } @@ -1559,7 +1790,7 @@ public class PdeSketch { // add the appropriate bagel to the classpath /* - String jdkVersion = PdePreferences.get("compiler.jdk_version"); + String jdkVersion = Preferences.get("compiler.jdk_version"); String bagelJar = "lib/export11.jar"; // default if (jdkVersion.equals("1.3") || jdkVersion.equals("1.4")) { bagelJar = "lib/export13.jar"; @@ -1582,7 +1813,7 @@ public class PdeSketch { if (!bagelClasses[i].endsWith(".class")) continue; entry = new ZipEntry(bagelClasses[i]); zos.putNextEntry(entry); - zos.write(PdeBase.grabFile(new File(exportDir + bagelClasses[i]))); + zos.write(Base.grabFile(new File(exportDir + bagelClasses[i]))); zos.closeEntry(); } */ @@ -1603,7 +1834,7 @@ public class PdeSketch { entry = new ZipEntry(dataFiles[i]); zos.putNextEntry(entry); - zos.write(PdeBase.grabFile(new File(dataFolder, dataFiles[i]))); + zos.write(Base.grabFile(new File(dataFolder, dataFiles[i]))); zos.closeEntry(); } } @@ -1617,7 +1848,7 @@ public class PdeSketch { if (classfiles[i].endsWith(".class")) { entry = new ZipEntry(classfiles[i]); zos.putNextEntry(entry); - zos.write(PdeBase.grabFile(new File(appletDir, classfiles[i]))); + zos.write(Base.grabFile(new File(appletDir, classfiles[i]))); zos.closeEntry(); } } @@ -1629,7 +1860,7 @@ public class PdeSketch { if (classfiles[i].endsWith(".class")) { File deadguy = new File(appletDir, classfiles[i]); if (!deadguy.delete()) { - PdeBase.showWarning("Could not delete", + Base.showWarning("Could not delete", classfiles[i] + " could not \n" + "be deleted from the applet folder. \n" + "You'll need to remove it by hand.", null); @@ -1641,7 +1872,7 @@ public class PdeSketch { zos.flush(); zos.close(); - PdeBase.openFolder(appletDir); + Base.openFolder(appletDir); //} catch (Exception e) { //e.printStackTrace(); @@ -1649,7 +1880,7 @@ public class PdeSketch { return true; } - + public boolean exportApplication() { return true; } @@ -1664,8 +1895,8 @@ public class PdeSketch { * Slurps up .class files from a colon (or semicolon on windows) * separated list of paths and adds them to a ZipOutputStream. */ - static public void packClassPathIntoZipFile(String path, - ZipOutputStream zos) + public void packClassPathIntoZipFile(String path, + ZipOutputStream zos) throws IOException { String pieces[] = PApplet.split(path, File.pathSeparatorChar); @@ -1685,10 +1916,15 @@ public class PdeSketch { // actually 'continue's for all dir entries } else { - String name = entry.getName(); + String entryName = entry.getName(); // ignore contents of the META-INF folders - if (name.indexOf("META-INF") == 0) continue; - ZipEntry entree = new ZipEntry(name); + if (entryName.indexOf("META-INF") == 0) continue; + + // don't allow duplicate entries + if (zipFileContents.get(entryName) != null) continue; + zipFileContents.put(entryName, new Object()); + + ZipEntry entree = new ZipEntry(entryName); zos.putNextEntry(entree); byte buffer[] = new byte[(int) entry.getSize()]; @@ -1753,7 +1989,7 @@ public class PdeSketch { files[i].charAt(0) != '.') { ZipEntry entry = new ZipEntry(nowfar); zos.putNextEntry(entry); - zos.write(PdeBase.grabFile(sub)); + zos.write(Base.grabFile(sub)); zos.closeEntry(); } } @@ -1764,12 +2000,12 @@ public class PdeSketch { /** * Returns true if this is a read-only sketch. Used for the * examples directory, or when sketches are loaded from read-only - * volumes or folders without appropraite permissions. + * volumes or folders without appropriate permissions. */ public boolean isReadOnly() { String apath = folder.getAbsolutePath(); - if (apath.startsWith(PdeSketchbook.examplesPath) || - apath.startsWith(PdeSketchbook.librariesPath)) { + if (apath.startsWith(Sketchbook.examplesPath) || + apath.startsWith(Sketchbook.librariesPath)) { return true; // this doesn't work on directories @@ -1777,7 +2013,9 @@ public class PdeSketch { } else { // check to see if each modified code file can be written to for (int i = 0; i < codeCount; i++) { - if (code[i].modified && !code[i].file.canWrite()) { + if (code[i].modified && + !code[i].file.canWrite() && + code[i].file.exists()) { //System.err.println("found a read-only file " + code[i].file); return true; } @@ -1798,6 +2036,11 @@ public class PdeSketch { /** Packages up sketch into an executable midlet with JAD descriptor. */ public boolean exportMIDlet() throws Exception { + // make sure the user didn't hide the sketch folder + ensureExistence(); + + zipFileContents = new Hashtable(); + boolean replaceJad = true; // create the project directory @@ -1819,9 +2062,9 @@ public class PdeSketch { } // build the sketch - String wtkPath = PdePreferences.get("wtk.path"); + String wtkPath = Preferences.get("wtk.path"); if (wtkPath == null) { - PdeBase.showWarning("Sun Wireless Toolkit (WTK) not found", + Base.showWarning("Sun Wireless Toolkit (WTK) not found", "Please specify the location of the WTK in your preferences.txt file. Example:\n\n" + "wtk.path=C:\\WTK22", null); } @@ -1843,14 +2086,14 @@ public class PdeSketch { // if name != exportSketchName, then that's weirdness // BUG unfortunately, that can also be a bug in the preproc :( if (!name.equals(foundName)) { - PdeBase.showWarning("Error during export", + Base.showWarning("Error during export", "Sketch name is " + name + " but the sketch\n" + "name in the code was " + foundName, null); return false; } //// preverify class files into temporary directory - PdePreverifier preverifier = new PdePreverifier(); + Preverifier preverifier = new Preverifier(); File tmpDir = new File(folder, "tmp"); if (preverifier.preverify(midletDir, tmpDir) != true) { return false; @@ -1871,7 +2114,7 @@ public class PdeSketch { is = new FileInputStream(customMf); } if (is == null) { - is = PdeBase.getStream("mobile.mf"); + is = Base.getStream("mobile.mf"); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); @@ -1904,7 +2147,7 @@ public class PdeSketch { // unpacks all jar files //File codeFolder = new File(folder, "code"); if (codeFolder.exists()) { - String includes = PdeCompiler.contentsToClassPath(codeFolder); + String includes = Compiler.contentsToClassPath(codeFolder); packClassPathIntoZipFile(includes, zos); } @@ -1912,11 +2155,11 @@ public class PdeSketch { // if a file called 'export.txt' is in there, it contains // a list of the files that should be exported. // otherwise, all files are exported. - Enumeration enum = importedLibraries.elements(); - while (enum.hasMoreElements()) { + Enumeration en = importedLibraries.elements(); + while (en.hasMoreElements()) { // in the list is a File object that points the // library sketch's "library" folder - File libraryFolder = (File)enum.nextElement(); + File libraryFolder = (File)en.nextElement(); //System.out.println("exporting files from " + libFolder); File exportSettings = new File(libraryFolder, "export.txt"); String exportList[] = null; @@ -1952,7 +2195,7 @@ public class PdeSketch { packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos); } else { // just copy the file over.. prolly a .dll or something - PdeBase.copyFile(exportFile, + Base.copyFile(exportFile, new File(midletDir, exportFile.getName())); } } @@ -1972,7 +2215,7 @@ public class PdeSketch { entry = new ZipEntry(dataFiles[i]); zos.putNextEntry(entry); - zos.write(PdeBase.grabFile(new File(dataFolder, dataFiles[i]))); + zos.write(Base.grabFile(new File(dataFolder, dataFiles[i]))); zos.closeEntry(); } } @@ -1983,12 +2226,12 @@ public class PdeSketch { if (classfiles[i].endsWith(".class")) { entry = new ZipEntry(classfiles[i]); zos.putNextEntry(entry); - zos.write(PdeBase.grabFile(new File(tmpDir, classfiles[i]))); + zos.write(Base.grabFile(new File(tmpDir, classfiles[i]))); zos.closeEntry(); } else if (classfiles[i].endsWith(".MF")) { entry = new ZipEntry("META-INF/MANIFEST.MF"); zos.putNextEntry(entry); - zos.write(PdeBase.grabFile(new File(tmpDir, classfiles[i]))); + zos.write(Base.grabFile(new File(tmpDir, classfiles[i]))); zos.closeEntry(); } } @@ -1999,7 +2242,7 @@ public class PdeSketch { if (classfiles[i].endsWith(".class")) { File deadguy = new File(midletDir, classfiles[i]); if (!deadguy.delete()) { - PdeBase.showWarning("Could not delete", + Base.showWarning("Could not delete", classfiles[i] + " could not \n" + "be deleted from the applet folder. \n" + "You'll need to remove it by hand.", null); @@ -2021,7 +2264,7 @@ public class PdeSketch { for (int i = 0; i < classfiles.length; i++) { File deadguy = new File(tmpDir, classfiles[i]); if (!deadguy.delete()) { - PdeBase.showWarning("Could not delete", + Base.showWarning("Could not delete", classfiles[i] + " could not \n" + "be deleted from the temporary folder. \n" + "You'll need to remove it by hand.", null); diff --git a/mobile/app/PdePreprocessor.java b/mobile/app/preproc/PdePreprocessor.java similarity index 84% rename from mobile/app/PdePreprocessor.java rename to mobile/app/preproc/PdePreprocessor.java index 6ba7a11df..a768b9e1b 100755 --- a/mobile/app/PdePreprocessor.java +++ b/mobile/app/preproc/PdePreprocessor.java @@ -4,10 +4,10 @@ PdePreprocessor - wrapper for default ANTLR-generated parser Part of the Processing project - http://processing.org - Except where noted, code is written by Ben Fry and - Copyright (c) 2001-03 Massachusetts Institute of Technology + Copyright (c) 2004-05 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology - ANTLR-generated parser and several supporting classes written + ANTLR-generated parser and several supporting classes written by Dan Mosedale via funding from the Interaction Institute IVREA. This program is free software; you can redistribute it and/or modify @@ -20,11 +20,14 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +package processing.app.preproc; + +import processing.app.*; import processing.core.*; import java.io.*; @@ -48,17 +51,17 @@ public class PdePreprocessor { // might be at the end instead of .* whcih would make trouble // other classes using this can lop of the . and anything after // it to produce a package name consistently. - String extraImports[]; + public String extraImports[]; // imports just from the code folder, treated differently // than the others, since the imports are auto-generated. - String codeFolderImports[]; - - static final int STATIC = 0; // formerly BEGINNER - static final int ACTIVE = 1; // formerly INTERMEDIATE - static final int JAVA = 2; // formerly ADVANCED + public String codeFolderImports[]; + + static public final int STATIC = 0; // formerly BEGINNER + static public final int ACTIVE = 1; // formerly INTERMEDIATE + static public final int JAVA = 2; // formerly ADVANCED // static to make it easier for the antlr preproc to get at it - static int programType = -1; + static public int programType = -1; Reader programReader; String buildPath; @@ -82,13 +85,13 @@ public class PdePreprocessor { * These may change in-between (if the prefs panel adds this option) * so grab them here on construction. */ - public PdePreprocessor() { - defaultImports[JDK11] = - PApplet.split(PdePreferences.get("preproc.imports.jdk11"), ','); - defaultImports[JDK13] = - PApplet.split(PdePreferences.get("preproc.imports.jdk13"), ','); - defaultImports[JDK14] = - PApplet.split(PdePreferences.get("preproc.imports.jdk14"), ','); + public PdePreprocessor() { + defaultImports[JDK11] = + PApplet.split(Preferences.get("preproc.imports.jdk11"), ','); + defaultImports[JDK13] = + PApplet.split(Preferences.get("preproc.imports.jdk13"), ','); + defaultImports[JDK14] = + PApplet.split(Preferences.get("preproc.imports.jdk14"), ','); } @@ -102,9 +105,10 @@ public class PdePreprocessor { * preprocesses a pde file and write out a java file * @return the classname of the exported Java */ - //public String write(String program, String buildPath, String name, + //public String write(String program, String buildPath, String name, // String extraImports[]) throws java.lang.Exception { - public String write(String program, String buildPath, String name, String codeFolderPackages[]) + public String write(String program, String buildPath, + String name, String codeFolderPackages[]) throws java.lang.Exception { // if the program ends with no CR or LF an OutOfMemoryError will happen. // not gonna track down the bug now, so here's a hack for it: @@ -113,7 +117,7 @@ public class PdePreprocessor { program += "\n"; } - if (PdePreferences.getBoolean("preproc.substitute_unicode")) { + if (Preferences.getBoolean("preproc.substitute_unicode")) { // check for non-ascii chars (these will be/must be in unicode format) char p[] = program.toCharArray(); int unicodeCount = 0; @@ -122,7 +126,7 @@ public class PdePreprocessor { } // if non-ascii chars are in there, convert to unicode escapes if (unicodeCount != 0) { - // add unicodeCount * 5.. replacing each unicode char + // add unicodeCount * 5.. replacing each unicode char // with six digit uXXXX sequence (xxxx is in hex) // (except for nbsp chars which will be a replaced with a space) int index = 0; @@ -150,7 +154,7 @@ public class PdePreprocessor { } } - // if this guy has his own imports, need to remove them + // if this guy has his own imports, need to remove them // just in case it's not an advanced mode sketch PatternMatcher matcher = new Perl5Matcher(); PatternCompiler compiler = new Perl5Compiler(); @@ -178,7 +182,7 @@ public class PdePreprocessor { int len = piece.length(); //imports.add(piece); - imports.add(piece2); + imports.add(piece2); int idx = program.indexOf(piece); // just remove altogether? program = program.substring(0, idx) + program.substring(idx + len); @@ -187,10 +191,17 @@ public class PdePreprocessor { } while (true); - int importsCount = imports.size(); - extraImports = new String[importsCount]; + extraImports = new String[imports.size()]; imports.copyInto(extraImports); + // if using opengl, add it to the special imports + /* + if (Preferences.get("renderer").equals("opengl")) { + extraImports = new String[imports.size() + 1]; + imports.copyInto(extraImports); + extraImports[extraImports.length - 1] = "processing.opengl.*"; + } + */ /* if (codeFolderPackages != null) { @@ -212,21 +223,19 @@ public class PdePreprocessor { codeFolderImports = null; } - // - // do this after the program gets re-combobulated this.programReader = new StringReader(program); this.buildPath = buildPath; - // create a lexer with the stream reader, and tell it to handle + // create a lexer with the stream reader, and tell it to handle // hidden tokens (eg whitespace, comments) since we want to pass these // through so that the line numbers when the compiler reports errors // match those that will be highlighted in the PDE IDE - // + // PdeLexer lexer = new PdeLexer(programReader); lexer.setTokenObjectClass("antlr.CommonHiddenStreamToken"); - // create the filter for hidden tokens and specify which tokens to + // create the filter for hidden tokens and specify which tokens to // hide and which to copy to the hidden text // filter = new TokenStreamCopyingHiddenTokenFilter(lexer); @@ -264,8 +273,10 @@ public class PdePreprocessor { // unclear if this actually works, but it's worth a shot // - ((CommonAST)parserAST).setVerboseStringConversion( - true, parser.getTokenNames()); + //((CommonAST)parserAST).setVerboseStringConversion( + // true, parser.getTokenNames()); + // (made to use the static version because of jikes 1.22 warning) + CommonAST.setVerboseStringConversion(true, parser.getTokenNames()); // if this is an advanced program, the classname is already defined. // @@ -273,9 +284,9 @@ public class PdePreprocessor { name = getFirstClassName(parserAST); } - // if 'null' was passed in for the name, but this isn't + // if 'null' was passed in for the name, but this isn't // a 'java' mode class, then there's a problem, so punt. - // + // if (name == null) return null; // output the code @@ -296,7 +307,7 @@ public class PdePreprocessor { // if desired, serialize the parse tree to an XML file. can // be viewed usefully with Mozilla or IE - if (PdePreferences.getBoolean("preproc.output_parse_tree")) { + if (Preferences.getBoolean("preproc.output_parse_tree")) { stream = new PrintStream(new FileOutputStream("parseTree.xml")); stream.println(""); @@ -316,7 +327,7 @@ public class PdePreprocessor { /** * Write any required header material (eg imports, class decl stuff) - * + * * @param out PrintStream to write it to. * @param exporting Is this being exported from PDE? * @param name Name of the class being created. @@ -341,7 +352,7 @@ public class PdePreprocessor { // emit standard imports (read from pde.properties) // for each language level that's being used. - String jdkVersionStr = PdePreferences.get("preproc.jdk_version"); + String jdkVersionStr = Preferences.get("preproc.jdk_version"); int jdkVersion = JDK11; // default if (jdkVersionStr.equals("1.3")) { jdkVersion = JDK13; }; @@ -360,8 +371,12 @@ public class PdePreprocessor { } } + //boolean opengl = Preferences.get("renderer").equals("opengl"); + //if (opengl) { + //out.println("import processing.opengl.*; "); + //} + if (programType < JAVA) { - // open the class definition if (baseClass != null) { out.print("public class " + className + " extends " + baseClass + "{"); } else { @@ -381,7 +396,7 @@ public class PdePreprocessor { /** * Write any necessary closing text. - * + * * @param out PrintStream to write it to. */ void writeFooter(PrintStream out) {