Search in sources :

Example 1 with Library

use of processing.app.Library in project processing by processing.

the class ExamplesFrame method buildTree.

protected DefaultMutableTreeNode buildTree() {
    //"Examples");
    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    try {
        // Get the list of Mode-specific examples, in the order the Mode wants
        // to present them (i.e. Basics, then Topics, then Demos...)
        File[] examples = mode.getExampleCategoryFolders();
        for (File subFolder : examples) {
            DefaultMutableTreeNode subNode = new DefaultMutableTreeNode(subFolder.getName());
            if (base.addSketches(subNode, subFolder, true)) {
                root.add(subNode);
            }
        }
        DefaultMutableTreeNode foundationLibraries = new DefaultMutableTreeNode(Language.text("examples.core_libraries"));
        // Get examples for core libraries
        for (Library lib : mode.coreLibraries) {
            if (lib.hasExamples()) {
                DefaultMutableTreeNode libNode = new DefaultMutableTreeNode(lib.getName());
                if (base.addSketches(libNode, lib.getExamplesFolder(), true)) {
                    foundationLibraries.add(libNode);
                }
            }
        }
        if (foundationLibraries.getChildCount() > 0) {
            root.add(foundationLibraries);
        }
        // Get examples for third party libraries
        DefaultMutableTreeNode contributedLibExamples = new DefaultMutableTreeNode(Language.text("examples.libraries"));
        for (Library lib : mode.contribLibraries) {
            if (lib.hasExamples()) {
                DefaultMutableTreeNode libNode = new DefaultMutableTreeNode(lib.getName());
                base.addSketches(libNode, lib.getExamplesFolder(), true);
                contributedLibExamples.add(libNode);
            }
        }
        if (contributedLibExamples.getChildCount() > 0) {
            root.add(contributedLibExamples);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    DefaultMutableTreeNode contributedExamplesNode = buildContribTree();
    if (contributedExamplesNode.getChildCount() > 0) {
        root.add(contributedExamplesNode);
    }
    return root;
}
Also used : DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) Library(processing.app.Library) IOException(java.io.IOException) File(java.io.File)

Example 2 with Library

use of processing.app.Library in project processing by processing.

the class Recent method updateMenuRecord.

private static void updateMenuRecord(JMenu menu, final Record rec, String sketchbookPath) {
    try {
        String recPath = new File(rec.getPath()).getParent();
        String purtyPath = null;
        if (recPath.startsWith(sketchbookPath)) {
            purtyPath = "sketchbook → " + recPath.substring(sketchbookPath.length() + 1);
        } else {
            List<Mode> modes = base.getModeList();
            for (Mode mode : modes) {
                File examplesFolder = mode.getExamplesFolder();
                String examplesPath = examplesFolder.getAbsolutePath();
                if (recPath.startsWith(examplesPath)) {
                    String modePrefix = mode.getTitle() + " ";
                    if (mode.getTitle().equals("Standard")) {
                        // "Standard examples" is dorky
                        modePrefix = "";
                    }
                    purtyPath = modePrefix + "examples → " + recPath.substring(examplesPath.length() + 1);
                    break;
                }
                if (mode.coreLibraries != null) {
                    for (Library lib : mode.coreLibraries) {
                        examplesFolder = lib.getExamplesFolder();
                        examplesPath = examplesFolder.getAbsolutePath();
                        if (recPath.startsWith(examplesPath)) {
                            purtyPath = lib.getName() + " examples → " + recPath.substring(examplesPath.length() + 1);
                            break;
                        }
                    }
                }
                if (mode.contribLibraries != null) {
                    for (Library lib : mode.contribLibraries) {
                        examplesFolder = lib.getExamplesFolder();
                        examplesPath = examplesFolder.getAbsolutePath();
                        if (recPath.startsWith(examplesPath)) {
                            purtyPath = lib.getName() + " examples → " + recPath.substring(examplesPath.length() + 1);
                            break;
                        }
                    }
                }
            }
        }
        if (purtyPath == null) {
            String homePath = System.getProperty("user.home");
            if (recPath.startsWith(homePath)) {
                // Not localized, but this is gravy. It'll work on OS X & EN Windows
                String desktopPath = homePath + File.separator + "Desktop";
                if (recPath.startsWith(desktopPath)) {
                    purtyPath = "Desktop → " + recPath.substring(desktopPath.length() + 1);
                } else {
                    //purtyPath = "⌂ → " + recPath.substring(homePath.length() + 1);
                    //purtyPath = "Home → " + recPath.substring(homePath.length() + 1);
                    String userName = new File(homePath).getName();
                    //purtyPath = "⌂ " + userName + " → " + recPath.substring(homePath.length() + 1);
                    purtyPath = userName + " → " + recPath.substring(homePath.length() + 1);
                }
            } else {
                purtyPath = recPath;
            }
        }
        //      JMenuItem item = new JMenuItem(rec.getName() + " | " + purtyPath);
        JMenuItem item = new JMenuItem(purtyPath);
        item.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // Base will call handle() (below) which will cause this entry to
                // be removed from the list and re-added to the end. If already
                // opened, Base will bring the window forward, and also call handle()
                // so that it's re-queued to the newest slot in the Recent menu.
                base.handleOpen(rec.path);
            //          if (rec.sketch == null) {
            //            // this will later call 'add' to put it back on the stack
            //            base.handleOpen(rec.path); //, rec.state);
            ////            int index = findRecord(rec);
            ////            if (index != -1) {
            ////              records.remove(index);  // remove from the list
            ////              save();  // write the recent file with the latest
            ////            }
            //          } else {
            ////              System.out.println("sketch not null in handleOpen: " + record.getPath());
            //          }
            }
        });
        //menu.add(item);
        menu.insert(item, 0);
    } catch (Exception e) {
        // Strange things can happen... report them for the geeky and move on:
        // https://github.com/processing/processing/issues/2463
        e.printStackTrace();
    }
}
Also used : ActionListener(java.awt.event.ActionListener) ActionEvent(java.awt.event.ActionEvent) Mode(processing.app.Mode) Library(processing.app.Library) JMenuItem(javax.swing.JMenuItem) File(java.io.File) IOException(java.io.IOException)

Example 3 with Library

use of processing.app.Library 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 4 with Library

use of processing.app.Library 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 5 with Library

use of processing.app.Library in project processing by processing.

the class PreprocessingService method buildModeClassPath.

private static List<String> buildModeClassPath(JavaMode mode, boolean search) {
    StringBuilder classPath = new StringBuilder();
    if (search) {
        String searchClassPath = mode.getSearchPath();
        if (searchClassPath != null) {
            classPath.append(File.pathSeparator).append(searchClassPath);
        }
    } else {
        Library coreLibrary = mode.getCoreLibrary();
        String coreClassPath = coreLibrary != null ? coreLibrary.getClassPath() : mode.getSearchPath();
        if (coreClassPath != null) {
            classPath.append(File.pathSeparator).append(coreClassPath);
        }
    }
    return sanitizeClassPath(classPath.toString());
}
Also used : Library(processing.app.Library)

Aggregations

Library (processing.app.Library)5 File (java.io.File)2 IOException (java.io.IOException)2 ZipFile (java.util.zip.ZipFile)2 SketchCode (processing.app.SketchCode)2 StringList (processing.data.StringList)2 ActionEvent (java.awt.event.ActionEvent)1 ActionListener (java.awt.event.ActionListener)1 ZipOutputStream (java.util.zip.ZipOutputStream)1 JMenuItem (javax.swing.JMenuItem)1 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)1 BuildException (org.apache.tools.ant.BuildException)1 Mode (processing.app.Mode)1 SketchException (processing.app.SketchException)1 XML (processing.data.XML)1 PreprocessorResult (processing.mode.java.preproc.PreprocessorResult)1 SurfaceInfo (processing.mode.java.preproc.SurfaceInfo)1