示例#1
0
  public static List<String> getLibraries(String path, Target target) {
    List<String> result = new ArrayList<String>();
    try {
      Sketch sketch = new Sketch(null, path);
      sketch.preprocess(Base.getBuildFolder().getAbsolutePath(), target);

      Vector<Library> libraries = new Vector<Library>();
      LibraryManager libraryManager = new LibraryManager();
      for (File file : sketch.getImportedLibraries()) {
        String item = file.getName();
        libraryManager.addLibrary(libraries, libraryManager.get(item), true);
      }

      String prefLibs = Preferences.get("boards." + Preferences.get("board") + ".build.libraries");
      if (prefLibs != null) {
        String[] boardLibraries = prefLibs.trim().split("\\s+");
        for (String item : boardLibraries) {
          libraryManager.addLibrary(libraries, libraryManager.get(item), true);
        }
      }

      for (Library library : libraries) {
        result.add(library.getName());
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (RunnerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return result;
  }
示例#2
0
  /** This is executed every time we launch the tool using the menu item in Processing IDE */
  public void run() {
    GCScheme.makeColorSchemes();

    //		Base base = editor.getBase();
    Sketch sketch = editor.getSketch();
    File sketchFolder = sketch.getFolder();
    File sketchbookFolder = Base.getSketchbookFolder();

    // Provide a warning (first time only) if G4P is not loaded
    if (!g4p_error_shown && !g4pJarExists(Base.getSketchbookLibrariesFolder())) {
      Base.showWarning(
          "GUI Builder error",
          "Although you can use this tool the sketch created will not \nwork because the G4P library needs to be installed.\nSee G4P at http://www.lagers.org.uk/g4p/",
          null);
      g4p_error_shown = true;
    }
    // The tool is not open so create the designer window
    if (dframe == null) {
      // If the gui.pde tab does not exist create it
      if (!guiTabExists(sketch)) {
        sketch.addFile(new File(sketchbookFolder, G4P_TOOL_DATA_FOLDER + SEP + PDE_TAB_NAME));
      }
      // Create data folder if necessary
      sketch.prepareDataFolder();

      // Create a sub-folder called 'GUI_BUILDER_DATA' inside the sketch folder if
      // it doesn't already exist
      File configFolder = new File(sketchFolder, CONFIG_FOLDER);
      if (!configFolder.exists()) {
        configFolder.mkdir();
      }
      dframe = new GuiDesigner(editor);
      System.out.println("===================================================");
      System.out.println("   G4PTool V2.2.1 created by Peter Lager");
      System.out.println("===================================================");

      //			try {
      //				BufferedImage img = ImageIO.read(new File(sketchbookFolder, G4P_TOOL_DATA_FOLDER + SEP +
      // "default_gui_palette.png"));
      //				System.out.println("Image " + img);
      //			} catch (IOException e) {
      //				System.out.println("Unable to load colour schemes");
      //				e.printStackTrace();
      //			}
    }
    // Design window exists so make visible, open to normal size
    // and bring to front.
    dframe.setVisible(true);
    dframe.setExtendedState(JFrame.NORMAL);
    dframe.toFront();
  }
示例#3
0
 // TODO Why is this necessary? Why isn't Sketch.isModified() used?
 private static boolean isSketchModified(Sketch sketch) {
   for (SketchCode sc : sketch.getCode()) {
     if (sc.isModified()) {
       return true;
     }
   }
   return false;
 }
 public static File getBuildFolder(Sketch data) throws IOException {
   File buildFolder;
   if (PreferencesData.get("build.path") != null) {
     buildFolder = BaseNoGui.absoluteFile(PreferencesData.get("build.path"));
     Files.createDirectories(buildFolder.toPath());
   } else {
     buildFolder =
         FileUtils.createTempFolder("build", DigestUtils.md5Hex(data.getMainFilePath()) + ".tmp");
     DeleteFilesOnShutdown.add(buildFolder);
   }
   return buildFolder;
 }
示例#5
0
  void applyDirectives() {
    findRemoveDirectives(true);

    StringBuffer buffer = new StringBuffer();
    String head = "", toe = "; \n";

    if (crispBox.isSelected()) buffer.append(head + "crisp=true" + toe);
    if (!fontField.getText().trim().equals(""))
      buffer.append(head + "font=\"" + fontField.getText().trim() + "\"" + toe);
    if (globalKeyEventsBox.isSelected()) buffer.append(head + "globalKeyEvents=true" + toe);
    if (pauseOnBlurBox.isSelected()) buffer.append(head + "pauseOnBlur=true" + toe);
    if (!preloadField.getText().trim().equals(""))
      buffer.append(head + "preload=\"" + preloadField.getText().trim() + "\"" + toe);
    /*if ( transparentBox.isSelected() )
    buffer.append( head + "transparent=true" + toe );*/

    Sketch sketch = editor.getSketch();
    SketchCode code = sketch.getCode(0); // first tab
    if (buffer.length() > 0) {
      code.setProgram("/* @pjs " + buffer.toString() + " */\n\n" + code.getProgram());
      if (sketch.getCurrentCode() == code) // update textarea if on first tab
      {
        editor.setText(sketch.getCurrentCode().getProgram());
        editor.setSelection(0, 0);
      }

      sketch.setModified(false);
      sketch.setModified(true);
    }
  }
示例#6
0
  void findRemoveDirectives(boolean clean) {
    // if ( clean ) editor.startCompoundEdit();

    Sketch sketch = editor.getSketch();
    for (int i = 0; i < sketch.getCodeCount(); i++) {
      SketchCode code = sketch.getCode(i);
      String program = code.getProgram();
      StringBuffer buffer = new StringBuffer();

      Matcher m = pjsPattern.matcher(program);
      while (m.find()) {
        String mm = m.group();

        // TODO this urgently needs tests ..

        /* remove framing */
        mm = mm.replaceAll("^\\/\\*\\s*@pjs", "").replaceAll("\\s*\\*\\/\\s*$", "");
        /* fix multiline nice formatting */
        mm = mm.replaceAll("[\\s]*([^;\\s\\n\\r]+)[\\s]*,[\\s]*[\\n\\r]+", "$1,");
        /* fix multiline version without semicolons */
        mm = mm.replaceAll("[\\s]*([^;\\s\\n\\r]+)[\\s]*[\\n\\r]+", "$1;");
        mm = mm.replaceAll("\n", " ").replaceAll("\r", " ");

        // System.out.println(mm);

        if (clean) {
          m.appendReplacement(buffer, "");
        } else {
          String[] directives = mm.split(";");
          for (String d : directives) {
            // System.out.println(d);
            parseDirective(d);
          }
        }
      }

      if (clean) {
        m.appendTail(buffer);

        // TODO: not working!
        code.setProgram(buffer.toString());
        code.setModified(true);
      }
    }

    if (clean) {
      // editor.stopCompoundEdit();
      editor.setText(sketch.getCurrentCode().getProgram());
      sketch.setModified(false);
      sketch.setModified(true);
    }
  }
示例#7
0
  /**
   * Compile with avr-gcc.
   *
   * @param sketch Sketch object to be compiled.
   * @param buildPath Where the temporary files live and will be built from.
   * @param primaryClassName the name of the combined sketch file w/ extension
   * @return true if successful.
   * @throws RunnerException Only if there's a problem. Only then.
   * 
  * [ROBOTIS]Changed prototype to support ARM Cortex-M3 based CM-900 Pandora project
  * 2012-09-26 [email protected]
  * */
  public boolean compile(Sketch sketch, //change return type[ROBOTIS]
                         String buildPath,
                         String primaryClassName,
                         boolean verbose,
                         List<String> ignored) throws RunnerException {
    this.sketch = sketch;
    this.buildPath = buildPath;
    this.primaryClassName = primaryClassName; //예를 들면 cpp파일로 변환된 AnalogReadSerial.cpp
    this.verbose = verbose;
    this.sketchIsCompiled = false;
    System.out.println("Compiler.compile() sketch ="+sketch.getName()+"buildpath ="+buildPath+"primaryClassName ="+primaryClassName);
    // the pms object isn't used for anything but storage
    MessageStream pms = new MessageStream(this);

    String avrBasePath = Base.getAvrBasePath();
    System.out.println("[ROBOTIS]avrBasePath ="+avrBasePath);
    Map<String, String> boardPreferences = Base.getBoardPreferences();
    String core = boardPreferences.get("build.core");
    System.out.println("[ROBOTIS]build.core ="+core);
    if (core == null) {
    	RunnerException re = new RunnerException(_("No board selected; please choose a board from the Tools > Board menu."));
      re.hideStackTrace();
      throw re;
    }
    String corePath;
    
    if (core.indexOf(':') == -1) {
      Target t = Base.getTarget();
      File coreFolder = new File(new File(t.getFolder(), "cores"), core);
      corePath = coreFolder.getAbsolutePath();
      
    } else {
      Target t = Base.targetsTable.get(core.substring(0, core.indexOf(':')));
      File coreFolder = new File(t.getFolder(), "cores");
      coreFolder = new File(coreFolder, core.substring(core.indexOf(':') + 1));
      corePath = coreFolder.getAbsolutePath();
    }

    System.out.println("[ROBOTIS]corePath ="+corePath);
    
    String variant = boardPreferences.get("build.variant");
    String variantPath = null;
    
    if (variant != null) {
      if (variant.indexOf(':') == -1) {
	Target t = Base.getTarget();
	File variantFolder = new File(new File(t.getFolder(), "variants"), variant);
	variantPath = variantFolder.getAbsolutePath();
      } else {
	Target t = Base.targetsTable.get(variant.substring(0, variant.indexOf(':')));
	File variantFolder = new File(t.getFolder(), "variants");
	variantFolder = new File(variantFolder, variant.substring(variant.indexOf(':') + 1));
	variantPath = variantFolder.getAbsolutePath();
      }
    }

    List<File> objectFiles = new ArrayList<File>();

   // 0. include paths for core + all libraries

   sketch.setCompilingProgress(20);
   List includePaths = new ArrayList();
   includePaths.add(corePath);
   if (variantPath != null) includePaths.add(variantPath);
   for (File file : sketch.getImportedLibraries()) {
     includePaths.add(file.getPath());
   }

   // 1. compile the sketch (already in the buildPath)

   sketch.setCompilingProgress(30);
   objectFiles.addAll(
     compileFiles(avrBasePath, buildPath, includePaths,
               findFilesInPath(buildPath, "S", false),
               findFilesInPath(buildPath, "c", false),
               findFilesInPath(buildPath, "cpp", false),
               boardPreferences));
   sketchIsCompiled = true;

   // 2. compile the libraries, outputting .o files to: <buildPath>/<library>/

   sketch.setCompilingProgress(40);
   for (File libraryFolder : sketch.getImportedLibraries()) {
     File outputFolder = new File(buildPath, libraryFolder.getName());
     File utilityFolder = new File(libraryFolder, "utility");
     createFolder(outputFolder);
     // this library can use includes in its utility/ folder
     includePaths.add(utilityFolder.getAbsolutePath());
     objectFiles.addAll(
       compileFiles(avrBasePath, outputFolder.getAbsolutePath(), includePaths,
               findFilesInFolder(libraryFolder, "S", false),
               findFilesInFolder(libraryFolder, "c", false),
               findFilesInFolder(libraryFolder, "cpp", false),
               boardPreferences));
     outputFolder = new File(outputFolder, "utility");
     createFolder(outputFolder);
     objectFiles.addAll(
       compileFiles(avrBasePath, outputFolder.getAbsolutePath(), includePaths,
               findFilesInFolder(utilityFolder, "S", false),
               findFilesInFolder(utilityFolder, "c", false),
               findFilesInFolder(utilityFolder, "cpp", false),
               boardPreferences));
     // other libraries should not see this library's utility/ folder
     includePaths.remove(includePaths.size() - 1);
   }

   // 3. compile the core, outputting .o files to <buildPath> and then
   // collecting them into the core.a library file.

   sketch.setCompilingProgress(50);
  includePaths.clear();
  includePaths.add(corePath);  // include path for core only
  if (variantPath != null) includePaths.add(variantPath);
  List<File> coreObjectFiles =
    compileFiles(avrBasePath, buildPath, includePaths,
              findFilesInPath(corePath, "S", true),
              findFilesInPath(corePath, "c", true),
              findFilesInPath(corePath, "cpp", true),
              boardPreferences);

   String runtimeLibraryName = buildPath + File.separator + "core.a";
   List baseCommandAR = new ArrayList(Arrays.asList(new String[] {
     avrBasePath + "avr-ar",
     "rcs",
     runtimeLibraryName
   }));
   for(File file : coreObjectFiles) {
     List commandAR = new ArrayList(baseCommandAR);
     commandAR.add(file.getAbsolutePath());
     execAsynchronously(commandAR);
   }

    // 4. link it all together into the .elf file
    // For atmega2560, need --relax linker option to link larger
    // programs correctly.
    String optRelax = "";
    String atmega2560 = new String ("atmega2560");
    if ( atmega2560.equals(boardPreferences.get("build.mcu")) ) {
        optRelax = new String(",--relax");
    }
   sketch.setCompilingProgress(60);
    List baseCommandLinker = new ArrayList(Arrays.asList(new String[] {
      avrBasePath + "avr-gcc",
      "-Os",
      "-Wl,--gc-sections"+optRelax,
      "-mmcu=" + boardPreferences.get("build.mcu"),
      "-o",
      buildPath + File.separator + primaryClassName + ".elf"
    }));

    for (File file : objectFiles) {
      baseCommandLinker.add(file.getAbsolutePath());
    }

    baseCommandLinker.add(runtimeLibraryName);
    baseCommandLinker.add("-L" + buildPath);
    baseCommandLinker.add("-lm");

    execAsynchronously(baseCommandLinker);

    List baseCommandObjcopy = new ArrayList(Arrays.asList(new String[] {
      avrBasePath + "avr-objcopy",
      "-O",
      "-R",
    }));
    
    List commandObjcopy;

    // 5. extract EEPROM data (from EEMEM directive) to .eep file.
    sketch.setCompilingProgress(70);
    commandObjcopy = new ArrayList(baseCommandObjcopy);
    commandObjcopy.add(2, "ihex");
    commandObjcopy.set(3, "-j");
    commandObjcopy.add(".eeprom");
    commandObjcopy.add("--set-section-flags=.eeprom=alloc,load");
    commandObjcopy.add("--no-change-warnings");
    commandObjcopy.add("--change-section-lma");
    commandObjcopy.add(".eeprom=0");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".elf");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".eep");
    execAsynchronously(commandObjcopy);
    
    // 6. build the .hex file
    sketch.setCompilingProgress(80);
    commandObjcopy = new ArrayList(baseCommandObjcopy);
    commandObjcopy.add(2, "ihex");
    commandObjcopy.add(".eeprom"); // remove eeprom data
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".elf");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".hex");
    execAsynchronously(commandObjcopy);
    
    sketch.setCompilingProgress(90);
   
    return true;
  }
示例#8
0
  /**
   * 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;

    System.out.println("**************[ROBOTIS]***********************************");
    // remove the build path so people only see the filename
    // can't use replaceAll() because the path may have characters in it which
    // 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 && exception == null) {
//      exception = sketch.placeException(pieces[3], pieces[1], PApplet.parseInt(pieces[2]) - 1);
//      if (exception != null) exception.hideStackTrace();
//    }
    
    if (pieces != null) {
      String error = pieces[3], msg = "";
      
      if (pieces[3].trim().equals("SPI.h: No such file or directory")) {
        error = _("Please import the SPI library from the Sketch > Import Library menu.");
        msg = _("\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.\n\n");
      }
      
      if (pieces[3].trim().equals("'BYTE' was not declared in this scope")) {
        error = _("The 'BYTE' keyword is no longer supported.");
        msg = _("\nAs of Arduino 1.0, the 'BYTE' keyword is no longer supported." +
              "\nPlease use Serial.write() instead.\n\n");
      }
      
      if (pieces[3].trim().equals("no matching function for call to 'Server::Server(int)'")) {
        error = _("The Server class has been renamed EthernetServer.");
        msg = _("\nAs of Arduino 1.0, the Server class in the Ethernet library " +
              "has been renamed to EthernetServer.\n\n");
      }
      
      if (pieces[3].trim().equals("no matching function for call to 'Client::Client(byte [4], int)'")) {
        error = _("The Client class has been renamed EthernetClient.");
        msg = _("\nAs of Arduino 1.0, the Client class in the Ethernet library " +
              "has been renamed to EthernetClient.\n\n");
      }
      
      if (pieces[3].trim().equals("'Udp' was not declared in this scope")) {
        error = _("The Udp class has been renamed EthernetUdp.");
        msg = _("\nAs of Arduino 1.0, the Udp class in the Ethernet library " +
              "has been renamed to EthernetUdp.\n\n");
      }
      
      if (pieces[3].trim().equals("'class TwoWire' has no member named 'send'")) {
        error = _("Wire.send() has been renamed Wire.write().");
        msg = _("\nAs of Arduino 1.0, the Wire.send() function was renamed " +
              "to Wire.write() for consistency with other libraries.\n\n");
      }
      
      if (pieces[3].trim().equals("'class TwoWire' has no member named 'receive'")) {
        error = _("Wire.receive() has been renamed Wire.read().");
        msg = _("\nAs of Arduino 1.0, the Wire.receive() function was renamed " +
              "to Wire.read() for consistency with other libraries.\n\n");
      }

      if (pieces[3].trim().equals("'Mouse' was not declared in this scope")) {
        error = _("'Mouse' only supported on the Arduino Leonardo");
        //msg = _("\nThe 'Mouse' class is only supported on the Arduino Leonardo.\n\n");
      }
      
      if (pieces[3].trim().equals("'Keyboard' was not declared in this scope")) {
        error = _("'Keyboard' only supported on the Arduino Leonardo");
        //msg = _("\nThe 'Keyboard' class is only supported on the Arduino Leonardo.\n\n");
      }
      
      RunnerException e = null;
      if (!sketchIsCompiled) {
        // Place errors when compiling the sketch, but never while compiling libraries
        // or the core.  The user's sketch might contain the same filename!
        e = sketch.placeException(error, pieces[1], PApplet.parseInt(pieces[2]) - 1);
      }

      // replace full file path with the name of the sketch tab (unless we're
      // 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("ino") || code.isExtension("pde")) ? code.getPrettyName() : code.getFileName();
        int lineNum = e.getCodeLine() + 1;
        s = fileName + ":" + lineNum + ": error: " + pieces[3] + msg;        
      }
            
      if (exception == null && e != null) {
        exception = e;
        exception.hideStackTrace();
      }      
    }
    
    System.err.print(s);
  }
示例#9
0
  /**
   * Compile with avr-gcc.
   *
   * @param sketch Sketch object to be compiled.
   * @param buildPath Where the temporary files live and will be built from.
   * @param primaryClassName the name of the combined sketch file w/ extension
   * @param target the target (core) to build against
   * @return true if successful.
   * @throws RunnerException Only if there's a problem. Only then.
   */
  public boolean compile(Sketch sketch, String buildPath, String primaryClassName, Target target)
      throws RunnerException {
    this.sketch = sketch;
    this.buildPath = buildPath;
    this.primaryClassName = primaryClassName;

    // the pms object isn't used for anything but storage
    MessageStream pms = new MessageStream(this);

    String avrBasePath = Base.getAvrBasePath();

    List<File> objectFiles = new ArrayList<File>();
    List<String> includePaths = new ArrayList<String>();

    try {
      Vector<Library> libraries = new Vector<Library>();

      LibraryManager libraryManager;
      libraryManager = new LibraryManager();
      libraryManager.buildAllUnbuilt();

      String prefLibs = Preferences.get("boards." + Preferences.get("board") + ".build.libraries");
      if (prefLibs != null) {
        String[] boardLibraries = prefLibs.trim().split("\\s+");
        for (String item : boardLibraries) {
          libraryManager.addLibrary(libraries, libraryManager.get(item));
        }
      }

      // 1. compile the target (core), outputting .o files to <buildPath> and
      // then collecting them into the core.a library file.
      includePaths.add(target.getPath());

      for (Library library : libraries) {
        includePaths.add(library.getFolder().getAbsolutePath());
      }

      List<File> targetObjectFiles =
          compileFiles(
              avrBasePath,
              buildPath,
              includePaths,
              findFilesInPath(target.getPath(), "c", true),
              findFilesInPath(target.getPath(), "cpp", true));

      // 2. compile the libraries, outputting .o files to: <buildPath>/<library>/

      for (File file : sketch.getImportedLibraries()) {
        String item = file.getName();
        libraryManager.addLibrary(libraries, libraryManager.get(item));
      }

      includePaths = new ArrayList<String>();
      includePaths.add(target.getPath());

      for (Library library : libraries) {
        String path = library.getFolder().getAbsolutePath();
        includePaths.add(library.getFolder().getAbsolutePath());
        for (File f : library.getObjectFiles()) {
          objectFiles.add(f);
        }
      }

      for (File f : targetObjectFiles) {
        objectFiles.add(f);
      }

      // 3. compile the sketch (already in the buildPath)

      objectFiles.addAll(
          compileFiles(
              avrBasePath,
              buildPath,
              includePaths,
              findFilesInPath(buildPath, "c", false),
              findFilesInPath(buildPath, "cpp", false)));

      // 4. link it all together into the .elf file

      List<String> baseCommandLinker =
          getCommandLinker(
              avrBasePath, objectFiles, buildPath + File.separator + primaryClassName + ".elf");

      baseCommandLinker.add("-L" + buildPath);
      baseCommandLinker.add("-lm");

      execAsynchronously(baseCommandLinker);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    List<String> baseCommandObjcopy = Arrays.asList(avrBasePath + "avr-objcopy", "-O", "-R");
    List<String> commandObjcopy;

    // 5. extract EEPROM data (from EEMEM directive) to .eep file.
    commandObjcopy = new ArrayList<String>(baseCommandObjcopy);
    commandObjcopy.add(2, "ihex");
    commandObjcopy.set(3, "-j");
    commandObjcopy.add(".eeprom");
    commandObjcopy.add("--set-section-flags=.eeprom=alloc,load");
    commandObjcopy.add("--no-change-warnings");
    commandObjcopy.add("--change-section-lma");
    commandObjcopy.add(".eeprom=0");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".elf");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".eep");
    execAsynchronously(commandObjcopy);

    // 6. build the .hex file
    commandObjcopy = new ArrayList<String>(baseCommandObjcopy);
    commandObjcopy.add(2, "ihex");
    commandObjcopy.add(".eeprom"); // remove eeprom data
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".elf");
    commandObjcopy.add(buildPath + File.separator + primaryClassName + ".hex");
    execAsynchronously(commandObjcopy);

    return true;
  }
示例#10
0
  /**
   * 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) {
    // This receives messages as full lines, so a newline needs
    // to be added as they're printed to the console.
    // ignore cautions
    if (s.indexOf("warning") != -1) {
      return;
    }

    // ignore this line; the real error is on the next one
    if (s.indexOf("In file included from") != -1) {
      return;
    }

    // jikes always uses a forward slash character as its separator,
    // so replace any platform-specific separator characters before
    // attemping to compare
    //
    // String buildPathSubst = buildPath.replace(File.separatorChar, '/') + "/";
    String buildPathSubst =
        buildPath.replace(File.separatorChar, File.separatorChar) + File.separatorChar;

    String partialTempPath = null;
    int partialStartIndex = -1; // s.indexOf(partialTempPath);
    int fileIndex = -1; // use this to build a better exception

    // check the main sketch file first.
    partialTempPath = buildPathSubst + primaryClassName;
    partialStartIndex = s.indexOf(partialTempPath);

    if (partialStartIndex != -1) {
      fileIndex = 0;
    } else {
      // wasn't there, check the other (non-pde) files in the sketch.
      // iterate through the project files to see who's causing the trouble
      for (int i = 0; i < sketch.getCodeCount(); i++) {
        if (sketch.getCode(i).isExtension("pde")) {
          continue;
        }

        partialTempPath = buildPathSubst + sketch.getCode(i).getFileName();
        // System.out.println(partialTempPath);
        partialStartIndex = s.indexOf(partialTempPath);
        if (partialStartIndex != -1) {
          fileIndex = i;
          // System.out.println("fileIndex is " + fileIndex);
          break;
        }
      }
      // + className + ".java";
    }

    // if the partial temp path appears in the error message...
    //
    // int partialStartIndex = s.indexOf(partialTempPath);
    if (partialStartIndex != -1) {

      // skip past the path and parse the int after the first colon
      //
      String s1 = s.substring(partialStartIndex + partialTempPath.length() + 1);
      // System.out.println(s1);
      int colon = s1.indexOf(':');

      if (s1.indexOf("In function") != -1 || colon == -1) {
        System.err.print(s1);
        // firstErrorFound = true;
        return;
      }

      int lineNumber;
      try {
        lineNumber = Integer.parseInt(s1.substring(0, colon));
      } catch (NumberFormatException e) {
        System.err.print(s1);
        return;
      }

      // System.out.println("pde / line number: " + lineNumber);

      if (fileIndex == 0) { // main class, figure out which tab
        for (int i = 1; i < sketch.getCodeCount(); i++) {
          if (sketch.getCode(i).isExtension("pde")) {
            // System.out.println("preprocOffset "+ sketch.getCode(i).getPreprocOffset());
            if (sketch.getCode(i).getPreprocOffset() < lineNumber) {
              fileIndex = i;
              // System.out.println("i'm thinkin file " + i);
            }
          }
        }
        // XXX: DAM: if the lineNumber is less than sketch.getCode(0).getPreprocOffset()
        // we shouldn't subtract anything from it, as the error is above the
        // location where the function prototypes and #include "Platform.h"
        // were inserted.
        lineNumber -= sketch.getCode(fileIndex).getPreprocOffset();
      }

      // String s2 = s1.substring(colon + 2);
      int err = s1.indexOf(":");
      if (err != -1) {

        // if the first error has already been found, then this must be
        // (at least) the second error found
        if (firstErrorFound) {
          secondErrorFound = true;
          return;
        }

        // if executing at this point, this is *at least* the first error
        firstErrorFound = true;

        err += ":".length();
        String description = s1.substring(err);
        description = description.trim();
        System.err.print(description);

        // System.out.println("description = " + description);
        // System.out.println("creating exception " + exception);
        exception = new RunnerException(description, fileIndex, lineNumber - 1, -1, false);

        // NOTE!! major change here, this exception will be queued
        // here to be thrown by the compile() function
        // editor.error(exception);

      } else {
        System.err.println("i suck: " + s);
      }

    } else {
      // this isn't the start of an error line, so don't attempt to parse
      // a line number out of it.

      // if the second error hasn't been discovered yet, these lines
      // are probably associated with the first error message,
      // which is already in the status bar, and are likely to be
      // of interest to the user, so spit them to the console.
      //
      if (!secondErrorFound) {
        System.err.println(s);
      }
    }
  }
示例#11
0
 /**
  * See if the gui.pde tab has been created already if not
  *
  * @param sketch
  * @return
  */
 private boolean guiTabExists(Sketch sketch) {
   File f = new File(sketch.getFolder(), PDE_TAB_NAME);
   return f.exists();
 }
  public void run() {
    if (!new File(m_generatorPy).exists()) {
      Base.showMessage(
          "ERROR", String.format("Could not find generator python script at %s", m_generatorPy));
    }
    Sketch sketch = m_editor.getSketch();
    if (sketch.isModified()) {
      try {
        sketch.save();
      } catch (java.io.IOException ex) {
        // Base.showMessage("ERROR", "Could not save sketch before trying to generate." );
      }
    }

    // String sketchName = sketch.getName();
    // SketchCode codeObject = sketch.getCurrentCode();
    // String code = codeObject.getProgram();
    try {
      String code = m_editor.getCurrentTab().getText();
      // String code = m_editor.getText();
      int start = code.indexOf("BEGIN AUTOMATION");
      if (start != -1) {
        int end = code.indexOf("END AUTOMATION", start);
        if (end != -1) {
          String automationCode = code.substring(start + "BEGIN AUTOMATION".length(), end);
          automationCode = automationCode.replaceAll("\\*\\s+", "");
          // SketchData sketchData = new MySketchData(sketch.getMainFilePath());
          // File buildFolder = BaseNoGui.getBuildFolder(sketchData);
          File buildFolder = getBuildFolder(sketch);
          // File codeFolder = sketchData.getCodeFolder();
          File codeFolder = new File(sketch.getFolder(), "code");
          Files.createDirectories(codeFolder.toPath());
          File automationFileName = new File(buildFolder, "automation.automation");
          FileWriter writer = new FileWriter(automationFileName);
          writer.write("name automation\n");
          writer.write("import " + sketch.getMainFilePath().toString() + "\n");
          writer.write(automationCode);
          writer.close();

          try {
            ProcessBuilder processBuilder = null;
            if (m_isWindows) {
              processBuilder =
                  new ProcessBuilder(
                      m_pythonPath.getAbsolutePath(),
                      m_generatorPy,
                      "-s",
                      "--arduino",
                      automationFileName.getAbsolutePath());
            } else {
              processBuilder =
                  new ProcessBuilder(
                      m_generatorPy, "-s", "--arduino", automationFileName.getAbsolutePath());
            }
            processBuilder.directory(codeFolder);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            inheritIO(process.getInputStream(), System.out);
            int result = process.waitFor();

            String includeLibLine = "#include \"SequantoAutomation.h\"\n";
            if (!code.contains(includeLibLine)) {
              code = includeLibLine + code;
            }

            /*
              File generatedFileName = new File(codeFolder, "automation_automation.c" );
              String includeLine = String.format("#include \"%s\"\n", generatedFileName.getAbsolutePath());
              if ( !code.contains(includeLine) )
              {
              int i = code.indexOf(includeLibLine);
              code = code.substring(0, i + includeLibLine.length()) +
              includeLine +
              code.substring ( i + includeLibLine.length(), code.length() );
              }
            */

            String includeLine = String.format("#include \"code/automation_automation.h\"\n");
            if (!code.contains(includeLine)) {
              int i = code.indexOf(includeLibLine);
              code =
                  code.substring(0, i + includeLibLine.length())
                      + includeLine
                      + code.substring(i + includeLibLine.length(), code.length());
            }

            String includeCodeLine = String.format("\n#include \"code/automation_automation.c\"\n");
            if (!code.contains(includeCodeLine)) {
              code = code + includeCodeLine;
            }

            if (m_editor.getCurrentTab().getText() != code) {
              // System.out.println ( "Setting code to" );
              // System.out.println ( code );
              // System.out.println ( "Current text was" );
              // System.out.println ( m_editor.getText() );
              m_editor.getCurrentTab().setText(code);
            }

            if (result == 0) {
              System.out.println("Sequanto automation code generated successfully!");
            } else {
              System.out.println("ERROR!!!");
            }
          } catch (Exception ex) {
            Base.showMessage("ERROR", String.format("Could not start generator script: %s", ex));
          }
        } else {
          Base.showMessage("ERROR", "Can not find END AUTOMATION.");
        }
      } else {
        Base.showMessage("ERROR", "Can not find BEGIN AUTOMATION.");
      }
    } catch (java.io.IOException ex) {
      Base.showMessage("ERROR", String.format("IO Error: %s.", ex));
    }
  }