();
-//// FileItem which = item.isDirectory() ? item : (FileItem) item.getParent();
-//// FileItem which = item;
-// FileItem which = (FileItem) item.getParent();
-// while (which != null) {
-// items.add(0, which);
-// which = (FileItem) which.getParent();
-// }
-// return new TreePath(items.toArray());
-//// FileItem[] array = items.toArray();
-//// return new TreePath(array);
-// }
-
-
-// public static void loadExpansionState(JTree tree, Enumeration enumeration) {
-// if (enumeration != null) {
-// while (enumeration.hasMoreElements()) {
-// TreePath treePath = (TreePath) enumeration.nextElement();
-// tree.expandPath(treePath);
-// }
-// }
-// }
-
-
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- public DefaultMutableTreeNode buildSketchbookTree(){
- DefaultMutableTreeNode sbNode = new DefaultMutableTreeNode(Language.text("sketchbook.tree"));
- try {
- base.addSketches(sbNode, Base.getSketchbookFolder());
- } catch (IOException e) {
- e.printStackTrace();
- }
- return sbNode;
- }
-
- protected JFrame sketchbookFrame;
-
- public void showSketchbookFrame() {
- if (sketchbookFrame == null) {
- sketchbookFrame = new JFrame(Language.text("sketchbook"));
- Toolkit.setIcon(sketchbookFrame);
- Toolkit.registerWindowCloseKeys(sketchbookFrame.getRootPane(),
- new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- sketchbookFrame.setVisible(false);
- }
- });
-
- final JTree tree = new JTree(buildSketchbookTree());
- tree.getSelectionModel()
- .setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
- tree.setShowsRootHandles(true);
- tree.expandRow(0);
- tree.setRootVisible(false);
-
- tree.addMouseListener(new MouseAdapter() {
- public void mouseClicked(MouseEvent e) {
- if (e.getClickCount() == 2) {
- DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
- .getLastSelectedPathComponent();
-
- int selRow = tree.getRowForLocation(e.getX(), e.getY());
- //TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
- //if (node != null && node.isLeaf() && node.getPath().equals(selPath)) {
- if (node != null && node.isLeaf() && selRow != -1) {
- SketchReference sketch = (SketchReference) node.getUserObject();
- base.handleOpen(sketch.getPath());
- }
- }
- }
- });
- tree.addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { // doesn't fire keyTyped()
- sketchbookFrame.setVisible(false);
- }
- }
-
- public void keyTyped(KeyEvent e) {
- if (e.getKeyChar() == KeyEvent.VK_ENTER) {
- DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
- .getLastSelectedPathComponent();
- if (node != null && node.isLeaf()) {
- SketchReference sketch = (SketchReference) node.getUserObject();
- base.handleOpen(sketch.getPath());
- }
- }
- }
- });
-
- tree.setBorder(new EmptyBorder(5, 5, 5, 5));
- if (Base.isMacOS()) {
- tree.setToggleClickCount(2);
- } else {
- tree.setToggleClickCount(1);
- }
- JScrollPane treePane = new JScrollPane(tree);
- treePane.setPreferredSize(new Dimension(250, 450));
- treePane.setBorder(new EmptyBorder(0, 0, 0, 0));
- sketchbookFrame.getContentPane().add(treePane);
- sketchbookFrame.pack();
+ /**
+ * Get an ImageIcon object from the Mode folder.
+ * Or when prefixed with /lib, load it from the main /lib folder.
+ * @since 3.0a6
+ */
+ public ImageIcon loadIcon(String filename) {
+ if (filename.startsWith("/lib/")) {
+ return Toolkit.getLibIcon(filename.substring(5));
}
-
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- // Space for the editor plus a li'l gap
- int roughWidth = sketchbookFrame.getWidth() + 20;
- Point p = null;
- // If no window open, or the editor is at the edge of the screen
- if (base.activeEditor == null
- || (p = base.activeEditor.getLocation()).x < roughWidth) {
- // Center the window on the screen
- sketchbookFrame.setLocationRelativeTo(null);
- } else {
- // Open the window relative to the editor
- sketchbookFrame.setLocation(p.x - roughWidth, p.y);
- }
- sketchbookFrame.setVisible(true);
- }
- });
+ File file = new File(folder, filename);
+ if (!file.exists()) {
+// EditorConsole.systemErr.println("file does not exist: " + file.getAbsolutePath());
+ return null;
+ }
+// EditorConsole.systemErr.println("found: " + file.getAbsolutePath());
+ return new ImageIcon(file.getAbsolutePath());
}
-/**
- * Get an image object from the theme folder.
+
+ /**
+ * Get an image object from the mode folder.
+ * Or when prefixed with /lib, load it from the main /lib folder.
*/
public Image loadImage(String filename) {
- File file = new File(folder, filename);
- if (!file.exists()) {
- return null;
+ ImageIcon icon = loadIcon(filename);
+ if (icon != null) {
+ return icon.getImage();
}
- return new ImageIcon(file.getAbsolutePath()).getImage();
+ return null;
+ }
+
+
+ public Image loadImageX(String filename) {
+ final int res = Toolkit.highResImages() ? 2 : 1;
+ return loadImage(filename + "-" + res + "x.png");
}
+// public EditorButton loadButton(String name) {
+// return new EditorButton(this, name);
+// }
+
+
//public Settings getTheme() {
// return theme;
//}
@@ -1014,16 +784,24 @@ public String lookupReference(String keyword) {
}
- //public TokenMarker getTokenMarker() throws IOException {
- // File keywordsFile = new File(folder, "keywords.txt");
- // return new PdeKeywords(keywordsFile);
- //}
+ /**
+ * Specialized version of getTokenMarker() that can be overridden to
+ * provide different TokenMarker objects for different file types.
+ * @since 3.2
+ * @param code the code for which we need a TokenMarker
+ */
+ public TokenMarker getTokenMarker(SketchCode code) {
+ return getTokenMarker();
+ }
+
+
public TokenMarker getTokenMarker() {
return tokenMarker;
}
-
+
+
protected TokenMarker createTokenMarker() {
- return new PdeKeywords();
+ return new PdeTokenMarker();
}
@@ -1042,10 +820,15 @@ protected TokenMarker createTokenMarker() {
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+ // Get attributes/values from the theme.txt file. To discourage burying this
+ // kind of information in code where it doesn't belong (and is difficult to
+ // track down), these don't have a "default" option as a second parameter.
- //public String get(String attribute) {
- // return theme.get(attribute);
- //}
+
+ /** @since 3.0a6 */
+ public String getString(String attribute) {
+ return theme.get(attribute);
+ }
public boolean getBoolean(String attribute) {
@@ -1064,7 +847,6 @@ public Color getColor(String attribute) {
public Font getFont(String attribute) {
-// System.out.println("getFont(" + attribute + ") -> " + theme.getFont(attribute));
return theme.getFont(attribute);
}
@@ -1090,6 +872,39 @@ public SyntaxStyle getStyle(String attribute) {
}
+ public Image makeGradient(String attribute, int wide, int high) {
+ int top = getColor(attribute + ".gradient.top").getRGB();
+ int bot = getColor(attribute + ".gradient.bottom").getRGB();
+
+// float r1 = (top >> 16) & 0xff;
+// float g1 = (top >> 8) & 0xff;
+// float b1 = top & 0xff;
+// float r2 = (bot >> 16) & 0xff;
+// float g2 = (bot >> 8) & 0xff;
+// float b2 = bot & 0xff;
+
+ BufferedImage outgoing =
+ new BufferedImage(wide, high, BufferedImage.TYPE_INT_RGB);
+ int[] row = new int[wide];
+ WritableRaster wr = outgoing.getRaster();
+ for (int i = 0; i < high; i++) {
+// Arrays.fill(row, (255 - (i + GRADIENT_TOP)) << 24);
+// int r = (int) PApplet.map(i, 0, high-1, r1, r2);
+ int rgb = PApplet.lerpColor(top, bot, i / (float)(high-1), PConstants.RGB);
+ Arrays.fill(row, rgb);
+// System.out.println(PApplet.hex(row[0]));
+ wr.setDataElements(0, i, wide, 1, row);
+ }
+// Graphics g = outgoing.getGraphics();
+// for (int i = 0; i < steps; i++) {
+// g.setColor(new Color(1, 1, 1, 255 - (i + GRADIENT_TOP)));
+// //g.fillRect(0, i, EditorButton.DIM, 10);
+// g.drawLine(0, i, EditorButton.DIM, i);
+// }
+ return outgoing;
+ }
+
+
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
@@ -1134,7 +949,7 @@ public boolean canEdit(final File f) {
}
return validExtension(f.getName().substring(dot + 1));
}
-
+
/**
* Check this extension (no dots, please) against the list of valid
* extensions.
@@ -1158,7 +973,7 @@ public boolean validExtension(String what) {
* Returns the appropriate file extension to use for auxilliary source files in a sketch.
* For example, in a Java-mode sketch, auxilliary files should be name "Foo.java"; in
* Python mode, they should be named "foo.py".
- *
+ *
* Modes that do not override this function will get the default behavior of returning the
* default extension.
*/
@@ -1181,6 +996,25 @@ public String getModuleExtension() {
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+ /**
+ * Checks coreLibraries and contribLibraries for a library with the specified name
+ * @param libName the name of the library to find
+ * @return the Library or null if not found
+ */
+ public Library findLibraryByName(String libName) {
+
+ for (Library lib : this.coreLibraries) {
+ if (libName.equals(lib.getName()))
+ return lib;
+ }
+
+ for (Library lib : this.contribLibraries) {
+ if (libName.equals(lib.getName()))
+ return lib;
+ }
+
+ return null;
+ }
/**
* Create a fresh applet/application folder if the 'delete target folder'
@@ -1190,9 +1024,14 @@ public void prepareExportFolder(File targetFolder) {
if (targetFolder != null) {
// Nuke the old applet/application folder because it can cause trouble
if (Preferences.getBoolean("export.delete_target_folder")) {
-// System.out.println("temporarily skipping deletion of " + targetFolder);
- Base.removeDir(targetFolder);
- // targetFolder.renameTo(dest);
+ if (targetFolder.exists()) {
+ try {
+ Platform.deleteFile(targetFolder);
+ } catch (IOException e) {
+ // ignore errors/continue; likely to be ok
+ e.printStackTrace();
+ }
+ }
}
// Create a fresh output folder (needed before preproc is run next)
targetFolder.mkdirs();
@@ -1207,9 +1046,16 @@ public void prepareExportFolder(File targetFolder) {
// public void handleNewReplace() {
// base.handleNewReplace();
// }
-
+
+
+ // this is Java-specific, so keeping it in JavaMode
+// public String getSearchPath() {
+// return null;
+// }
+
+
@Override
public String toString() {
return getTitle();
}
-}
\ No newline at end of file
+}
diff --git a/app/src/processing/app/Platform.java b/app/src/processing/app/Platform.java
index c5248ec512..16a31bf80e 100644
--- a/app/src/processing/app/Platform.java
+++ b/app/src/processing/app/Platform.java
@@ -3,7 +3,8 @@
/*
Part of the Processing project - http://processing.org
- Copyright (c) 2008 Ben Fry and Casey Reas
+ Copyright (c) 2012-15 The Processing Foundation
+ Copyright (c) 2008-12 Ben Fry and Casey Reas
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
@@ -22,152 +23,365 @@
package processing.app;
-import java.awt.Desktop;
import java.io.File;
+import java.io.FilenameFilter;
import java.io.IOException;
-import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
-import javax.swing.UIManager;
-
-import com.sun.jna.Library;
-import com.sun.jna.Native;
import com.sun.jna.platform.FileUtils;
+import processing.app.platform.DefaultPlatform;
+import processing.core.PApplet;
+import processing.core.PConstants;
+
-/**
- * Used by Base for platform-specific tweaking, for instance finding the
- * sketchbook location using the Windows registry, or OS X event handling.
- *
- * The methods in this implementation are used by default, and can be
- * overridden by a subclass, if loaded by Base.main().
- *
- * These methods throw vanilla-flavored Exceptions, so that error handling
- * occurs inside Base.
- *
- * There is currently no mechanism for adding new platforms, as the setup is
- * not automated. We could use getProperty("os.arch") perhaps, but that's
- * debatable (could be upper/lowercase, have spaces, etc.. basically we don't
- * know if name is proper Java package syntax.)
- */
public class Platform {
- Base base;
+ static DefaultPlatform inst;
+
+ static Map platformNames = new HashMap<>();
+ static {
+ platformNames.put(PConstants.WINDOWS, "windows"); //$NON-NLS-1$
+ platformNames.put(PConstants.MACOSX, "macosx"); //$NON-NLS-1$
+ platformNames.put(PConstants.LINUX, "linux"); //$NON-NLS-1$
+ }
+
+ static Map platformIndices = new HashMap<>();
+ static {
+ platformIndices.put("windows", PConstants.WINDOWS); //$NON-NLS-1$
+ platformIndices.put("macosx", PConstants.MACOSX); //$NON-NLS-1$
+ platformIndices.put("linux", PConstants.LINUX); //$NON-NLS-1$
+ }
+
+ /** How many bits this machine is */
+ static int nativeBits;
+ static {
+ nativeBits = 32; // perhaps start with 32
+ String bits = System.getProperty("sun.arch.data.model"); //$NON-NLS-1$
+ if (bits != null) {
+ if (bits.equals("64")) { //$NON-NLS-1$
+ nativeBits = 64;
+ }
+ } else {
+ // if some other strange vm, maybe try this instead
+ if (System.getProperty("java.vm.name").contains("64")) { //$NON-NLS-1$ //$NON-NLS-2$
+ nativeBits = 64;
+ }
+ }
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ static public void init() {
+ try {
+ Class> platformClass = Class.forName("processing.app.Platform"); //$NON-NLS-1$
+ if (Platform.isMacOS()) {
+ platformClass = Class.forName("processing.app.platform.MacPlatform"); //$NON-NLS-1$
+ } else if (Platform.isWindows()) {
+ platformClass = Class.forName("processing.app.platform.WindowsPlatform"); //$NON-NLS-1$
+ } else if (Platform.isLinux()) {
+ platformClass = Class.forName("processing.app.platform.LinuxPlatform"); //$NON-NLS-1$
+ }
+ inst = (DefaultPlatform) platformClass.getDeclaredConstructor().newInstance();
+ } catch (Exception e) {
+ Messages.showError("Problem Setting the Platform",
+ "An unknown error occurred while trying to load\n" +
+ "platform-specific code for your machine.", e);
+ }
+ }
+
+
+ static public void initBase(Base base) throws Exception {
+ inst.initBase(base);
+ }
+
+
+ static public void setLookAndFeel() throws Exception {
+ inst.setLookAndFeel();
+ }
+
+
+ static public File getSettingsFolder() throws Exception {
+ return inst.getSettingsFolder();
+ }
+
+
+ static public File getDefaultSketchbookFolder() throws Exception {
+ return inst.getDefaultSketchbookFolder();
+ }
+
+
+ static public void saveLanguage(String languageCode) {
+ inst.saveLanguage(languageCode);
+ }
+
+
+// static public void openURL(String url) throws Exception {
+// inst.openURL(url);
+// }
+//
+//
+// public boolean openFolderAvailable() {
+// return inst.openFolderAvailable();
+// }
+//
+//
+// public void openFolder(File file) throws Exception {
+// inst.openFolder(file);
+// }
/**
- * Set the default L & F. While I enjoy the bounty of the sixteen possible
- * exception types that this UIManager method might throw, I feel that in
- * just this one particular case, I'm being spoiled by those engineers
- * at Sun, those Masters of the Abstractionverse. It leaves me feeling sad
- * and overweight. So instead, I'll pretend that I'm not offered eleven dozen
- * ways to report to the user exactly what went wrong, and I'll bundle them
- * all into a single catch-all "Exception". Because in the end, all I really
- * care about is whether things worked or not. And even then, I don't care.
+ * Implements the cross-platform headache of opening URLs.
*
- * @throws Exception Just like I said.
+ * For 2.0a8 and later, this requires the parameter to be an actual URL,
+ * meaning that you can't send it a file:// path without a prefix. It also
+ * just calls into Platform, which now uses java.awt.Desktop (where
+ * possible, meaning not on Linux) now that we're requiring Java 6.
+ * As it happens the URL must also be properly URL-encoded.
*/
- public void setLookAndFeel() throws Exception {
- String laf = Preferences.get("editor.laf");
- if (laf == null || laf.length() == 0) { // normal situation
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } else {
- UIManager.setLookAndFeel(laf);
+ static public void openURL(String url) {
+ try {
+ inst.openURL(url);
+
+ } catch (Exception e) {
+ Messages.showWarning("Problem Opening URL",
+ "Could not open the URL\n" + url, e);
}
}
- public void init(Base base) {
- this.base = base;
+ /**
+ * Used to determine whether to disable the "Show Sketch Folder" option.
+ * @return true If a means of opening a folder is known to be available.
+ */
+ static public boolean openFolderAvailable() {
+ return inst.openFolderAvailable();
}
- /**
- * This function should throw an exception or return a value.
- * Do not return null.
- */
- public File getSettingsFolder() throws Exception {
- // otherwise make a .processing directory int the user's home dir
- File home = new File(System.getProperty("user.home"));
- return new File(home, ".processing");
-
- /*
+ /**
+ * Implements the other cross-platform headache of opening
+ * a folder in the machine's native file browser.
+ */
+ static public void openFolder(File file) {
try {
- Class clazz = Class.forName("processing.app.macosx.ThinkDifferent");
- Method m = clazz.getMethod("getLibraryFolder", new Class[] { });
- String libraryPath = (String) m.invoke(null, new Object[] { });
- //String libraryPath = BaseMacOS.getLibraryFolder();
- File libraryFolder = new File(libraryPath);
- dataFolder = new File(libraryFolder, "Processing");
+ inst.openFolder(file);
} catch (Exception e) {
- showError("Problem getting data folder",
- "Error getting the Processing data folder.", e);
+ Messages.showWarning("Problem Opening Folder",
+ "Could not open the folder\n" + file.getAbsolutePath(), e);
}
- */
}
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
/**
- * @return if not overridden, a folder named "sketchbook" in user.home.
- * @throws Exception so that subclasses can throw a fit
+ * Return whether sketches will run as 32- or 64-bits based
+ * on the JVM that's in use.
*/
- public File getDefaultSketchbookFolder() throws Exception {
- return new File(System.getProperty("user.home"), "sketchbook");
+ static public int getNativeBits() {
+ return nativeBits;
}
- public void openURL(String url) throws Exception {
- Desktop.getDesktop().browse(new URI(url));
- /*
- String launcher = Preferences.get("launcher");
- if (launcher != null) {
- Runtime.getRuntime().exec(new String[] { launcher, url });
- } else {
- showLauncherWarning();
+ /**
+ * Return the value of the os.arch property
+ */
+ static public String getNativeArch() {
+ // This will return "arm" for 32-bit ARM, "aarch64" for 64-bit ARM (both on Linux)
+ return System.getProperty("os.arch");
+ }
+
+
+ /*
+ * Return a string that identifies the variant of a platform
+ * e.g. "32" or "64" on Intel
+ */
+ static public String getVariant() {
+ return getVariant(PApplet.platform, getNativeArch(), getNativeBits());
+ }
+
+
+ static public String getVariant(int platform, String arch, int bits) {
+ if (platform == PConstants.LINUX &&
+ bits == 32 && "arm".equals(Platform.getNativeArch())) {
+ return "armv6hf"; // assume armv6hf
+ } else if (platform == PConstants.LINUX &&
+ bits == 64 && "aarch64".equals(Platform.getNativeArch())) {
+ return "arm64";
}
- */
+
+ return Integer.toString(bits); // 32 or 64
}
- public boolean openFolderAvailable() {
- return Desktop.isDesktopSupported();
- /*
- return Preferences.get("launcher") != null;
- */
+ static public String getName() {
+ return PConstants.platformNames[PApplet.platform];
}
- public void openFolder(File file) throws Exception {
- Desktop.getDesktop().open(file);
- /*
- String launcher = Preferences.get("launcher");
- if (launcher != null) {
- String folder = file.getAbsolutePath();
- Runtime.getRuntime().exec(new String[] { launcher, folder });
- } else {
- showLauncherWarning();
+ /**
+ * Map a platform constant to its name.
+ * @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX
+ * @return one of "windows", "macosx", or "linux"
+ */
+ static public String getName(int which) {
+ return platformNames.get(which);
+ }
+
+
+ static public int getIndex(String what) {
+ Integer entry = platformIndices.get(what);
+ return (entry == null) ? -1 : entry.intValue();
+ }
+
+
+ // These were changed to no longer rely on PApplet and PConstants because
+ // of conflicts that could happen with older versions of core.jar, where
+ // the MACOSX constant would instead read as the LINUX constant.
+
+
+ /**
+ * returns true if Processing is running on a Mac OS X machine.
+ */
+ static public boolean isMacOS() {
+ //return PApplet.platform == PConstants.MACOSX;
+ return System.getProperty("os.name").indexOf("Mac") != -1; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+
+ /**
+ * returns true if running on windows.
+ */
+ static public boolean isWindows() {
+ //return PApplet.platform == PConstants.WINDOWS;
+ return System.getProperty("os.name").indexOf("Windows") != -1; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+
+ /**
+ * true if running on linux.
+ */
+ static public boolean isLinux() {
+ //return PApplet.platform == PConstants.LINUX;
+ return System.getProperty("os.name").indexOf("Linux") != -1; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ static protected File processingRoot;
+
+ /**
+ * Get reference to a file adjacent to the executable on Windows and Linux,
+ * or inside Contents/Resources/Java on Mac OS X. This will return the local
+ * JRE location, *whether or not it is the active JRE*.
+ */
+ static public File getContentFile(String name) {
+ if (processingRoot == null) {
+ // Get the path to the .jar file that contains Base.class
+ URL pathURL =
+ Base.class.getProtectionDomain().getCodeSource().getLocation();
+ // Decode URL
+ String decodedPath;
+ try {
+ decodedPath = pathURL.toURI().getSchemeSpecificPart();
+ } catch (URISyntaxException e) {
+ e.printStackTrace();
+ return null;
+ }
+
+ if (decodedPath.contains("/app/bin")) { // This means we're in Eclipse
+ final File build = new File(decodedPath, "../../build").getAbsoluteFile();
+ if (Platform.isMacOS()) {
+ processingRoot = new File(build, "macosx/work/Processing.app/Contents/Java");
+ } else if (Platform.isWindows()) {
+ processingRoot = new File(build, "windows/work");
+ } else if (Platform.isLinux()) {
+ processingRoot = new File(build, "linux/work");
+ }
+ } else {
+ // The .jar file will be in the lib folder
+ File jarFolder = new File(decodedPath).getParentFile();
+ if (jarFolder.getName().equals("lib")) {
+ // The main Processing installation directory.
+ // This works for Windows, Linux, and Apple's Java 6 on OS X.
+ processingRoot = jarFolder.getParentFile();
+ } else if (Platform.isMacOS()) {
+ // This works for Java 8 on OS X. We don't have things inside a 'lib'
+ // folder on OS X. Adding it caused more problems than it was worth.
+ processingRoot = jarFolder;
+ }
+ if (processingRoot == null || !processingRoot.exists()) {
+ // Try working directory instead (user.dir, different from user.home)
+ System.err.println("Could not find lib folder via " +
+ jarFolder.getAbsolutePath() +
+ ", switching to user.dir");
+ processingRoot = new File(""); // resolves to "user.dir"
+ }
+ }
+ }
+ return new File(processingRoot, name);
+ }
+
+
+ static public File getJavaHome() {
+ if (Platform.isMacOS()) {
+ //return "Contents/PlugIns/jdk1.7.0_40.jdk/Contents/Home/jre/bin/java";
+ File[] plugins = getContentFile("../PlugIns").listFiles(new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return dir.isDirectory() &&
+ name.endsWith(".jdk") && !name.startsWith(".");
+ }
+ });
+ return new File(plugins[0], "Contents/Home/jre");
+ }
+ // On all other platforms, it's the 'java' folder adjacent to Processing
+ return getContentFile("java");
+ }
+
+
+ /** Get the path to the embedded Java executable. */
+ static public String getJavaPath() {
+ String javaPath = "bin/java" + (Platform.isWindows() ? ".exe" : "");
+ File javaFile = new File(getJavaHome(), javaPath);
+ try {
+ return javaFile.getCanonicalPath();
+ } catch (IOException e) {
+ return javaFile.getAbsolutePath();
}
- */
}
-
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
/**
- * Attempts to move to the Trash on OS X, or the Recycle Bin on Windows.
- * Also tries to find a suitable Trash location on Linux.
- * If not possible, just deletes the file or folder instead.
+ * Attempts to move to the Trash on OS X, or the Recycle Bin on Windows.
+ * Also tries to find a suitable Trash location on Linux.
+ * If not possible, just deletes the file or folder instead.
* @param file the folder or file to be removed/deleted
* @return true if the folder was successfully removed
- * @throws IOException
+ * @throws IOException
*/
- final public boolean deleteFile(File file) throws IOException {
+ static public boolean deleteFile(File file) throws IOException {
FileUtils fu = FileUtils.getInstance();
if (fu.hasTrash()) {
fu.moveToTrash(new File[] { file });
return true;
-
+
} else if (file.isDirectory()) {
- Base.removeDir(file);
+ Util.removeDir(file);
return true;
-
+
} else {
return file.delete();
}
@@ -177,43 +391,25 @@ final public boolean deleteFile(File file) throws IOException {
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- public interface CLibrary extends Library {
- CLibrary INSTANCE = (CLibrary)Native.loadLibrary("c", CLibrary.class);
- int setenv(String name, String value, int overwrite);
- String getenv(String name);
- int unsetenv(String name);
- int putenv(String string);
+ static public void setenv(String variable, String value) {
+ inst.setenv(variable, value);
}
- public void setenv(String variable, String value) {
- CLibrary clib = CLibrary.INSTANCE;
- clib.setenv(variable, value, 1);
+ static public String getenv(String variable) {
+ return inst.getenv(variable);
}
- public String getenv(String variable) {
- CLibrary clib = CLibrary.INSTANCE;
- return clib.getenv(variable);
- }
-
-
- public int unsetenv(String variable) {
- CLibrary clib = CLibrary.INSTANCE;
- return clib.unsetenv(variable);
+ static public int unsetenv(String variable) {
+ return inst.unsetenv(variable);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- /*
- protected void showLauncherWarning() {
- Base.showWarning("No launcher available",
- "Unspecified platform, no launcher available.\n" +
- "To enable opening URLs or folders, add a \n" +
- "\"launcher=/path/to/app\" line to preferences.txt",
- null);
- }
- */
+ static public int getSystemDPI() {
+ return inst.getSystemDPI();
+ }
}
\ No newline at end of file
diff --git a/app/src/processing/app/Preferences.java b/app/src/processing/app/Preferences.java
index 85bd12ac20..1b05083e19 100644
--- a/app/src/processing/app/Preferences.java
+++ b/app/src/processing/app/Preferences.java
@@ -3,8 +3,8 @@
/*
Part of the Processing project - http://processing.org
- Copyright (c) 2014 The Processing Foundation
-
+ Copyright (c) 2014-19 The Processing Foundation
+
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
@@ -21,10 +21,13 @@
package processing.app;
-import java.awt.*;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.SystemColor;
import java.io.*;
import java.util.*;
+import processing.app.ui.Toolkit;
import processing.core.*;
@@ -35,127 +38,125 @@
* ISO 8859-1 encoding, which is highly likely to be a problem when trying to
* save sketch folders and locations. Like the rest of Processing, we use UTF8.
*
- * We don't use the Java Preferences API because it would entail writing to
- * the registry (on Windows), or an obscure file location (on Mac OS X) and
- * make it far more difficult (impossible) to remove the preferences.txt to
- * reset them (when they become corrupt), or to find the the file to make
+ * We don't use the Java Preferences API because it would entail writing to
+ * the registry (on Windows), or an obscure file location (on Mac OS X) and
+ * make it far more difficult (impossible) to remove the preferences.txt to
+ * reset them (when they become corrupt), or to find the the file to make
* edits for numerous obscure preferences that are not part of the preferences
- * window. If we added a generic editor (e.g. about:config in Mozilla) for
+ * window. If we added a generic editor (e.g. about:config in Mozilla) for
* such things, we could start using the Java Preferences API. But wow, that
- * sounds like a lot of work. Not unlike writing this paragraph.
+ * sounds like a lot of work. Not unlike writing this paragraph.
*/
public class Preferences {
- // had to rename this file because people were editing it
+ // had to rename the defaults file because people were editing it
static final String DEFAULTS_FILE = "defaults.txt"; //$NON-NLS-1$
static final String PREFS_FILE = "preferences.txt"; //$NON-NLS-1$
- static HashMap defaults;
- static HashMap table = new HashMap();
+ static Map defaults;
+ static Map table = new HashMap<>();
static File preferencesFile;
- static final String PROMPT_YES = Language.text("prompt.yes");
- static final String PROMPT_NO = Language.text("prompt.no");
- static final String PROMPT_CANCEL = Language.text("prompt.cancel");
- static final String PROMPT_OK = Language.text("prompt.ok");
- static final String PROMPT_BROWSE = Language.text("prompt.browse");
-
- /**
- * Standardized width for buttons. Mac OS X 10.3 wants 70 as its default,
- * Windows XP needs 66, and my Ubuntu machine needs 80+, so 80 seems proper.
- */
- static public int BUTTON_WIDTH =
- Integer.valueOf(Language.text("preferences.button.width"));
-
- /** height of the EditorHeader, EditorToolbar, and EditorStatus */
- static final int GRID_SIZE = 32;
-
- // Indents and spacing standards. These probably need to be modified
- // per platform as well, because Mac OS X is so huge, Windows is smaller,
- // and Linux is all over the map. Consider these deprecated.
-
- static final int GUI_BIG = 13;
- static final int GUI_BETWEEN = 8;
- static final int GUI_SMALL = 6;
-
+// /** @return true if the sketchbook file did not exist */
+// static public boolean init() {
static public void init() {
// start by loading the defaults, in case something
// important was deleted from the user prefs
try {
- // Name changed for 2.1b2 to avoid problems with users modifying or
+ // Name changed for 2.1b2 to avoid problems with users modifying or
// replacing the file after doing a search for "preferences.txt".
load(Base.getLibStream(DEFAULTS_FILE));
} catch (Exception e) {
- Base.showError(null, "Could not read default settings.\n" +
- "You'll need to reinstall Processing.", e);
+ Messages.showError(null, "Could not read default settings.\n" +
+ "You'll need to reinstall Processing.", e);
}
- // check for platform-specific properties in the defaults
- String platformExt = "." + PConstants.platformNames[PApplet.platform]; //$NON-NLS-1$
- int platformExtLength = platformExt.length();
-
- // Get a list of keys that are specific to this platform
- ArrayList platformKeys = new ArrayList();
- for (String key : table.keySet()) {
- if (key.endsWith(platformExt)) {
- platformKeys.add(key);
- }
- }
-
- // Use those platform-specific keys to override
- for (String key : platformKeys) {
- // this is a key specific to a particular platform
- String actualKey = key.substring(0, key.length() - platformExtLength);
- String value = get(key);
- set(actualKey, value);
- }
-
- // clone the hash table
- defaults = (HashMap) table.clone();
+ // Clone the defaults, then override any them with the user's preferences.
+ // This ensures that any new/added preference will be present.
+ defaults = new HashMap<>(table);
// other things that have to be set explicitly for the defaults
setColor("run.window.bgcolor", SystemColor.control); //$NON-NLS-1$
-
+
+ // For CJK users, enable IM support by default
+ if (Language.useInputMethod()) {
+ setBoolean("editor.input_method_support", true);
+ }
+
// next load user preferences file
preferencesFile = Base.getSettingsFile(PREFS_FILE);
- if (preferencesFile.exists()) {
+ boolean firstRun = !preferencesFile.exists();
+ if (!firstRun) {
try {
load(new FileInputStream(preferencesFile));
} catch (Exception ex) {
- Base.showError("Error reading preferences",
- "Error reading the preferences file. " +
- "Please delete (or move)\n" +
- preferencesFile.getAbsolutePath() +
- " and restart Processing.", ex);
+ Messages.showError("Error reading preferences",
+ "Error reading the preferences file. " +
+ "Please delete (or move)\n" +
+ preferencesFile.getAbsolutePath() +
+ " and restart Processing.", ex);
}
- }
-
- if (checkSketchbookPref() || !preferencesFile.exists()) {
+ }
+
+ if (checkSketchbookPref() || firstRun) {
+// if (firstRun) {
// create a new preferences file if none exists
// saves the defaults out to the file
save();
}
- PApplet.useNativeSelect =
+ PApplet.useNativeSelect =
Preferences.getBoolean("chooser.files.native"); //$NON-NLS-1$
-
- // Set http proxy for folks that require it.
+
+ // Adding option to disable this in case it's getting in the way
+ if (get("proxy.system").equals("true")) {
+ // Use the system proxy settings by default
+ // https://github.com/processing/processing/issues/2643
+ System.setProperty("java.net.useSystemProxies", "true");
+ }
+
+ // Set HTTP, HTTPS, and SOCKS proxies for individuals
+ // who want/need to override the system setting
// http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
- String proxyHost = get("proxy.host");
- String proxyPort = get("proxy.port");
- if (proxyHost != null && proxyHost.trim().length() != 0 &&
- proxyPort != null && proxyPort.trim().length() != 0) {
- System.setProperty("http.proxyHost", proxyHost);
- System.setProperty("http.proxyPort", proxyPort);
+ // Less readable version with the Oracle style sheet:
+ // http://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html
+ handleProxy("http", "http.proxyHost", "http.proxyPort");
+ handleProxy("https", "https.proxyHost", "https.proxyPort");
+ handleProxy("socks", "socksProxyHost", "socksProxyPort");
+ }
+
+
+ static void handleProxy(String protocol, String hostProp, String portProp) {
+ String proxyHost = get("proxy." + protocol + ".host");
+ String proxyPort = get("proxy." + protocol + ".port");
+ if (proxyHost != null && proxyHost.length() != 0 &&
+ proxyPort != null && proxyPort.length() != 0) {
+ System.setProperty(hostProp, proxyHost);
+ System.setProperty(portProp, proxyPort);
}
+
+ }
+
+
+ static public String getPreferencesPath() {
+ return preferencesFile.getAbsolutePath();
}
- // .................................................................
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+ /**
+ * Load a set of key/value pairs from a UTF-8 encoded file into 'table'.
+ * For 3.0a6, this removes any platform-specific extensions from keys, so
+ * that we don't have platform-specific entries in a user's preferences.txt
+ * file, which would require all prefs to be changed twice, or risk being
+ * overwritten by the unchanged platform-specific version on reload.
+ */
static public void load(InputStream input) throws IOException {
+ HashMap platformSpecific = new HashMap<>();
+
String[] lines = PApplet.loadStrings(input); // Reads as UTF-8
for (String line : lines) {
if ((line.length() == 0) ||
@@ -166,46 +167,94 @@ static public void load(InputStream input) throws IOException {
if (equals != -1) {
String key = line.substring(0, equals).trim();
String value = line.substring(equals + 1).trim();
- table.put(key, value);
+ if (!isPlatformSpecific(key, value, platformSpecific)) {
+ table.put(key, value);
+ }
}
}
+ // Now override the keys with any platform-specific defaults we've found.
+ for (String key : platformSpecific.keySet()) {
+ table.put(key, platformSpecific.get(key));
+ }
}
- // .................................................................
-
+ /**
+ * @param key original key (may include platform extension)
+ * @param value
+ * @param specific where to put the key/value pairs for *this* platform
+ * @return true if a platform-specific key
+ */
+ static protected boolean isPlatformSpecific(String key, String value,
+ Map specific) {
+ for (String platform : PConstants.platformNames) {
+ String ext = "." + platform;
+ if (key.endsWith(ext)) {
+ String thisPlatform = PConstants.platformNames[PApplet.platform];
+ if (platform.equals(thisPlatform)) {
+ key = key.substring(0, key.lastIndexOf(ext));
+ // store this for later overrides
+ specific.put(key, value);
+ } else {
+ // ignore platform-specific defaults for other platforms,
+ // but return 'true' because it needn't be added to the big list
+ }
+ return true;
+ }
+ }
+ return false;
+ }
- static protected void save() {
-// try {
- // on startup, don't worry about it
- // this is trying to update the prefs for who is open
- // before Preferences.init() has been called.
- if (preferencesFile == null) return;
- // Fix for 0163 to properly use Unicode when writing preferences.txt
- PrintWriter writer = PApplet.createWriter(preferencesFile);
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-// Enumeration e = table.keys(); //properties.propertyNames();
-// while (e.hasMoreElements()) {
-// String key = (String) e.nextElement();
-// writer.println(key + "=" + ((String) table.get(key)));
-// }
- String[] keyList = table.keySet().toArray(new String[table.size()]);
- keyList = PApplet.sort(keyList);
- for (String key : keyList) {
- writer.println(key + "=" + table.get(key)); //$NON-NLS-1$
- }
- writer.flush();
- writer.close();
+ static public void save() {
+ // On startup it'll be null, don't worry about it. It's trying to update
+ // the prefs for the open sketch before Preferences.init() has been called.
+ if (preferencesFile != null) {
+ try {
+ File dir = preferencesFile.getParentFile();
+ File preferencesTemp = File.createTempFile("preferences", ".txt", dir);
+ preferencesTemp.setWritable(true, false);
+
+ // Fix for 0163 to properly use Unicode when writing preferences.txt
+ PrintWriter writer = PApplet.createWriter(preferencesTemp);
+
+ String[] keyList = table.keySet().toArray(new String[table.size()]);
+ // Sorting is really helpful for debugging, diffing, and finding keys
+ keyList = PApplet.sort(keyList);
+ for (String key : keyList) {
+ writer.println(key + "=" + table.get(key)); //$NON-NLS-1$
+ }
+ writer.flush();
+ writer.close();
+
+ // Rename preferences.txt to preferences.old
+ File oldPreferences = new File(dir, "preferences.old");
+ if (oldPreferences.exists()) {
+ if (!oldPreferences.delete()) {
+ throw new IOException("Could not delete preferences.old");
+ }
+ }
+ if (preferencesFile.exists() &&
+ !preferencesFile.renameTo(oldPreferences)) {
+ throw new IOException("Could not replace preferences.old");
+ }
+ // Make the temporary file into the real preferences
+ if (!preferencesTemp.renameTo(preferencesFile)) {
+ throw new IOException("Could not move preferences file into place");
+ }
-// } catch (Exception ex) {
-// Base.showWarning(null, "Error while saving the settings file", ex);
-// }
+ } catch (IOException e) {
+ Messages.showWarning("Preferences",
+ "Could not save the Preferences file.", e);
+ }
+ }
}
- // .................................................................
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// all the information from preferences.txt
@@ -232,7 +281,7 @@ static public void unset(String attribute) {
static public boolean getBoolean(String attribute) {
String value = get(attribute); //, null);
- return (new Boolean(value)).booleanValue();
+ return Boolean.parseBoolean(value);
/*
supposedly not needed, because anything besides 'true'
@@ -325,7 +374,7 @@ static public Font getFont(String attr) {
style |= Font.ITALIC;
}
int size = PApplet.parseInt(pieces[2], 12);
-
+
// replace bad font with the default from lib/preferences.txt
if (replace) {
set(attr, value);
@@ -343,20 +392,20 @@ static public Font getFont(String attr) {
}
} catch (Exception e) {
- // Adding try/catch block because this may be where
- // a lot of startup crashes are happening.
- Base.log("Error with font " + get(attr) + " for attribute " + attr);
+ // Adding try/catch block because this may be where
+ // a lot of startup crashes are happening.
+ Messages.log("Error with font " + get(attr) + " for attribute " + attr);
}
return new Font("Dialog", Font.PLAIN, 12);
}
-
-
+
+
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
+
/**
- * Check for a 3.0 sketchbook location, and if none exists,
- * try to grab it from the 2.0 sketchbook location.
+ * Check for a 3.0 sketchbook location, and if none exists,
+ * try to grab it from the 2.0 sketchbook location.
* @return true if a location was found and the pref didn't exist
*/
static protected boolean checkSketchbookPref() {
@@ -372,14 +421,19 @@ static protected boolean checkSketchbookPref() {
}
return false;
}
-
-
- static protected String getSketchbookPath() {
+
+
+ static public String getOldSketchbookPath() {
+ return get("sketchbook.path");
+ }
+
+
+ static public String getSketchbookPath() {
return get("sketchbook.path.three"); //$NON-NLS-1$
}
-
-
+
+
static protected void setSketchbookPath(String path) {
set("sketchbook.path.three", path); //$NON-NLS-1$
}
-}
\ No newline at end of file
+}
diff --git a/app/src/processing/app/PreferencesFrame.java b/app/src/processing/app/PreferencesFrame.java
deleted file mode 100644
index 6ab7942ac1..0000000000
--- a/app/src/processing/app/PreferencesFrame.java
+++ /dev/null
@@ -1,862 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2012-14 The Processing Foundation
- Copyright (c) 2004-12 Ben Fry and Casey Reas
- Copyright (c) 2001-04 Massachusetts Institute of Technology
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License version 2
- as published by the Free Software Foundation.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU 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,
- Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-
-package processing.app;
-
-import java.awt.*;
-import java.awt.event.*;
-import java.io.*;
-import java.util.*;
-
-import javax.swing.*;
-import javax.swing.border.*;
-import javax.swing.event.*;
-
-import processing.app.ColorChooser;
-import processing.app.Language;
-import processing.core.*;
-
-
-/**
- * Window for modifying preferences.
- *
- * This is ugly GUI code that uses exact layout. This was done in frustration
- * one evening (and pre-Swing), but that's long since past, and the code
- * should instead be ported to a proper Swing layout like Group or BoxLayout.
- * See here.
- */
-public class PreferencesFrame {
- JFrame dialog;
- int wide, high;
-
- static final Integer[] FONT_SIZES = { 10, 12, 14, 18, 24, 36, 48 };
-
- JTextField sketchbookLocationField;
- JTextField presentColor;
- JTextField presentColorHex;
- JCheckBox editorAntialiasBox;
- JCheckBox deletePreviousBox;
- JCheckBox whinyBox;
- JCheckBox memoryOverrideBox;
- JTextField memoryField;
- JCheckBox checkUpdatesBox;
- JComboBox fontSizeField;
- JComboBox consoleSizeField;
- JCheckBox inputMethodBox;
- JCheckBox autoAssociateBox;
-
- ColorChooser selector;
-
- JCheckBox errorCheckerBox;
- JCheckBox warningsCheckerBox;
- JCheckBox codeCompletionBox;
- JCheckBox importSuggestionsBox;
- JCheckBox codeCompletionTriggerBox;
-
- JComboBox displaySelectionBox;
- JComboBox languageSelectionBox;
-
- int displayCount;
-
- String[] monoFontFamilies;
- JComboBox fontSelectionBox;
-
- /** Base object so that updates can be applied to the list of editors. */
- Base base;
-
-
- public PreferencesFrame(Base base) {
- this.base = base;
- //dialog = new JDialog(editor, "Preferences", true);
- dialog = new JFrame(Language.text("preferences"));
- dialog.setResizable(false);
-
- Container pain = dialog.getContentPane();
- pain.setLayout(null);
-
- final int GUI_BETWEEN = Preferences.GUI_BETWEEN;
- final int GUI_BIG = Preferences.GUI_BIG;
- final int GUI_SMALL = Preferences.GUI_SMALL;
- final int BUTTON_WIDTH = Preferences.BUTTON_WIDTH;
-
- int top = GUI_BIG;
- int left = GUI_BIG;
- int right = 0;
-
- JLabel label;
- JButton button; //, button2;
- //JComboBox combo;
- Dimension d, d2; //, d3;
- int h, vmax;
-
-
- // Sketchbook location:
- // [...............................] [ Browse ]
-
- label = new JLabel(Language.text("preferences.sketchbook_location")+":");
- pain.add(label);
- d = label.getPreferredSize();
- label.setBounds(left, top, d.width, d.height);
- top += d.height; // + GUI_SMALL;
-
- sketchbookLocationField = new JTextField(40);
- pain.add(sketchbookLocationField);
- d = sketchbookLocationField.getPreferredSize();
-
- button = new JButton(Preferences.PROMPT_BROWSE);
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- File dflt = new File(sketchbookLocationField.getText());
- PApplet.selectFolder(Language.text("preferences.sketchbook_location.popup"),
- "sketchbookCallback", dflt,
- PreferencesFrame.this, dialog);
- }
- });
- pain.add(button);
- d2 = button.getPreferredSize();
-
- // take max height of all components to vertically align em
- vmax = Math.max(d.height, d2.height);
- sketchbookLocationField.setBounds(left, top + (vmax-d.height)/2,
- d.width, d.height);
- h = left + d.width + GUI_SMALL;
- button.setBounds(h, top + (vmax-d2.height)/2,
- d2.width, d2.height);
-
- right = Math.max(right, h + d2.width + GUI_BIG);
- top += vmax + GUI_BETWEEN;
-
-
- // Language: [ English ] (requires restart of Processing)
-
- Container languageBox = Box.createHorizontalBox();
- JLabel languageLabel = new JLabel(Language.text("preferences.language")+": ");
- languageBox.add(languageLabel);
- languageSelectionBox = new JComboBox();
-
- Map languages = Language.getLanguages();
- String[] languageSelection = new String[languages.size()];
- languageSelection[0] = languages.get(Language.getLanguage());
- int i = 1;
- for (Map.Entry lang : languages.entrySet()) {
- if(!lang.getKey().equals(Language.getLanguage())){
- languageSelection[i++] = lang.getValue();
- }
- }
- languageSelectionBox.setModel(new DefaultComboBoxModel(languageSelection));
- languageBox.add(languageSelectionBox);
- label = new JLabel(" ("+Language.text("preferences.requires_restart")+")");
- languageBox.add(label);
- pain.add(languageBox);
- d = languageBox.getPreferredSize();
- languageBox.setBounds(left, top, d.width, d.height);
- top += d.height + GUI_BETWEEN;
-
-
- // Editor and console font [ Source Code Pro ]
-
- // Nevermind on this for now.. Java doesn't seem to have a method for
- // enumerating only the fixed-width (monospaced) fonts. To do this
- // properly, we'd need to list the fonts, and compare the metrics of
- // i and M for each. When they're identical (and not degenerate),
- // we'd call that font fixed width. That's all a very expensive set of
- // operations, so it should also probably be cached between runs and
- // updated in the background.
-
- Container fontBox = Box.createHorizontalBox();
- JLabel fontLabel = new JLabel(Language.text("preferences.editor_and_console_font")+": ");
- final String fontTip = "" + Language.text("preferences.editor_and_console_font.tip");
- fontLabel.setToolTipText(fontTip);
- fontBox.add(fontLabel);
- // get a wide name in there before getPreferredSize() is called
- fontSelectionBox = new JComboBox(new Object[] { Toolkit.getMonoFontName() });
- fontSelectionBox.setToolTipText(fontTip);
-// fontSelectionBox.addItem(Toolkit.getMonoFont(size, style));
- //updateDisplayList();
- fontSelectionBox.setEnabled(false); // don't enable until fonts are loaded
- fontBox.add(fontSelectionBox);
-// fontBox.add(Box.createHorizontalGlue());
- pain.add(fontBox);
- d = fontBox.getPreferredSize();
- fontBox.setBounds(left, top, d.width + 150, d.height);
-// fontBox.setBounds(left, top, dialog.getWidth() - left*2, d.height);
- top += d.height + GUI_BETWEEN;
-
-
- // Editor font size [ 12 ] Console font size [ 10 ]
-
- Container box = Box.createHorizontalBox();
- label = new JLabel(Language.text("preferences.editor_font_size")+": ");
- box.add(label);
- fontSizeField = new JComboBox(FONT_SIZES);
-// fontSizeField = new JComboBox(FONT_SIZES);
- fontSizeField.setEditable(true);
- box.add(fontSizeField);
- box.add(Box.createHorizontalStrut(GUI_BETWEEN));
-
- label = new JLabel(Language.text("preferences.console_font_size")+": ");
-
- box.add(label);
-// consoleSizeField = new JComboBox(FONT_SIZES);
- consoleSizeField = new JComboBox(FONT_SIZES);
- consoleSizeField.setEditable(true);
- box.add(consoleSizeField);
-
- pain.add(box);
- d = box.getPreferredSize();
- box.setBounds(left, top, d.width, d.height);
- fontSizeField.setSelectedItem(Preferences.getFont("editor.font.size"));
- top += d.height + GUI_BETWEEN;
-
-
- Container colorBox = Box.createHorizontalBox();
-
- label = new JLabel(Language.text("preferences.background_color")+": ");
- colorBox.add(label);
-
- final String colorTip = "" + Language.text("preferences.background_color.tip");
- label.setToolTipText(colorTip);
-
- presentColor = new JTextField(" ");
- presentColor.setOpaque(true);
- presentColor.setEnabled(false);
- presentColor.setBorder(new CompoundBorder(BorderFactory.createMatteBorder(
- 1, 1, 0, 0, new Color(195, 195, 195)), BorderFactory.createMatteBorder(
- 0, 0, 1, 1, new Color(54, 54, 54))));
- presentColor.setBackground(Preferences.getColor("run.present.bgcolor"));
-
- presentColorHex = new JTextField(6);
- presentColorHex
- .setText(Preferences.get("run.present.bgcolor").substring(1));
- presentColorHex.getDocument().addDocumentListener(new DocumentListener() {
-
- @Override
- public void removeUpdate(DocumentEvent e) {
- final String colorValue = presentColorHex.getText().toUpperCase();
- if (colorValue.length() == 7 && (colorValue.startsWith("#")))
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- presentColorHex.setText(colorValue.substring(1));
- }
- });
- if (colorValue.length() == 6
- && colorValue.matches("[0123456789ABCDEF]*")) {
- presentColor.setBackground(new Color(Integer.parseInt(
- colorValue.substring(0, 2), 16), Integer.parseInt(
- colorValue.substring(2, 4), 16), Integer.parseInt(
- colorValue.substring(4, 6), 16)));
- if (!colorValue.equals(presentColorHex.getText()))
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- presentColorHex.setText(colorValue);
- }
- });
- }
- }
-
- @Override
- public void insertUpdate(DocumentEvent e) {
- final String colorValue = presentColorHex.getText().toUpperCase();
- if (colorValue.length() == 7 && (colorValue.startsWith("#")))
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- presentColorHex.setText(colorValue.substring(1));
- }
- });
- if (colorValue.length() == 6
- && colorValue.matches("[0123456789ABCDEF]*")) {
- presentColor.setBackground(new Color(Integer.parseInt(
- colorValue.substring(0, 2), 16), Integer.parseInt(
- colorValue.substring(2, 4), 16), Integer.parseInt(
- colorValue.substring(4, 6), 16)));
- if (!colorValue.equals(presentColorHex.getText()))
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- presentColorHex.setText(colorValue);
- }
- });
- }
- }
-
- @Override public void changedUpdate(DocumentEvent e) {}
- });
-
- selector = new ColorChooser(dialog, false,
- Preferences.getColor("run.present.bgcolor"), Language.text("prompt.ok"),
- new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- String colorValue = selector.getHexColor();
- presentColorHex.setText(colorValue.substring(1));
- presentColor.setBackground(new Color(Integer.parseInt(
- colorValue.substring(1, 3), 16), Integer.parseInt(
- colorValue.substring(3, 5), 16), Integer.parseInt(
- colorValue.substring(5, 7), 16)));
- selector.hide();
- }
- });
-
- presentColor.addMouseListener(new MouseListener() {
- @Override public void mouseReleased(MouseEvent e) {}
- @Override public void mousePressed(MouseEvent e) {}
-
- @Override
- public void mouseExited(MouseEvent e) {
- dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
- }
-
- @Override
- public void mouseEntered(MouseEvent e) {
- dialog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
- }
-
- @Override
- public void mouseClicked(MouseEvent e) {
- selector.show();
- }
- });
-
- label = new JLabel("#");
- colorBox.add(label);
- colorBox.add(presentColorHex);
- colorBox.add(Box.createHorizontalStrut(GUI_SMALL + 2 / 3 * GUI_SMALL));
- colorBox.add(presentColor);
-
- pain.add(colorBox);
- d = colorBox.getPreferredSize();
- colorBox.setBounds(left, top, d.width, d.height);
-
- top += d.height + GUI_BETWEEN;
-
-
- // [ ] Use smooth text in editor window
-
- editorAntialiasBox = new JCheckBox(Language.text("preferences.use_smooth_text"));
- pain.add(editorAntialiasBox);
- d = editorAntialiasBox.getPreferredSize();
- // adding +10 because ubuntu + jre 1.5 truncating items
- editorAntialiasBox.setBounds(left, top, d.width + 10, d.height);
- right = Math.max(right, left + d.width);
- top += d.height + GUI_BETWEEN;
-
-
- // [ ] Enable complex text input (for Japanese et al, requires restart)
-
- inputMethodBox =
- new JCheckBox(Language.text("preferences.enable_complex_text_input")+
- " ("+Language.text("preferences.enable_complex_text_input_example")+
- ", "+Language.text("preferences.requires_restart")+")");
- pain.add(inputMethodBox);
- d = inputMethodBox.getPreferredSize();
- inputMethodBox.setBounds(left, top, d.width + 10, d.height);
- right = Math.max(right, left + d.width);
- top += d.height + GUI_BETWEEN;
-
-
- // [ ] Continuously check for errors - PDE X
-
- errorCheckerBox =
- new JCheckBox(Language.text("preferences.continuously_check"));
-
- pain.add(errorCheckerBox);
- d = errorCheckerBox.getPreferredSize();
- errorCheckerBox.setBounds(left, top, d.width + 10, d.height);
- //right = Math.max(right, left + d.width);
- //top += d.height + GUI_BETWEEN;
- int warningLeft = left + d.width;
-
-
- // [ ] Show Warnings - PDE X
-
- warningsCheckerBox =
- new JCheckBox(Language.text("preferences.show_warnings"));
- pain.add(warningsCheckerBox);
- d = warningsCheckerBox.getPreferredSize();
- warningsCheckerBox.setBounds(warningLeft, top, d.width + 10, d.height);
- right = Math.max(right, warningLeft + d.width);
- top += d.height + GUI_BETWEEN;
-
-
- // [ ] Enable Code Completion - PDE X
-
- codeCompletionBox =
- new JCheckBox(Language.text("preferences.code_completion"));
- pain.add(codeCompletionBox);
- d = codeCompletionBox.getPreferredSize();
- codeCompletionBox.setBounds(left, top, d.width + 10, d.height);
- codeCompletionBox.addActionListener(new ActionListener() {
-
- @Override
- public void actionPerformed(ActionEvent e) {
- // Disble code completion trigger option if CC is disabled
- codeCompletionTriggerBox.setEnabled(codeCompletionBox.isSelected());
- }
- });
-
- int toggleLeft = left + d.width;
-
- // [ ] Toggle Code Completion Trigger - PDE X
-
- codeCompletionTriggerBox =
- new JCheckBox(Language.text("preferences.trigger_with")+" Ctrl-"+Language.text("preferences.cmd_space"));
- pain.add(codeCompletionTriggerBox);
- d = codeCompletionTriggerBox.getPreferredSize();
- codeCompletionTriggerBox.setBounds(toggleLeft, top, d.width + 10, d.height);
- right = Math.max(right, toggleLeft + d.width);
- top += d.height + GUI_BETWEEN;
-
-
- // [ ] Increase maximum available memory to [______] MB
-
- Container memoryBox = Box.createHorizontalBox();
- memoryOverrideBox = new JCheckBox(Language.text("preferences.increase_max_memory")+": ");
- memoryBox.add(memoryOverrideBox);
- memoryField = new JTextField(4);
- memoryOverrideBox.addChangeListener(new ChangeListener() {
- @Override
- public void stateChanged(ChangeEvent e) {
- memoryField.setEnabled(memoryOverrideBox.isSelected());
- }
- });
- memoryBox.add(memoryField);
- memoryBox.add(new JLabel(" MB"));
- pain.add(memoryBox);
- d = memoryBox.getPreferredSize();
- memoryBox.setBounds(left, top, d.width, d.height);
- top += d.height + GUI_BETWEEN;
-
-
- // [ ] Delete previous application folder on export
-
- deletePreviousBox =
- new JCheckBox(Language.text("preferences.delete_previous_folder_on_export"));
- pain.add(deletePreviousBox);
- d = deletePreviousBox.getPreferredSize();
- deletePreviousBox.setBounds(left, top, d.width + 10, d.height);
- right = Math.max(right, left + d.width);
- top += d.height + GUI_BETWEEN;
-
-
- // [ ] Hide tab/toolbar background image
-
- whinyBox = new JCheckBox(Language.text("preferences.hide_toolbar_background_image")+
- " ("+Language.text("preferences.requires_restart")+")");
- pain.add(whinyBox);
- d = whinyBox.getPreferredSize();
- whinyBox.setBounds(left, top, d.width + 10, d.height);
- right = Math.max(right, left + d.width);
- top += d.height + GUI_BETWEEN;
-
-
- // [ ] Check for updates on startup
-
- checkUpdatesBox = new JCheckBox(Language.text("preferences.check_for_updates_on_startup"));
- pain.add(checkUpdatesBox);
- d = checkUpdatesBox.getPreferredSize();
- checkUpdatesBox.setBounds(left, top, d.width + 10, d.height);
- right = Math.max(right, left + d.width);
- top += d.height + GUI_BETWEEN;
-
-
- // Run sketches on display [ 1 ]
-
- Container displayBox = Box.createHorizontalBox();
- JLabel displayLabel = new JLabel(Language.text("preferences.run_sketches_on_display")+": ");
- final String tip = "" + Language.text("preferences.run_sketches_on_display.tip");
- displayLabel.setToolTipText(tip);
- displayBox.add(displayLabel);
- displaySelectionBox = new JComboBox();
- updateDisplayList(); // needs to happen here for getPreferredSize()
- displayBox.add(displaySelectionBox);
- pain.add(displayBox);
- d = displayBox.getPreferredSize();
- displayBox.setBounds(left, top, d.width, d.height);
- top += d.height + GUI_BETWEEN;
-
-
- // [ ] Automatically associate .pde files with Processing
-
- if (Base.isWindows()) {
- autoAssociateBox =
- new JCheckBox(Language.text("preferences.automatically_associate_pde_files"));
- pain.add(autoAssociateBox);
- d = autoAssociateBox.getPreferredSize();
- autoAssociateBox.setBounds(left, top, d.width + 10, d.height);
- right = Math.max(right, left + d.width);
- top += d.height + GUI_BETWEEN;
- }
-
-
- // More preferences are in the ...
-
- label = new JLabel(Language.text("preferences.file")+":");
- pain.add(label);
- d = label.getPreferredSize();
- label.setForeground(Color.gray);
- label.setBounds(left, top, d.width, d.height);
- right = Math.max(right, left + d.width);
- top += d.height; // + GUI_SMALL;
-
- label = new JLabel(Preferences.getSketchbookPath());
- final JLabel clickable = label;
- label.addMouseListener(new MouseAdapter() {
- public void mousePressed(MouseEvent e) {
- Base.openFolder(Base.getSettingsFolder());
- }
-
- public void mouseEntered(MouseEvent e) {
- clickable.setForeground(new Color(0, 0, 140));
- }
-
- public void mouseExited(MouseEvent e) {
- clickable.setForeground(Color.BLACK);
- }
- });
- pain.add(label);
- d = label.getPreferredSize();
- label.setBounds(left, top, d.width, d.height);
- right = Math.max(right, left + d.width);
- top += d.height;
-
- label = new JLabel("("+Language.text("preferences.file.hint")+")");
- pain.add(label);
- d = label.getPreferredSize();
- label.setForeground(Color.gray);
- label.setBounds(left, top, d.width, d.height);
- right = Math.max(right, left + d.width);
- top += d.height; // + GUI_SMALL;
-
-
- // [ OK ] [ Cancel ] maybe these should be next to the message?
-
- button = new JButton(Preferences.PROMPT_OK);
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- applyFrame();
- disposeFrame();
- }
- });
- pain.add(button);
- d2 = button.getPreferredSize();
- int BUTTON_HEIGHT = d2.height;
-
- h = right - (BUTTON_WIDTH + GUI_SMALL + BUTTON_WIDTH);
- button.setBounds(h, top, BUTTON_WIDTH, BUTTON_HEIGHT);
- h += BUTTON_WIDTH + GUI_SMALL;
-
- button = new JButton(Preferences.PROMPT_CANCEL);
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- disposeFrame();
- }
- });
- pain.add(button);
- button.setBounds(h, top, BUTTON_WIDTH, BUTTON_HEIGHT);
-
- top += BUTTON_HEIGHT + GUI_BETWEEN;
-
-
- // finish up
-
- wide = right + GUI_BIG;
- high = top + GUI_SMALL;
-
-
- // closing the window is same as hitting cancel button
-
- dialog.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- disposeFrame();
- }
- });
-
- ActionListener disposer = new ActionListener() {
- public void actionPerformed(ActionEvent actionEvent) {
- disposeFrame();
- }
- };
- Toolkit.registerWindowCloseKeys(dialog.getRootPane(), disposer);
- Toolkit.setIcon(dialog);
-
- Dimension screen = Toolkit.getScreenSize();
- dialog.setLocation((screen.width - wide) / 2,
- (screen.height - high) / 2);
-
- dialog.pack(); // get insets
- Insets insets = dialog.getInsets();
- dialog.setSize(wide + insets.left + insets.right,
- high + insets.top + insets.bottom);
-
-
- // handle window closing commands for ctrl/cmd-W or hitting ESC.
-
- pain.addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- //System.out.println(e);
- KeyStroke wc = Toolkit.WINDOW_CLOSE_KEYSTROKE;
- if ((e.getKeyCode() == KeyEvent.VK_ESCAPE) ||
- (KeyStroke.getKeyStrokeForEvent(e).equals(wc))) {
- disposeFrame();
- }
- }
- });
- }
-
-
- public void sketchbookCallback(File file) {
- if (file != null) {
- sketchbookLocationField.setText(file.getAbsolutePath());
- }
- }
-
-
- public Dimension getPreferredSize() {
- return new Dimension(wide, high);
- }
-
-
- // .................................................................
-
-
- /**
- * Close the window after an OK or Cancel.
- */
- protected void disposeFrame() {
- dialog.dispose();
- }
-
-
- /**
- * Change internal settings based on what was chosen in the prefs,
- * then send a message to the editor saying that it's time to do the same.
- */
- protected void applyFrame() {
- Preferences.setBoolean("editor.smooth", //$NON-NLS-1$
- editorAntialiasBox.isSelected());
-
- Preferences.setBoolean("export.delete_target_folder", //$NON-NLS-1$
- deletePreviousBox.isSelected());
-
- boolean wine = whinyBox.isSelected();
- Preferences.setBoolean("header.hide.image", wine); //$NON-NLS-1$
- Preferences.setBoolean("buttons.hide.image", wine); //$NON-NLS-1$
- // Could iterate through editors here and repaint them all, but probably
- // requires a doLayout() call, and that may have different effects on
- // each platform, and nobody wants to debug/support that.
-
- // if the sketchbook path has changed, rebuild the menus
- String oldPath = Preferences.getSketchbookPath();
- String newPath = sketchbookLocationField.getText();
- if (!newPath.equals(oldPath)) {
- base.setSketchbookFolder(new File(newPath));
- }
-
-// setBoolean("editor.external", externalEditorBox.isSelected());
- Preferences.setBoolean("update.check", checkUpdatesBox.isSelected()); //$NON-NLS-1$
-
- // Save Language
- Map languages = Language.getLanguages();
- String language = "";
- for (Map.Entry lang : languages.entrySet()) {
- if (lang.getValue().equals(String.valueOf(languageSelectionBox.getSelectedItem()))) {
- language = lang.getKey().trim().toLowerCase();
- break;
- }
- }
- if (!language.equals(Language.getLanguage()) && !language.equals("")) {
- Language.saveLanguage(language);
- }
-
- int oldDisplayIndex = Preferences.getInteger("run.display"); //$NON-NLS-1$
- int displayIndex = 0;
- for (int d = 0; d < displaySelectionBox.getItemCount(); d++) {
- if (displaySelectionBox.getSelectedIndex() == d) {
- displayIndex = d;
- }
- }
- if (oldDisplayIndex != displayIndex) {
- Preferences.setInteger("run.display", displayIndex); //$NON-NLS-1$
- for (Editor editor : base.getEditors()) {
- editor.setSketchLocation(null);
- }
- }
-
- Preferences.setBoolean("run.options.memory", memoryOverrideBox.isSelected()); //$NON-NLS-1$
- int memoryMin = Preferences.getInteger("run.options.memory.initial"); //$NON-NLS-1$
- int memoryMax = Preferences.getInteger("run.options.memory.maximum"); //$NON-NLS-1$
- try {
- memoryMax = Integer.parseInt(memoryField.getText().trim());
- // make sure memory setting isn't too small
- if (memoryMax < memoryMin) memoryMax = memoryMin;
- Preferences.setInteger("run.options.memory.maximum", memoryMax); //$NON-NLS-1$
- } catch (NumberFormatException e) {
- System.err.println("Ignoring bad memory setting");
- }
-
- // Don't change anything if the user closes the window before fonts load
- if (fontSelectionBox.isEnabled()) {
- String fontFamily = (String) fontSelectionBox.getSelectedItem();
- Preferences.set("editor.font.family", fontFamily);
- }
-
- try {
- Object selection = fontSizeField.getSelectedItem();
- if (selection instanceof String) {
- // Replace with Integer version
- selection = Integer.parseInt((String) selection);
- }
- Preferences.set("editor.font.size", String.valueOf(selection));
-
- } catch (NumberFormatException e) {
- Base.log("Ignoring invalid font size " + fontSizeField); //$NON-NLS-1$
- fontSizeField.setSelectedItem(Preferences.getInteger("editor.font.size"));
- }
-
- try {
- Object selection = consoleSizeField.getSelectedItem();
- if (selection instanceof String) {
- // Replace with Integer version
- selection = Integer.parseInt((String) selection);
- }
- Preferences.set("console.font.size", String.valueOf(selection));
-
- } catch (NumberFormatException e) {
- Base.log("Ignoring invalid font size " + consoleSizeField); //$NON-NLS-1$
- consoleSizeField.setSelectedItem(Preferences.getInteger("console.font.size"));
- }
-
- Preferences.setColor("run.present.bgcolor", presentColor.getBackground());
-
- Preferences.setBoolean("editor.input_method_support", inputMethodBox.isSelected()); //$NON-NLS-1$
-
- if (autoAssociateBox != null) {
- Preferences.setBoolean("platform.auto_file_type_associations", //$NON-NLS-1$
- autoAssociateBox.isSelected());
- }
-
- Preferences.setBoolean("pdex.errorCheckEnabled", errorCheckerBox.isSelected());
- Preferences.setBoolean("pdex.warningsEnabled", warningsCheckerBox.isSelected());
- Preferences.setBoolean("pdex.ccEnabled", codeCompletionBox.isSelected());
- Preferences.setBoolean("pdex.ccTriggerEnabled", codeCompletionTriggerBox.isSelected());
- for (Editor editor : base.getEditors()) {
- editor.applyPreferences();
- }
- }
-
-
- protected void showFrame() {
- editorAntialiasBox.setSelected(Preferences.getBoolean("editor.smooth")); //$NON-NLS-1$
- inputMethodBox.setSelected(Preferences.getBoolean("editor.input_method_support")); //$NON-NLS-1$
- errorCheckerBox.setSelected(Preferences.getBoolean("pdex.errorCheckEnabled"));
- warningsCheckerBox.setSelected(Preferences.getBoolean("pdex.warningsEnabled"));
- codeCompletionBox.setSelected(Preferences.getBoolean("pdex.ccEnabled"));
- codeCompletionTriggerBox.setSelected(Preferences.getBoolean("pdex.ccTriggerEnabled"));
- codeCompletionTriggerBox.setEnabled(codeCompletionBox.isSelected());
- deletePreviousBox.
- setSelected(Preferences.getBoolean("export.delete_target_folder")); //$NON-NLS-1$
-
- sketchbookLocationField.setText(Preferences.getSketchbookPath());
- checkUpdatesBox.setSelected(Preferences.getBoolean("update.check")); //$NON-NLS-1$
-
- whinyBox.setSelected(Preferences.getBoolean("header.hide.image") || //$NON-NLS-1$
- Preferences.getBoolean("buttons.hide.image")); //$NON-NLS-1$
-
- updateDisplayList();
- int displayNum = Preferences.getInteger("run.display"); //$NON-NLS-1$
- if (displayNum >= 0 && displayNum < displayCount) {
- displaySelectionBox.setSelectedIndex(displayNum);
- }
-
- // This takes a while to load, so run it from a separate thread
- new Thread(new Runnable() {
- public void run() {
- initFontList();
- }
- }).start();
-
- fontSizeField.setSelectedItem(Preferences.getInteger("editor.font.size"));
- consoleSizeField.setSelectedItem(Preferences.getInteger("console.font.size"));
-
- presentColor.setBackground(Preferences.getColor("run.present.bgcolor"));
- presentColorHex.setText(Preferences.get("run.present.bgcolor").substring(1));
-
- memoryOverrideBox.
- setSelected(Preferences.getBoolean("run.options.memory")); //$NON-NLS-1$
- memoryField.
- setText(Preferences.get("run.options.memory.maximum")); //$NON-NLS-1$
- memoryField.setEnabled(memoryOverrideBox.isSelected());
-
- if (autoAssociateBox != null) {
- autoAssociateBox.
- setSelected(Preferences.getBoolean("platform.auto_file_type_associations")); //$NON-NLS-1$
- }
-
- dialog.setVisible(true);
- }
-
-
- /**
- * I have some ideas on how we could make Swing even more obtuse for the
- * most basic usage scenarios. Is there someone on the team I can contact?
- * Oracle, are you listening?
- */
- class FontNamer extends JLabel implements ListCellRenderer {
- public Component getListCellRendererComponent(JList extends Font> list,
- Font value, int index,
- boolean isSelected,
- boolean cellHasFocus) {
- //if (Base.isMacOS()) {
- setText(value.getFamily() + " / " + value.getName() + " (" + value.getPSName() + ")");
- return this;
- }
- }
-
-
- void initFontList() {
- if (monoFontFamilies == null) {
- monoFontFamilies = Toolkit.getMonoFontFamilies();
- fontSelectionBox.setModel(new DefaultComboBoxModel(monoFontFamilies));
- String family = Preferences.get("editor.font.family");
-
- // Set a reasonable default, in case selecting the family fails
- fontSelectionBox.setSelectedItem("Monospaced");
- fontSelectionBox.setSelectedItem(family);
- fontSelectionBox.setEnabled(true);
- }
- }
-
-
- void updateDisplayList() {
- GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
- displayCount = ge.getScreenDevices().length;
-// displaySelectionBox.removeAll();
- String[] items = new String[displayCount];
- for (int i = 0; i < displayCount; i++) {
- items[i] = String.valueOf(i + 1);
-// displaySelectionBox.add(String.valueOf(i + 1));
- }
-// PApplet.println(items);
- displaySelectionBox.setModel(new DefaultComboBoxModel(items));
-// displaySelectionBox = new JComboBox(items);
- }
-}
diff --git a/app/src/processing/app/Problem.java b/app/src/processing/app/Problem.java
new file mode 100644
index 0000000000..cb12ad5e3e
--- /dev/null
+++ b/app/src/processing/app/Problem.java
@@ -0,0 +1,35 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+ Copyright (c) 2012-16 The Processing Foundation
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 2
+ as published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU 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, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+package processing.app;
+
+
+public interface Problem {
+ public boolean isError();
+ public boolean isWarning();
+
+ public int getTabIndex();
+ public int getLineNumber(); // 0-indexed
+ public String getMessage();
+
+ public int getStartOffset();
+ public int getStopOffset();
+}
+
diff --git a/app/src/processing/app/ProgressFrame.java b/app/src/processing/app/ProgressFrame.java
deleted file mode 100644
index 3e91ee54cd..0000000000
--- a/app/src/processing/app/ProgressFrame.java
+++ /dev/null
@@ -1,379 +0,0 @@
-package processing.app;
-
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JProgressBar;
-import javax.swing.SwingWorker;
-
-//Class used to handle progress bar, and run Save As or Add File in
-//background so that
-//progress bar can update without freezing
-public class ProgressFrame extends JFrame implements PropertyChangeListener {
-
- private static final long serialVersionUID = 1L;
-
- private JProgressBar progressBar;
-
- private JLabel saveAsLabel;
-
- private TaskSaveAs t;
-
- private TaskAddFile t2;
-
- private File[] copyItems;
-
- private File newFolder;
-
- private File addFile, sourceFile;
-
- private Editor editor;
-
- // create a new background thread to save as
- public class TaskSaveAs extends SwingWorker {
-
- @Override
- protected Void doInBackground() throws Exception {
- // a large part of the file copying happens in this background
- // thread
-
- long totalSize = 0;
- for (File copyable : copyItems) {
- totalSize += getFileLength(copyable);
- }
-
- long progress = 0;
- setProgress(0);
- for (File copyable : ProgressFrame.this.copyItems) {
- // loop to copy over the items that make sense, and to set the
- // current progress
-
- if (copyable.isDirectory()) {
- copyDir(copyable,
- new File(ProgressFrame.this.newFolder, copyable.getName()),
- this, progress, totalSize);
- progress += getFileLength(copyable);
- } else {
- copyFile(copyable,
- new File(ProgressFrame.this.newFolder, copyable.getName()),
- this, progress, totalSize);
- if (getFileLength(copyable) < 524288) {
- // If the file length > 0.5MB, the copyFile() function has
- // been redesigned to change progress every 0.5MB so that
- // the progress bar doesn't stagnate during that time
- progress += getFileLength(copyable);
- setProgress((int) Math.min(Math.ceil(progress * 100.0 / totalSize),
- 100));
- }
- }
- }
-
- return null;
- }
-
- public void setProgressBarStatus(int status) {
-
- setProgress(status);
- }
-
- @Override
- public void done() {
- // to close the progress bar automatically when done, and to
- // print that Saving is done in Message Area
-
- editor.statusNotice("Done Saving.");
- ProgressFrame.this.closeProgressBar();
- }
-
- }
-
- // create a new background thread to add a file
- public class TaskAddFile extends SwingWorker {
-
- @Override
- protected Void doInBackground() throws Exception {
- // a large part of the file copying happens in this background
- // thread
-
- setProgress(0);
-
- copyFile(sourceFile, addFile, this);
-
- if (addFile.length() < 1024) {
- // If the file length > 1kB, the copyFile() function has
- // been redesigned to change progress every 1kB so that
- // the progress bar doesn't stagnate during that time
-
- // If file <1 kB, just fill up Progress Bar to 100%
- // directly, since time to copy is now negligable (when
- // perceived by a human, anyway)
- setProgress(100);
- }
-
- return null;
- }
-
- public void setProgressBarStatus(int status) {
- setProgress(status);
- }
-
- @Override
- public void done() {
- // to close the progress bar automatically when done, and to
- // print that adding file is done in Message Area
-
- editor.statusNotice("One file added to the sketch.");
- ProgressFrame.this.closeProgressBar();
- }
-
- }
-
- //Use for Save As
- public ProgressFrame(File[] c, File nf, String oldName, String newName,
- Editor editor) {
- // initialize a copyItems and newFolder, which are used for file
- // copying in the background thread
- copyItems = c;
- newFolder = nf;
- this.editor = editor;
-
- // the UI of the progress bar follows
- setDefaultCloseOperation(HIDE_ON_CLOSE);
- setBounds(200, 200, 400, 140);
- setResizable(false);
- setTitle("Saving As...");
- JPanel panel = new JPanel(null);
- add(panel);
- setContentPane(panel);
- saveAsLabel = new JLabel("Saving " + oldName + " as " + newName + "...");
- saveAsLabel.setBounds(40, 20, 300, 20);
-
- progressBar = new JProgressBar(0, 100);
- progressBar.setValue(0);
- progressBar.setBounds(40, 50, 300, 30);
- progressBar.setStringPainted(true);
-
- panel.add(progressBar);
- panel.add(saveAsLabel);
- Toolkit.setIcon(this);
- this.setVisible(true);
-
- // create an instance of TaskSaveAs and run execute() on this
- // instance to
- // start background thread
- t = new TaskSaveAs();
- t.addPropertyChangeListener(this);
- t.execute();
- }
-
- //Use for Add File
- public ProgressFrame(File sf, File add, Editor editor) {
-
- addFile = add;
- sourceFile = sf;
- this.editor = editor;
-
- // the UI of the progress bar follows
- setDefaultCloseOperation(HIDE_ON_CLOSE);
- setBounds(200, 200, 400, 140);
- setResizable(false);
- setTitle("Adding File...");
- JPanel panel = new JPanel(null);
- add(panel);
- setContentPane(panel);
- saveAsLabel = new JLabel("Adding " + addFile.getName());
- saveAsLabel.setBounds(40, 20, 300, 20);
-
- progressBar = new JProgressBar(0, 100);
- progressBar.setValue(0);
- progressBar.setBounds(40, 50, 300, 30);
- progressBar.setStringPainted(true);
-
- panel.add(progressBar);
- panel.add(saveAsLabel);
- Toolkit.setIcon(this);
- this.setVisible(true);
-
- // create an instance of TaskAddFile and run execute() on this
- // instance to
- // start background thread
- t2 = new TaskAddFile();
- t2.addPropertyChangeListener(this);
- t2.execute();
- }
-
- public long getFileLength(File f)// function to return the length of
- // the file, or
- // ENTIRE directory, including the
- // component files
- // and sub-folders if passed
- {
- long fol_len = 0;
- if (f.isDirectory()) {
- String files[] = f.list();
- for (int i = 0; i < files.length; i++) {
- File temp = new File(f, files[i]);
- if (temp.isDirectory()) {
- fol_len += getFileLength(temp);
- } else {
- fol_len += (temp.length());
- }
- }
- } else {
- return (f.length());
- }
- return fol_len;
- }
-
- public void propertyChange(PropertyChangeEvent evt)
- // detects a change in the property of the background task, i.e., is
- // called when the size of files already copied changes
- {
- if ("progress" == evt.getPropertyName()) {
- int progress = (Integer) evt.getNewValue();
- progressBar.setValue(progress);
- }
- }
-
- private void closeProgressBar()
- // closes progress bar
- {
- this.dispose();
- }
-
- static public void copyFile(File sourceFile, File targetFile,
- ProgressFrame.TaskSaveAs progBar,
- double progress, double totalSize)
- throws IOException {
- // Overloaded copyFile that is called whenever a Save As is being done, so that the
- // ProgressBar is updated for very large files as well
- BufferedInputStream from = new BufferedInputStream(
- new FileInputStream(
- sourceFile));
- BufferedOutputStream to = new BufferedOutputStream(
- new FileOutputStream(
- targetFile));
- byte[] buffer = new byte[16 * 1024];
- int bytesRead;
- int totalRead = 0;
- while ((bytesRead = from.read(buffer)) != -1) {
- to.write(buffer, 0, bytesRead);
- totalRead += bytesRead;
- if (totalRead >= 524288) //to update progress bar every 0.5MB
- {
- progress += totalRead;
- progBar.setProgressBarStatus((int) Math.min(Math.ceil(progress * 100.0
- / totalSize), 100));
- totalRead = 0;
- }
- }
- if (sourceFile.length() > 524288) {
- // Update the progress bar one final time if file size is more than 0.5MB,
- // otherwise, the update is handled either by the copyDir function,
- // or directly by ProgressFrame.TaskSaveAs.doInBackground()
- progress += totalRead;
- progBar.setProgressBarStatus((int) Math.min(Math.ceil(progress * 100.0
- / totalSize), 100));
- }
- from.close();
- from = null;
- to.flush();
- to.close();
- to = null;
-
- targetFile.setLastModified(sourceFile.lastModified());
- targetFile.setExecutable(sourceFile.canExecute());
- }
-
- static public void copyFile(File sourceFile, File targetFile,
- ProgressFrame.TaskAddFile progBar)
- throws IOException {
- // Overloaded copyFile that is called whenever a addFile is being done,
- // so that the
- // ProgressBar is updated
- double totalSize = sourceFile.length();
- int progress = 0;
- BufferedInputStream from = new BufferedInputStream(
- new FileInputStream(
- sourceFile));
- BufferedOutputStream to = new BufferedOutputStream(
- new FileOutputStream(
- targetFile));
- byte[] buffer = new byte[16 * 1024];
- int bytesRead;
- int totalRead = 0;
- while ((bytesRead = from.read(buffer)) != -1) {
- to.write(buffer, 0, bytesRead);
- totalRead += bytesRead;
- if (totalRead >= 1024) // to update progress bar every 1kB
- {
- progress += totalRead;
- progBar.setProgressBarStatus((int) Math.min(Math.ceil(progress * 100.0
- / totalSize), 100));
- totalRead = 0;
- }
- }
- if (sourceFile.length() > 1024) {
- // Update the progress bar one final time if file size is more than
- // 1kB,
- // otherwise, the update is handled directly by
- // ProgressFrame.TaskAddFile.doInBackground()
- progress += totalRead;
- progBar.setProgressBarStatus((int) Math.min(Math.ceil(progress * 100.0
- / totalSize), 100));
- }
- from.close();
- from = null;
- to.flush();
- to.close();
- to = null;
- targetFile.setLastModified(sourceFile.lastModified());
- targetFile.setExecutable(sourceFile.canExecute());
- }
-
- static public double copyDir(File sourceDir, File targetDir,
- ProgressFrame.TaskSaveAs progBar,
- double progress, double totalSize)
- throws IOException {
- // Overloaded copyDir so that the Save As progress bar gets updated when the
- // files are in folders as well (like in the data folder)
- if (sourceDir.equals(targetDir)) {
- final String urDum = "source and target directories are identical";
- throw new IllegalArgumentException(urDum);
- }
- targetDir.mkdirs();
- String files[] = sourceDir.list();
- for (int i = 0; i < files.length; i++) {
- // Ignore dot files (.DS_Store), dot folders (.svn) while copying
- if (files[i].charAt(0) == '.')
- continue;
- //if (files[i].equals(".") || files[i].equals("..")) continue;
- File source = new File(sourceDir, files[i]);
- File target = new File(targetDir, files[i]);
- if (source.isDirectory()) {
- //target.mkdirs();
- progress = copyDir(source, target, progBar, progress, totalSize);
- progBar.setProgressBarStatus((int) Math.min(Math.ceil(progress * 100.0
- / totalSize), 100));
- target.setLastModified(source.lastModified());
- } else {
- copyFile(source, target, progBar, progress, totalSize);
- // Update SaveAs progress bar
- progress += source.length();
- progBar.setProgressBarStatus((int) Math.min(Math.ceil(progress * 100.0
- / totalSize), 100));
- }
- }
- return progress;
- }
-
-}
diff --git a/app/src/processing/app/RunnerListenerEdtAdapter.java b/app/src/processing/app/RunnerListenerEdtAdapter.java
new file mode 100644
index 0000000000..a436eefbca
--- /dev/null
+++ b/app/src/processing/app/RunnerListenerEdtAdapter.java
@@ -0,0 +1,48 @@
+package processing.app;
+
+import java.awt.EventQueue;
+
+public class RunnerListenerEdtAdapter implements RunnerListener {
+
+ private RunnerListener wrapped;
+
+ public RunnerListenerEdtAdapter(RunnerListener wrapped) {
+ this.wrapped = wrapped;
+ }
+
+ @Override
+ public void statusError(String message) {
+ EventQueue.invokeLater(() -> wrapped.statusError(message));
+ }
+
+ @Override
+ public void statusError(Exception exception) {
+ EventQueue.invokeLater(() -> wrapped.statusError(exception));
+ }
+
+ @Override
+ public void statusNotice(String message) {
+ EventQueue.invokeLater(() -> wrapped.statusNotice(message));
+ }
+
+ @Override
+ public void startIndeterminate() {
+ EventQueue.invokeLater(() -> wrapped.startIndeterminate());
+ }
+
+ @Override
+ public void stopIndeterminate() {
+ EventQueue.invokeLater(() -> wrapped.stopIndeterminate());
+ }
+
+ @Override
+ public void statusHalt() {
+ EventQueue.invokeLater(() -> wrapped.statusHalt());
+ }
+
+ @Override
+ public boolean isHalted() {
+ return wrapped.isHalted();
+ }
+}
+
diff --git a/app/src/processing/app/Settings.java b/app/src/processing/app/Settings.java
index eea88204b9..efd016f231 100644
--- a/app/src/processing/app/Settings.java
+++ b/app/src/processing/app/Settings.java
@@ -27,6 +27,7 @@
import java.io.*;
import java.util.*;
+import processing.app.ui.Toolkit;
import processing.core.*;
@@ -36,31 +37,31 @@
* and to make way for future ability to customize.
*/
public class Settings {
- /**
- * Copy of the defaults in case the user mangles a preference.
+ /**
+ * Copy of the defaults in case the user mangles a preference.
* It's necessary to keep a copy of the defaults around, because the user may
- * have mangled a setting on their own. In the past, we used to load the
+ * have replaced a setting on their own. In the past, we used to load the
* defaults, then replace those with what was in the user's preferences file.
- * Problem is, if something like a font entry in the user's file no longer
+ * Problem is, if something like a font entry in the user's file no longer
* parses properly, we need to be able to get back to a clean version of that
* setting so we can recover.
*/
HashMap defaults;
-
+
/** Table of attributes/values. */
HashMap table = new HashMap();;
-
+
/** Associated file for this settings data. */
File file;
public Settings(File file) throws IOException {
this.file = file;
-
+
if (file.exists()) {
load();
}
-
+
// clone the hash table
defaults = (HashMap) table.clone();
}
@@ -70,7 +71,7 @@ public void load() {
load(file);
}
-
+
public void load(File additions) {
String[] lines = PApplet.loadStrings(additions);
for (String line : lines) {
@@ -87,7 +88,7 @@ public void load(File additions) {
}
// check for platform-specific properties in the defaults
- String platformExt = "." + Base.getPlatformName();
+ String platformExt = "." + Platform.getName();
int platformExtLength = platformExt.length();
for (String key : table.keySet()) {
if (key.endsWith(platformExt)) {
@@ -176,7 +177,7 @@ public void setColor(String attr, Color what) {
}
- // identical version found in Preferences.java
+ // identical version found in Preferences.java
public Font getFont(String attr) {
try {
boolean replace = false;
@@ -204,7 +205,8 @@ public Font getFont(String attr) {
style |= Font.ITALIC;
}
int size = PApplet.parseInt(pieces[2], 12);
-
+ size = Toolkit.zoom(size);
+
// replace bad font with the default from lib/preferences.txt
if (replace) {
set(attr, value);
@@ -222,9 +224,9 @@ public Font getFont(String attr) {
}
} catch (Exception e) {
- // Adding try/catch block because this may be where
- // a lot of startup crashes are happening.
- Base.log("Error with font " + get(attr) + " for attribute " + attr);
+ // Adding try/catch block because this may be where
+ // a lot of startup crashes are happening.
+ Messages.log("Error with font " + get(attr) + " for attribute " + attr);
}
return new Font("Dialog", Font.PLAIN, 12);
}
diff --git a/app/src/processing/app/SingleInstance.java b/app/src/processing/app/SingleInstance.java
index 4fa08a2d83..d9409d1526 100644
--- a/app/src/processing/app/SingleInstance.java
+++ b/app/src/processing/app/SingleInstance.java
@@ -3,6 +3,7 @@
/*
Part of the Processing project - http://processing.org
+ Copyright (c) 2012-14 The Processing Foundation
Copyright (c) 2011-12 Ben Fry and Casey Reas
This program is free software; you can redistribute it and/or modify
@@ -20,6 +21,7 @@
*/
package processing.app;
+import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
@@ -27,8 +29,6 @@
import java.net.ServerSocket;
import java.net.Socket;
-import javax.swing.SwingUtilities;
-
import processing.core.PApplet;
@@ -37,8 +37,6 @@
* Processing from running simultaneously. If there's already an instance
* running, it'll handle opening a new empty sketch, or any files that had
* been passed in on the command line.
- *
- * @author Peter Kalauskas, Ben Fry
*/
public class SingleInstance {
static final String SERVER_PORT = "instance_server.port";
@@ -54,19 +52,20 @@ public class SingleInstance {
*/
static boolean alreadyRunning(String[] args) {
return Preferences.get(SERVER_PORT) != null && sendArguments(args);
-// sendArguments(args, 5000));
}
-// static void startServer(final Platform platform) {
static void startServer(final Base base) {
try {
- final ServerSocket ss = new ServerSocket(0, 0, InetAddress.getByName(null));
+ Messages.log("Opening SingleInstance socket");
+ final ServerSocket ss =
+ new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
Preferences.set(SERVER_PORT, "" + ss.getLocalPort());
final String key = "" + Math.random();
Preferences.set(SERVER_KEY, key);
Preferences.save();
+ Messages.log("Starting SingleInstance thread");
new Thread(new Runnable() {
public void run() {
while (true) {
@@ -74,28 +73,26 @@ public void run() {
Socket s = ss.accept(); // blocks (sleeps) until connection
final BufferedReader reader = PApplet.createReader(s.getInputStream());
String receivedKey = reader.readLine();
- Base.log(this, "key is " + key + ", received is " + receivedKey);
-// Base.log(this, "platform base is " + platform.base);
+ Messages.log(this, "key is " + key + ", received is " + receivedKey);
-// if (platform.base != null) {
if (key.equals(receivedKey)) {
- SwingUtilities.invokeLater(new Runnable() {
+ EventQueue.invokeLater(new Runnable() {
public void run() {
try {
- Base.log(this, "about to read line");
+ Messages.log(this, "about to read line");
String path = reader.readLine();
if (path == null) {
// Because an attempt was made to launch the PDE again,
// throw the user a bone by at least opening a new
// Untitled window for them.
- Base.log(this, "opening new empty sketch");
+ Messages.log(this, "opening new empty sketch");
// platform.base.handleNew();
base.handleNew();
} else {
// loop through the sketches that were passed in
do {
- Base.log(this, "calling open with " + path);
+ Messages.log(this, "calling open with " + path);
// platform.base.handleOpen(filename);
base.handleOpen(path);
path = reader.readLine();
@@ -107,67 +104,48 @@ public void run() {
}
});
} else {
- Base.log(this, "keys do not match");
+ Messages.log(this, "keys do not match");
}
// }
} catch (IOException e) {
- Base.log("SingleInstance error while listening", e);
+ Messages.loge("SingleInstance error while listening", e);
}
}
}
}, "SingleInstance Server").start();
} catch (IOException e) {
- Base.log("Could not create single instance server.", e);
+ Messages.loge("Could not create single instance server.", e);
}
}
static boolean sendArguments(String[] args) { //, long timeout) {
try {
- //int port = Integer.parseInt(Preferences.get("server.port"));
- //String key = Preferences.get("server.key");
+ Messages.log("Checking to see if Processing is already running");
int port = Preferences.getInteger(SERVER_PORT);
String key = Preferences.get(SERVER_KEY);
-// long endTime = System.currentTimeMillis() + timeout;
-//
-// Socket socket = null;
-// while (socket == null && System.currentTimeMillis() < endTime) {
-// try {
-// socket = new Socket(InetAddress.getByName(null), port);
-// } catch (Exception ioe) {
-// try {
-// Thread.sleep(50);
-// } catch (InterruptedException ie) {
-// Thread.yield();
-// }
-// }
-// }
Socket socket = null;
try {
- socket = new Socket(InetAddress.getByName(null), port);
+ socket = new Socket(InetAddress.getLoopbackAddress(), port);
} catch (Exception ignored) { }
if (socket != null) {
+ Messages.log("Processing is already running, sending command line");
PrintWriter writer = PApplet.createWriter(socket.getOutputStream());
-// bw.write(key + "\n");
writer.println(key);
for (String arg : args) {
-// if (filename != null) {
-//// bw.write(filename + "\n");
-// writer.println(filename);
writer.println(arg);
}
-// bw.close();
writer.flush();
writer.close();
return true;
}
} catch (IOException e) {
- System.err.println("Error sending commands to other instance.");
- e.printStackTrace();
+ Messages.loge("Error sending commands to other instance", e);
}
+ Messages.log("Processing is not already running (or could not connect)");
return false;
}
}
diff --git a/app/src/processing/app/Sketch.java b/app/src/processing/app/Sketch.java
index 957f785d84..e686dc1823 100644
--- a/app/src/processing/app/Sketch.java
+++ b/app/src/processing/app/Sketch.java
@@ -23,15 +23,28 @@
package processing.app;
+import processing.app.ui.Editor;
+import processing.app.ui.Recent;
+import processing.app.ui.Toolkit;
import processing.core.*;
-import java.awt.*;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.EventQueue;
+import java.awt.FileDialog;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
import java.io.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.*;
+import javax.swing.border.EmptyBorder;
/**
@@ -64,6 +77,7 @@ public class Sketch {
private SketchCode current;
private int currentIndex;
+
/**
* Number of sketchCode objects (tabs) in the current sketch. Note that this
* will be the same as code.length, because the getCode() method returns
@@ -77,28 +91,8 @@ public class Sketch {
/** Moved out of Editor and into here for cleaner access. */
private boolean untitled;
-// /** Class path determined during build. */
-// private String classPath;
-//
-// /**
-// * This is *not* the "Processing" libraries path, this is the Java libraries
-// * path, as in java.library.path=BlahBlah, which identifies search paths for
-// * DLLs or JNILIBs. (It's Java's LD_LIBRARY_PATH, for you UNIX fans.)
-// */
-// private String javaLibraryPath;
-//
-// /**
-// * List of library folders, set up in the preprocess() method.
-// */
-// private ArrayList importedLibraries;
-// //private ArrayList importedLibraries;
-
- /**
- * Most recent, default build path. This will contain the .java files that
- * have been preprocessed, as well as any .class files that were compiled.
- */
-// private File buildFolder;
-
+ /** true if we've posted a "sketch disappeared" warning */
+ private boolean disappearedWarning;
/**
* Used by the command-line version to create a sketch object.
@@ -131,6 +125,7 @@ protected void load(String path) {
int suffixLength = mode.getDefaultExtension().length() + 1;
name = mainFilename.substring(0, mainFilename.length() - suffixLength);
folder = new File(new File(path).getParent());
+ disappearedWarning = false;
load();
}
@@ -153,16 +148,46 @@ protected void load() {
codeFolder = new File(folder, "code");
dataFolder = new File(folder, "data");
- // get list of files in the sketch folder
- String list[] = folder.list();
+ List filenames = new ArrayList<>();
+ List extensions = new ArrayList<>();
- // reset these because load() may be called after an
- // external editor event. (fix for 0099)
- codeCount = 0;
+ getSketchCodeFiles(filenames, extensions);
- code = new SketchCode[list.length];
+ codeCount = filenames.size();
+ code = new SketchCode[codeCount];
- String[] extensions = mode.getExtensions();
+ for (int i = 0; i < codeCount; i++) {
+ String filename = filenames.get(i);
+ String extension = extensions.get(i);
+ code[i] = new SketchCode(new File(folder, filename), extension);
+ }
+
+ // move the main class to the first tab
+ // start at 1, if it's at zero, don't bother
+ for (int i = 1; i < codeCount; i++) {
+ //if (code[i].file.getName().equals(mainFilename)) {
+ if (code[i].getFile().equals(primaryFile)) {
+ SketchCode temp = code[0];
+ code[0] = code[i];
+ code[i] = temp;
+ break;
+ }
+ }
+
+ // sort the entries at the top
+ sortCode();
+
+ // set the main file to be the current tab
+ if (editor != null) {
+ setCurrentCode(0);
+ }
+ }
+
+
+ public void getSketchCodeFiles(List outFilenames,
+ List outExtensions) {
+ // get list of files in the sketch folder
+ String list[] = folder.list();
for (String filename : list) {
// Ignoring the dot prefix files is especially important to avoid files
@@ -176,41 +201,19 @@ protected void load() {
// figure out the name without any extension
String base = filename;
// now strip off the .pde and .java extensions
- for (String extension : extensions) {
+ for (String extension : mode.getExtensions()) {
if (base.toLowerCase().endsWith("." + extension)) {
base = base.substring(0, base.length() - (extension.length() + 1));
// Don't allow people to use files with invalid names, since on load,
// it would be otherwise possible to sneak in nasty filenames. [0116]
if (isSanitaryName(base)) {
- code[codeCount++] =
- new SketchCode(new File(folder, filename), extension);
+ if (outFilenames != null) outFilenames.add(filename);
+ if (outExtensions != null) outExtensions.add(extension);
}
}
}
}
- // Remove any code that wasn't proper
- code = (SketchCode[]) PApplet.subset(code, 0, codeCount);
-
- // move the main class to the first tab
- // start at 1, if it's at zero, don't bother
- for (int i = 1; i < codeCount; i++) {
- //if (code[i].file.getName().equals(mainFilename)) {
- if (code[i].getFile().equals(primaryFile)) {
- SketchCode temp = code[0];
- code[0] = code[i];
- code[i] = temp;
- break;
- }
- }
-
- // sort the entries at the top
- sortCode();
-
- // set the main file to be the current tab
- if (editor != null) {
- setCurrentCode(0);
- }
}
@@ -227,6 +230,20 @@ public void reload() {
}
+ /**
+ * Load a tab that the user added to the sketch or modified with an external
+ * editor.
+ */
+ public void loadNewTab(String filename, String ext, boolean newAddition) {
+ if (newAddition) {
+ insertCode(new SketchCode(new File(folder, filename), ext));
+ } else {
+ replaceCode(new SketchCode(new File(folder, filename), ext));
+ }
+ sortCode();
+ }
+
+
protected void replaceCode(SketchCode newCode) {
for (int i = 0; i < codeCount; i++) {
if (code[i].getFileName().equals(newCode.getFileName())) {
@@ -264,6 +281,13 @@ protected void sortCode() {
SketchCode temp = code[who];
code[who] = code[i];
code[i] = temp;
+
+ // We also need to update the current tab
+ if (currentIndex == i) {
+ currentIndex = who;
+ } else if (currentIndex == who) {
+ currentIndex = i;
+ }
}
}
}
@@ -281,10 +305,8 @@ public void handleNewCode() {
// if read-only, give an error
if (isReadOnly()) {
// 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 the sketch in another location,\n" +
- "and try again.");
+ Messages.showMessage(Language.text("new.messages.is_read_only"),
+ Language.text("new.messages.is_read_only.description"));
return;
}
@@ -302,24 +324,22 @@ public void handleRenameCode() {
ensureExistence();
if (currentIndex == 0 && isUntitled()) {
- Base.showMessage("Sketch is Untitled",
- "How about saving the sketch first \n" +
- "before trying to rename it?");
+ Messages.showMessage(Language.text("rename.messages.is_untitled"),
+ Language.text("rename.messages.is_untitled.description"));
return;
}
if (isModified()) {
- Base.showMessage("Save", "Please save the sketch before renaming.");
+ Messages.showMessage(Language.text("menu.file.save"),
+ Language.text("rename.messages.is_modified"));
return;
}
// if read-only, give an error
if (isReadOnly()) {
// 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 the sketch in another location,\n" +
- "and try again.");
+ Messages.showMessage(Language.text("rename.messages.is_read_only"),
+ Language.text("rename.messages.is_read_only.description"));
return;
}
@@ -327,31 +347,30 @@ public void handleRenameCode() {
// TODO maybe just popup a text area?
renamingCode = true;
String prompt = (currentIndex == 0) ?
- Language.text("editor.sketch.rename.description") : Language.text("editor.tab.rename.description");
+ Language.text("editor.sketch.rename.description") :
+ Language.text("editor.tab.rename.description");
String oldName = (current.isExtension(mode.getDefaultExtension())) ?
current.getPrettyName() : current.getFileName();
- // editor.status.edit(prompt, oldName);
- promptForTabName(prompt+":", oldName);
+ promptForTabName(prompt + ":", oldName);
}
-
+
+
/**
* Displays a dialog for renaming or creating a new tab
- * @param prompt - msg to display
- * @param oldName
*/
protected void promptForTabName(String prompt, String oldName) {
final JTextField field = new JTextField(oldName);
-
+
field.addKeyListener(new KeyAdapter() {
// Forget ESC, the JDialog should handle it.
- // Use keyTyped to catch when the feller is actually added to the text
- // field. With keyTyped, as opposed to keyPressed, the keyCode will be
- // zero, even if it's enter or backspace or whatever, so the keychar
+ // Use keyTyped to catch when the feller is actually added to the text
+ // field. With keyTyped, as opposed to keyPressed, the keyCode will be
+ // zero, even if it's enter or backspace or whatever, so the keychar
// should be used instead. Grr.
public void keyTyped(KeyEvent event) {
//System.out.println("got event " + event);
char ch = event.getKeyChar();
- if ((ch == '_') || (ch == '.') || // allow.pde and .java
+ if ((ch == '_') || (ch == '.') || // allow.pde and .java
(('A' <= ch) && (ch <= 'Z')) || (('a' <= ch) && (ch <= 'z'))) {
// These events are allowed straight through.
} else if (ch == ' ') {
@@ -367,13 +386,13 @@ public void keyTyped(KeyEvent event) {
// getSelectionStart means that it *will be* the first
// char, because the selection is about to be replaced
// with whatever is typed.
- if (field.getCaretPosition() == 0 ||
+ if (field.getCaretPosition() == 0 ||
field.getSelectionStart() == 0) {
// number not allowed as first digit
event.consume();
}
} else if (ch == KeyEvent.VK_ENTER) {
- // Slightly ugly hack that ensures OK button of the dialog consumes
+ // Slightly ugly hack that ensures OK button of the dialog consumes
// the Enter key event. Since the text field is the default component
// in the dialog, OK doesn't consume Enter key event, by default.
Container parent = field.getParent();
@@ -381,14 +400,14 @@ public void keyTyped(KeyEvent event) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
- final JPanel pnlBottom = (JPanel)
+ final JPanel pnlBottom = (JPanel)
pane.getComponent(pane.getComponentCount() - 1);
for (int i = 0; i < pnlBottom.getComponents().length; i++) {
Component component = pnlBottom.getComponents()[i];
if (component instanceof JButton) {
final JButton okButton = (JButton) component;
if (okButton.getText().equalsIgnoreCase("OK")) {
- ActionListener[] actionListeners =
+ ActionListener[] actionListeners =
okButton.getActionListeners();
if (actionListeners.length > 0) {
actionListeners[0].actionPerformed(null);
@@ -409,8 +428,8 @@ public void keyTyped(KeyEvent event) {
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, new Object[] {
- Preferences.PROMPT_OK,
- Preferences.PROMPT_CANCEL },
+ Language.getPrompt("ok"),
+ Language.getPrompt("cancel") },
field);
if (userReply == JOptionPane.OK_OPTION) {
@@ -452,17 +471,17 @@ protected void nameCode(String newName) {
}
if (newName.startsWith(".")) {
- Base.showWarning("Problem with rename",
- "The name cannot start with a period.");
+ Messages.showWarning(Language.text("name.messages.problem_renaming"),
+ Language.text("name.messages.starts_with_dot.description"));
return;
}
int dot = newName.lastIndexOf('.');
String newExtension = newName.substring(dot+1).toLowerCase();
if (!mode.validExtension(newExtension)) {
- Base.showWarning("Problem with rename",
- "\"." + newExtension + "\"" +
- "is not a valid extension.");
+ Messages.showWarning(Language.text("name.messages.problem_renaming"),
+ Language.interpolate("name.messages.invalid_extension.description",
+ newExtension));
return;
}
@@ -470,10 +489,9 @@ protected void nameCode(String newName) {
if (!mode.isDefaultExtension(newExtension)) {
if (renamingCode) { // If creating a new tab, don't show this error
if (current == code[0]) { // If this is the main tab, disallow
- Base.showWarning("Problem with rename",
- "The first tab cannot be a ." + newExtension + " file.\n" +
- "(It may be time for you to graduate to a\n" +
- "\"real\" programming environment, hotshot.)");
+ Messages.showWarning(Language.text("name.messages.problem_renaming"),
+ Language.interpolate("name.messages.main_java_extension.description",
+ newExtension));
return;
}
}
@@ -493,12 +511,13 @@ protected void nameCode(String newName) {
// A regression introduced by Florian's bug report (below) years earlier.
if (!(renamingCode && sanitaryName.equals(current.getPrettyName()))) {
// Make sure no .pde *and* no .java files with the same name already exist
+ // (other than the one we are currently attempting to rename)
// http://processing.org/bugs/bugzilla/543.html
for (SketchCode c : code) {
- if (sanitaryName.equalsIgnoreCase(c.getPrettyName())) {
- Base.showMessage("Nope",
- "A file named \"" + c.getFileName() + "\" already exists at\n" +
- "\"" + folder.getAbsolutePath() + "\"");
+ if (c != current && sanitaryName.equalsIgnoreCase(c.getPrettyName())) {
+ Messages.showMessage(Language.text("name.messages.new_sketch_exists"),
+ Language.interpolate("name.messages.new_sketch_exists.description",
+ c.getFileName(), folder.getAbsolutePath()));
return;
}
}
@@ -512,16 +531,17 @@ protected void nameCode(String newName) {
String folderName = newName.substring(0, newName.indexOf('.'));
File newFolder = new File(folder.getParentFile(), folderName);
if (newFolder.exists()) {
- Base.showWarning("Cannot Rename",
- "Sorry, a sketch (or folder) named " +
- "\"" + newName + "\" already exists.");
+ Messages.showWarning(Language.text("name.messages.new_folder_exists"),
+ Language.interpolate("name.messages.new_folder_exists.description",
+ newName));
return;
}
// renaming the containing sketch folder
boolean success = folder.renameTo(newFolder);
if (!success) {
- Base.showWarning("Error", "Could not rename the sketch folder.");
+ Messages.showWarning(Language.text("name.messages.error"),
+ Language.text("name.messages.no_rename_folder.description"));
return;
}
// let this guy know where he's living (at least for a split second)
@@ -541,9 +561,9 @@ protected void nameCode(String newName) {
// This isn't changing folders, just changes the name
newFile = new File(newFolder, newName);
if (!current.renameTo(newFile, newExtension)) {
- Base.showWarning("Error",
- "Could not rename \"" + current.getFileName() +
- "\" to \"" + newFile.getName() + "\"");
+ Messages.showWarning(Language.text("name.messages.error"),
+ Language.interpolate("name.messages.no_rename_file.description",
+ current.getFileName(), newFile.getName()));
return;
}
@@ -552,8 +572,8 @@ protected void nameCode(String newName) {
for (int i = 1; i < codeCount; i++) {
code[i].setFolder(newFolder);
}
- // Update internal state to reflect the new location
- updateInternal(sanitaryName, newFolder);
+ // Update internal state to reflect the new location
+ updateInternal(sanitaryName, newFolder, renamingCode);
// File newMainFile = new File(newFolder, newName + ".pde");
// String newMainFilePath = newMainFile.getAbsolutePath();
@@ -573,9 +593,9 @@ protected void nameCode(String newName) {
} else { // else if something besides code[0]
if (!current.renameTo(newFile, newExtension)) {
- Base.showWarning("Error",
- "Could not rename \"" + current.getFileName() +
- "\" to \"" + newFile.getName() + "\"");
+ Messages.showWarning(Language.text("name.messages.error"),
+ Language.interpolate("name.messages.no_rename_file.description",
+ current.getFileName(), newFile.getName()));
return;
}
}
@@ -587,9 +607,9 @@ protected void nameCode(String newName) {
throw new IOException("createNewFile() returned false");
}
} catch (IOException e) {
- Base.showWarning("Error",
- "Could not create the file \"" + newFile + "\"\n" +
- "in \"" + folder.getAbsolutePath() + "\"", e);
+ Messages.showWarning(Language.text("name.messages.error"),
+ Language.interpolate("name.messages.no_create_file.description",
+ newFile, folder.getAbsolutePath()), e);
return;
}
SketchCode newCode = new SketchCode(newFile, newExtension);
@@ -604,7 +624,7 @@ protected void nameCode(String newName) {
setCurrentCode(newName);
// update the tabs
- editor.header.rebuild();
+ editor.rebuildHeader();
}
@@ -618,20 +638,18 @@ public void handleDeleteCode() {
// if read-only, give an error
if (isReadOnly()) {
// 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 the sketch in another location,\n" +
- "and try again.");
+ Messages.showMessage(Language.text("delete.messages.is_read_only"),
+ Language.text("delete.messages.is_read_only.description"));
return;
}
// don't allow if untitled
- if (currentIndex == 0 && isUntitled()) {
- Base.showMessage("Cannot Delete",
- "You can't delete a sketch that has not been saved.");
+ if (currentIndex == 0 && isUntitled()) {
+ Messages.showMessage(Language.text("delete.messages.cannot_delete"),
+ Language.text("delete.messages.cannot_delete.description"));
return;
}
-
+
// confirm deletion with user, yes/no
Object[] options = { Language.text("prompt.ok"), Language.text("prompt.cancel") };
String prompt = (currentIndex == 0) ?
@@ -651,39 +669,45 @@ public void handleDeleteCode() {
// to do a save on the handleNew()
// delete the entire sketch
- Base.removeDir(folder);
+ Util.removeDir(folder);
// get the changes into the sketchbook menu
//sketchbook.rebuildMenus();
- // make a new sketch, and i think this will rebuild the sketch menu
+ // make a new sketch and rebuild the sketch menu
//editor.handleNewUnchecked();
//editor.handleClose2();
- editor.base.handleClose(editor, false);
+ editor.getBase().rebuildSketchbookMenus();
+ editor.getBase().handleClose(editor, false);
} else {
// delete the file
if (!current.deleteFile()) {
- Base.showMessage("Couldn't do it",
- "Could not delete \"" +
- current.getFileName() + "\".");
+ Messages.showMessage(Language.text("delete.messages.cannot_delete.file"),
+ Language.text("delete.messages.cannot_delete.file.description")+" \"" +
+ current.getFileName() + "\".");
return;
}
// remove code from the list
removeCode(current);
+ // update the tabs
+ editor.rebuildHeader();
+
// just set current tab to the main tab
setCurrentCode(0);
- // update the tabs
- editor.header.repaint();
}
}
}
- protected void removeCode(SketchCode which) {
+ /**
+ * Remove a SketchCode from the list of files without deleting its file.
+ * @see #handleDeleteCode()
+ */
+ public void removeCode(SketchCode which) {
// remove it from the internal list of files
// resort internal list of files
for (int i = 0; i < codeCount; i++) {
@@ -739,9 +763,9 @@ protected void calcModified() {
break;
}
}
- editor.header.repaint();
+ editor.repaintHeader();
- if (Base.isMacOS()) {
+ if (Platform.isMacOS()) {
// http://developer.apple.com/qa/qa2001/qa1146.html
Object modifiedParam = modified ? Boolean.TRUE : Boolean.FALSE;
// https://developer.apple.com/library/mac/technotes/tn2007/tn2196.html#WINDOW_DOCUMENTMODIFIED
@@ -755,6 +779,16 @@ public boolean isModified() {
}
+ /**
+ * Ensure that all SketchCodes are up-to-date, so that sc.save() works.
+ */
+ public void updateSketchCodes() {
+// if (current.isModified()) {
+ current.setProgram(editor.getText());
+// }
+ }
+
+
/**
* Save all code in the current sketch. This just forces the files to save
* in place, so if it's an untitled (un-saved) sketch, saveAs() should be
@@ -765,24 +799,23 @@ public boolean save() throws IOException {
ensureExistence();
// first get the contents of the editor text area
-// if (current.isModified()) {
- current.setProgram(editor.getText());
-// }
+ updateSketchCodes();
// don't do anything if not actually modified
//if (!modified) return false;
if (isReadOnly()) {
// 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.");
+ Messages.showMessage(Language.text("save_file.messages.is_read_only"),
+ Language.text("save_file.messages.is_read_only.description"));
// if the user cancels, give up on the save()
if (!saveAs()) return false;
}
- for (int i = 0; i < codeCount; i++) {
- if (code[i].isModified()) code[i].save();
+ for (SketchCode sc : code) {
+ if (sc.isModified()) {
+ sc.save();
+ }
}
calcModified();
return true;
@@ -800,12 +833,13 @@ public boolean save() throws IOException {
* Also removes the previously-generated .class and .jar files,
* because they can cause trouble.
*/
- protected boolean saveAs() throws IOException {
+ public boolean saveAs() throws IOException {
String newParentDir = null;
String newName = null;
-
- final String oldName2 = folder.getName();
- // TODO rewrite this to use shared version from PApplet
+ String oldName = folder.getName();
+
+ // TODO rewrite this to use shared version from PApplet (But because that
+ // specifies a callback function, this needs to wait until the refactoring)
final String PROMPT = Language.text("save");
if (Preferences.getBoolean("chooser.files.native")) {
// get new name for folder
@@ -817,8 +851,8 @@ protected boolean saveAs() throws IOException {
// default to the parent folder of where this was
fd.setDirectory(folder.getParent());
}
- String oldName = folder.getName();
- fd.setFile(oldName);
+ String oldFolderName = folder.getName();
+ fd.setFile(oldFolderName);
fd.setVisible(true);
newParentDir = fd.getDirectory();
newName = fd.getFile();
@@ -849,9 +883,9 @@ protected boolean saveAs() throws IOException {
String sanitaryName = Sketch.checkName(newName);
File newFolder = new File(newParentDir, sanitaryName);
if (!sanitaryName.equals(newName) && newFolder.exists()) {
- Base.showMessage("Cannot Save",
- "A sketch with the cleaned name\n" +
- "“" + sanitaryName + "” already exists.");
+ Messages.showMessage(Language.text("save_file.messages.sketch_exists"),
+ Language.interpolate("save_file.messages.sketch_exists.description",
+ sanitaryName));
return false;
}
newName = sanitaryName;
@@ -868,9 +902,9 @@ protected boolean saveAs() throws IOException {
// resaved (with the same name) to another location/folder.
for (int i = 1; i < codeCount; i++) {
if (newName.equalsIgnoreCase(code[i].getPrettyName())) {
- Base.showMessage("Nope",
- "You can't save the sketch as \"" + newName + "\"\n" +
- "because the sketch already has a tab with that name.");
+ Messages.showMessage(Language.text("save_file.messages.tab_exists"),
+ Language.interpolate("save_file.messages.tab_exists.description",
+ newName));
return false;
}
}
@@ -880,7 +914,7 @@ protected boolean saveAs() throws IOException {
// just use "save" here instead, because the user will have received a
// message (from the operating system) about "do you want to replace?"
return save();
- }
+ }
// check to see if the user is trying to save this sketch inside itself
try {
@@ -888,9 +922,8 @@ protected boolean saveAs() throws IOException {
String oldPath = folder.getCanonicalPath() + File.separator;
if (newPath.indexOf(oldPath) == 0) {
- Base.showWarning("How very Borges of you",
- "You cannot save the sketch into a folder\n" +
- "inside itself. This would go on forever.", null);
+ Messages.showWarning(Language.text("save_file.messages.recursive_save"),
+ Language.text("save_file.messages.recursive_save.description"));
return false;
}
} catch (IOException e) { }
@@ -898,7 +931,7 @@ protected boolean saveAs() throws IOException {
// if the new folder already exists, then first remove its contents before
// copying everything over (user will have already been warned).
if (newFolder.exists()) {
- Base.removeDir(newFolder);
+ Util.removeDir(newFolder);
}
// in fact, you can't do this on Windows because the file dialog
// will instead put you inside the folder, but it happens on OS X a lot.
@@ -908,9 +941,7 @@ protected boolean saveAs() throws IOException {
// grab the contents of the current tab before saving
// first get the contents of the editor text area
- if (current.isModified()) {
- current.setProgram(editor.getText());
- }
+ updateSketchCodes();
File[] copyItems = folder.listFiles(new FileFilter() {
public boolean accept(File file) {
@@ -920,9 +951,12 @@ public boolean accept(File file) {
return false;
}
// list of files/folders to be ignored during "save as"
- for (String ignorable : mode.getIgnorable()) {
- if (name.equals(ignorable)) {
- return false;
+ String[] ignorable = mode.getIgnorable();
+ if (ignorable != null) {
+ for (String ignore : ignorable) {
+ if (name.equals(ignore)) {
+ return false;
+ }
}
}
// ignore the extensions for code, since that'll be copied below
@@ -939,22 +973,10 @@ public boolean accept(File file) {
return true;
}
});
-
-
- final File newFolder2 = newFolder;
- final File[] copyItems2 = copyItems;
- final String newName2 = newName;
-
- // Create a new event dispatch thread- to display ProgressBar
- // while Saving As
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- new ProgressFrame(copyItems2, newFolder2, oldName2, newName2, editor);
- }
- });
-
-
- // save the other tabs to their new location
+
+ startSaveAsThread(oldName, newName, newFolder, copyItems);
+
+ // save the other tabs to their new location (main tab saved below)
for (int i = 1; i < codeCount; i++) {
File newFile = new File(newFolder, code[i].getFileName());
code[i].saveAs(newFile);
@@ -963,41 +985,225 @@ public void run() {
// While the old path to the main .pde is still set, remove the entry from
// the Recent menu so that it's not sticking around after the rename.
// If untitled, it won't be in the menu, so there's no point.
- if (!isUntitled()) {
- editor.removeRecent();
- }
+// if (!isUntitled()) {
+// Recent.remove(editor);
+// }
+ // Folks didn't like this behavior, so shutting it off
+ // https://github.com/processing/processing/issues/5902
// save the main tab with its new name
File newFile = new File(newFolder, newName + "." + mode.getDefaultExtension());
code[0].saveAs(newFile);
- updateInternal(newName, newFolder);
+ updateInternal(newName, newFolder, false);
// Make sure that it's not an untitled sketch
setUntitled(false);
// Add this sketch back using the new name
- editor.addRecent();
+ Recent.append(editor);
// let Editor know that the save was successful
return true;
}
+ AtomicBoolean saving = new AtomicBoolean();
+
+ public boolean isSaving() {
+ return saving.get();
+ }
+
+
+ /**
+ * Kick off a background thread to copy everything *but* the .pde files.
+ * Due to the poor way (dating back to the late 90s with DBN) that our
+ * save() and saveAs() methods have been implemented to return booleans,
+ * there isn't a good way to return a value to the calling thread without
+ * a good bit of refactoring (that should be done at some point).
+ * As a result, this method will return 'true' before the full "Save As"
+ * has completed, which will cause problems in weird cases.
+ *
+ * For instance, the threading will cause problems while saving an untitled
+ * sketch that has an enormous data folder while quitting. The save thread to
+ * move those data folder files won't have finished before this returns true,
+ * and the PDE may quit before the SwingWorker completes its job.
+ *
+ * 3843
+ */
+ void startSaveAsThread(final String oldName, final String newName,
+ final File newFolder, final File[] copyItems) {
+ saving.set(true);
+ EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ final JFrame frame =
+ new JFrame("Saving \u201C" + newName + "\u201C...");
+ frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
+
+ Box box = Box.createVerticalBox();
+ box.setBorder(new EmptyBorder(16, 16, 16, 16));
+
+ if (Platform.isMacOS()) {
+ frame.setBackground(Color.WHITE);
+ }
+
+ JLabel label =
+ new JLabel("Saving additional files from the sketch folder...");
+ box.add(label);
+ box.add(Box.createVerticalStrut(8));
+
+ final JProgressBar progressBar = new JProgressBar(0, 100);
+ // no luck, stuck with ugly on OS X
+ //progressBar.putClientProperty("JComponent.sizeVariant", "regular");
+ progressBar.setValue(0);
+ progressBar.setStringPainted(true);
+ box.add(progressBar);
+
+ frame.getContentPane().add(box);
+ frame.pack();
+ frame.setLocationRelativeTo(editor);
+ Toolkit.setIcon(frame);
+ frame.setVisible(true);
+
+ new SwingWorker() {
+
+ @Override
+ protected Void doInBackground() throws Exception {
+ addPropertyChangeListener(new PropertyChangeListener() {
+ public void propertyChange(PropertyChangeEvent evt) {
+ if ("progress".equals(evt.getPropertyName())) {
+ progressBar.setValue((Integer) evt.getNewValue());
+ }
+ }
+ });
+
+ long totalSize = 0;
+ for (File copyable : copyItems) {
+ totalSize += Util.calcSize(copyable);
+ }
+
+ long progress = 0;
+ setProgress(0);
+ for (File copyable : copyItems) {
+ if (copyable.isDirectory()) {
+ copyDir(copyable,
+ new File(newFolder, copyable.getName()),
+ progress, totalSize);
+ progress += Util.calcSize(copyable);
+ } else {
+ copyFile(copyable,
+ new File(newFolder, copyable.getName()),
+ progress, totalSize);
+ if (Util.calcSize(copyable) < 512 * 1024) {
+ // If the file length > 0.5MB, the copyFile() function has
+ // been redesigned to change progress every 0.5MB so that
+ // the progress bar doesn't stagnate during that time
+ progress += Util.calcSize(copyable);
+ setProgress((int) (progress * 100L / totalSize));
+ }
+ }
+ }
+ saving.set(false);
+ return null;
+ }
+
+
+ /**
+ * Overloaded copyFile that is called whenever a Save As is being done,
+ * so that the ProgressBar is updated for very large files as well.
+ */
+ void copyFile(File sourceFile, File targetFile,
+ long progress, long totalSize) throws IOException {
+ BufferedInputStream from =
+ new BufferedInputStream(new FileInputStream(sourceFile));
+ BufferedOutputStream to =
+ new BufferedOutputStream(new FileOutputStream(targetFile));
+ byte[] buffer = new byte[16 * 1024];
+ int bytesRead;
+ int progRead = 0;
+ while ((bytesRead = from.read(buffer)) != -1) {
+ to.write(buffer, 0, bytesRead);
+ progRead += bytesRead;
+ if (progRead >= 512 * 1024) { // to update progress bar every 0.5MB
+ progress += progRead;
+ //progressBar.setValue((int) Math.min(Math.ceil(progress * 100.0 / totalSize), 100));
+ setProgress((int) (100L * progress / totalSize));
+ progRead = 0;
+ }
+ }
+ // Final update to progress bar
+ setProgress((int) (100L * progress / totalSize));
+
+ from.close();
+ from = null;
+ to.flush();
+ to.close();
+ to = null;
+
+ targetFile.setLastModified(sourceFile.lastModified());
+ targetFile.setExecutable(sourceFile.canExecute());
+ }
+
+
+ long copyDir(File sourceDir, File targetDir,
+ long progress, long totalSize) throws IOException {
+ // Overloaded copyDir so that the Save As progress bar gets updated when the
+ // files are in folders as well (like in the data folder)
+ if (sourceDir.equals(targetDir)) {
+ final String urDum = "source and target directories are identical";
+ throw new IllegalArgumentException(urDum);
+ }
+ targetDir.mkdirs();
+ String files[] = sourceDir.list();
+ for (String filename : files) {
+ // Ignore dot files (.DS_Store), dot folders (.svn) while copying
+ if (filename.charAt(0) == '.') {
+ continue;
+ }
+
+ File source = new File(sourceDir, filename);
+ File target = new File(targetDir, filename);
+ if (source.isDirectory()) {
+ progress = copyDir(source, target, progress, totalSize);
+ //progressBar.setValue((int) Math.min(Math.ceil(progress * 100.0 / totalSize), 100));
+ setProgress((int) (100L * progress / totalSize));
+ target.setLastModified(source.lastModified());
+ } else {
+ copyFile(source, target, progress, totalSize);
+ progress += source.length();
+ //progressBar.setValue((int) Math.min(Math.ceil(progress * 100.0 / totalSize), 100));
+ setProgress((int) (100L * progress / totalSize));
+ }
+ }
+ return progress;
+ }
+
+
+ @Override
+ public void done() {
+ frame.dispose();
+ editor.statusNotice(Language.text("editor.status.saving.done"));
+ }
+ }.execute();
+ }
+ });
+ }
+
/**
* Update internal state for new sketch name or folder location.
*/
- protected void updateInternal(String sketchName, File sketchFolder) {
+ protected void updateInternal(String sketchName, File sketchFolder,
+ boolean renaming) {
// reset all the state information for the sketch object
-
-// String oldPath = getMainFilePath();
+ String oldPath = getMainFilePath();
primaryFile = code[0].getFile();
// String newPath = getMainFilePath();
// editor.base.renameRecent(oldPath, newPath);
name = sketchName;
folder = sketchFolder;
+ disappearedWarning = false;
codeFolder = new File(folder, "code");
dataFolder = new File(folder, "data");
@@ -1009,7 +1215,12 @@ protected void updateInternal(String sketchName, File sketchFolder) {
calcModified();
// System.out.println("modified is now " + modified);
editor.updateTitle();
- editor.base.rebuildSketchbookMenus();
+ editor.getBase().rebuildSketchbookMenus();
+ if (renaming) {
+ // only update the Recent menu if it's a rename, not a Save As
+ // https://github.com/processing/processing/issues/5902
+ Recent.rename(editor, oldPath);
+ }
// editor.header.rebuild();
}
@@ -1025,10 +1236,8 @@ public void handleAddFile() {
// if read-only, give an error
if (isReadOnly()) {
// 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 the sketch in another location,\n" +
- "and try again.");
+ Messages.showMessage(Language.text("add_file.messages.is_read_only"),
+ Language.text("add_file.messages.is_read_only.description"));
return;
}
@@ -1075,18 +1284,21 @@ public boolean addFile(File sourceFile) {
String codeExtension = null;
boolean replacement = false;
+ boolean isCode = false;
+
// if the file appears to be code related, drop it
// into the code folder, instead of the data folder
if (filename.toLowerCase().endsWith(".class") ||
filename.toLowerCase().endsWith(".jar") ||
filename.toLowerCase().endsWith(".dll") ||
+ filename.toLowerCase().endsWith(".dylib") ||
filename.toLowerCase().endsWith(".jnilib") ||
filename.toLowerCase().endsWith(".so")) {
//if (!codeFolder.exists()) codeFolder.mkdirs();
prepareCodeFolder();
destFile = new File(codeFolder, filename);
-
+ isCode = true;
} else {
for (String extension : mode.getExtensions()) {
String lower = filename.toLowerCase();
@@ -1104,7 +1316,8 @@ public boolean addFile(File sourceFile) {
// check whether this file already exists
if (destFile.exists()) {
Object[] options = { Language.text("prompt.ok"), Language.text("prompt.cancel") };
- String prompt = "Replace the existing version of " + filename + "?";
+ String prompt = Language.interpolate("add_file.messages.confirm_replace",
+ filename);
int result = JOptionPane.showOptionDialog(editor,
prompt,
"Replace",
@@ -1126,35 +1339,38 @@ public boolean addFile(File sourceFile) {
if (replacement) {
boolean muchSuccess = destFile.delete();
if (!muchSuccess) {
- Base.showWarning("Error adding file",
- "Could not delete the existing '" +
- filename + "' file.", null);
+ Messages.showWarning(Language.text("add_file.messages.error_adding"),
+ Language.interpolate("add_file.messages.cannot_delete.description", filename));
return false;
}
}
// make sure they aren't the same file
if ((codeExtension == null) && sourceFile.equals(destFile)) {
- Base.showWarning("You can't fool me",
- "This file has already been copied to the\n" +
- "location from which where you're trying to add it.\n" +
- "I ain't not doin nuthin'.", null);
+ Messages.showWarning(Language.text("add_file.messages.same_file"),
+ Language.text("add_file.messages.same_file.description"));
return false;
}
- // in case the user is "adding" the code in an attempt
- // to update the sketch's tabs
- if (!sourceFile.equals(destFile)) {
- final File sourceFile2 = sourceFile;
- final File destFile2 = destFile;
- // Create a new event dispatch thread- to display ProgressBar
- // while Saving As
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- new ProgressFrame(sourceFile2, destFile2, editor);
+ // Handles "Add File" when a .pde is used. For beta 1, this no longer runs
+ // on a separate thread because it's totally unnecessary (a .pde file is
+ // not going to be so large that it's ever required) and otherwise we have
+ // to introduce a threading block here.
+ // https://github.com/processing/processing/issues/3383
+ if (!sourceFile.equals(destFile)) {
+ try {
+ Util.copyFile(sourceFile, destFile);
+
+ } catch (IOException e) {
+ Messages.showWarning(Language.text("add_file.messages.error_adding"),
+ Language.interpolate("add_file.messages.cannot_add.description", filename), e);
+ return false;
}
- });
- }
+ }
+
+ if (isCode) {
+ editor.codeFolderChanged();
+ }
if (codeExtension != null) {
SketchCode newCode = new SketchCode(destFile, codeExtension);
@@ -1167,7 +1383,7 @@ public void run() {
sortCode();
}
setCurrentCode(filename);
- editor.header.repaint();
+ editor.repaintHeader();
if (isUntitled()) { // TODO probably not necessary? problematic?
// Mark the new code as modified so that the sketch is saved
current.setModified(true);
@@ -1199,7 +1415,8 @@ public void setCurrentCode(int which) {
// System.out.println(current.visited);
// }
// if current is null, then this is the first setCurrent(0)
- if ((currentIndex == which) && (current != null)) {
+ if (which < 0 || which >= codeCount ||
+ ((currentIndex == which) && (current == code[currentIndex]))) {
return;
}
@@ -1216,8 +1433,7 @@ public void setCurrentCode(int which) {
current.visited = System.currentTimeMillis();
editor.setCode(current);
-// editor.header.rebuild();
- editor.header.repaint();
+ editor.repaintHeader();
}
@@ -1225,7 +1441,7 @@ public void setCurrentCode(int which) {
* Internal helper function to set the current tab based on a name.
* @param findName the file name (not pretty name) to be shown
*/
- protected void setCurrentCode(String findName) {
+ public void setCurrentCode(String findName) {
for (int i = 0; i < codeCount; i++) {
if (findName.equals(code[i].getFileName()) ||
findName.equals(code[i].getPrettyName())) {
@@ -1241,17 +1457,11 @@ protected void setCurrentCode(String findName) {
*/
public File makeTempFolder() {
try {
- File buildFolder = Base.createTempFolder(name, "temp", null);
-// if (buildFolder.mkdirs()) {
- return buildFolder;
-
-// } else {
-// Base.showWarning("Build folder bad",
-// "Could not create a place to build the sketch.", null);
-// }
+ return Util.createTempFolder(name, "temp", null);
+
} catch (IOException e) {
- Base.showWarning("Build folder bad",
- "Could not find a place to build the sketch.", e);
+ Messages.showWarning(Language.text("temp_dir.messages.bad_build_folder"),
+ Language.text("temp_dir.messages.bad_build_folder.description"), e);
}
return null;
}
@@ -1299,33 +1509,34 @@ public void prepareBuild(File targetFolder) throws SketchException {
/**
- * Make sure the sketch hasn't been moved or deleted by some
- * nefarious user. If they did, try to re-create it and save.
- * Only checks to see if the main folder is still around,
- * but not its contents.
+ * Make sure the sketch hasn't been moved or deleted by a nefarious user.
+ * If they did, try to re-create it and save. Only checks whether the
+ * main folder is still around, but not its contents.
*/
public void ensureExistence() {
if (!folder.exists()) {
- // Disaster recovery, try to salvage what's there already.
- Base.showWarning("Sketch Disappeared",
- "The sketch folder has disappeared.\n " +
- "Will attempt to re-save in the same location,\n" +
- "but anything besides the code will be lost.", null);
- try {
- folder.mkdirs();
- modified = true;
+ // Avoid an infinite loop if we've already warned about this
+ // https://github.com/processing/processing/issues/4805
+ if (!disappearedWarning) {
+ disappearedWarning = true;
+
+ // Disaster recovery, try to salvage what's there already.
+ Messages.showWarning(Language.text("ensure_exist.messages.missing_sketch"),
+ Language.text("ensure_exist.messages.missing_sketch.description"));
+ try {
+ folder.mkdirs();
+ modified = true;
+
+ for (int i = 0; i < codeCount; i++) {
+ code[i].save(); // this will force a save
+ }
+ calcModified();
- for (int i = 0; i < codeCount; i++) {
- code[i].save(); // this will force a save
+ } catch (Exception e) {
+ // disappearedWarning prevents infinite loop in this scenario
+ Messages.showWarning(Language.text("ensure_exist.messages.unrecoverable"),
+ Language.text("ensure_exist.messages.unrecoverable.description"), e);
}
- 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);
}
}
}
@@ -1338,25 +1549,27 @@ public void ensureExistence() {
*/
public boolean isReadOnly() {
String apath = folder.getAbsolutePath();
- Mode mode = editor.getMode();
- if (apath.startsWith(mode.getExamplesFolder().getAbsolutePath()) ||
- apath.startsWith(mode.getLibrariesFolder().getAbsolutePath())) {
- return true;
+ List modes = editor.getBase().getModeList();
+ // Make sure it's not read-only for another Mode besides this one
+ // https://github.com/processing/processing/issues/773
+ for (Mode mode : modes) {
+ if (apath.startsWith(mode.getExamplesFolder().getAbsolutePath()) ||
+ apath.startsWith(mode.getLibrariesFolder().getAbsolutePath())) {
+ return true;
+ }
+ }
- // canWrite() doesn't work on directories
- //} else if (!folder.canWrite()) {
- } else {
- // check to see if each modified code file can be written to
- for (int i = 0; i < codeCount; i++) {
- if (code[i].isModified() &&
- code[i].fileReadOnly() &&
- code[i].fileExists()) {
- //System.err.println("found a read-only file " + code[i].file);
- return true;
- }
+ // check to see if each modified code file can be written to
+ // canWrite() doesn't work on directories
+ for (int i = 0; i < codeCount; i++) {
+ if (code[i].isModified() &&
+ code[i].fileReadOnly() &&
+ code[i].fileExists()) {
+ //System.err.println("found a read-only file " + code[i].file);
+ return true;
}
- //return true;
}
+
return false;
}
@@ -1524,9 +1737,7 @@ static public String checkName(String origName) {
if (!newName.equals(origName)) {
String msg =
- "The sketch name had to be modified. Sketch names can only consist\n" +
- "of ASCII characters and numbers (but cannot start with a number).\n" +
- "They should also be less than 64 characters long.";
+ Language.text("check_name.messages.is_name_modified");
System.out.println(msg);
}
return newName;
@@ -1570,24 +1781,24 @@ static final boolean asciiLetter(char c) {
*/
static public String sanitizeName(String origName) {
char orig[] = origName.toCharArray();
- StringBuffer buffer = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
// Can't lead with a digit (or anything besides a letter), so prefix with
// "sketch_". In 1.x this prefixed with an underscore, but those get shaved
// off later, since you can't start a sketch name with underscore anymore.
if (!asciiLetter(orig[0])) {
- buffer.append("sketch_");
+ sb.append("sketch_");
}
// for (int i = 0; i < orig.length; i++) {
for (char c : orig) {
if (asciiLetter(c) || (c >= '0' && c <= '9')) {
- buffer.append(c);
+ sb.append(c);
} else {
// Tempting to only add if prev char is not underscore, but that
// might be more confusing if lots of chars are converted and the
// result is a very short string thats nothing like the original.
- buffer.append('_');
+ sb.append('_');
}
}
// Let's not be ridiculous about the length of filenames.
@@ -1596,22 +1807,22 @@ static public String sanitizeName(String origName) {
// Limiting to that for sketches would mean setting the
// upper-bound on the character limit here to 25 characters
// (to handle the base name + ".class")
- if (buffer.length() > 63) {
- buffer.setLength(63);
+ if (sb.length() > 63) {
+ sb.setLength(63);
}
// Remove underscores from the beginning, these seem to be a reserved
// thing on Android, plus it sometimes causes trouble elsewhere.
int underscore = 0;
- while (underscore < buffer.length() && buffer.charAt(underscore) == '_') {
+ while (underscore < sb.length() && sb.charAt(underscore) == '_') {
underscore++;
}
- if (underscore == buffer.length()) {
+ if (underscore == sb.length()) {
return "bad_sketch_name_please_fix";
} else if (underscore != 0) {
- return buffer.substring(underscore);
+ return sb.substring(underscore);
}
- return buffer.toString();
+ return sb.toString();
}
diff --git a/app/src/processing/app/SketchCode.java b/app/src/processing/app/SketchCode.java
index 4b1a458147..59ed06652e 100644
--- a/app/src/processing/app/SketchCode.java
+++ b/app/src/processing/app/SketchCode.java
@@ -26,6 +26,7 @@
import java.io.*;
+import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.undo.*;
@@ -55,6 +56,9 @@ public class SketchCode {
/** Last time this tab was visited */
long visited;
+ /** The last time this tab was saved to disk */
+ private long lastModified;
+
/**
* Undo Manager for this tab, each tab keeps track of their own
* Editor.undo will be set to this object when this code is the tab
@@ -133,7 +137,7 @@ protected boolean renameTo(File what, String ext) {
public void copyTo(File dest) throws IOException {
- Base.saveFile(program, dest);
+ Util.saveFile(program, dest);
}
@@ -176,7 +180,7 @@ public String getSavedProgram() {
public int getLineCount() {
- return Base.countLines(program);
+ return Util.countLines(program);
}
@@ -220,6 +224,11 @@ public Document getDocument() {
}
+ public String getDocumentText() throws BadLocationException {
+ return document.getText(0, document.getLength());
+ }
+
+
public void setDocument(Document d) {
document = d;
}
@@ -272,7 +281,13 @@ public long lastVisited() {
* Load this piece of code from a file.
*/
public void load() throws IOException {
- program = Base.loadFile(file);
+ program = Util.loadFile(file);
+
+ if (program == null) {
+ System.err.println("There was a problem loading " + file);
+ System.err.println("This may happen because you don't have permissions to read the file, or the file has gone missing.");
+ throw new IOException("Cannot read or access " + file);
+ }
// Remove NUL characters because they'll cause problems,
// and their presence is very difficult to debug.
@@ -283,7 +298,7 @@ public void load() throws IOException {
savedProgram = program;
// This used to be the "Fix Encoding and Reload" warning, but since that
- // tool has been removed, it just rambles about text editors and encodings.
+ // tool has been removed, let's ramble about text editors and encodings.
if (program.indexOf('\uFFFD') != -1) {
System.err.println(file.getName() + " contains unrecognized characters.");
System.err.println("You should re-open " + file.getName() +
@@ -293,6 +308,7 @@ public void load() throws IOException {
System.err.println();
}
+ setLastModified();
setModified(false);
}
@@ -305,8 +321,9 @@ public void save() throws IOException {
// TODO re-enable history
//history.record(s, SketchHistory.SAVE);
- Base.saveFile(program, file);
+ Util.saveFile(program, file);
savedProgram = program;
+ lastModified = file.lastModified();
setModified(false);
}
@@ -315,10 +332,11 @@ public void save() throws IOException {
* Save this file to another location, used by Sketch.saveAs()
*/
public void saveAs(File newFile) throws IOException {
- Base.saveFile(program, newFile);
+ Util.saveFile(program, newFile);
savedProgram = program;
file = newFile;
makePrettyName();
+ setLastModified();
setModified(false);
}
@@ -330,4 +348,22 @@ public void saveAs(File newFile) throws IOException {
public void setFolder(File sketchFolder) {
file = new File(sketchFolder, file.getName());
}
+
+
+ /**
+ * Set the last known modification time, so that we're not re-firing
+ * "hey, this is modified!" events incessantly.
+ */
+ public void setLastModified() {
+ lastModified = file.lastModified();
+ }
+
+
+ /**
+ * Used to determine whether this file was modified externally
+ * @return The time the file was last modified
+ */
+ public long getLastModified() {
+ return lastModified;
+ }
}
diff --git a/app/src/processing/app/SketchException.java b/app/src/processing/app/SketchException.java
index e2d6eeef35..4a32d2e79d 100644
--- a/app/src/processing/app/SketchException.java
+++ b/app/src/processing/app/SketchException.java
@@ -28,33 +28,35 @@
* An exception with a line number attached that occurs
* during either pre-processing, compile, or run time.
*/
-public class SketchException extends Exception /*RuntimeException*/ {
+public class SketchException extends Exception {
protected String message;
protected int codeIndex;
protected int codeLine;
protected int codeColumn;
protected boolean showStackTrace;
-
+
public SketchException(String message) {
this(message, true);
}
+
public SketchException(String message, boolean showStackTrace) {
this(message, -1, -1, -1, showStackTrace);
}
+
public SketchException(String message, int file, int line) {
this(message, file, line, -1, true);
}
-
+
public SketchException(String message, int file, int line, int column) {
this(message, file, line, column, true);
}
-
-
- public SketchException(String message, int file, int line, int column,
+
+
+ public SketchException(String message, int file, int line, int column,
boolean showStackTrace) {
this.message = message;
this.codeIndex = file;
@@ -62,71 +64,76 @@ public SketchException(String message, int file, int line, int column,
this.codeColumn = column;
this.showStackTrace = showStackTrace;
}
-
-
- /**
- * Override getMessage() in Throwable, so that I can set
+
+
+ /**
+ * Override getMessage() in Throwable, so that I can set
* the message text outside the constructor.
*/
public String getMessage() {
return message;
}
-
-
+
+
public void setMessage(String message) {
this.message = message;
}
-
-
+
+
public int getCodeIndex() {
return codeIndex;
}
-
-
+
+
public void setCodeIndex(int index) {
codeIndex = index;
}
-
-
+
+
public boolean hasCodeIndex() {
return codeIndex != -1;
}
-
-
+
+
public int getCodeLine() {
return codeLine;
}
-
-
+
+
public void setCodeLine(int line) {
this.codeLine = line;
}
-
-
+
+
public boolean hasCodeLine() {
return codeLine != -1;
}
-
-
+
+
public void setCodeColumn(int column) {
this.codeColumn = column;
}
-
-
+
+
public int getCodeColumn() {
return codeColumn;
}
-
+
public void showStackTrace() {
showStackTrace = true;
}
-
-
+
+
public void hideStackTrace() {
showStackTrace = false;
}
-
+
+
+ public boolean isStackTraceEnabled() {
+ return showStackTrace;
+ }
+
/**
* Nix the java.lang crap out of an exception message
diff --git a/app/src/processing/app/SketchReference.java b/app/src/processing/app/SketchReference.java
index 7e55f23219..f87fc23f71 100644
--- a/app/src/processing/app/SketchReference.java
+++ b/app/src/processing/app/SketchReference.java
@@ -6,19 +6,19 @@
public class SketchReference {
String name;
File pde;
-
-
+
+
public SketchReference(String name, File pde) {
this.name = name;
this.pde = pde;
}
-
-
+
+
public String getPath() {
return pde.getAbsolutePath();
}
-
-
+
+
public String toString() {
return name;
}
diff --git a/app/src/processing/app/Toolkit.java b/app/src/processing/app/Toolkit.java
deleted file mode 100644
index c9407ad434..0000000000
--- a/app/src/processing/app/Toolkit.java
+++ /dev/null
@@ -1,481 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2012 The Processing Foundation
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License version 2
- as published by the Free Software Foundation.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU 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,
- Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-
-package processing.app;
-
-import java.awt.Dimension;
-import java.awt.Font;
-import java.awt.FontFormatException;
-import java.awt.Frame;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.GraphicsDevice;
-import java.awt.GraphicsEnvironment;
-import java.awt.Image;
-import java.awt.Window;
-import java.awt.datatransfer.Clipboard;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.KeyEvent;
-import java.awt.font.FontRenderContext;
-import java.awt.font.TextLayout;
-import java.awt.geom.AffineTransform;
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-
-import javax.swing.ImageIcon;
-import javax.swing.JCheckBoxMenuItem;
-import javax.swing.JComponent;
-import javax.swing.JMenu;
-import javax.swing.JMenuItem;
-import javax.swing.JRootPane;
-import javax.swing.KeyStroke;
-
-
-/**
- * Utility functions for base that require a java.awt.Toolkit object. These
- * are broken out from Base as we start moving toward the possibility of the
- * code running in headless mode.
- * @author fry
- */
-public class Toolkit {
- static final java.awt.Toolkit awtToolkit =
- java.awt.Toolkit.getDefaultToolkit();
-
- /** Command on Mac OS X, Ctrl on Windows and Linux */
- static final int SHORTCUT_KEY_MASK =
- awtToolkit.getMenuShortcutKeyMask();
- /** Command-W on Mac OS X, Ctrl-W on Windows and Linux */
- public static final KeyStroke WINDOW_CLOSE_KEYSTROKE =
- KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK);
- /** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */
- static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK |
- awtToolkit.getMenuShortcutKeyMask();
-
-
- /**
- * A software engineer, somewhere, needs to have his abstraction
- * taken away. In some countries they jail or beat people for crafting
- * the sort of API that would require a five line helper function
- * just to set the shortcut key for a menu item.
- */
- static public JMenuItem newJMenuItem(String title, int what) {
- JMenuItem menuItem = new JMenuItem(title);
- int modifiers = awtToolkit.getMenuShortcutKeyMask();
- menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers));
- return menuItem;
- }
-
-
- /**
- * Like newJMenuItem() but adds shift as a modifier for the shortcut.
- */
- static public JMenuItem newJMenuItemShift(String title, int what) {
- JMenuItem menuItem = new JMenuItem(title);
- int modifiers = awtToolkit.getMenuShortcutKeyMask();
- modifiers |= ActionEvent.SHIFT_MASK;
- menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers));
- return menuItem;
- }
-
-
- /**
- * Same as newJMenuItem(), but adds the ALT (on Linux and Windows)
- * or OPTION (on Mac OS X) key as a modifier.
- */
- static public JMenuItem newJMenuItemAlt(String title, int what) {
- JMenuItem menuItem = new JMenuItem(title);
- menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK));
- return menuItem;
- }
-
-
- static public JCheckBoxMenuItem newJCheckBoxMenuItem(String title, int what) {
- JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(title);
- int modifiers = awtToolkit.getMenuShortcutKeyMask();
- menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers));
- return menuItem;
- }
-
-
- static public void addDisabledItem(JMenu menu, String title) {
- JMenuItem item = new JMenuItem(title);
- item.setEnabled(false);
- menu.add(item);
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- static public Dimension getScreenSize() {
- return awtToolkit.getScreenSize();
- }
-
-
- /**
- * Return an Image object from inside the Processing lib folder.
- * Moved here so that Base can stay headless.
- */
- static public Image getLibImage(String filename) {
- File file = Base.getContentFile("lib/" + filename);
- if (!file.exists()) {
- return null;
- }
- return new ImageIcon(file.getAbsolutePath()).getImage();
- }
-
-
- static ArrayList iconImages;
-
-
- // Deprecated version of the function, but can't get rid of it without
- // breaking tools and modes (they'd only require a recompile, but they would
- // no longer be backwards compatible.
- static public void setIcon(Frame frame) {
- setIcon((Window) frame);
- }
-
-
- /**
- * Give this Frame the Processing icon set. Ignored on OS X, because they
- * thought different and made this function set the minified image of the
- * window, not the window icon for the dock or cmd-tab.
- */
- static public void setIcon(Window window) {
- if (!Base.isMacOS()) {
- if (iconImages == null) {
- iconImages = new ArrayList();
- final int[] sizes = { 16, 32, 48, 64, 128, 256, 512 };
- for (int sz : sizes) {
- iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png"));
- }
- }
- window.setIconImages(iconImages);
- }
- }
-
-
- // someone needs to be slapped
- //static KeyStroke closeWindowKeyStroke;
-
- /**
- * Return true if the key event was a Ctrl-W or an ESC,
- * both indicators to close the window.
- * Use as part of a keyPressed() event handler for frames.
- */
- /*
- static public boolean isCloseWindowEvent(KeyEvent e) {
- if (closeWindowKeyStroke == null) {
- int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
- closeWindowKeyStroke = KeyStroke.getKeyStroke('W', modifiers);
- }
- return ((e.getKeyCode() == KeyEvent.VK_ESCAPE) ||
- KeyStroke.getKeyStrokeForEvent(e).equals(closeWindowKeyStroke));
- }
- */
-
- /**
- * Registers key events for a Ctrl-W and ESC with an ActionListener
- * that will take care of disposing the window.
- */
- static public void registerWindowCloseKeys(JRootPane root,
- ActionListener disposer) {
- KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
- root.registerKeyboardAction(disposer, stroke,
- JComponent.WHEN_IN_FOCUSED_WINDOW);
-
- int modifiers = awtToolkit.getMenuShortcutKeyMask();
- stroke = KeyStroke.getKeyStroke('W', modifiers);
- root.registerKeyboardAction(disposer, stroke,
- JComponent.WHEN_IN_FOCUSED_WINDOW);
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- static public void beep() {
- awtToolkit.beep();
- }
-
-
- static public Clipboard getSystemClipboard() {
- return awtToolkit.getSystemClipboard();
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
- static Boolean highResProp;
-
-
- static public boolean highResDisplay() {
- if (highResProp == null) {
- highResProp = checkRetina();
- }
- return highResProp;
- }
-
-
- static private boolean checkRetina() {
- if (Base.isMacOS()) {
- // This should probably be reset each time there's a display change.
- // A 5-minute search didn't turn up any such event in the Java API.
- // Also, should we use the Toolkit associated with the editor window?
-// String javaVendor = System.getProperty("java.vendor");
-// if (javaVendor.contains("Apple")) {
- if (System.getProperty("java.vendor").contains("Apple")) {
- Float prop = (Float)
- awtToolkit.getDesktopProperty("apple.awt.contentScaleFactor");
- if (prop != null) {
- return prop == 2;
- }
-// } else if (javaVendor.contains("Oracle")) {
-// String version = System.getProperty("java.version"); // 1.7.0_40
-// String[] m = PApplet.match(version, "1.(\\d).*_(\\d+)");
-//
-// // Make sure this is Oracle Java 7u40 or later
-// if (m != null &&
-// PApplet.parseInt(m[1]) >= 7 &&
-// PApplet.parseInt(m[1]) >= 40) {
- } else if (Base.isUsableOracleJava()) {
- GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
- GraphicsDevice device = env.getDefaultScreenDevice();
-
- try {
- Field field = device.getClass().getDeclaredField("scale");
- if (field != null) {
- field.setAccessible(true);
- Object scale = field.get(device);
-
- if (scale instanceof Integer && ((Integer)scale).intValue() == 2) {
- return true;
- }
- }
- } catch (Exception ignore) { }
- }
- }
- return false;
- }
-
-
- // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-
-
-// static Font monoFont;
-// static Font plainFont;
-// static Font boldFont;
-//
-//
-// static public Font getMonoFont(int size) {
-// if (monoFont == null) {
-// try {
-// monoFont = createFont("DroidSansMono.ttf", size);
-// } catch (Exception e) {
-// monoFont = new Font("Monospaced", Font.PLAIN, size);
-// }
-// }
-// return monoFont;
-// }
-//
-//
-// static public Font getPlainFont(int size) {
-// if (plainFont == null) {
-// try {
-// plainFont = createFont("DroidSans.ttf", size);
-// } catch (Exception e) {
-// plainFont = new Font("SansSerif", Font.PLAIN, size);
-// }
-// }
-// return plainFont;
-// }
-//
-//
-// static public Font getBoldFont(int size) {
-// if (boldFont == null) {
-// try {
-// boldFont = createFont("DroidSans-Bold.ttf", size);
-// } catch (Exception e) {
-// boldFont = new Font("SansSerif", Font.BOLD, size);
-// }
-// }
-// return boldFont;
-// }
-
-
- // Gets the plain (not bold, not italic) version of each
- static private List getMonoFontList() {
- GraphicsEnvironment ge =
- GraphicsEnvironment.getLocalGraphicsEnvironment();
- Font[] fonts = ge.getAllFonts();
- ArrayList outgoing = new ArrayList();
- // Using AffineTransform.getScaleInstance(100, 100) doesn't change sizes
- FontRenderContext frc =
- new FontRenderContext(new AffineTransform(),
- Preferences.getBoolean("editor.antialias"),
- true); // use fractional metrics
- for (Font font : fonts) {
- if (font.getStyle() == Font.PLAIN &&
- font.canDisplay('i') && font.canDisplay('M') &&
- font.canDisplay(' ') && font.canDisplay('.')) {
-
- // The old method just returns 1 or 0, and using deriveFont(size)
- // is overkill. It also causes deprecation warnings
-// @SuppressWarnings("deprecation")
-// FontMetrics fm = awtToolkit.getFontMetrics(font);
- //FontMetrics fm = awtToolkit.getFontMetrics(font.deriveFont(24));
-// System.out.println(fm.charWidth('i') + " " + fm.charWidth('M'));
-// if (fm.charWidth('i') == fm.charWidth('M') &&
-// fm.charWidth('M') == fm.charWidth(' ') &&
-// fm.charWidth(' ') == fm.charWidth('.')) {
- double w = font.getStringBounds(" ", frc).getWidth();
- if (w == font.getStringBounds("i", frc).getWidth() &&
- w == font.getStringBounds("M", frc).getWidth() &&
- w == font.getStringBounds(".", frc).getWidth()) {
-
-// //PApplet.printArray(font.getAvailableAttributes());
-// Map attr = font.getAttributes();
-// System.out.println(font.getFamily() + " > " + font.getName());
-// System.out.println(font.getAttributes());
-// System.out.println(" " + attr.get(TextAttribute.WEIGHT));
-// System.out.println(" " + attr.get(TextAttribute.POSTURE));
-
- outgoing.add(font);
-// System.out.println(" good " + w);
- }
- }
- }
- return outgoing;
- }
-
-
- static public String[] getMonoFontFamilies() {
- HashSet families = new HashSet();
- for (Font font : getMonoFontList()) {
- families.add(font.getFamily());
- }
- String[] names = families.toArray(new String[0]);
- Arrays.sort(names);
- return names;
- }
-
-
- static Font monoFont;
- static Font monoBoldFont;
- static Font sansFont;
- static Font sansBoldFont;
-
-
- static public String getMonoFontName() {
- if (monoFont == null) {
- getMonoFont(12, Font.PLAIN); // load a dummy version
- }
- return monoFont.getName();
- }
-
-
- static public Font getMonoFont(int size, int style) {
- if (monoFont == null) {
- try {
- monoFont = createFont("SourceCodePro-Regular.ttf", size);
- //monoBoldFont = createFont("SourceCodePro-Semibold.ttf", size);
- monoBoldFont = createFont("SourceCodePro-Bold.ttf", size);
- } catch (Exception e) {
- Base.log("Could not load mono font", e);
- monoFont = new Font("Monospaced", Font.PLAIN, size);
- monoBoldFont = new Font("Monospaced", Font.BOLD, size);
- }
- }
- if (style == Font.BOLD) {
- if (size == monoBoldFont.getSize()) {
- return monoBoldFont;
- } else {
- return monoBoldFont.deriveFont((float) size);
- }
- } else {
- if (size == monoFont.getSize()) {
- return monoFont;
- } else {
- return monoFont.deriveFont((float) size);
- }
- }
- }
-
-
- static public Font getSansFont(int size, int style) {
- if (sansFont == null) {
- try {
- sansFont = createFont("SourceSansPro-Regular.ttf", size);
- sansBoldFont = createFont("SourceSansPro-Semibold.ttf", size);
- } catch (Exception e) {
- Base.log("Could not load sans font", e);
- sansFont = new Font("SansSerif", Font.PLAIN, size);
- sansBoldFont = new Font("SansSerif", Font.BOLD, size);
- }
- }
- if (style == Font.BOLD) {
- if (size == sansBoldFont.getSize()) {
- return sansBoldFont;
- } else {
- return sansBoldFont.deriveFont((float) size);
- }
- } else {
- if (size == sansFont.getSize()) {
- return sansFont;
- } else {
- return sansFont.deriveFont((float) size);
- }
- }
- }
-
-
- /**
- * Get a font from the JRE lib/fonts folder. Our default fonts are also
- * installed there so that the monospace (and others) can be used by other
- * font listing calls (i.e. it appears in the list of monospace fonts in
- * the Preferences window).
- */
- static private Font createFont(String filename, int size) throws IOException, FontFormatException {
- //InputStream is = Base.getLibStream("fonts/" + filename);
- File fontFile = new File(System.getProperty("java.home"), "lib/fonts/" + filename);
- BufferedInputStream input = new BufferedInputStream(new FileInputStream(fontFile));
- Font font = Font.createFont(Font.TRUETYPE_FONT, input);
- input.close();
- return font.deriveFont((float) size);
- }
-
-
- static double getAscent(Graphics g) { //, Font font) {
- Graphics2D g2 = (Graphics2D) g;
- FontRenderContext frc = g2.getFontRenderContext();
- //return new TextLayout("H", font, frc).getBounds().getHeight();
- return new TextLayout("H", g.getFont(), frc).getBounds().getHeight();
- }
-}
diff --git a/app/src/processing/app/UpdateCheck.java b/app/src/processing/app/UpdateCheck.java
index 23e5b96beb..5103f5d856 100644
--- a/app/src/processing/app/UpdateCheck.java
+++ b/app/src/processing/app/UpdateCheck.java
@@ -3,7 +3,7 @@
/*
Part of the Processing project - http://processing.org
- Copyright (c) 2005-12 Ben Fry and Casey Reas
+ Copyright (c) 2005-15 Ben Fry and Casey Reas
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
@@ -25,11 +25,13 @@
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
+import java.io.IOException;
import java.net.URL;
import java.util.Random;
import javax.swing.JOptionPane;
+import processing.app.contrib.ContributionManager;
import processing.core.PApplet;
@@ -42,40 +44,51 @@
* to check for updates. Also included is the operating system and
* its version and the version of Java being used to run Processing.
*
- * The ID number also helps provide us a general idea of how many
- * people are using Processing, which helps us when writing grant
- * proposals and that kind of thing so that we can keep Processing free.
+ * Aside from the privacy invasion of knowing that an anonymous Processing
+ * user opened the software at one time during a 24-hour period somewhere
+ * in the world, we use the ID number to give us a general idea of how many
+ * people are using Processing, which helps us when writing grant proposals
+ * and that kind of thing so that we can keep Processing free. The numbers
+ * are also sometimes used in ugly charts when Ben and Casey present.
*/
public class UpdateCheck {
- Base base;
- String downloadURL = "http://processing.org/download/latest.txt";
+ private final Base base;
- static final long ONE_DAY = 24 * 60 * 60 * 1000;
+ static private final String DOWNLOAD_URL = "http://processing.org/download/";
+ static private final String LATEST_URL = "http://processing.org/download/latest.txt";
+
+ static private final long ONE_DAY = 24 * 60 * 60 * 1000;
+
+ static boolean allowed;
public UpdateCheck(Base base) {
this.base = base;
- new Thread(new Runnable() {
- public void run() {
- try {
- Thread.sleep(20 * 1000); // give the PDE time to get rolling
- updateCheck();
- } catch (Exception e) {
- // this can safely be ignored, too many instances where no net
- // connection is available, so we'll leave it well alone.
-// String msg = e.getMessage();
-// if (msg.contains("UnknownHostException")) {
-// // nah, do nothing.. this happens when not connected to the net
-// } else {
-// e.printStackTrace();
-// }
+
+ if (isAllowed()) {
+ new Thread(new Runnable() {
+ public void run() {
+ try {
+ Thread.sleep(5 * 1000); // give the PDE time to get rolling
+ updateCheck();
+
+ } catch (Exception e) {
+ // This can safely be ignored, too many situations where no net
+ // connection is available that behave in strange ways.
+ // Covers likely IOException, InterruptedException, and any others.
+ }
}
- }
- }, "Update Checker").start();
+ }, "Update Checker").start();
+ }
}
- public void updateCheck() throws Exception {
+ /**
+ * Turned into a separate method so that anyone needed update.id will get
+ * a legit answer. Had a problem with the contribs script where the id
+ * wouldn't be set so a null id would be sent to the contribs server.
+ */
+ static public long getUpdateID() {
// generate a random id in case none exists yet
Random r = new Random();
long id = r.nextLong();
@@ -86,8 +99,12 @@ public void updateCheck() throws Exception {
} else {
Preferences.set("update.id", String.valueOf(id));
}
+ return id;
+ }
- String info = PApplet.urlEncode(id + "\t" +
+
+ public void updateCheck() throws IOException, InterruptedException {
+ String info = PApplet.urlEncode(getUpdateID() + "\t" +
PApplet.nf(Base.getRevision(), 4) + "\t" +
System.getProperty("java.version") + "\t" +
System.getProperty("java.vendor") + "\t" +
@@ -95,7 +112,7 @@ public void updateCheck() throws Exception {
System.getProperty("os.version") + "\t" +
System.getProperty("os.arch"));
- int latest = readInt(downloadURL + "?" + info);
+ int latest = readInt(LATEST_URL + "?" + info);
String lastString = Preferences.get("update.last");
long now = System.currentTimeMillis();
@@ -109,29 +126,28 @@ public void updateCheck() throws Exception {
Preferences.set("update.last", String.valueOf(now));
if (base.activeEditor != null) {
- boolean offerToUpdateContributions = true;
+// boolean offerToUpdateContributions = true;
if (latest > Base.getRevision()) {
System.out.println("You are running Processing revision 0" +
Base.getRevision() + ", the latest build is 0" +
latest + ".");
// Assume the person is busy downloading the latest version
- offerToUpdateContributions = !promptToVisitDownloadPage();
+// offerToUpdateContributions = !promptToVisitDownloadPage();
+ promptToVisitDownloadPage();
}
+ /*
if (offerToUpdateContributions) {
// Wait for xml file to be downloaded and updates to come in.
// (this should really be handled better).
Thread.sleep(5 * 1000);
- if ((!base.libraryManagerFrame.hasAlreadyBeenOpened() &&
- base.libraryManagerFrame.hasUpdates(base)) ||
- (!base.toolManagerFrame.hasAlreadyBeenOpened() &&
- base.toolManagerFrame.hasUpdates(base)) ||
- (!base.modeManagerFrame.hasAlreadyBeenOpened() &&
- base.modeManagerFrame.hasUpdates(base))) {
+ if ((!base.contributionManagerFrame.hasAlreadyBeenOpened()
+ && (base.contributionManagerFrame.hasUpdates(base)))){
promptToOpenContributionManager();
}
}
+ */
}
}
@@ -149,7 +165,7 @@ protected boolean promptToVisitDownloadPage() {
options,
options[0]);
if (result == JOptionPane.YES_OPTION) {
- Base.openURL("http://processing.org/download/");
+ Platform.openURL(DOWNLOAD_URL);
return true;
}
@@ -158,9 +174,12 @@ protected boolean promptToVisitDownloadPage() {
protected boolean promptToOpenContributionManager() {
- String contributionPrompt = Language.text("update_check.updates_available.contributions");
+ String contributionPrompt =
+ Language.text("update_check.updates_available.contributions");
- Object[] options = { Language.text("prompt.yes"), Language.text("prompt.no") };
+ Object[] options = {
+ Language.text("prompt.yes"), Language.text("prompt.no")
+ };
int result = JOptionPane.showOptionDialog(base.activeEditor,
contributionPrompt,
Language.text("update_check"),
@@ -170,7 +189,7 @@ protected boolean promptToOpenContributionManager() {
options,
options[0]);
if (result == JOptionPane.YES_OPTION) {
- base.handleShowUpdates();
+ ContributionManager.openUpdates();
return true;
}
@@ -178,11 +197,17 @@ protected boolean promptToOpenContributionManager() {
}
- protected int readInt(String filename) throws Exception {
+ protected int readInt(String filename) throws IOException {
URL url = new URL(filename);
InputStream stream = url.openStream();
InputStreamReader isr = new InputStreamReader(stream);
BufferedReader reader = new BufferedReader(isr);
return Integer.parseInt(reader.readLine());
}
+
+
+ static public boolean isAllowed() {
+ // Disable update checks for the paranoid
+ return Preferences.getBoolean("update.check");
+ }
}
diff --git a/app/src/processing/app/Util.java b/app/src/processing/app/Util.java
new file mode 100644
index 0000000000..fefc3b8b71
--- /dev/null
+++ b/app/src/processing/app/Util.java
@@ -0,0 +1,677 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2012-15 The Processing Foundation
+ Copyright (c) 2004-12 Ben Fry and Casey Reas
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License
+ version 2, as published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU 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,
+ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*/
+
+package processing.app;
+
+import java.io.*;
+import java.nio.file.Files;
+import java.util.Enumeration;
+import java.util.zip.*;
+
+import processing.core.PApplet;
+import processing.data.StringDict;
+import processing.data.StringList;
+
+
+public class Util {
+
+ /**
+ * Get the number of lines in a file by counting the number of newline
+ * characters inside a String (and adding 1).
+ */
+ static public int countLines(String what) {
+ int count = 1;
+ for (char c : what.toCharArray()) {
+ if (c == '\n') count++;
+ }
+ return count;
+ }
+
+
+ /**
+ * Same as PApplet.loadBytes(), however never does gzip decoding.
+ */
+ static public byte[] loadBytesRaw(File file) throws IOException {
+ int size = (int) file.length();
+ FileInputStream input = new FileInputStream(file);
+ byte buffer[] = new byte[size];
+ int offset = 0;
+ int bytesRead;
+ while ((bytesRead = input.read(buffer, offset, size-offset)) != -1) {
+ offset += bytesRead;
+ if (bytesRead == 0) break;
+ }
+ input.close(); // weren't properly being closed
+ input = null;
+ return buffer;
+ }
+
+
+ /**
+ * Read from a file with a bunch of attribute/value pairs
+ * that are separated by = and ignore comments with #.
+ * Changed in 3.x to return null (rather than empty hash) if no file,
+ * and changed return type to StringDict instead of Map or HashMap.
+ */
+ static public StringDict readSettings(File inputFile) {
+ if (!inputFile.exists()) {
+ Messages.loge(inputFile + " does not exist inside readSettings()");
+ return null;
+ }
+ String lines[] = PApplet.loadStrings(inputFile);
+ if (lines == null) {
+ System.err.println("Could not read " + inputFile);
+ return null;
+ }
+ return readSettings(inputFile.toString(), lines);
+ }
+
+
+ /**
+ * Parse a String array that contains attribute/value pairs separated
+ * by = (the equals sign). The # (hash) symbol is used to denote comments.
+ * Comments can be anywhere on a line. Blank lines are ignored.
+ * In 3.0a6, no longer taking a blank HashMap as param; no cases in the main
+ * PDE code of adding to a (Hash)Map. Also returning the Map instead of void.
+ * Both changes modify the method signature, but this was only used by the
+ * contrib classes.
+ */
+ static public StringDict readSettings(String filename, String[] lines) {
+ StringDict settings = new StringDict();
+ for (String line : lines) {
+ // Remove comments
+ int commentMarker = line.indexOf('#');
+ if (commentMarker != -1) {
+ line = line.substring(0, commentMarker);
+ }
+ // Remove extra whitespace
+ line = line.trim();
+
+ if (line.length() != 0) {
+ int equals = line.indexOf('=');
+ if (equals == -1) {
+ if (filename != null) {
+ System.err.println("Ignoring illegal line in " + filename);
+ System.err.println(" " + line);
+ }
+ } else {
+ String attr = line.substring(0, equals).trim();
+ String valu = line.substring(equals + 1).trim();
+ settings.set(attr, valu);
+ }
+ }
+ }
+ return settings;
+ }
+
+
+ static public void copyFile(File sourceFile,
+ File targetFile) throws IOException {
+ BufferedInputStream from =
+ new BufferedInputStream(new FileInputStream(sourceFile));
+ BufferedOutputStream to =
+ new BufferedOutputStream(new FileOutputStream(targetFile));
+ byte[] buffer = new byte[16 * 1024];
+ int bytesRead;
+ while ((bytesRead = from.read(buffer)) != -1) {
+ to.write(buffer, 0, bytesRead);
+ }
+ from.close();
+ from = null;
+
+ to.flush();
+ to.close();
+ to = null;
+
+ targetFile.setLastModified(sourceFile.lastModified());
+ targetFile.setExecutable(sourceFile.canExecute());
+ }
+
+
+ /**
+ * Grab the contents of a file as a string. Connects lines with \n,
+ * even if the input file used \r\n.
+ */
+ static public String loadFile(File file) throws IOException {
+ String[] contents = PApplet.loadStrings(file);
+ if (contents == null) return null;
+ return PApplet.join(contents, "\n");
+ }
+
+
+ /**
+ * Spew the contents of a String object out to a file. As of 3.0 beta 2,
+ * this will replace and write \r\n for newlines on Windows.
+ * https://github.com/processing/processing/issues/3455
+ * As of 3.3.7, this puts a newline at the end of the file,
+ * per good practice/POSIX: https://stackoverflow.com/a/729795
+ */
+ static public void saveFile(String text, File file) throws IOException {
+ String[] lines = text.split("\\r?\\n");
+ File temp = File.createTempFile(file.getName(), null, file.getParentFile());
+ try {
+ // fix from cjwant to prevent symlinks from being destroyed.
+ File canon = file.getCanonicalFile();
+ // assign the var as second step since previous line may throw exception
+ file = canon;
+ } catch (IOException e) {
+ throw new IOException("Could not resolve canonical representation of " +
+ file.getAbsolutePath());
+ }
+ // Could use saveStrings(), but the we wouldn't be able to checkError()
+ PrintWriter writer = PApplet.createWriter(temp);
+ for (String line : lines) {
+ writer.println(line);
+ }
+ boolean error = writer.checkError(); // calls flush()
+ writer.close(); // attempt to close regardless
+ if (error) {
+ throw new IOException("Error while trying to save " + file);
+ }
+
+ // remove the old file before renaming the temp file
+ if (file.exists()) {
+ boolean result = file.delete();
+ if (!result) {
+ throw new IOException("Could not remove old version of " +
+ file.getAbsolutePath());
+ }
+ }
+ boolean result = temp.renameTo(file);
+ if (!result) {
+ throw new IOException("Could not replace " + file.getAbsolutePath() +
+ " with " + temp.getAbsolutePath());
+ }
+ }
+
+
+ /**
+ * Create a temporary folder by using the createTempFile() mechanism,
+ * deleting the file it creates, and making a folder using the location
+ * that was provided.
+ *
+ * Unlike createTempFile(), there is no minimum size for prefix. If
+ * prefix is less than 3 characters, the remaining characters will be
+ * filled with underscores
+ */
+ static public File createTempFolder(String prefix, String suffix,
+ File directory) throws IOException {
+ int fillChars = 3 - prefix.length();
+ for (int i = 0; i < fillChars; i++) {
+ prefix += '_';
+ }
+ File folder = File.createTempFile(prefix, suffix, directory);
+ // Now delete that file and create a folder in its place
+ folder.delete();
+ folder.mkdirs();
+ // And send the folder back to your friends
+ return folder;
+ }
+
+
+ /**
+ * Copy a folder from one place to another. This ignores all dot files and
+ * folders found in the source directory, to avoid copying silly .DS_Store
+ * files and potentially troublesome .svn folders.
+ */
+ static public void copyDir(File sourceDir,
+ File targetDir) throws IOException {
+ if (sourceDir.equals(targetDir)) {
+ final String urDum = "source and target directories are identical";
+ throw new IllegalArgumentException(urDum);
+ }
+ targetDir.mkdirs();
+ String files[] = sourceDir.list();
+ for (int i = 0; i < files.length; i++) {
+ // Ignore dot files (.DS_Store), dot folders (.svn) while copying
+ if (files[i].charAt(0) == '.') continue;
+ //if (files[i].equals(".") || files[i].equals("..")) continue;
+ File source = new File(sourceDir, files[i]);
+ File target = new File(targetDir, files[i]);
+ if (source.isDirectory()) {
+ //target.mkdirs();
+ copyDir(source, target);
+ target.setLastModified(source.lastModified());
+ } else {
+ copyFile(source, target);
+ }
+ }
+ }
+
+
+ static public void copyDirNative(File sourceDir,
+ File targetDir) throws IOException {
+ Process process = null;
+ if (Platform.isMacOS() || Platform.isLinux()) {
+ process = Runtime.getRuntime().exec(new String[] {
+ "cp", "-a", sourceDir.getAbsolutePath(), targetDir.getAbsolutePath()
+ });
+ } else {
+ // TODO implement version that uses XCOPY here on Windows
+ throw new RuntimeException("Not yet implemented on Windows");
+ }
+ try {
+ int result = process.waitFor();
+ if (result != 0) {
+ throw new IOException("Error while copying (result " + result + ")");
+ }
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+// /**
+// * Delete a file or directory in a platform-specific manner. Removes a File
+// * object (a file or directory) from the system by placing it in the Trash
+// * or Recycle Bin (if available) or simply deleting it (if not).
+// *
+// * When the file/folder is on another file system, it may simply be removed
+// * immediately, without additional warning. So only use this if you want to,
+// * you know, "delete" the subject in question.
+// *
+// * NOTE: Not yet tested nor ready for prime-time.
+// *
+// * @param file the victim (a directory or individual file)
+// * @return true if all ends well
+// * @throws IOException what went wrong
+// */
+// static public boolean platformDelete(File file) throws IOException {
+// return Base.getPlatform().deleteFile(file);
+// }
+
+
+ /**
+ * Remove all files in a directory and the directory itself.
+ * Prints error messages with failed filenames. Does not follow symlinks.
+ */
+ static public boolean removeDir(File dir) {
+ return removeDir(dir, true);
+ }
+
+ /**
+ * Remove all files in a directory and the directory itself.
+ * Optinally prints error messages with failed filenames.
+ * Does not follow symlinks.
+ */
+ static public boolean removeDir(File dir, boolean printErrorMessages) {
+ if (!dir.exists()) return true;
+
+ boolean result = true;
+ if (!Files.isSymbolicLink(dir.toPath())) {
+ File[] files = dir.listFiles();
+ if (files != null) {
+ for (File child : files) {
+ if (child.isFile()) {
+ boolean deleted = child.delete();
+ if (!deleted && printErrorMessages) {
+ System.err.println("Could not delete " + child.getAbsolutePath());
+ }
+ result &= deleted;
+ } else if (child.isDirectory()) {
+ result &= removeDir(child, printErrorMessages);
+ }
+ }
+ }
+ }
+ boolean deleted = dir.delete();
+ if (!deleted && printErrorMessages) {
+ System.err.println("Could not delete " + dir.getAbsolutePath());
+ }
+ result &= deleted;
+ return result;
+ }
+
+
+ /**
+ * Function to return the length of the file, or entire directory, including
+ * the component files and sub-folders if passed.
+ * @param file The file or folder to calculate
+ */
+ static public long calcSize(File file) {
+ return file.isFile() ? file.length() : Util.calcFolderSize(file);
+ }
+
+
+ /**
+ * Calculate the size of the contents of a folder.
+ * Used to determine whether sketches are empty or not.
+ * Note that the function calls itself recursively.
+ */
+ static public long calcFolderSize(File folder) {
+ int size = 0;
+
+ String files[] = folder.list();
+ // null if folder doesn't exist, happens when deleting sketch
+ if (files == null) return -1;
+
+ for (int i = 0; i < files.length; i++) {
+ if (files[i].equals(".") ||
+ files[i].equals("..") ||
+ files[i].equals(".DS_Store")) continue;
+ File fella = new File(folder, files[i]);
+ if (fella.isDirectory()) {
+ size += calcFolderSize(fella);
+ } else {
+ size += (int) fella.length();
+ }
+ }
+ return size;
+ }
+
+
+ /**
+ * Recursively creates a list of all files within the specified folder,
+ * and returns a list of their relative paths.
+ * Ignores any files/folders prefixed with a dot.
+ * @param relative true return relative paths instead of absolute paths
+ */
+ static public String[] listFiles(File folder, boolean relative) {
+ return listFiles(folder, relative, null);
+ }
+
+
+ static public String[] listFiles(File folder, boolean relative,
+ String extension) {
+ if (extension != null) {
+ if (!extension.startsWith(".")) {
+ extension = "." + extension;
+ }
+ }
+
+ StringList list = new StringList();
+ listFilesImpl(folder, relative, extension, list);
+
+ if (relative) {
+ String[] outgoing = new String[list.size()];
+ // remove the slash (or backslash) as well
+ int prefixLength = folder.getAbsolutePath().length() + 1;
+ for (int i = 0; i < outgoing.length; i++) {
+ outgoing[i] = list.get(i).substring(prefixLength);
+ }
+ return outgoing;
+ }
+ return list.array();
+ }
+
+
+ static void listFilesImpl(File folder, boolean relative,
+ String extension, StringList list) {
+ File[] items = folder.listFiles();
+ if (items != null) {
+ for (File item : items) {
+ String name = item.getName();
+ if (name.charAt(0) != '.') {
+ if (item.isDirectory()) {
+ listFilesImpl(item, relative, extension, list);
+
+ } else { // a file
+ if (extension == null || name.endsWith(extension)) {
+ list.append(item.getAbsolutePath());
+ }
+ }
+ }
+ }
+ }
+ }
+
+
+ /**
+ * @param folder source folder to search
+ * @return a list of .jar and .zip files in that folder
+ */
+ static public File[] listJarFiles(File folder) {
+ return folder.listFiles(new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return (!name.startsWith(".") &&
+ (name.toLowerCase().endsWith(".jar") ||
+ name.toLowerCase().endsWith(".zip")));
+ }
+ });
+ }
+
+
+ /////////////////////////////////////////////////////////////////////////////
+
+
+ /**
+ * Given a folder, return a list of absolute paths to all jar or zip files
+ * inside that folder, separated by pathSeparatorChar.
+ *
+ * This will prepend a colon (or whatever the path separator is)
+ * so that it can be directly appended to another path string.
+ *
+ * As of 0136, this will no longer add the root folder as well.
+ *
+ * This function doesn't bother checking to see if there are any .class
+ * files in the folder or within a subfolder.
+ */
+ static public String contentsToClassPath(File folder) {
+ if (folder == null) return "";
+
+ StringBuilder sb = new StringBuilder();
+ String sep = System.getProperty("path.separator");
+
+ try {
+ String path = folder.getCanonicalPath();
+
+ // When getting the name of this folder, make sure it has a slash
+ // after it, so that the names of sub-items can be added.
+ if (!path.endsWith(File.separator)) {
+ path += File.separator;
+ }
+
+ String list[] = folder.list();
+ for (int i = 0; i < list.length; i++) {
+ // Skip . and ._ files. Prior to 0125p3, .jar files that had
+ // OS X AppleDouble files associated would cause trouble.
+ if (list[i].startsWith(".")) continue;
+
+ if (list[i].toLowerCase().endsWith(".jar") ||
+ list[i].toLowerCase().endsWith(".zip")) {
+ sb.append(sep);
+ sb.append(path);
+ sb.append(list[i]);
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace(); // this would be odd
+ }
+ return sb.toString();
+ }
+
+
+ /**
+ * A classpath, separated by the path separator, will contain
+ * a series of .jar/.zip files or directories containing .class
+ * files, or containing subdirectories that have .class files.
+ *
+ * @param path the input classpath
+ * @return array of possible package names
+ */
+ static public StringList packageListFromClassPath(String path) {
+// Map map = new HashMap();
+ StringList list = new StringList();
+ 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") ||
+ pieces[i].toLowerCase().endsWith(".zip")) {
+ //System.out.println("checking " + pieces[i]);
+ packageListFromZip(pieces[i], list);
+
+ } else { // it's another type of file or directory
+ File dir = new File(pieces[i]);
+ if (dir.exists() && dir.isDirectory()) {
+ packageListFromFolder(dir, null, list);
+ //importCount = magicImportsRecursive(dir, null,
+ // map);
+ //imports, importCount);
+ }
+ }
+ }
+// int mapCount = map.size();
+// String output[] = new String[mapCount];
+// int index = 0;
+// Set set = map.keySet();
+// for (String s : set) {
+// output[index++] = s.replace('/', '.');
+// }
+// return output;
+ StringList outgoing = new StringList(list.size());
+ for (String item : list) {
+ outgoing.append(item.replace('/', '.'));
+ }
+ return outgoing;
+ }
+
+
+ static private void packageListFromZip(String filename, StringList list) {
+ try {
+ ZipFile file = new ZipFile(filename);
+ Enumeration> entries = file.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry entry = (ZipEntry) entries.nextElement();
+
+ if (!entry.isDirectory()) {
+ String name = entry.getName();
+
+ // Avoid META-INF because some jokers but .class files in there
+ // https://github.com/processing/processing/issues/5778
+ if (name.endsWith(".class") && !name.startsWith("META-INF/")) {
+ int slash = name.lastIndexOf('/');
+ if (slash != -1) {
+ String packageName = name.substring(0, slash);
+ list.appendUnique(packageName);
+ }
+ }
+ }
+ }
+ file.close();
+ } catch (IOException e) {
+ System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
+ //e.printStackTrace();
+ }
+ }
+
+
+ /**
+ * 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,
+ * walk down into that folder and continue.
+ */
+ static private void packageListFromFolder(File dir, String sofar,
+ StringList list) {
+// Map map) {
+ boolean foundClass = false;
+ String files[] = dir.list();
+
+ for (int i = 0; i < files.length; i++) {
+ if (files[i].equals(".") || files[i].equals("..")) continue;
+
+ File sub = new File(dir, files[i]);
+ if (sub.isDirectory()) {
+ String nowfar =
+ (sofar == null) ? files[i] : (sofar + "." + files[i]);
+ packageListFromFolder(sub, nowfar, list);
+ //System.out.println(nowfar);
+ //imports[importCount++] = nowfar;
+ //importCount = magicImportsRecursive(sub, nowfar,
+ // imports, importCount);
+ } else if (!foundClass) { // if no classes found in this folder yet
+ if (files[i].endsWith(".class")) {
+ //System.out.println("unique class: " + files[i] + " for " + sofar);
+// map.put(sofar, new Object());
+ list.appendUnique(sofar);
+ foundClass = true;
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Extract the contents of a .zip archive into a folder.
+ * Ignores (does not extract) any __MACOSX files from macOS archives.
+ */
+ static public void unzip(File zipFile, File dest) {
+ try {
+ FileInputStream fis = new FileInputStream(zipFile);
+ CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
+ ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum));
+ ZipEntry entry = null;
+ while ((entry = zis.getNextEntry()) != null) {
+ final String name = entry.getName();
+ if (!name.startsWith(("__MACOSX"))) {
+ File currentFile = new File(dest, name);
+ if (entry.isDirectory()) {
+ currentFile.mkdirs();
+ } else {
+ File parentDir = currentFile.getParentFile();
+ // Sometimes the directory entries aren't already created
+ if (!parentDir.exists()) {
+ parentDir.mkdirs();
+ }
+ currentFile.createNewFile();
+ unzipEntry(zis, currentFile);
+ }
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ static protected void unzipEntry(ZipInputStream zin, File f) throws IOException {
+ FileOutputStream out = new FileOutputStream(f);
+ byte[] b = new byte[512];
+ int len = 0;
+ while ((len = zin.read(b)) != -1) {
+ out.write(b, 0, len);
+ }
+ out.flush();
+ out.close();
+ }
+
+
+ static public byte[] gzipEncode(byte[] what) throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ GZIPOutputStream output = new GZIPOutputStream(baos);
+ PApplet.saveStream(output, new ByteArrayInputStream(what));
+ output.close();
+ return baos.toByteArray();
+ }
+
+
+ static public final boolean containsNonASCII(String what) {
+ for (char c : what.toCharArray()) {
+ if (c < 32 || c > 127) return true;
+ }
+ return false;
+ }
+}
diff --git a/app/src/processing/app/WebServer.java b/app/src/processing/app/WebServer.java
index 1a33a365c2..710fd7b2e6 100644
--- a/app/src/processing/app/WebServer.java
+++ b/app/src/processing/app/WebServer.java
@@ -5,21 +5,20 @@
import java.util.*;
import java.util.zip.*;
-//import javax.swing.SwingUtilities;
/**
* This code is placed here in anticipation of running the reference from an
* internal web server that reads the docs from a zip file, instead of using
* thousands of .html files on the disk, which is really inefficient.
*
- * This is a very simple, multi-threaded HTTP server, originally based on
+ * This is a very simple, multi-threaded HTTP server, originally based on
* this article on java.sun.com.
*/
public class WebServer implements HttpConstants {
/* Where worker threads stand idle */
static Vector threads = new Vector();
-
+
/* the web server's virtual root */
//static File root;
@@ -29,7 +28,7 @@ public class WebServer implements HttpConstants {
/* max # worker threads */
static int workers = 5;
-// static PrintStream log = System.out;
+// static PrintStream log = System.out;
/*
@@ -88,7 +87,7 @@ static void printProps() {
}
*/
-
+
/* print to stdout */
// protected static void p(String s) {
// System.out.println(s);
@@ -105,17 +104,17 @@ protected static void log(String s) {
// }
}
-
+
//public static void main(String[] a) throws Exception {
static public int launch(String zipPath) throws IOException {
final ZipFile zip = new ZipFile(zipPath);
- final HashMap entries = new HashMap();
+ final Map entries = new HashMap();
Enumeration en = zip.entries();
while (en.hasMoreElements()) {
ZipEntry entry = (ZipEntry) en.nextElement();
entries.put(entry.getName(), entry);
}
-
+
// if (a.length > 0) {
// port = Integer.parseInt(a[0]);
// }
@@ -164,9 +163,9 @@ public void run() {
class WebServerWorker /*extends WebServer*/ implements HttpConstants, Runnable {
- ZipFile zip;
- HashMap entries;
-
+ private final ZipFile zip;
+ private final Map entries;
+
final static int BUF_SIZE = 2048;
static final byte[] EOL = { (byte)'\r', (byte)'\n' };
@@ -176,10 +175,10 @@ class WebServerWorker /*extends WebServer*/ implements HttpConstants, Runnable {
/* Socket to client we're handling */
private Socket s;
- WebServerWorker(ZipFile zip, HashMap entries) {
+ WebServerWorker(ZipFile zip, Map entries) {
this.entries = entries;
this.zip = zip;
-
+
buf = new byte[BUF_SIZE];
s = null;
}
@@ -226,7 +225,7 @@ public synchronized void run() {
}
}
-
+
void handleClient() throws IOException {
InputStream is = new BufferedInputStream(s.getInputStream());
PrintStream ps = new PrintStream(s.getOutputStream());
@@ -240,7 +239,7 @@ void handleClient() throws IOException {
buf[i] = 0;
}
try {
- // We only support HTTP GET/HEAD, and don't support any fancy HTTP
+ // We only support HTTP GET/HEAD, and don't support any fancy HTTP
// options, so we're only interested really in the first line.
int nread = 0, r = 0;
@@ -254,7 +253,7 @@ void handleClient() throws IOException {
nread += r;
for (; i < nread; i++) {
if (buf[i] == (byte)'\n' || buf[i] == (byte)'\r') {
- break outerloop; // read one line
+ break outerloop; // read one line
}
}
}
@@ -312,7 +311,7 @@ void handleClient() throws IOException {
send404(ps);
}
/*
- String fname =
+ String fname =
(new String(buf, 0, index, i-index)).replace('/', File.separatorChar);
if (fname.startsWith(File.separator)) {
fname = fname.substring(1);
@@ -338,7 +337,7 @@ void handleClient() throws IOException {
}
}
-
+
boolean printHeaders(ZipEntry targ, PrintStream ps) throws IOException {
boolean ret = false;
int rCode = 0;
@@ -370,7 +369,7 @@ boolean printHeaders(ZipEntry targ, PrintStream ps) throws IOException {
int ind = name.lastIndexOf('.');
String ct = null;
if (ind > 0) {
- ct = (String) map.get(name.substring(ind));
+ ct = map.get(name.substring(ind));
}
if (ct == null) {
//System.err.println("unknown content type " + name.substring(ind));
@@ -386,8 +385,8 @@ boolean printHeaders(ZipEntry targ, PrintStream ps) throws IOException {
ps.write(EOL); // adding another newline here [fry]
return ret;
}
-
-
+
+
boolean printHeaders(File targ, PrintStream ps) throws IOException {
boolean ret = false;
int rCode = 0;
@@ -417,7 +416,7 @@ boolean printHeaders(File targ, PrintStream ps) throws IOException {
int ind = name.lastIndexOf('.');
String ct = null;
if (ind > 0) {
- ct = (String) map.get(name.substring(ind));
+ ct = map.get(name.substring(ind));
}
if (ct == null) {
ct = "unknown/unknown";
@@ -432,7 +431,7 @@ boolean printHeaders(File targ, PrintStream ps) throws IOException {
return ret;
}
-
+
void send404(PrintStream ps) throws IOException {
ps.write(EOL);
ps.write(EOL);
@@ -442,7 +441,7 @@ void send404(PrintStream ps) throws IOException {
ps.write(EOL);
}
-
+
void sendFile(File targ, PrintStream ps) throws IOException {
InputStream is = null;
ps.write(EOL);
@@ -454,8 +453,8 @@ void sendFile(File targ, PrintStream ps) throws IOException {
}
sendFile(is, ps);
}
-
-
+
+
void sendFile(InputStream is, PrintStream ps) throws IOException {
try {
int n;
@@ -468,7 +467,7 @@ void sendFile(InputStream is, PrintStream ps) throws IOException {
}
/* mapping of file extensions to content-types */
- static java.util.Hashtable map = new java.util.Hashtable();
+ static Map map = new HashMap();
static {
fillMap();
@@ -489,19 +488,19 @@ static void fillMap() {
setSuffix(".snd", "audio/basic");
setSuffix(".au", "audio/basic");
setSuffix(".wav", "audio/x-wav");
-
+
setSuffix(".gif", "image/gif");
setSuffix(".jpg", "image/jpeg");
setSuffix(".jpeg", "image/jpeg");
-
+
setSuffix(".htm", "text/html");
setSuffix(".html", "text/html");
- setSuffix(".css", "text/css");
+ setSuffix(".css", "text/css");
setSuffix(".java", "text/javascript");
-
+
setSuffix(".txt", "text/plain");
setSuffix(".java", "text/plain");
-
+
setSuffix(".c", "text/plain");
setSuffix(".cc", "text/plain");
setSuffix(".c++", "text/plain");
diff --git a/app/src/processing/app/contrib/AvailableContribution.java b/app/src/processing/app/contrib/AvailableContribution.java
index 1023f2a839..4d5240c451 100644
--- a/app/src/processing/app/contrib/AvailableContribution.java
+++ b/app/src/processing/app/contrib/AvailableContribution.java
@@ -1,9 +1,9 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
- Copyright (c) 2013 The Processing Foundation
+ Copyright (c) 2013-20 The Processing Foundation
Copyright (c) 2011-12 Ben Fry and Casey Reas
This program is free software; you can redistribute it and/or modify
@@ -15,55 +15,74 @@
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
+ 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.contrib;
import java.io.*;
-import java.util.HashMap;
-import java.util.List;
import processing.app.Base;
import processing.app.Language;
+import processing.app.Platform;
+import processing.app.Util;
import processing.core.PApplet;
+import processing.data.StringDict;
+import processing.data.StringList;
/**
- * A class to hold information about a Contribution that can be downloaded.
+ * A class to hold information about a Contribution that can be downloaded.
*/
-class AvailableContribution extends Contribution {
+public class AvailableContribution extends Contribution {
protected final ContributionType type; // Library, tool, etc.
protected final String link; // Direct link to download the file
-
- public AvailableContribution(ContributionType type, HashMap params) {
+
+ public AvailableContribution(ContributionType type, StringDict params) {
this.type = type;
this.link = params.get("download");
-
- //category = ContributionListing.getCategory(params.get("category"));
- categories = parseCategories(params.get("category"));
+
+ categories = parseCategories(params);
+ imports = parseImports(params);
name = params.get("name");
- authorList = params.get("authorList");
+ authors = params.get("authors");
+// if (authors == null) {
+// authors = params.get("authorList");
+// }
url = params.get("url");
sentence = params.get("sentence");
paragraph = params.get("paragraph");
+
String versionStr = params.get("version");
if (versionStr != null) {
version = PApplet.parseInt(versionStr, 0);
}
- prettyVersion = params.get("prettyVersion");
+
+ setPrettyVersion(params.get("prettyVersion"));
+
String lastUpdatedStr = params.get("lastUpdated");
- if (lastUpdatedStr != null)
+ if (lastUpdatedStr != null) {
try {
lastUpdated = Long.parseLong(lastUpdatedStr);
} catch (NumberFormatException e) {
lastUpdated = 0;
}
+ }
+ String minRev = params.get("minRevision");
+ if (minRev != null) {
+ minRevision = PApplet.parseInt(minRev, 0);
+ }
+
+ String maxRev = params.get("maxRevision");
+ if (maxRev != null) {
+ maxRevision = PApplet.parseInt(maxRev, 0);
+ }
}
-
-
+
+
/**
* @param contribArchive
* a zip file containing the library to install
@@ -77,12 +96,11 @@ public AvailableContribution(ContributionType type, HashMap para
*/
public LocalContribution install(Base base, File contribArchive,
boolean confirmReplace, StatusPanel status) {
- // Unzip the file into the modes, tools, or libraries folder inside the
- // sketchbook. Unzipping to /tmp is problematic because it may be on
+ // Unzip the file into the modes, tools, or libraries folder inside the
+ // sketchbook. Unzipping to /tmp is problematic because it may be on
// another file system, so move/rename operations will break.
-// File sketchbookContribFolder = type.getSketchbookFolder();
- File tempFolder = null;
-
+ File tempFolder = null;
+
try {
tempFolder = type.createTempFolder();
} catch (IOException e) {
@@ -90,85 +108,62 @@ public LocalContribution install(Base base, File contribArchive,
status.setErrorMessage(Language.text("contrib.errors.temporary_directory"));
return null;
}
- Base.unzip(contribArchive, tempFolder);
-// System.out.println("temp folder is " + tempFolder);
-// Base.openFolder(tempFolder);
+ Util.unzip(contribArchive, tempFolder);
// Now go looking for a legit contrib inside what's been unpacked.
File contribFolder = null;
-
- // Sometimes contrib authors place all their folders in the base directory
- // of the .zip file instead of in single folder as the guidelines suggest.
- if (type.isCandidate(tempFolder)) {
- /*
- // Can't just rename the temp folder, because a contrib with this name
- // may already exist. Instead, create a new temp folder, and rename the
- // old one to be the correct folder.
- File enclosingFolder = null;
- try {
- enclosingFolder = Base.createTempFolder(type.toString(), "tmp", sketchbookContribFolder);
- } catch (IOException e) {
- status.setErrorMessage("Could not create a secondary folder to install.");
- return null;
- }
- contribFolder = new File(enclosingFolder, getName());
- tempFolder.renameTo(contribFolder);
- tempFolder = enclosingFolder;
- */
- if (status != null)
+
+ /*
+ if (!type.isCandidate(tempFolder)) {
+ if (status != null) {
status.setErrorMessage(Language.interpolate("contrib.errors.needs_repackage", getName(), type.getTitle()));
- //status.setErrorMessage("This " + type + " needs to be repackaged according to the guidelines.");
+ }
return null;
}
+ */
-// if (contribFolder == null) {
- // Find the first legitimate looking folder in what we just unzipped
- contribFolder = type.findCandidate(tempFolder);
-// }
LocalContribution installedContrib = null;
-
+ // Find the first legitimate folder in what we just unzipped
+ contribFolder = type.findCandidate(tempFolder);
if (contribFolder == null) {
- if (status != null)
+ if (status != null) {
status.setErrorMessage(Language.interpolate("contrib.errors.no_contribution_found", type));
-
+ }
} else {
File propFile = new File(contribFolder, type + ".properties");
- if (writePropertiesFile(propFile)) {
- // 1. contribFolder now has a legit contribution, load it to get info.
- LocalContribution newContrib =
- type.load(base, contribFolder);
-
- // 1.1. get info we need to delete the newContrib folder later
+ if (!propFile.exists()) {
+ status.setErrorMessage("This contribution is missing " +
+ propFile.getName() +
+ ", please contact the author for a fix.");
+
+ } else if (writePropertiesFile(propFile)) {
+ // contribFolder now has a legit contribution, load it to get info.
+ LocalContribution newContrib = type.load(base, contribFolder);
+
+ // get info we need to delete the newContrib folder later
File newContribFolder = newContrib.getFolder();
-
- // 2. Check to make sure nothing has the same name already,
+
+ // Check to make sure nothing has the same name already,
// backup old if needed, then move things into place and reload.
- installedContrib =
+ installedContrib =
newContrib.copyAndLoad(base, confirmReplace, status);
-
- // Restart no longer needed. Yay!
-// if (newContrib != null && type.requiresRestart()) {
-// installedContrib.setRestartFlag();
-// //status.setMessage("Restart Processing to finish the installation.");
-// }
-
- // 3.1 Unlock all the jars if it is a mode or tool
+
+ // Unlock all the jars if it is a mode or tool
if (newContrib.getType() == ContributionType.MODE) {
- ((ModeContribution)newContrib).clearClassLoader(base);
- }
- else if (newContrib.getType() == ContributionType.TOOL) {
- ((ToolContribution)newContrib).clearClassLoader(base);
+ ((ModeContribution) newContrib).clearClassLoader(base);
+
+ } else if (newContrib.getType() == ContributionType.TOOL) {
+ ((ToolContribution) newContrib).clearClassLoader();
}
-
- // 3.2 Delete the newContrib, do a garbage collection, hope and pray
+
+ // Delete the newContrib, do a garbage collection, hope and pray
// that Java will unlock the temp folder on Windows now
newContrib = null;
System.gc();
-
-
- if (Base.isWindows()) {
- // we'll even give it a second to finish up ... because file ops are
- // just that flaky on Windows.
+
+ if (Platform.isWindows()) {
+ // we'll even give it a second to finish up,
+ // because file ops are just that flaky on Windows.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
@@ -176,28 +171,29 @@ else if (newContrib.getType() == ContributionType.TOOL) {
}
}
- // 4. Okay, now actually delete that temp folder
- Base.removeDir(newContribFolder);
-
+ // delete the contrib folder inside the libraryXXXXXXtmp folder
+ Util.removeDir(newContribFolder, false);
+
} else {
- if (status != null)
+ if (status != null) {
status.setErrorMessage(Language.text("contrib.errors.overwriting_properties"));
+ }
}
}
// Remove any remaining boogers
if (tempFolder.exists()) {
- Base.removeDir(tempFolder);
+ Util.removeDir(tempFolder, false);
}
return installedContrib;
}
-
-
+
+
public boolean isInstalled() {
return false;
}
-
+
public ContributionType getType() {
return type;
}
@@ -211,89 +207,123 @@ public ContributionType getType() {
* manager. However, it also ensures that valid fields in the properties file
* aren't overwritten, since the properties file may be more recent than the
* contributions.txt file.
- *
- * @param propFile
- * @return
*/
public boolean writePropertiesFile(File propFile) {
try {
-
- HashMap properties = Base.readSettings(propFile);
+ StringDict properties = Util.readSettings(propFile);
String name = properties.get("name");
- if (name == null || name.isEmpty())
+ if (name == null || name.isEmpty()) {
name = getName();
+ }
String category;
- List categoryList = parseCategories(properties.get("category"));
- if (categoryList.size() == 1 && categoryList.get(0).equals("Unknown"))
+ StringList categoryList = parseCategories(properties);
+ if (categoryList.size() == 1 &&
+ categoryList.get(0).equals(UNKNOWN_CATEGORY)) {
category = getCategoryStr();
- else {
- StringBuilder sb = new StringBuilder();
- for (String cat : categories) {
- sb.append(cat);
- sb.append(',');
- }
- sb.deleteCharAt(sb.length() - 1);
- category = sb.toString();
+ } else {
+ category = categoryList.join(",");
}
- String authorList = properties.get("authorList");
- if (authorList == null || authorList.isEmpty())
- authorList = getAuthorList();
+ StringList importsList = parseImports(properties);
+
+ String authors = properties.get(AUTHORS_PROPERTY);
+// if (authors == null) {
+// authors = properties.get("authorList"); // before 3.0a11
+// }
+ if (authors == null || authors.isEmpty()) {
+ authors = getAuthorList();
+ }
String url = properties.get("url");
- if (url == null || url.isEmpty())
+ if (url == null || url.isEmpty()) {
url = getUrl();
+ }
String sentence = properties.get("sentence");
- if (sentence == null || sentence.isEmpty())
+ if (sentence == null || sentence.isEmpty()) {
sentence = getSentence();
+ }
String paragraph = properties.get("paragraph");
- if (paragraph == null || paragraph.isEmpty())
+ if (paragraph == null || paragraph.isEmpty()) {
paragraph = getParagraph();
+ }
int version;
try {
version = Integer.parseInt(properties.get("version"));
} catch (NumberFormatException e) {
version = getVersion();
- System.err.println("The version number for the “" + name
- + "” contribution is not set properly.");
- System.err
- .println("Please contact the author to fix it according to the guidelines.");
+ System.err.println("The version number for “" + name + "” is not a number.");
+ System.err.println("Please contact the author to fix it according to the guidelines.");
}
String prettyVersion = properties.get("prettyVersion");
- if (prettyVersion == null || prettyVersion.isEmpty())
- prettyVersion = getPrettyVersion();
+ if (prettyVersion != null && prettyVersion.isEmpty()) {
+ prettyVersion = null;
+ }
+
+ String compatibleContribsList = null;
+ if (getType() == ContributionType.EXAMPLES) {
+ compatibleContribsList = properties.get(MODES_PROPERTY);
+ }
long lastUpdated;
try {
lastUpdated = Long.parseLong(properties.get("lastUpdated"));
- }
- catch (NumberFormatException nfe) {
+ } catch (NumberFormatException nfe) {
lastUpdated = getLastUpdated();
- // Better comment these out till all contribs have a lastUpdated
+ // Better comment these out till all contribs have a lastUpdated
// System.err.println("The last updated date for the “" + name
// + "” contribution is not set properly.");
// System.err
// .println("Please contact the author to fix it according to the guidelines.");
}
+ int minRev;
+ try {
+ minRev = Integer.parseInt(properties.get("minRevision"));
+ } catch (NumberFormatException e) {
+ minRev = getMinRevision();
+// System.err.println("The minimum compatible revision for the “" + name
+// + "” contribution is not set properly. Assuming minimum revision 0.");
+ }
+
+ int maxRev;
+ try {
+ maxRev = Integer.parseInt(properties.get("maxRevision"));
+ } catch (NumberFormatException e) {
+ maxRev = getMaxRevision();
+// System.err.println("The maximum compatible revision for the “" + name
+// + "” contribution is not set properly. Assuming maximum revision INF.");
+ }
+
if (propFile.delete() && propFile.createNewFile() && propFile.setWritable(true)) {
PrintWriter writer = PApplet.createWriter(propFile);
writer.println("name=" + name);
writer.println("category=" + category);
- writer.println("authorList=" + authorList);
+ writer.println(AUTHORS_PROPERTY + "=" + authors);
writer.println("url=" + url);
writer.println("sentence=" + sentence);
writer.println("paragraph=" + paragraph);
writer.println("version=" + version);
- writer.println("prettyVersion=" + prettyVersion);
+ if (prettyVersion != null) {
+ writer.println("prettyVersion=" + prettyVersion);
+ }
writer.println("lastUpdated=" + lastUpdated);
+ writer.println("minRevision=" + minRev);
+ writer.println("maxRevision=" + maxRev);
+ if ((getType() == ContributionType.LIBRARY || getType() == ContributionType.MODE) && importsList != null) {
+ writer.println("imports=" + importsList.join(","));
+ }
+ if (getType() == ContributionType.EXAMPLES) {
+ if (compatibleContribsList != null) {
+ writer.println(MODES_PROPERTY + "=" + compatibleContribsList);
+ }
+ }
writer.flush();
writer.close();
diff --git a/app/src/processing/app/contrib/ContribProgressBar.java b/app/src/processing/app/contrib/ContribProgressBar.java
new file mode 100644
index 0000000000..8a0d41c3b6
--- /dev/null
+++ b/app/src/processing/app/contrib/ContribProgressBar.java
@@ -0,0 +1,100 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2013-20 The Processing Foundation
+ Copyright (c) 2011-12 Ben Fry and Casey Reas
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 2
+ as published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU 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, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*/
+package processing.app.contrib;
+
+import java.awt.EventQueue;
+import java.lang.reflect.InvocationTargetException;
+
+import javax.swing.JProgressBar;
+
+
+// I suspect this code can mostly be replaced with built-in Swing functions.
+// This code seems like it's adapted from old example code found on the web.
+// https://github.com/processing/processing/issues/3176
+
+abstract class ContribProgressBar extends ContribProgressMonitor {
+ JProgressBar progressBar;
+
+ public ContribProgressBar(JProgressBar progressBar) {
+ this.progressBar = progressBar;
+ }
+
+ public void startTask(String name, int maxValue) {
+ finished = false;
+ progressBar.setString(name);
+ progressBar.setIndeterminate(maxValue == UNKNOWN);
+ progressBar.setMaximum(maxValue);
+ }
+
+ public void setProgress(int value) {
+ super.setProgress(value);
+ progressBar.setValue(value);
+ }
+
+ @Override
+ public final void finished() {
+ super.finished();
+ try {
+ EventQueue.invokeAndWait(new Runnable() {
+ @Override
+ public void run() {
+ finishedAction();
+ }
+ });
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ } catch (InvocationTargetException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof RuntimeException) {
+ throw (RuntimeException) cause;
+ } else {
+ cause.printStackTrace();
+ }
+ }
+ }
+
+ public abstract void finishedAction();
+
+ @Override
+ public final void cancel() {
+ super.cancel();
+ try {
+ EventQueue.invokeAndWait(new Runnable() {
+ @Override
+ public void run() {
+ cancelAction();
+ }
+ });
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ } catch (InvocationTargetException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof RuntimeException) {
+ throw (RuntimeException) cause;
+ } else {
+ cause.printStackTrace();
+ }
+ }
+ }
+
+ public void cancelAction() { }
+}
diff --git a/app/src/processing/app/contrib/ContribProgressMonitor.java b/app/src/processing/app/contrib/ContribProgressMonitor.java
new file mode 100644
index 0000000000..4c897e22ae
--- /dev/null
+++ b/app/src/processing/app/contrib/ContribProgressMonitor.java
@@ -0,0 +1,78 @@
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2013-15 The Processing Foundation
+ Copyright (c) 2011-12 Ben Fry and Casey Reas
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 2
+ as published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU 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, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*/
+package processing.app.contrib;
+
+
+// I suspect this code can mostly be replaced with built-in Swing functions.
+// This code seems like it's adapted from old example code found on the web.
+// https://github.com/processing/processing/issues/3176
+
+public abstract class ContribProgressMonitor {
+ static final int UNKNOWN = -1;
+ boolean canceled = false;
+ boolean error = false;
+ boolean finished = false;
+ Exception exception;
+ int max;
+ int progress = 0;
+
+ public void startTask(String name, int maxValue) {
+ }
+
+ public void setProgress(int value) {
+ progress = value;
+ }
+
+ public int getProgress() {
+ return progress;
+ }
+
+ public boolean isCanceled() {
+ return canceled;
+ }
+
+ public void cancel() {
+ canceled = true;
+ }
+
+ public boolean isError() {
+ return error;
+ }
+
+ public Exception getException() {
+ return exception;
+ }
+
+ public void error(Exception e) {
+ error = true;
+ exception = e;
+ }
+
+ public boolean isFinished() {
+ return finished;
+ }
+
+ public void finished() {
+ finished = true;
+ }
+}
+
diff --git a/app/src/processing/app/contrib/Contribution.java b/app/src/processing/app/contrib/Contribution.java
index 451ab7d4e3..aa401375e6 100644
--- a/app/src/processing/app/contrib/Contribution.java
+++ b/app/src/processing/app/contrib/Contribution.java
@@ -1,198 +1,394 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2013 The Processing Foundation
- Copyright (c) 2011-12 Ben Fry and Casey Reas
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License version 2
- as published by the Free Software Foundation.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU 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, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-package processing.app.contrib;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import processing.app.Language;
-import processing.core.PApplet;
-
-
-abstract public class Contribution {
- static final List validCategories =
- Arrays.asList("3D", "Animation", "Data", "Geometry", "GUI", "Hardware",
- "I/O", "Math", "Simulation", "Sound", "Typography",
- "Utilities", "Video & Vision", "Other");
-
- //protected String category; // "Sound"
- protected List categories; // "Sound", "Typography"
- protected String name; // "pdf" or "PDF Export"
- protected String authorList; // Ben Fry
- protected String url; // http://processing.org
- protected String sentence; // Write graphics to PDF files.
- protected String paragraph; //
- protected int version; // 102
- protected String prettyVersion; // "1.0.2"
- protected long lastUpdated; // 1402805757
-
-
- // "Sound"
-// public String getCategory() {
-// return category;
-// }
-
-
- // "Sound", "Utilities"... see valid list in ContributionListing
- protected List getCategories() {
- return categories;
- }
-
-
- protected String getCategoryStr() {
- StringBuilder sb = new StringBuilder();
- for (String category : categories) {
- sb.append(category);
- sb.append(',');
- }
- sb.deleteCharAt(sb.length()-1); // delete last comma
- return sb.toString();
- }
-
-
- protected boolean hasCategory(String category) {
- if (category != null) {
- for (String c : categories) {
- if (category.equalsIgnoreCase(c)) {
- return true;
- }
- }
- }
- return false;
- }
-
-
- // "pdf" or "PDF Export"
- public String getName() {
- return name;
- }
-
-
- // "[Ben Fry](http://benfry.com/)"
- public String getAuthorList() {
- return authorList;
- }
-
-
- // "http://processing.org"
- public String getUrl() {
- return url;
- }
-
-
- // "Write graphics to PDF files."
- public String getSentence() {
- return sentence;
- }
-
-
- //
- public String getParagraph() {
- return paragraph;
- }
-
-
- // 102
- public int getVersion() {
- return version;
- }
-
-
- // "1.0.2"
- public String getPrettyVersion() {
- return prettyVersion;
- }
-
- // 1402805757
- public long getLastUpdated() {
- return lastUpdated;
- }
-
-
- abstract public ContributionType getType();
-
-
- public String getTypeName() {
- return getType().toString();
- }
-
-
- abstract public boolean isInstalled();
-
-
-// /**
-// * Returns true if the type of contribution requires the PDE to restart
-// * when being added or removed.
-// */
-// public boolean requiresRestart() {
-// return getType() == ContributionType.TOOL || getType() == ContributionType.MODE;
-// }
-
-
- boolean isRestartFlagged() {
- return false;
- }
-
-
- /** Overridden by LocalContribution. */
- boolean isDeletionFlagged() {
- return false;
- }
-
-
- boolean isUpdateFlagged() {
- return false;
- }
-
-
- /**
- * @return a single element list with "Unknown" as the category.
- */
- static List defaultCategory() {
- List outgoing = new ArrayList();
- outgoing.add("Unknown");
- return outgoing;
- }
-
-
- /**
- * @return the list of categories that this contribution is part of
- * (e.g. "Typography / Geometry"). "Unknown" if the category null.
- */
- static List parseCategories(String categoryStr) {
- List outgoing = new ArrayList();
-
- if (categoryStr != null) {
- String[] listing = PApplet.trim(PApplet.split(categoryStr, ','));
- for (String category : listing) {
- if (validCategories.contains(category)) {
- outgoing.add(category);
- }
- }
- }
- if (outgoing.size() == 0) {
- return defaultCategory();
- }
- return outgoing;
- }
-}
+/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Processing project - http://processing.org
+
+ Copyright (c) 2013-16 The Processing Foundation
+ Copyright (c) 2011-12 Ben Fry and Casey Reas
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License version 2
+ as published by the Free Software Foundation.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU 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, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*/
+package processing.app.contrib;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.List;
+
+import processing.core.PApplet;
+import processing.data.StringDict;
+import processing.data.StringList;
+import processing.app.Language;
+import processing.app.Util;
+
+
+abstract public class Contribution {
+ static final String IMPORTS_PROPERTY = "imports";
+ static final String CATEGORIES_PROPERTY = "categories";
+ static final String MODES_PROPERTY = "modes";
+ static final String AUTHORS_PROPERTY = "authors";
+
+ static final String SPECIAL_CATEGORY = "Starred";
+ static final String UNKNOWN_CATEGORY = "Unknown";
+ static final List validCategories =
+ Arrays.asList("3D", "Animation", "Data", "Geometry", "GUI", "Hardware",
+ "I/O", "Math", "Simulation", "Sound", SPECIAL_CATEGORY,
+ "Typography", "Utilities", "Video & Vision", "Other");
+
+ static final String FOUNDATION_AUTHOR = "The Processing Foundation";
+
+ protected StringList categories; // "Sound", "Typography"
+ protected String name; // "pdf" or "PDF Export"
+ protected String authors; // [Ben Fry](http://benfry.com)
+ protected String url; // http://processing.org
+ protected String sentence; // Write graphics to PDF files.
+ protected String paragraph; //
+ protected int version; // 102
+ protected String prettyVersion; // "1.0.2"
+ protected long lastUpdated; // 1402805757
+ protected int minRevision; // 0
+ protected int maxRevision; // 227
+ protected StringList imports; // pdf.export,pdf.convert.common (list of packages, not imports)
+
+
+ // "Sound", "Utilities"... see valid list in ContributionListing
+ protected StringList getCategories() {
+ return categories;
+ }
+
+
+ protected String getCategoryStr() {
+ StringBuilder sb = new StringBuilder();
+ for (String category : categories) {
+ sb.append(category);
+ sb.append(',');
+ }
+ sb.deleteCharAt(sb.length()-1); // delete last comma
+ return sb.toString();
+ }
+
+
+ protected boolean hasCategory(String category) {
+ if (category != null) {
+ for (String c : categories) {
+ if (category.equalsIgnoreCase(c)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+
+ // pdf.export.*,pdf.convert.common.*
+ protected StringList getImports() {
+ return imports;
+ }
+
+/*
+ protected String getImportStr() {
+ if (imports == null || imports.isEmpty()) {
+ return "";
+ }
+ StringBuilder sb = new StringBuilder();
+ for (String importName : imports) {
+ sb.append(importName);
+ sb.append(',');
+ }
+ sb.deleteCharAt(sb.length() - 1); // delete last comma
+ return sb.toString();
+ }
+*/
+
+ protected boolean hasImport(String importName) {
+ if (imports != null && importName != null) {
+ for (String c : imports) {
+ if (importName.equals(c)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+
+ // "pdf" or "PDF Export"
+ public String getName() {
+ return name;
+ }
+
+
+ // "[Ben Fry](http://benfry.com/)"
+ public String getAuthorList() {
+ return authors;
+ }
+
+
+ // "http://processing.org"
+ public String getUrl() {
+ return url;
+ }
+
+
+ // "Write graphics to PDF files."
+ public String getSentence() {
+ return sentence;
+ }
+
+
+ //
+ public String getParagraph() {
+ return paragraph;
+ }
+
+
+ // 102
+ public int getVersion() {
+ return version;
+ }
+
+
+ public void setPrettyVersion(String pretty) {
+ if (pretty != null) {
+ // some entries were written as "null", causing that to show in the ui
+ if (pretty.equals("null") || pretty.length() == 0) {
+ pretty = null;
+ }
+ }
+ prettyVersion = pretty;
+ }
+
+
+ // "1.0.2" or null if not present
+ public String getPrettyVersion() {
+ return prettyVersion;
+ }
+
+
+ // returns prettyVersion, or "" if null
+ public String getBenignVersion() {
+ return (prettyVersion != null) ? prettyVersion : "";
+ }
+
+
+ // 1402805757
+ public long getLastUpdated() {
+ return lastUpdated;
+ }
+
+
+ // 0
+ public int getMinRevision() {
+ return minRevision;
+ }
+
+
+ // 227
+ public int getMaxRevision() {
+ return maxRevision;
+ }
+
+
+ public boolean isCompatible(int versionNum) {
+ return ((maxRevision == 0 || versionNum <= maxRevision) && versionNum >= minRevision);
+ }
+
+
+ abstract public ContributionType getType();
+
+
+ public String getTypeName() {
+ return getType().toString();
+ }
+
+
+ abstract public boolean isInstalled();
+
+
+// /**
+// * Returns true if the type of contribution requires the PDE to restart
+// * when being added or removed.
+// */
+// public boolean requiresRestart() {
+// return getType() == ContributionType.TOOL || getType() == ContributionType.MODE;
+// }
+
+
+ boolean isRestartFlagged() {
+ return false;
+ }
+
+
+ /** Overridden by LocalContribution. */
+ boolean isDeletionFlagged() {
+ return false;
+ }
+
+
+ boolean isUpdateFlagged() {
+ return false;
+ }
+
+
+ /**
+ * Returns true if the contribution is a starred/recommended contribution,
+ * or is by the Processing Foundation.
+ */
+ boolean isSpecial() {
+ if (authors != null &&
+ authors.contains(FOUNDATION_AUTHOR)) {
+ return true;
+ }
+
+ if (categories != null &&
+ categories.hasValue(SPECIAL_CATEGORY)) {
+ return true;
+ }
+
+ return false;
+ }
+
+
+ public boolean isFoundation() {
+ return FOUNDATION_AUTHOR.equals(authors);
+ }
+
+
+ public StringDict loadProperties(File contribFolder) {
+ return loadProperties(contribFolder, getType());
+ }
+
+
+ static public StringDict loadProperties(File contribFolder,
+ ContributionType type) {
+ File propertiesFile = new File(contribFolder, type.getPropertiesName());
+ if (propertiesFile.exists()) {
+ return Util.readSettings(propertiesFile);
+ }
+ return null;
+ }
+
+ /**
+ * @return a single element list with "Unknown" as the category.
+ */
+ static StringList unknownCategoryList() {
+ return new StringList(UNKNOWN_CATEGORY);
+ }
+
+
+ /**
+ * @return the list of categories that this contribution is part of
+ * (e.g. "Typography / Geometry"). "Unknown" if the category null.
+ */
+ static StringList parseCategories(StringDict properties) {
+ StringList outgoing = new StringList();
+
+ String categoryStr = properties.get(CATEGORIES_PROPERTY);
+ if (categoryStr == null) {
+ categoryStr = properties.get("category"); // try the old way
+ }
+ if (categoryStr != null) {
+ // Can't use splitTokens() because the names sometimes have spaces
+ String[] listing = PApplet.trim(PApplet.split(categoryStr, ','));
+ for (String category : listing) {
+ if (validCategories.contains(category)) {
+ category = translateCategory(category);
+ outgoing.append(category);
+ }
+ }
+ }
+ if (outgoing.size() == 0) {
+ return unknownCategoryList();
+ }
+ return outgoing;
+ }
+
+
+ /**
+ * Returns the list of imports specified by this library author. Only
+ * necessary for library authors that want to override the default behavior
+ * of importing all packages in their library.
+ * @return null if no entries found
+ */
+ static StringList parseImports(StringDict properties) {
+ StringList outgoing = new StringList();
+
+ String importStr = properties.get(IMPORTS_PROPERTY);
+ if (importStr != null) {
+ String[] importList = PApplet.trim(PApplet.split(importStr, ','));
+ for (String importName : importList) {
+ if (!importName.isEmpty()) {
+ outgoing.append(importName);
+ }
+ }
+ }
+ return (outgoing.size() > 0) ? outgoing : null;
+ }
+
+
+ /**
+ * Helper function that creates a StringList of the compatible Modes
+ * for this Contribution.
+ */
+ static StringList parseModeList(StringDict properties) {
+ String unparsedModes = properties.get(MODES_PROPERTY);
+
+ // Workaround for 3.0 alpha/beta bug for 3.0b2
+ if ("null".equals(unparsedModes)) {
+ properties.remove(MODES_PROPERTY);
+ unparsedModes = null;
+ }
+
+ StringList outgoing = new StringList();
+ if (unparsedModes != null) {
+ outgoing.append(PApplet.trim(PApplet.split(unparsedModes, ',')));
+ }
+ return outgoing;
+ }
+
+
+ static private String translateCategory(String cat) {
+ // Converts Other to other, I/O to i_o, Video & Vision to video_vision
+ String cleaned = cat.replaceAll("[\\W]+", "_").toLowerCase();
+ return Language.text("contrib.category." + cleaned);
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+
+ if (o instanceof Contribution) {
+ Contribution that = (Contribution) o;
+ return name.toLowerCase().equals(that.name.toLowerCase());
+ }
+ return false;
+ }
+
+
+ @Override
+ public int hashCode() {
+ return name.toLowerCase().hashCode();
+ }
+
+
+ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
+
+
+ public interface Filter {
+ boolean matches(Contribution contrib);
+ }
+}
diff --git a/app/src/processing/app/contrib/ContributionChangeListener.java b/app/src/processing/app/contrib/ContributionChangeListener.java
deleted file mode 100644
index 66283e50bc..0000000000
--- a/app/src/processing/app/contrib/ContributionChangeListener.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2013 The Processing Foundation
- Copyright (c) 2011-12 Ben Fry and Casey Reas
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License version 2
- as published by the Free Software Foundation.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU 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, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-package processing.app.contrib;
-
-
-public interface ContributionChangeListener {
- public void contributionAdded(Contribution Contribution);
- public void contributionRemoved(Contribution Contribution);
- public void contributionChanged(Contribution oldLib, Contribution newLib);
-}
diff --git a/app/src/processing/app/contrib/ContributionFilter.java b/app/src/processing/app/contrib/ContributionFilter.java
deleted file mode 100644
index 0419b7a69a..0000000000
--- a/app/src/processing/app/contrib/ContributionFilter.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package processing.app.contrib;
-
-interface ContributionFilter {
- boolean matches(Contribution contrib);
-}
\ No newline at end of file
diff --git a/app/src/processing/app/contrib/ContributionListPanel.java b/app/src/processing/app/contrib/ContributionListPanel.java
deleted file mode 100644
index 0a4c0ed8a8..0000000000
--- a/app/src/processing/app/contrib/ContributionListPanel.java
+++ /dev/null
@@ -1,344 +0,0 @@
-/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
-
-/*
- Part of the Processing project - http://processing.org
-
- Copyright (c) 2013 The Processing Foundation
- Copyright (c) 2011-12 Ben Fry and Casey Reas
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License version 2
- as published by the Free Software Foundation.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU 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, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-package processing.app.contrib;
-
-import java.util.*;
-import java.util.List;
-import java.util.Map.Entry;
-
-import javax.swing.*;
-import javax.swing.border.*;
-import javax.swing.event.*;
-
-import java.awt.*;
-
-import processing.app.Base;
-
-
-// The "Scrollable" implementation and its methods here take care of preventing
-// the scrolling area from running exceptionally slowly. Not sure why they're
-// necessary in the first place, however; seems like odd behavior.
-// It also allows the description text in the panels to wrap properly.
-
-public class ContributionListPanel extends JPanel implements Scrollable, ContributionChangeListener {
-
- ContributionManagerDialog contribManager;
- TreeMap panelByContribution;
-
- static HyperlinkListener nullHyperlinkListener = new HyperlinkListener() {
- public void hyperlinkUpdate(HyperlinkEvent e) { }
- };
-
- private ContributionPanel selectedPanel;
-// protected JPanel statusPlaceholder;
- private StatusPanel status;
- private ContributionFilter filter;
-// private ContributionListing contribListing;
- private ContributionListing contribListing = ContributionListing.getInstance();
-
-
- public ContributionListPanel(ContributionManagerDialog libraryManager,
- ContributionFilter filter) {
- super();
- this.contribManager = libraryManager;
- this.filter = filter;
-
-// contribListing = ContributionListing.getInstance();
-
- setLayout(new GridBagLayout());
- setOpaque(true);
-
- if (Base.isLinux()) {
- // Because of a bug with GNOME, getColor returns the wrong value for
- // List.background. We'll just assume its white. The number of people
- // using Linux and an inverted color theme should be small enough.
- setBackground(Color.white);
- } else {
- setBackground(UIManager.getColor("List.background"));
- }
-
- panelByContribution = new TreeMap(
- contribListing.getComparator());
-
-// statusPlaceholder = new JPanel();
-// statusPlaceholder.setVisible(false);
- status = new StatusPanel();
- }
-
-
- private void updatePanelOrdering() {
- int row = 0;
- for (Entry entry : panelByContribution.entrySet()) {
- GridBagConstraints c = new GridBagConstraints();
- c.fill = GridBagConstraints.HORIZONTAL;
- c.weightx = 1;
- c.gridx = 0;
- c.gridy = row++;
- c.anchor = GridBagConstraints.NORTH;
-
- add(entry.getValue(), c);
- }
-
- GridBagConstraints c = new GridBagConstraints();
- c.fill = GridBagConstraints.BOTH;
- c.weightx = 1;
- c.weighty = 1;
- c.gridx = 0;
- c.gridy = row++;
- c.anchor = GridBagConstraints.NORTH;
- add(status, c);
- }
-
-
-// static int inc;
-
- public void contributionAdded(final Contribution contribution) {
-// new Exception().printStackTrace();
- if (filter.matches(contribution)) {
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- if (!panelByContribution.containsKey(contribution)) {
- ContributionPanel newPanel = new ContributionPanel(ContributionListPanel.this);
- synchronized (panelByContribution) {
- panelByContribution.put(contribution, newPanel);
- }
- if (newPanel != null) {
-// System.out.println("ContributionListPanel.contributionAdded(" + contribution.getName() + ")");
- newPanel.setContribution(contribution);
- add(newPanel);
- updatePanelOrdering();
-// PrintWriter writer = PApplet.createWriter(new File("/Users/fry/Desktop/traces/" + PApplet.nf(++inc, 4) + ".txt"));
-// new Exception().printStackTrace(writer);
-// writer.flush();
-// writer.close();
- updateColors(); // XXX this is the place
- }
- }
- }
- });
- }
- }
-
-
- public void contributionRemoved(final Contribution contribution) {
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- synchronized (panelByContribution) {
- ContributionPanel panel = panelByContribution.get(contribution);
- if (panel != null) {
- remove(panel);
- panelByContribution.remove(contribution);
- }
- }
- updatePanelOrdering();
- updateColors();
- updateUI();
- }
- });
- }
-
-
- public void contributionChanged(final Contribution oldContrib,
- final Contribution newContrib) {
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- synchronized (panelByContribution) {
- ContributionPanel panel = panelByContribution.get(oldContrib);
- if (panel == null) {
- contributionAdded(newContrib);
- } else {
- panelByContribution.remove(oldContrib);
- panel.setContribution(newContrib);
- panelByContribution.put(newContrib, panel);
- updatePanelOrdering();
- }
- }
- }
- });
- }
-
-
- public void filterLibraries(List filteredContributions) {
- synchronized (panelByContribution) {
- Set hiddenPanels = new TreeSet(contribListing.getComparator());
- hiddenPanels.addAll(panelByContribution.keySet());
-
- for (Contribution info : filteredContributions) {
- ContributionPanel panel = panelByContribution.get(info);
- if (panel != null) {
- panel.setVisible(true);
- hiddenPanels.remove(info);
- }
- }
-
- for (Contribution info : hiddenPanels) {
- ContributionPanel panel = panelByContribution.get(info);
- if (panel != null) {
- panel.setVisible(false);
- }
- }
- }
- }
-
-
- protected void setSelectedPanel(ContributionPanel panel) {
- if (selectedPanel == panel) {
- selectedPanel.setSelected(true);
- } else {
- ContributionPanel lastSelected = selectedPanel;
- selectedPanel = panel;
-
- if (lastSelected != null) {
- lastSelected.setSelected(false);
- }
- panel.setSelected(true);
-
- updateColors();
- requestFocusInWindow();
- }
- }
-
-
- protected ContributionPanel getSelectedPanel() {
- return selectedPanel;
- }
-
-
- /**
- * Updates the colors of all library panels that are visible.
- */
- protected void updateColors() {
- int count = 0;
- synchronized (panelByContribution) {
- for (Entry entry : panelByContribution.entrySet()) {
- ContributionPanel panel = entry.getValue();
-
- if (panel.isVisible() && panel.isSelected()) {
- panel.setBackground(UIManager.getColor("List.selectionBackground"));
- panel.setForeground(UIManager.getColor("List.selectionForeground"));
- panel.setBorder(UIManager.getBorder("List.focusCellHighlightBorder"));
- count++;
-
- } else {
- Border border = null;
- if (panel.isVisible()) {
- if (Base.isMacOS()) {
- if (count % 2 == 1) {
- border = UIManager.getBorder("List.oddRowBackgroundPainter");
- } else {
- border = UIManager.getBorder("List.evenRowBackgroundPainter");
- }
- } else {
- if (count % 2 == 1) {
- panel.setBackground(new Color(219, 224, 229));
- } else {
- panel.setBackground(new Color(241, 241, 241));
- }
- }
- count++;
- }
-
- if (border == null) {
- border = BorderFactory.createEmptyBorder(1, 1, 1, 1);
- }
- panel.setBorder(border);
- panel.setForeground(UIManager.getColor("List.foreground"));
- }
- }
- }
- }
-
-
- public Dimension getPreferredScrollableViewportSize() {
- return getPreferredSize();
- }
-
-
- /**
- * Amount to scroll to reveal a new page of items
- */
- public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
- if (orientation == SwingConstants.VERTICAL) {
- int blockAmount = visibleRect.height;
- if (direction > 0) {
- visibleRect.y += blockAmount;
- } else {
- visibleRect.y -= blockAmount;
- }
-
- blockAmount += getScrollableUnitIncrement(visibleRect, orientation, direction);
- return blockAmount;
- }
- return 0;
- }
-
-
- /**
- * Amount to scroll to reveal the rest of something we are on or a new item
- */
- public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
- if (orientation == SwingConstants.VERTICAL) {
- int lastHeight = 0, height = 0;
- int bottomOfScrollArea = visibleRect.y + visibleRect.height;
-
- for (Component c : getComponents()) {
- if (c.isVisible()) {
- if (c instanceof ContributionPanel) {
- Dimension d = c.getPreferredSize();
-
- int nextHeight = height + d.height;
-
- if (direction > 0) {
- // scrolling down
- if (nextHeight > bottomOfScrollArea) {
- return nextHeight - bottomOfScrollArea;
- }
- } else {
- // scrolling up
- if (nextHeight > visibleRect.y) {
- if (visibleRect.y != height) {
- return visibleRect.y - height;
- } else {
- return visibleRect.y - lastHeight;
- }
- }
- }
-
- lastHeight = height;
- height = nextHeight;
- }
- }
- }
- }
- return 0;
- }
-
-
- public boolean getScrollableTracksViewportHeight() {
- return false;
- }
-
-
- public boolean getScrollableTracksViewportWidth() {
- return true;
- }
-}
diff --git a/app/src/processing/app/contrib/ContributionListing.java b/app/src/processing/app/contrib/ContributionListing.java
index 083f856856..6f35ca3fd7 100644
--- a/app/src/processing/app/contrib/ContributionListing.java
+++ b/app/src/processing/app/contrib/ContributionListing.java
@@ -3,7 +3,7 @@
/*
Part of the Processing project - http://processing.org
- Copyright (c) 2013 The Processing Foundation
+ Copyright (c) 2013-16 The Processing Foundation
Copyright (c) 2011-12 Ben Fry and Casey Reas
This program is free software; you can redistribute it and/or modify
@@ -21,48 +21,62 @@
*/
package processing.app.contrib;
+import java.awt.EventQueue;
import java.io.*;
+import java.lang.reflect.InvocationTargetException;
import java.net.*;
+import java.text.Normalizer;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
+import java.util.regex.Pattern;
import processing.app.Base;
import processing.app.Library;
+import processing.app.Util;
import processing.core.PApplet;
+import processing.data.StringDict;
public class ContributionListing {
- // Stable URL that will redirect to wherever we're hosting the file
- static final String LISTING_URL =
- "http://download.processing.org/contributions.txt";
-
static volatile ContributionListing singleInstance;
+ /** Stable URL that will redirect to wherever the file is hosted */
+ static final String LISTING_URL = "http://download.processing.org/contribs";
+ static final String LOCAL_FILENAME = "contribs.txt";
+
+ /** Location of the listing file on disk, will be read and written. */
File listingFile;
- ArrayList listeners;
- ArrayList advertisedContributions;
+
+ List listeners;
+ List advertisedContributions;
Map> librariesByCategory;
- ArrayList allContributions;
- boolean hasDownloadedLatestList;
+ Map librariesByImportHeader;
+ // TODO: Every contribution is getting added twice
+ // and nothing is replaced ever.
+ Set allContributions;
+ boolean listDownloaded;
+ boolean listDownloadFailed;
ReentrantLock downloadingListingLock;
private ContributionListing() {
- listeners = new ArrayList();
- advertisedContributions = new ArrayList();
- librariesByCategory = new HashMap>();
- allContributions = new ArrayList();
+ listeners = new ArrayList<>();
+ advertisedContributions = new ArrayList<>();
+ librariesByCategory = new HashMap<>();
+ librariesByImportHeader = new HashMap<>();
+ allContributions = new LinkedHashSet<>();
downloadingListingLock = new ReentrantLock();
- listingFile = Base.getSettingsFile("contributions.txt");
- listingFile.setWritable(true);
+ //listingFile = Base.getSettingsFile("contributions.txt");
+ listingFile = Base.getSettingsFile(LOCAL_FILENAME);
+ listingFile.setWritable(true, false);
if (listingFile.exists()) {
setAdvertisedList(listingFile);
}
}
- static ContributionListing getInstance() {
+ static public ContributionListing getInstance() {
if (singleInstance == null) {
synchronized (ContributionListing.class) {
if (singleInstance == null) {
@@ -74,7 +88,7 @@ static ContributionListing getInstance() {
}
- void setAdvertisedList(File file) {
+ private void setAdvertisedList(File file) {
listingFile = file;
advertisedContributions.clear();
@@ -82,7 +96,6 @@ void setAdvertisedList(File file) {
for (Contribution contribution : advertisedContributions) {
addContribution(contribution);
}
- Collections.sort(allContributions, nameComparator);
}
@@ -90,8 +103,8 @@ void setAdvertisedList(File file) {
* Adds the installed libraries to the listing of libraries, replacing any
* pre-existing libraries by the same name as one in the list.
*/
- protected void updateInstalledList(List installedContributions) {
- for (Contribution contribution : installedContributions) {
+ protected void updateInstalledList(List installed) {
+ for (Contribution contribution : installed) {
Contribution existingContribution = getContribution(contribution);
if (existingContribution != null) {
replaceContribution(existingContribution, contribution);
@@ -117,32 +130,41 @@ protected void replaceContribution(Contribution oldLib, Contribution newLib) {
}
}
- for (int i = 0; i < allContributions.size(); i++) {
- if (allContributions.get(i) == oldLib) {
- allContributions.set(i, newLib);
+ if (oldLib.getImports() != null) {
+ for (String importName : oldLib.getImports()) {
+ if (getLibrariesByImportHeader().containsKey(importName)) {
+ getLibrariesByImportHeader().put(importName, newLib);
+ }
}
}
+ allContributions.remove(oldLib);
+ allContributions.add(newLib);
+
notifyChange(oldLib, newLib);
}
}
private void addContribution(Contribution contribution) {
+ if (contribution.getImports() != null) {
+ for (String importName : contribution.getImports()) {
+ getLibrariesByImportHeader().put(importName, contribution);
+ }
+ }
for (String category : contribution.getCategories()) {
if (librariesByCategory.containsKey(category)) {
List list = librariesByCategory.get(category);
list.add(contribution);
- Collections.sort(list, nameComparator);
+ Collections.sort(list, COMPARATOR);
} else {
- ArrayList list = new ArrayList();
+ ArrayList list = new ArrayList<>();
list.add(contribution);
librariesByCategory.put(category, list);
}
allContributions.add(contribution);
notifyAdd(contribution);
- Collections.sort(allContributions, nameComparator);
}
}
@@ -153,6 +175,11 @@ protected void removeContribution(Contribution contribution) {
librariesByCategory.get(category).remove(contribution);
}
}
+ if (contribution.getImports() != null) {
+ for (String importName : contribution.getImports()) {
+ getLibrariesByImportHeader().remove(importName);
+ }
+ }
allContributions.remove(contribution);
notifyRemove(contribution);
}
@@ -170,20 +197,20 @@ private Contribution getContribution(Contribution contribution) {
protected AvailableContribution getAvailableContribution(Contribution info) {
- Iterator iter = advertisedContributions.iterator();
- while(iter.hasNext()) {
- AvailableContribution advertised = iter.next();
- if (advertised.getType() == info.getType() &&
- advertised.getName().equals(info.getName())) {
- return advertised;
+ synchronized (advertisedContributions) {
+ for (AvailableContribution advertised : advertisedContributions) {
+ if (advertised.getType() == info.getType() &&
+ advertised.getName().equals(info.getName())) {
+ return advertised;
+ }
}
}
return null;
}
- protected Set getCategories(ContributionFilter filter) {
- Set outgoing = new HashSet();
+ protected Set getCategories(Contribution.Filter filter) {
+ Set outgoing = new HashSet<>();
Set categorySet = librariesByCategory.keySet();
for (String categoryName : categorySet) {
@@ -191,7 +218,7 @@ protected Set getCategories(ContributionFilter filter) {
if (filter.matches(contrib)) {
// TODO still not sure why category would be coming back null [fry]
// http://code.google.com/p/processing/issues/detail?id=1387
- if (categoryName != null && categoryName.trim().length() != 0) {
+ if (categoryName != null && !categoryName.trim().isEmpty()) {
outgoing.add(categoryName);
}
break;
@@ -202,47 +229,11 @@ protected Set getCategories(ContributionFilter filter) {
}
-// public List getAllContributions() {
-// return new ArrayList(allContributions);
-// }
-
-
-// public List