public boolean uploadUsingProgrammer(String buildPath, String className) throws Exception {

    TargetPlatform targetPlatform = BaseNoGui.getTargetPlatform();
    String programmer = PreferencesData.get("programmer");
    if (programmer.contains(":")) {
      String[] split = programmer.split(":", 2);
      targetPlatform = BaseNoGui.getCurrentTargetPlatformFromPackage(split[0]);
      programmer = split[1];
    }

    PreferencesMap prefs = PreferencesData.getMap();
    prefs.putAll(BaseNoGui.getBoardPreferences());
    PreferencesMap programmerPrefs = targetPlatform.getProgrammer(programmer);
    if (programmerPrefs == null)
      throw new RunnerException(
          _("Please select a programmer from Tools->Programmer menu"));
    prefs.putAll(programmerPrefs);
    prefs.putAll(targetPlatform.getTool(prefs.getOrExcept("program.tool")));

    prefs.put("build.path", buildPath);
    prefs.put("build.project_name", className);

    if (verbose)
      prefs.put("program.verbose", prefs.getOrExcept("program.params.verbose"));
    else
      prefs.put("program.verbose", prefs.getOrExcept("program.params.quiet"));

    try {
      // if (prefs.get("program.disable_flushing") == null
      // || prefs.get("program.disable_flushing").toLowerCase().equals("false"))
      // {
      // flushSerialBuffer();
      // }

      String pattern = prefs.getOrExcept("program.pattern");
      String[] cmd = StringReplacer.formatAndSplit(pattern, prefs, true);
      return executeUploadCommand(cmd);
    } catch (RunnerException e) {
      throw e;
    } catch (Exception e) {
      throw new RunnerException(e);
    }
  }
 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;
 }
  private void setTheme(String name) throws IOException {
    FileInputStream defaultXmlInputStream = null;
    try {
      defaultXmlInputStream =
          new FileInputStream(
              new File(BaseNoGui.getContentFile("lib"), "theme/syntax/" + name + ".xml"));
      Theme theme = Theme.load(defaultXmlInputStream);
      theme.apply(this);
    } finally {
      IOUtils.closeQuietly(defaultXmlInputStream);
    }

    setBackground(processing.app.Theme.getColor("editor.bgcolor"));
    setHighlightCurrentLine(processing.app.Theme.getBoolean("editor.linehighlight"));
    setCurrentLineHighlightColor(processing.app.Theme.getColor("editor.linehighlight.color"));
    setCaretColor(processing.app.Theme.getColor("editor.caret.color"));
    setSelectedTextColor(null);
    setUseSelectedTextColor(false);
    setSelectionColor(processing.app.Theme.getColor("editor.selection.color"));
    setMatchedBracketBorderColor(processing.app.Theme.getColor("editor.brackethighlight.color"));
    setHyperlinkForeground(
        (Color) processing.app.Theme.getStyledFont("url", getFont()).get("color"));

    setSyntaxTheme(TokenTypes.DATA_TYPE, "data_type");
    setSyntaxTheme(TokenTypes.FUNCTION, "function");
    setSyntaxTheme(TokenTypes.RESERVED_WORD, "reserved_word");
    setSyntaxTheme(TokenTypes.RESERVED_WORD_2, "reserved_word_2");
    setSyntaxTheme(TokenTypes.VARIABLE, "variable");
    setSyntaxTheme(TokenTypes.OPERATOR, "operator");
    setSyntaxTheme(TokenTypes.COMMENT_DOCUMENTATION, "comment1");
    setSyntaxTheme(TokenTypes.COMMENT_EOL, "comment1");
    setSyntaxTheme(TokenTypes.COMMENT_KEYWORD, "comment1");
    setSyntaxTheme(TokenTypes.COMMENT_MARKUP, "comment1");
    setSyntaxTheme(TokenTypes.COMMENT_MULTILINE, "comment2");
    setSyntaxTheme(TokenTypes.LITERAL_BOOLEAN, "literal_boolean");
    setSyntaxTheme(TokenTypes.LITERAL_CHAR, "literal_char");
    setSyntaxTheme(TokenTypes.LITERAL_STRING_DOUBLE_QUOTE, "literal_string_double_quote");
    setSyntaxTheme(TokenTypes.PREPROCESSOR, "preprocessor");

    Style style = getSyntaxScheme().getStyle(TokenTypes.IDENTIFIER);
    style.foreground = processing.app.Theme.getColor("editor.fgcolor");
    getSyntaxScheme().setStyle(TokenTypes.IDENTIFIER, style);
  }
  public boolean uploadUsingPreferences(File sourcePath, String buildPath, String className, boolean usingProgrammer, List<String> warningsAccumulator) throws Exception {
    // FIXME: Preferences should be reorganized
    TargetPlatform targetPlatform = BaseNoGui.getTargetPlatform();
    PreferencesMap prefs = PreferencesData.getMap();
    prefs.putAll(BaseNoGui.getBoardPreferences());
    String tool = prefs.getOrExcept("upload.tool");
    if (tool.contains(":")) {
      String[] split = tool.split(":", 2);
      targetPlatform = BaseNoGui.getCurrentTargetPlatformFromPackage(split[0]);
      tool = split[1];
    }
    prefs.putAll(targetPlatform.getTool(tool));

    // if no protocol is specified for this board, assume it lacks a 
    // bootloader and upload using the selected programmer.
    if (usingProgrammer || prefs.get("upload.protocol") == null) {
      return uploadUsingProgrammer(buildPath, className);
    }

    if (noUploadPort)
    {
      prefs.put("build.path", buildPath);
      prefs.put("build.project_name", className);
      if (verbose)
        prefs.put("upload.verbose", prefs.getOrExcept("upload.params.verbose"));
      else
        prefs.put("upload.verbose", prefs.getOrExcept("upload.params.quiet"));

      boolean uploadResult;
      try {
        String pattern = prefs.getOrExcept("upload.pattern");
        String[] cmd = StringReplacer.formatAndSplit(pattern, prefs, true);
        uploadResult = executeUploadCommand(cmd);
      } catch (Exception e) {
        throw new RunnerException(e);
      }
      return uploadResult;
    }

    // need to do a little dance for Leonardo and derivatives:
    // open then close the port at the magic baudrate (usually 1200 bps) first
    // to signal to the sketch that it should reset into bootloader. after doing
    // this wait a moment for the bootloader to enumerate. On Windows, also must
    // deal with the fact that the COM port number changes from bootloader to
    // sketch.
    String t = prefs.get("upload.use_1200bps_touch");
    boolean doTouch = t != null && t.equals("true");

    t = prefs.get("upload.wait_for_upload_port");
    boolean waitForUploadPort = (t != null) && t.equals("true");

    if (doTouch) {
      String uploadPort = prefs.getOrExcept("serial.port");
      try {
        // Toggle 1200 bps on selected serial port to force board reset.
        List<String> before = Serial.list();
        if (before.contains(uploadPort)) {
          if (verbose)
            System.out.println(_("Forcing reset using 1200bps open/close on port ") + uploadPort);
          Serial.touchPort(uploadPort, 1200);
        }
        Thread.sleep(400);
        if (waitForUploadPort) {
          // Scanning for available ports seems to open the port or
          // otherwise assert DTR, which would cancel the WDT reset if
          // it happened within 250 ms. So we wait until the reset should
          // have already occured before we start scanning.
          uploadPort = waitForUploadPort(uploadPort, before);
        }
      } catch (SerialException e) {
        throw new RunnerException(e);
      } catch (InterruptedException e) {
        throw new RunnerException(e.getMessage());
      }
      prefs.put("serial.port", uploadPort);
      if (uploadPort.startsWith("/dev/"))
        prefs.put("serial.port.file", uploadPort.substring(5));
      else
        prefs.put("serial.port.file", uploadPort);
    }

    prefs.put("build.path", buildPath);
    prefs.put("build.project_name", className);
    if (verbose)
      prefs.put("upload.verbose", prefs.getOrExcept("upload.params.verbose"));
    else
      prefs.put("upload.verbose", prefs.getOrExcept("upload.params.quiet"));

    boolean uploadResult;
    try {
//      if (prefs.get("upload.disable_flushing") == null
//          || prefs.get("upload.disable_flushing").toLowerCase().equals("false")) {
//        flushSerialBuffer();
//      }

      String pattern = prefs.getOrExcept("upload.pattern");
      String[] cmd = StringReplacer.formatAndSplit(pattern, prefs, true);
      uploadResult = executeUploadCommand(cmd);
    } catch (RunnerException e) {
      throw e;
    } catch (Exception e) {
      throw new RunnerException(e);
    }

    try {
      if (uploadResult && doTouch) {
        String uploadPort = PreferencesData.get("serial.port");
        if (waitForUploadPort) {
          // For Due/Leonardo wait until the bootloader serial port disconnects and the
          // sketch serial port reconnects (or timeout after a few seconds if the
          // sketch port never comes back). Doing this saves users from accidentally
          // opening Serial Monitor on the soon-to-be-orphaned bootloader port.
          Thread.sleep(1000);
          long started = System.currentTimeMillis();
          while (System.currentTimeMillis() - started < 2000) {
            List<String> portList = Serial.list();
            if (portList.contains(uploadPort))
              break;
            Thread.sleep(250);
          }
        }
      }
    } catch (InterruptedException ex) {
      // noop
    }
    return uploadResult;
  }
  public boolean burnBootloader() throws Exception {
    TargetPlatform targetPlatform = BaseNoGui.getTargetPlatform();

    // Find preferences for the selected programmer
    PreferencesMap programmerPrefs;
    String programmer = PreferencesData.get("programmer");
    if (programmer.contains(":")) {
      String[] split = programmer.split(":", 2);
      TargetPlatform platform = BaseNoGui.getCurrentTargetPlatformFromPackage(split[0]);
      programmer = split[1];
      programmerPrefs = platform.getProgrammer(programmer);
    } else {
      programmerPrefs = targetPlatform.getProgrammer(programmer);
    }
    if (programmerPrefs == null)
      throw new RunnerException(
          _("Please select a programmer from Tools->Programmer menu"));

    // Build configuration for the current programmer
    PreferencesMap prefs = PreferencesData.getMap();
    prefs.putAll(BaseNoGui.getBoardPreferences());
    prefs.putAll(programmerPrefs);

    // Create configuration for bootloader tool
    PreferencesMap toolPrefs = new PreferencesMap();
    String tool = prefs.getOrExcept("bootloader.tool");
    if (tool.contains(":")) {
      String[] split = tool.split(":", 2);
      TargetPlatform platform = BaseNoGui.getCurrentTargetPlatformFromPackage(split[0]);
      tool = split[1];
      toolPrefs.putAll(platform.getTool(tool));
      if (toolPrefs.size() == 0)
        throw new RunnerException(I18n.format(_("Could not find tool {0} from package {1}"), tool, split[0]));
    }
    toolPrefs.putAll(targetPlatform.getTool(tool));
    if (toolPrefs.size() == 0)
      throw new RunnerException(I18n.format(_("Could not find tool {0}"), tool));

    // Merge tool with global configuration
    prefs.putAll(toolPrefs);
    if (verbose) {
      prefs.put("erase.verbose", prefs.getOrExcept("erase.params.verbose"));
      prefs.put("bootloader.verbose", prefs.getOrExcept("bootloader.params.verbose"));
    } else {
      prefs.put("erase.verbose", prefs.getOrExcept("erase.params.quiet"));
      prefs.put("bootloader.verbose", prefs.getOrExcept("bootloader.params.quiet"));
    }

    try {
      String pattern = prefs.getOrExcept("erase.pattern");
      String[] cmd = StringReplacer.formatAndSplit(pattern, prefs, true);
      if (!executeUploadCommand(cmd))
        return false;

      pattern = prefs.getOrExcept("bootloader.pattern");
      cmd = StringReplacer.formatAndSplit(pattern, prefs, true);
      return executeUploadCommand(cmd);
    } catch (RunnerException e) {
      throw e;
    } catch (Exception e) {
      throw new RunnerException(e);
    }
  }