Search in sources :

Example 6 with SketchCode

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

use of processing.app.SketchCode 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 8 with SketchCode

use of processing.app.SketchCode in project chipKIT32-MAX by chipKIT32.

the class Compiler method message.

/**
	 * Part of the MessageConsumer interface, this is called whenever a piece
	 * (usually a line) of error message is spewed out from the compiler. The
	 * errors are parsed for their contents and line number, which is then
	 * reported back to Editor.
	 */
public void message(String s) {
    int i;
    // have meaning in a regular expression.
    if (!verbose) {
        while ((i = s.indexOf(buildPath + File.separator)) != -1) {
            s = s.substring(0, i) + s.substring(i + (buildPath + File.separator).length());
        }
    }
    // look for error line, which contains file name, line number,
    // and at least the first line of the error message
    String errorFormat = "([\\w\\d_]+.\\w+):(\\d+):\\s*error:\\s*(.*)\\s*";
    String[] pieces = PApplet.match(s, errorFormat);
    if (pieces != null) {
        RunnerException e = sketch.placeException(pieces[3], pieces[1], PApplet.parseInt(pieces[2]) - 1);
        // in verbose mode, in which case don't modify the compiler output)
        if (e != null && !verbose) {
            SketchCode code = sketch.getCode(e.getCodeIndex());
            String fileName = code.isExtension(sketch.getDefaultExtension()) ? code.getPrettyName() : code.getFileName();
            s = fileName + ":" + e.getCodeLine() + ": error: " + e.getMessage();
        }
        if (pieces[3].trim().equals("SPI.h: No such file or directory")) {
            e = new RunnerException("Please import the SPI library from the Sketch > Import Library menu.");
            s += "\nAs of Arduino 0019, the Ethernet library depends on the SPI library." + "\nYou appear to be using it or another library that depends on the SPI library.";
        }
        if (exception == null && e != null) {
            exception = e;
            exception.hideStackTrace();
        }
    }
    System.err.print(s);
}
Also used : SketchCode(processing.app.SketchCode)

Example 9 with SketchCode

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

the class Debugger method sketchToJavaLine.

/**
   * Translate a line (index) from sketch space to java space.
   * @param sketchLine the sketch line id
   * @return the corresponding java line id or null if failed to translate
   */
public LineID sketchToJavaLine(LineID sketchLine) {
    // transform back to orig (before changes at runtime)
    sketchLine = runtimeToOriginalLine(sketchLine);
    // check if there is a tab for this line
    SketchCode tab = editor.getTab(sketchLine.fileName());
    if (tab == null) {
        return null;
    }
    // check if the tab is a pure java file anyway
    if (tab.isExtension("java")) {
        // 1:1 translation
        return sketchLine;
    }
    // the java file has a name sketchname.java
    // just add the tab's offset to get the java name
    LineID javaLine = new LineID(editor.getSketch().getName() + ".java", sketchLine.lineIdx() + tab.getPreprocOffset());
    return javaLine;
}
Also used : SketchCode(processing.app.SketchCode)

Example 10 with SketchCode

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

the class Debugger method vmStartEvent.

private void vmStartEvent() {
    // break on main class load
    log("requesting event on main class load: " + mainClassName);
    ClassPrepareRequest mainClassPrepare = runtime.vm().eventRequestManager().createClassPrepareRequest();
    mainClassPrepare.addClassFilter(mainClassName);
    mainClassPrepare.enable();
    // break on loading custom classes
    for (SketchCode tab : editor.getSketch().getCode()) {
        if (tab.isExtension("java")) {
            log("requesting event on class load: " + tab.getPrettyName());
            ClassPrepareRequest customClassPrepare = runtime.vm().eventRequestManager().createClassPrepareRequest();
            customClassPrepare.addClassFilter(tab.getPrettyName());
            customClassPrepare.enable();
        }
    }
    runtime.vm().resume();
}
Also used : SketchCode(processing.app.SketchCode)

Aggregations

SketchCode (processing.app.SketchCode)18 Sketch (processing.app.Sketch)7 Point (java.awt.Point)3 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 List (java.util.List)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 ZipFile (java.util.zip.ZipFile)2 Library (processing.app.Library)2 Messages (processing.app.Messages)2 SketchException (processing.app.SketchException)2 StringList (processing.data.StringList)2 Handle (processing.mode.java.tweak.Handle)2 ClassPathFactory (com.google.classpath.ClassPathFactory)1 EventQueue (java.awt.EventQueue)1 Font (java.awt.Font)1 WindowEvent (java.awt.event.WindowEvent)1 WindowFocusListener (java.awt.event.WindowFocusListener)1