Search in sources :

Example 6 with StringList

use of processing.data.StringList in project processing by processing.

the class Contribution method parseCategories.

/**
   * @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) {
        // try the old way
        categoryStr = properties.get("category");
    }
    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;
}
Also used : StringList(processing.data.StringList)

Example 7 with StringList

use of processing.data.StringList in project processing by processing.

the class JavaBuild method preprocess.

/**
   * @param srcFolder location where the .java source files will be placed
   * @param packageName null, or the package name that should be used as default
   * @param preprocessor the preprocessor object ready to do the work
   * @return main PApplet class name found during preprocess, or null if error
   * @throws SketchException
   */
public String preprocess(File srcFolder, String packageName, PdePreprocessor preprocessor, boolean sizeWarning) throws SketchException {
    // make sure the user isn't playing "hide the sketch folder"
    sketch.ensureExistence();
    //    System.out.println("srcFolder is " + srcFolder);
    classPath = binFolder.getAbsolutePath();
    // figure out the contents of the code folder to see if there
    // are files that need to be added to the imports
    StringList codeFolderPackages = null;
    if (sketch.hasCodeFolder()) {
        File codeFolder = sketch.getCodeFolder();
        javaLibraryPath = codeFolder.getAbsolutePath();
        // get a list of .jar files in the "code" folder
        // (class files in subfolders should also be picked up)
        String codeFolderClassPath = Util.contentsToClassPath(codeFolder);
        // append the jar files in the code folder to the class path
        classPath += File.pathSeparator + codeFolderClassPath;
        // get list of packages found in those jars
        codeFolderPackages = Util.packageListFromClassPath(codeFolderClassPath);
    } else {
        javaLibraryPath = "";
    }
    // 1. concatenate all .pde files to the 'main' pde
    //    store line number for starting point of each code bit
    StringBuilder bigCode = new StringBuilder();
    int bigCount = 0;
    for (SketchCode sc : sketch.getCode()) {
        if (sc.isExtension("pde")) {
            sc.setPreprocOffset(bigCount);
            bigCode.append(sc.getProgram());
            bigCode.append('\n');
            bigCount += sc.getLineCount();
        }
    }
    // initSketchSize() sets the internal sketchWidth/Height/Renderer vars
    // in the preprocessor. Those are used in preproc.write() so that they
    // can be used to add methods (settings() or sketchXxxx())
    //String[] sizeParts =
    SurfaceInfo sizeInfo = preprocessor.initSketchSize(sketch.getMainProgram(), sizeWarning);
    if (sizeInfo == null) {
        // An error occurred while trying to pull out the size, so exit here
        return null;
    }
    // by writeFooter() when it emits the settings() method.
    if (sizeInfo != null && sizeInfo.hasSettings()) {
        //      String sizeStatement = sizeInfo.getStatement();
        for (String stmt : sizeInfo.getStatements()) {
            //System.out.format("size stmt is '%s'%n", sizeStatement);
            // Don't remove newlines (and while you're at it, just keep spaces)
            // https://github.com/processing/processing/issues/3654
            stmt = stmt.trim();
            int index = bigCode.indexOf(stmt);
            if (index != -1) {
                bigCode.delete(index, index + stmt.length());
            } else {
                // TODO remove once we hit final; but prevent an exception like in
                // https://github.com/processing/processing/issues/3531
                System.err.format("Error removing '%s' from the code.", stmt);
            }
        }
    }
    PreprocessorResult result;
    try {
        File outputFolder = (packageName == null) ? srcFolder : new File(srcFolder, packageName.replace('.', '/'));
        outputFolder.mkdirs();
        //      Base.openFolder(outputFolder);
        final File java = new File(outputFolder, sketch.getName() + ".java");
        final PrintWriter stream = new PrintWriter(new FileWriter(java));
        try {
            result = preprocessor.write(stream, bigCode.toString(), codeFolderPackages);
        } finally {
            stream.close();
        }
    } catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
        String msg = "Build folder disappeared or could not be written";
        throw new SketchException(msg);
    } catch (antlr.RecognitionException re) {
        // re also returns a column that we're not bothering with for now
        // first assume that it's the main file
        //      int errorFile = 0;
        int errorLine = re.getLine() - 1;
        // then search through for anyone else whose preprocName is null,
        // since they've also been combined into the main pde.
        int errorFile = findErrorFile(errorLine);
        //      System.out.println("error line is " + errorLine + ", file is " + errorFile);
        errorLine -= sketch.getCode(errorFile).getPreprocOffset();
        //      System.out.println("  preproc offset for that file: " + sketch.getCode(errorFile).getPreprocOffset());
        //      System.out.println("i found this guy snooping around..");
        //      System.out.println("whatcha want me to do with 'im boss?");
        //      System.out.println(errorLine + " " + errorFile + " " + code[errorFile].getPreprocOffset());
        String msg = re.getMessage();
        if (msg.contains("expecting RCURLY")) {
            // useful for other similar situations).
            throw new SketchException("Found one too many { characters " + "without a } to match it.", errorFile, errorLine, re.getColumn(), false);
        }
        if (msg.contains("expecting LCURLY")) {
            System.err.println(msg);
            String suffix = ".";
            String[] m = PApplet.match(msg, "found ('.*')");
            if (m != null) {
                suffix = ", not " + m[1] + ".";
            }
            throw new SketchException("Was expecting a { character" + suffix, errorFile, errorLine, re.getColumn(), false);
        }
        if (msg.indexOf("expecting RBRACK") != -1) {
            System.err.println(msg);
            throw new SketchException("Syntax error, " + "maybe a missing ] character?", errorFile, errorLine, re.getColumn(), false);
        }
        if (msg.indexOf("expecting SEMI") != -1) {
            System.err.println(msg);
            throw new SketchException("Syntax error, " + "maybe a missing semicolon?", errorFile, errorLine, re.getColumn(), false);
        }
        if (msg.indexOf("expecting RPAREN") != -1) {
            System.err.println(msg);
            throw new SketchException("Syntax error, " + "maybe a missing right parenthesis?", errorFile, errorLine, re.getColumn(), false);
        }
        if (msg.indexOf("preproc.web_colors") != -1) {
            throw new SketchException("A web color (such as #ffcc00) " + "must be six digits.", errorFile, errorLine, re.getColumn(), false);
        }
        //System.out.println("msg is " + msg);
        throw new SketchException(msg, errorFile, errorLine, re.getColumn(), false);
    } catch (antlr.TokenStreamRecognitionException tsre) {
        // while this seems to store line and column internally,
        // there doesn't seem to be a method to grab it..
        // so instead it's done using a regexp
        //      System.err.println("and then she tells me " + tsre.toString());
        // TODO not tested since removing ORO matcher.. ^ could be a problem
        String mess = "^line (\\d+):(\\d+):\\s";
        String[] matches = PApplet.match(tsre.toString(), mess);
        if (matches != null) {
            int errorLine = Integer.parseInt(matches[1]) - 1;
            int errorColumn = Integer.parseInt(matches[2]);
            int errorFile = 0;
            for (int i = 1; i < sketch.getCodeCount(); i++) {
                SketchCode sc = sketch.getCode(i);
                if (sc.isExtension("pde") && (sc.getPreprocOffset() < errorLine)) {
                    errorFile = i;
                }
            }
            errorLine -= sketch.getCode(errorFile).getPreprocOffset();
            throw new SketchException(tsre.getMessage(), errorFile, errorLine, errorColumn);
        } else {
            // this is bad, defaults to the main class.. hrm.
            String msg = tsre.toString();
            throw new SketchException(msg, 0, -1, -1);
        }
    } catch (SketchException pe) {
        // get lost in the more general "Exception" handler below.
        throw pe;
    } catch (Exception ex) {
        // TODO better method for handling this?
        System.err.println("Uncaught exception type:" + ex.getClass());
        ex.printStackTrace();
        throw new SketchException(ex.toString());
    }
    // grab the imports from the code just preprocessed
    importedLibraries = new ArrayList<Library>();
    Library core = mode.getCoreLibrary();
    if (core != null) {
        importedLibraries.add(core);
        classPath += core.getClassPath();
        javaLibraryPath += File.pathSeparator + core.getNativePath();
    }
    //    System.out.println("extra imports: " + result.extraImports);
    for (String item : result.extraImports) {
        //      System.out.println("item = '" + item + "'");
        // remove things up to the last dot
        int dot = item.lastIndexOf('.');
        // http://dev.processing.org/bugs/show_bug.cgi?id=1145
        String entry = (dot == -1) ? item : item.substring(0, dot);
        if (item.startsWith("static ")) {
            // import static - https://github.com/processing/processing/issues/8
            // Remove more stuff.
            int dot2 = item.lastIndexOf('.');
            entry = entry.substring(7, (dot2 == -1) ? entry.length() : dot2);
        //        System.out.println(entry);
        }
        //      System.out.println("library searching for " + entry);
        Library library = mode.getLibrary(entry);
        if (library != null) {
            if (!importedLibraries.contains(library)) {
                importedLibraries.add(library);
                classPath += library.getClassPath();
                javaLibraryPath += File.pathSeparator + library.getNativePath();
            }
        } else {
            boolean found = false;
            // import, don't show an error for it.
            if (codeFolderPackages != null) {
                String itemPkg = entry;
                for (String pkg : codeFolderPackages) {
                    if (pkg.equals(itemPkg)) {
                        found = true;
                        break;
                    }
                }
            }
            if (ignorableImport(entry + '.')) {
                found = true;
            }
            if (!found) {
                System.err.println("No library found for " + entry);
            }
        }
    }
    //    PApplet.println(PApplet.split(libraryPath, File.pathSeparatorChar));
    // Finally, add the regular Java CLASSPATH. This contains everything
    // imported by the PDE itself (core.jar, pde.jar, quaqua.jar) which may
    // in fact be more of a problem.
    String javaClassPath = System.getProperty("java.class.path");
    // Remove quotes if any.. A messy (and frequent) Windows problem
    if (javaClassPath.startsWith("\"") && javaClassPath.endsWith("\"")) {
        javaClassPath = javaClassPath.substring(1, javaClassPath.length() - 1);
    }
    classPath += File.pathSeparator + javaClassPath;
    for (SketchCode sc : sketch.getCode()) {
        if (sc.isExtension("java")) {
            // In most cases, no pre-processing services necessary for Java files.
            // Just write the the contents of 'program' to a .java file
            // into the build directory. However, if a default package is being
            // used (as in Android), and no package is specified in the source,
            // then we need to move this code to the same package as the sketch.
            // Otherwise, the class may not be found, or at a minimum, the default
            // access across the packages will mean that things behave incorrectly.
            // For instance, desktop code that uses a .java file with no packages,
            // will be fine with the default access, but since Android's PApplet
            // requires a package, code from that (default) package (such as the
            // PApplet itself) won't have access to methods/variables from the
            // package-less .java file (unless they're all marked public).
            String filename = sc.getFileName();
            try {
                String javaCode = sc.getProgram();
                String[] packageMatch = PApplet.match(javaCode, PACKAGE_REGEX);
                if (packageMatch == null && packageName == null) {
                    sc.copyTo(new File(srcFolder, filename));
                } else {
                    if (packageMatch == null) {
                        // use the default package name, since mixing with package-less code will break
                        packageMatch = new String[] { "", packageName };
                        // add the package name to the source before writing it
                        javaCode = "package " + packageName + ";" + javaCode;
                    }
                    File packageFolder = new File(srcFolder, packageMatch[1].replace('.', File.separatorChar));
                    packageFolder.mkdirs();
                    Util.saveFile(javaCode, new File(packageFolder, filename));
                }
            } catch (IOException e) {
                e.printStackTrace();
                String msg = "Problem moving " + filename + " to the build folder";
                throw new SketchException(msg);
            }
        } else if (sc.isExtension("pde")) {
            // The compiler and runner will need this to have a proper offset
            sc.addPreprocOffset(result.headerOffset);
        }
    }
    foundMain = preprocessor.hasMethod("main");
    return result.className;
}
Also used : SketchCode(processing.app.SketchCode) StringList(processing.data.StringList) SketchException(processing.app.SketchException) BuildException(org.apache.tools.ant.BuildException) PreprocessorResult(processing.mode.java.preproc.PreprocessorResult) SketchException(processing.app.SketchException) Library(processing.app.Library) ZipFile(java.util.zip.ZipFile) SurfaceInfo(processing.mode.java.preproc.SurfaceInfo)

Example 8 with StringList

use of processing.data.StringList in project processing by processing.

the class JavaBuild method exportApplication.

/**
   * Export to application without GUI. Also called by the Commander.
   */
protected boolean exportApplication(File destFolder, int exportPlatform, String exportVariant, boolean embedJava) throws IOException, SketchException {
    // http://code.google.com/p/processing/issues/detail?id=884
    for (Library library : importedLibraries) {
        if (!library.supportsArch(exportPlatform, exportVariant)) {
            String pn = PConstants.platformNames[exportPlatform];
            Messages.showWarning("Quibbles 'n Bits", "The application." + pn + exportVariant + " folder will not be created\n" + "because no " + exportVariant + " version of " + library.getName() + " is available for " + pn, null);
            // don't cancel all exports for this, just move along
            return true;
        }
    }
    /// prep the output directory
    mode.prepareExportFolder(destFolder);
    /// figure out where the jar files will be placed
    File jarFolder = new File(destFolder, "lib");
    /// where all the skeleton info lives
    /// on macosx, need to copy .app skeleton since that's
    /// also where the jar files will be placed
    File dotAppFolder = null;
    String jvmRuntime = "";
    String jdkPath = null;
    if (exportPlatform == PConstants.MACOSX) {
        dotAppFolder = new File(destFolder, sketch.getName() + ".app");
        File contentsOrig = new File(Platform.getJavaHome(), "../../../../..");
        if (embedJava) {
            File jdkFolder = new File(Platform.getJavaHome(), "../../..");
            String jdkFolderName = jdkFolder.getCanonicalFile().getName();
            jvmRuntime = "<key>JVMRuntime</key>\n    <string>" + jdkFolderName + "</string>";
            jdkPath = new File(dotAppFolder, "Contents/PlugIns/" + jdkFolderName).getAbsolutePath();
        }
        File contentsFolder = new File(dotAppFolder, "Contents");
        contentsFolder.mkdirs();
        // Info.plist will be written later
        // set the jar folder to a different location than windows/linux
        //jarFolder = new File(dotAppFolder, "Contents/Resources/Java");
        jarFolder = new File(contentsFolder, "Java");
        File macosFolder = new File(contentsFolder, "MacOS");
        macosFolder.mkdirs();
        Util.copyFile(new File(contentsOrig, "MacOS/Processing"), new File(contentsFolder, "MacOS/" + sketch.getName()));
        File pkgInfo = new File(contentsFolder, "PkgInfo");
        PrintWriter writer = PApplet.createWriter(pkgInfo);
        writer.println("APPL????");
        writer.flush();
        writer.close();
        // Use faster(?) native copy here (also to do sym links)
        if (embedJava) {
            Util.copyDirNative(new File(contentsOrig, "PlugIns"), new File(contentsFolder, "PlugIns"));
        }
        File resourcesFolder = new File(contentsFolder, "Resources");
        Util.copyDir(new File(contentsOrig, "Resources/en.lproj"), new File(resourcesFolder, "en.lproj"));
        Util.copyFile(mode.getContentFile("application/sketch.icns"), new File(resourcesFolder, "sketch.icns"));
    } else if (exportPlatform == PConstants.LINUX) {
        if (embedJava) {
            Util.copyDirNative(Platform.getJavaHome(), new File(destFolder, "java"));
        }
    } else if (exportPlatform == PConstants.WINDOWS) {
        if (embedJava) {
            Util.copyDir(Platform.getJavaHome(), new File(destFolder, "java"));
        }
    }
    if (!jarFolder.exists())
        jarFolder.mkdirs();
    /// start copying all jar files
    StringList jarList = new StringList();
    /// create the main .jar file
    //    HashMap<String,Object> zipFileContents = new HashMap<String,Object>();
    FileOutputStream zipOutputFile = new FileOutputStream(new File(jarFolder, sketch.getName() + ".jar"));
    ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
    //    ZipEntry entry;
    // add the manifest file so that the .jar can be double clickable
    addManifest(zos);
    // add the project's .class files to the jar
    // (just grabs everything from the build directory,
    // since there may be some inner classes)
    // TODO this needs to be recursive (for packages)
    //    File classFiles[] = tempClassesFolder.listFiles(new FilenameFilter() {
    //      public boolean accept(File dir, String name) {
    //        return name.endsWith(".class");
    //      }
    //    });
    //    for (File file : classFiles) {
    //      entry = new ZipEntry(file.getName());
    //      zos.putNextEntry(entry);
    //      zos.write(Base.loadBytesRaw(file));
    //      zos.closeEntry();
    //    }
    addClasses(zos, binFolder);
    // 'data' folder next to 'lib'.
    if (sketch.hasDataFolder()) {
        if (exportPlatform == PConstants.MACOSX) {
            Util.copyDir(sketch.getDataFolder(), new File(jarFolder, "data"));
        } else {
            Util.copyDir(sketch.getDataFolder(), new File(destFolder, "data"));
        }
    }
    // add the contents of the code folder to the jar
    if (sketch.hasCodeFolder()) {
        String includes = Util.contentsToClassPath(sketch.getCodeFolder());
        // Use tokens to get rid of extra blanks, which causes huge exports
        String[] codeList = PApplet.splitTokens(includes, File.pathSeparator);
        for (int i = 0; i < codeList.length; i++) {
            if (codeList[i].toLowerCase().endsWith(".jar") || codeList[i].toLowerCase().endsWith(".zip")) {
                File exportFile = new File(codeList[i]);
                String exportFilename = exportFile.getName();
                Util.copyFile(exportFile, new File(jarFolder, exportFilename));
                jarList.append(exportFilename);
            } else {
            //          cp += codeList[i] + File.pathSeparator;
            }
        }
    }
    zos.flush();
    zos.close();
    jarList.append(sketch.getName() + ".jar");
    /// add contents of 'library' folders to the export
    for (Library library : importedLibraries) {
        // add each item from the library folder / export list to the output
        for (File exportFile : library.getApplicationExports(exportPlatform, exportVariant)) {
            //        System.out.println("export: " + exportFile);
            String exportName = exportFile.getName();
            if (!exportFile.exists()) {
                System.err.println(exportFile.getName() + " is mentioned in export.txt, but it's " + "a big fat lie and does not exist.");
            } else if (exportFile.isDirectory()) {
                Util.copyDir(exportFile, new File(jarFolder, exportName));
            } else if (exportName.toLowerCase().endsWith(".zip") || exportName.toLowerCase().endsWith(".jar")) {
                Util.copyFile(exportFile, new File(jarFolder, exportName));
                jarList.append(exportName);
            } else {
                // Starting with 2.0a2 put extra export files (DLLs, plugins folder,
                // anything else for libraries) inside lib or Contents/Resources/Java
                Util.copyFile(exportFile, new File(jarFolder, exportName));
            }
        }
    }
    /// create platform-specific CLASSPATH based on included jars
    String exportClassPath = null;
    if (exportPlatform == PConstants.MACOSX) {
        exportClassPath = "$JAVAROOT/" + jarList.join(":$JAVAROOT/");
    } else if (exportPlatform == PConstants.WINDOWS) {
        exportClassPath = jarList.join(",");
    } else if (exportPlatform == PConstants.LINUX) {
        // why is $APPDIR at the front of this list?
        exportClassPath = "$APPDIR" + ":$APPDIR/lib/" + jarList.join(":$APPDIR/lib/");
    }
    /// figure out run options for the VM
    StringList runOptions = new StringList();
    // https://github.com/processing/processing/pull/4406
    if (Preferences.getBoolean("run.options.memory") && !exportVariant.equals("armv6hf")) {
        runOptions.append("-Xms" + Preferences.get("run.options.memory.initial") + "m");
        runOptions.append("-Xmx" + Preferences.get("run.options.memory.maximum") + "m");
    }
    // https://github.com/processing/processing/issues/2239
    runOptions.append("-Djna.nosys=true");
    // https://github.com/processing/processing/issues/4608
    if (embedJava) {
        // if people don't embed Java, it might be a mess, but what can we do?
        if (exportPlatform == PConstants.MACOSX) {
            runOptions.append("-Djava.ext.dirs=$APP_ROOT/Contents/PlugIns/jdk" + PApplet.javaVersionName + ".jdk/Contents/Home/jre/lib/ext");
        } else if (exportPlatform == PConstants.WINDOWS) {
            runOptions.append("-Djava.ext.dirs=\"%EXEDIR%\\java\\lib\\ext\"");
        } else if (exportPlatform == PConstants.LINUX) {
            runOptions.append("-Djava.ext.dirs=\"$APPDIR/java/lib/ext\"");
        }
    }
    // https://github.com/processing/processing/issues/2559
    if (exportPlatform == PConstants.WINDOWS) {
        runOptions.append("-Djava.library.path=\"%EXEDIR%\\lib\"");
    }
    if (exportPlatform == PConstants.MACOSX) {
        StringBuilder runOptionsXML = new StringBuilder();
        for (String opt : runOptions) {
            runOptionsXML.append("      <string>");
            runOptionsXML.append(opt);
            runOptionsXML.append("</string>");
            runOptionsXML.append('\n');
        }
        String PLIST_TEMPLATE = "Info.plist.tmpl";
        File plistTemplate = new File(sketch.getFolder(), PLIST_TEMPLATE);
        if (!plistTemplate.exists()) {
            plistTemplate = mode.getContentFile("application/" + PLIST_TEMPLATE);
        }
        File plistFile = new File(dotAppFolder, "Contents/Info.plist");
        PrintWriter pw = PApplet.createWriter(plistFile);
        String[] lines = PApplet.loadStrings(plistTemplate);
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].indexOf("@@") != -1) {
                StringBuilder sb = new StringBuilder(lines[i]);
                int index = 0;
                while ((index = sb.indexOf("@@jvm_runtime@@")) != -1) {
                    sb.replace(index, index + "@@jvm_runtime@@".length(), jvmRuntime);
                }
                while ((index = sb.indexOf("@@jvm_options_list@@")) != -1) {
                    sb.replace(index, index + "@@jvm_options_list@@".length(), runOptionsXML.toString());
                }
                while ((index = sb.indexOf("@@sketch@@")) != -1) {
                    sb.replace(index, index + "@@sketch@@".length(), sketch.getName());
                }
                while ((index = sb.indexOf("@@lsuipresentationmode@@")) != -1) {
                    sb.replace(index, index + "@@lsuipresentationmode@@".length(), Preferences.getBoolean("export.application.present") ? "4" : "0");
                }
                lines[i] = sb.toString();
            }
            // explicit newlines to avoid Windows CRLF
            pw.print(lines[i] + "\n");
        }
        pw.flush();
        pw.close();
        // attempt to code sign if the Xcode tools appear to be installed
        if (Platform.isMacOS() && isXcodeInstalled()) {
            if (embedJava) {
                ProcessHelper.ffs("codesign", "--force", "--sign", "-", jdkPath);
            }
            String appPath = dotAppFolder.getAbsolutePath();
            ProcessHelper.ffs("codesign", "--force", "--sign", "-", appPath);
        }
    } else if (exportPlatform == PConstants.WINDOWS) {
        File buildFile = new File(destFolder, "launch4j-build.xml");
        File configFile = new File(destFolder, "launch4j-config.xml");
        XML project = new XML("project");
        XML target = project.addChild("target");
        target.setString("name", "windows");
        XML taskdef = target.addChild("taskdef");
        taskdef.setString("name", "launch4j");
        taskdef.setString("classname", "net.sf.launch4j.ant.Launch4jTask");
        String launchPath = mode.getContentFile("application/launch4j").getAbsolutePath();
        taskdef.setString("classpath", launchPath + "/launch4j.jar:" + launchPath + "/lib/xstream.jar");
        XML launch4j = target.addChild("launch4j");
        // not all launch4j options are available when embedded inside the ant
        // build file (i.e. the icon param doesn't work), so use a config file
        //<launch4j configFile="windows/work/config.xml" />
        launch4j.setString("configFile", configFile.getAbsolutePath());
        XML config = new XML("launch4jConfig");
        config.addChild("headerType").setContent("gui");
        config.addChild("dontWrapJar").setContent("true");
        config.addChild("downloadUrl").setContent("http://java.com/download");
        File exeFile = new File(destFolder, sketch.getName() + ".exe");
        config.addChild("outfile").setContent(exeFile.getAbsolutePath());
        File iconFile = mode.getContentFile("application/sketch.ico");
        config.addChild("icon").setContent(iconFile.getAbsolutePath());
        XML clazzPath = config.addChild("classPath");
        clazzPath.addChild("mainClass").setContent(sketch.getName());
        for (String jarName : jarList) {
            clazzPath.addChild("cp").setContent("lib/" + jarName);
        }
        XML jre = config.addChild("jre");
        if (embedJava) {
            jre.addChild("path").setContent("java");
        }
        // Need u74 for a major JavaFX issue (upside-down display)
        // https://github.com/processing/processing/issues/3795
        jre.addChild("minVersion").setContent("1.8.0_74");
        for (String opt : runOptions) {
            jre.addChild("opt").setContent(opt);
        }
        config.save(configFile);
        project.save(buildFile);
        if (!buildWindowsLauncher(buildFile, "windows")) {
            // don't delete the build file, might be useful for debugging
            return false;
        }
        configFile.delete();
        buildFile.delete();
    } else {
        File shellScript = new File(destFolder, sketch.getName());
        PrintWriter pw = PApplet.createWriter(shellScript);
        // Do the newlines explicitly so that Windows CRLF
        // isn't used when exporting for Unix.
        pw.print("#!/bin/sh\n\n");
        // allow symlinks
        pw.print("APPDIR=$(readlink -f \"$0\")\n");
        // more POSIX compliant
        pw.print("APPDIR=$(dirname \"$APPDIR\")\n");
        if (embedJava) {
            // https://github.com/processing/processing/issues/2349
            pw.print("$APPDIR/java/bin/");
        }
        String runOptionsStr = runOptions.join(" ");
        pw.print("java " + runOptionsStr + " -Djava.library.path=\"$APPDIR:$APPDIR/lib\"" + //" -Djna.nosys=true" +
        " -cp \"" + exportClassPath + "\"" + " " + sketch.getName() + " \"$@\"\n");
        pw.flush();
        pw.close();
        String shellPath = shellScript.getAbsolutePath();
        // will work on osx or *nix, but just dies on windows, oh well..
        if (!Platform.isWindows()) {
            Runtime.getRuntime().exec(new String[] { "chmod", "+x", shellPath });
        }
    }
    /// copy the source files to the target
    /// (we like to encourage people to share their code)
    File sourceFolder = new File(destFolder, "source");
    sourceFolder.mkdirs();
    for (SketchCode code : sketch.getCode()) {
        try {
            code.copyTo(new File(sourceFolder, code.getFileName()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // move the .java file from the preproc there too
    String preprocFilename = sketch.getName() + ".java";
    File preprocFile = new File(srcFolder, preprocFilename);
    if (preprocFile.exists()) {
        Util.copyFile(preprocFile, new File(sourceFolder, preprocFilename));
    } else {
        System.err.println("Could not copy source file: " + preprocFile.getAbsolutePath());
    }
    /// goodbye
    return true;
}
Also used : SketchCode(processing.app.SketchCode) StringList(processing.data.StringList) ZipOutputStream(java.util.zip.ZipOutputStream) XML(processing.data.XML) Library(processing.app.Library) ZipFile(java.util.zip.ZipFile)

Example 9 with StringList

use of processing.data.StringList in project processing by processing.

the class Runner method getSketchParams.

protected StringList getSketchParams(boolean present, String[] args) {
    StringList params = new StringList();
    // http://processing.org/bugs/bugzilla/1446.html
    if (build.getFoundMain()) {
        params.append(build.getSketchClassName());
    } else {
        params.append("processing.core.PApplet");
        // get the stored device index (starts at 1)
        int runDisplay = Preferences.getInteger("run.display");
        // --editor-location=150,20
        if (editor != null) {
            // if running processing-cmd, don't do placement
            GraphicsDevice editorDevice = editor.getGraphicsConfiguration().getDevice();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice[] devices = ge.getScreenDevices();
            // Make sure the display set in Preferences actually exists
            GraphicsDevice runDevice = editorDevice;
            if (runDisplay > 0 && runDisplay <= devices.length) {
                runDevice = devices[runDisplay - 1];
            } else {
                // If a bad display is selected, use the same display as the editor
                if (runDisplay > 0) {
                    // don't complain about -1 or 0
                    System.err.println("Display " + runDisplay + " not available.");
                }
                runDevice = editorDevice;
                for (int i = 0; i < devices.length; i++) {
                    if (devices[i] == runDevice) {
                        // Wasn't setting the pref to avoid screwing things up with
                        // something temporary. But not setting it makes debugging one's
                        // setup just too damn weird, so changing that behavior.
                        runDisplay = i + 1;
                        System.err.println("Setting 'Run Sketches on Display' preference to display " + runDisplay);
                        Preferences.setInteger("run.display", runDisplay);
                        break;
                    }
                }
            }
            Point windowLocation = editor.getSketchLocation();
            //        }
            if (windowLocation == null) {
                if (editorDevice == runDevice) {
                    // If sketches are to be shown on the same display as the editor,
                    // provide the editor location so the sketch's main() can place it.
                    Point editorLocation = editor.getLocation();
                    params.append(PApplet.ARGS_EDITOR_LOCATION + "=" + editorLocation.x + "," + editorLocation.y);
                } else {
                // The sketch's main() will set a location centered on the new
                // display. It has to happen in main() because the width/height
                // of the sketch are not known here.
                //             Set a location centered on the other display
                //            Rectangle screenRect =
                //              runDevice.getDefaultConfiguration().getBounds();
                //            int runX =
                //            params.add(PApplet.ARGS_LOCATION + "=" + runX + "," + runY);
                }
            } else {
                params.append(PApplet.ARGS_LOCATION + "=" + windowLocation.x + "," + windowLocation.y);
            }
            params.append(PApplet.ARGS_EXTERNAL);
        }
        params.append(PApplet.ARGS_DISPLAY + "=" + runDisplay);
        if (present) {
            params.append(PApplet.ARGS_PRESENT);
            //        if (Preferences.getBoolean("run.present.exclusive")) {
            //          params.add(PApplet.ARGS_EXCLUSIVE);
            //        }
            params.append(PApplet.ARGS_STOP_COLOR + "=" + Preferences.get("run.present.stop.color"));
            params.append(PApplet.ARGS_WINDOW_COLOR + "=" + Preferences.get("run.present.bgcolor"));
        }
        // There was a PDE X hack that put this after the class name, but it was
        // removed for 3.0a6 because it would break the args passed to sketches.
        params.append(PApplet.ARGS_SKETCH_FOLDER + "=" + build.getSketchPath());
        params.append(build.getSketchClassName());
    }
    // Add command-line arguments to be given to the sketch itself
    if (args != null) {
        params.append(args);
    }
    // Pass back the whole list
    return params;
}
Also used : GraphicsDevice(java.awt.GraphicsDevice) StringList(processing.data.StringList) Point(java.awt.Point) GraphicsEnvironment(java.awt.GraphicsEnvironment) Point(java.awt.Point)

Example 10 with StringList

use of processing.data.StringList in project processing by processing.

the class Runner method getMachineParams.

protected StringList getMachineParams() {
    StringList params = new StringList();
    //params.add("-Xint"); // interpreted mode
    //params.add("-Xprof");  // profiler
    //params.add("-Xaprof");  // allocation profiler
    //params.add("-Xrunhprof:cpu=samples");  // old-style profiler
    // TODO change this to use run.args = true, run.args.0, run.args.1, etc.
    // so that spaces can be included in the arg names
    String options = Preferences.get("run.options");
    if (options.length() > 0) {
        String[] pieces = PApplet.split(options, ' ');
        for (int i = 0; i < pieces.length; i++) {
            String p = pieces[i].trim();
            if (p.length() > 0) {
                params.append(p);
            }
        }
    }
    if (Preferences.getBoolean("run.options.memory")) {
        params.append("-Xms" + Preferences.get("run.options.memory.initial") + "m");
        params.append("-Xmx" + Preferences.get("run.options.memory.maximum") + "m");
    }
    // Surprised this wasn't here before; added for 3.2.1
    params.append("-Djna.nosys=true");
    // Added for 3.2.1, was still using the default ext.dirs in the PDE
    try {
        String extPath = new File(Platform.getJavaHome(), "lib/ext").getCanonicalPath();
        // quoting this on OS X causes it to fail
        //params.append("-Djava.ext.dirs=\"" + extPath + "\"");
        params.append("-Djava.ext.dirs=" + extPath);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (Platform.isMacOS()) {
        params.append("-Xdock:name=" + build.getSketchClassName());
    //      params.add("-Dcom.apple.mrj.application.apple.menu.about.name=" +
    //                 sketch.getMainClassName());
    }
    // sketch.libraryPath might be ""
    // librariesClassPath will always have sep char prepended
    params.append("-Djava.library.path=" + build.getJavaLibraryPath() + File.pathSeparator + System.getProperty("java.library.path"));
    params.append("-cp");
    params.append(build.getClassPath());
    // enable assertions
    // http://dev.processing.org/bugs/show_bug.cgi?id=1188
    params.append("-ea");
    return params;
}
Also used : StringList(processing.data.StringList) Point(java.awt.Point)

Aggregations

StringList (processing.data.StringList)21 Point (java.awt.Point)3 File (java.io.File)2 ZipFile (java.util.zip.ZipFile)2 Library (processing.app.Library)2 SketchCode (processing.app.SketchCode)2 SketchException (processing.app.SketchException)2 Argument (com.sun.jdi.connect.Connector.Argument)1 FileDialog (java.awt.FileDialog)1 Font (java.awt.Font)1 GraphicsDevice (java.awt.GraphicsDevice)1 GraphicsEnvironment (java.awt.GraphicsEnvironment)1 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1 ConnectException (java.net.ConnectException)1 MatchResult (java.util.regex.MatchResult)1 ZipOutputStream (java.util.zip.ZipOutputStream)1 JFileChooser (javax.swing.JFileChooser)1 BuildException (org.apache.tools.ant.BuildException)1 Editor (processing.app.ui.Editor)1