コード例 #1
0
  /** Handler for the Rename Code menu option. */
  public void handleRenameCode() {
    SketchFile current = editor.getCurrentTab().getSketchFile();

    editor.status.clearState();
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    if (current.isPrimary() && editor.untitled) {
      Base.showMessage(
          tr("Sketch is Untitled"),
          tr("How about saving the sketch first \n" + "before trying to rename it?"));
      return;
    }

    // if read-only, give an error
    if (isReadOnly(
        BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath())) {
      // if the files are read-only, need to first do a "save as".
      Base.showMessage(
          tr("Sketch is Read-Only"),
          tr(
              "Some files are marked \"read-only\", so you'll\n"
                  + "need to re-save the sketch in another location,\n"
                  + "and try again."));
      return;
    }

    // ask for new name of file (internal to window)
    // TODO maybe just popup a text area?
    renamingCode = true;
    String prompt = current.isPrimary() ? "New name for sketch:" : "New name for file:";
    String oldName = current.getPrettyName();
    editor.status.edit(prompt, oldName);
  }
コード例 #2
0
  /**
   * Make sure the sketch hasn't been moved or deleted by some nefarious user. If they did, try to
   * re-create it and save. Only checks to see if the main folder is still around, but not its
   * contents.
   */
  private void ensureExistence() {
    if (sketch.getFolder().exists()) return;

    Base.showWarning(
        tr("Sketch Disappeared"),
        tr(
            "The sketch folder has disappeared.\n "
                + "Will attempt to re-save in the same location,\n"
                + "but anything besides the code will be lost."),
        null);
    try {
      sketch.getFolder().mkdirs();

      for (SketchFile file : sketch.getFiles()) {
        file.save(); // this will force a save
      }
      calcModified();

    } catch (Exception e) {
      Base.showWarning(
          tr("Could not re-save sketch"),
          tr(
              "Could not properly re-save the sketch. "
                  + "You may be in trouble at this point,\n"
                  + "and it might be time to copy and paste "
                  + "your code to another text editor."),
          e);
    }
  }
コード例 #3
0
  /** Add import statements to the current tab for the specified library */
  public void importLibrary(UserLibrary lib) throws IOException {
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    List<String> list = lib.getIncludes();
    if (list == null) {
      File srcFolder = lib.getSrcFolder();
      String[] headers = Base.headerListFromIncludePath(srcFolder);
      list = Arrays.asList(headers);
    }
    if (list.isEmpty()) {
      return;
    }

    // import statements into the main sketch file (code[0])
    // if the current code is a .java file, insert into current
    // if (current.flavor == PDE) {
    SketchFile file = editor.getCurrentTab().getSketchFile();
    if (file.isExtension(Sketch.SKETCH_EXTENSIONS)) editor.selectTab(0);

    // could also scan the text in the file to see if each import
    // statement is already in there, but if the user has the import
    // commented out, then this will be a problem.
    StringBuilder buffer = new StringBuilder();
    for (String aList : list) {
      buffer.append("#include <");
      buffer.append(aList);
      buffer.append(">\n");
    }
    buffer.append('\n');
    buffer.append(editor.getCurrentTab().getText());
    editor.getCurrentTab().setText(buffer.toString());
    editor.getCurrentTab().setSelection(0, 0); // scroll to start
  }
コード例 #4
0
  /** Save all code in the current sketch. */
  public boolean save() throws IOException {
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    if (isReadOnly(
        BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath())) {
      Base.showMessage(
          tr("Sketch is read-only"),
          tr(
              "Some files are marked \"read-only\", so you'll\n"
                  + "need to re-save this sketch to another location."));
      return saveAs();
    }

    // rename .pde files to .ino
    List<SketchFile> oldFiles = new ArrayList<>();
    for (SketchFile file : sketch.getFiles()) {
      if (file.isExtension(Sketch.OLD_SKETCH_EXTENSIONS)) oldFiles.add(file);
    }

    if (oldFiles.size() > 0) {
      if (PreferencesData.get("editor.update_extension") == null) {
        Object[] options = {tr("OK"), tr("Cancel")};
        int result =
            JOptionPane.showOptionDialog(
                editor,
                tr(
                    "In Arduino 1.0, the default file extension has changed\n"
                        + "from .pde to .ino.  New sketches (including those created\n"
                        + "by \"Save-As\") will use the new extension.  The extension\n"
                        + "of existing sketches will be updated on save, but you can\n"
                        + "disable this in the Preferences dialog.\n"
                        + "\n"
                        + "Save sketch and update its extension?"),
                tr(".pde -> .ino"),
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[0]);

        if (result != JOptionPane.OK_OPTION) return false; // save cancelled

        PreferencesData.setBoolean("editor.update_extension", true);
      }

      if (PreferencesData.getBoolean("editor.update_extension")) {
        // Do rename of all .pde files to new .ino extension
        for (SketchFile file : oldFiles) {
          File newName =
              FileUtils.replaceExtension(file.getFile(), Sketch.DEFAULT_SKETCH_EXTENSION);
          file.renameTo(newName.getName());
        }
      }
    }

    sketch.save();
    return true;
  }
コード例 #5
0
 private boolean sketchFilesAreReadOnly() {
   for (SketchFile file : sketch.getFiles()) {
     if (file.isModified() && file.fileReadOnly() && file.fileExists()) {
       return true;
     }
   }
   return false;
 }
コード例 #6
0
  private File saveSketchInTempFolder() throws IOException {
    File tempFolder = FileUtils.createTempFolder("arduino_modified_sketch_");
    FileUtils.copy(sketch.getFolder(), tempFolder);

    for (SketchFile file :
        Stream.of(sketch.getFiles()).filter(SketchFile::isModified).collect(Collectors.toList())) {
      Files.write(
          Paths.get(tempFolder.getAbsolutePath(), file.getFileName()),
          file.getProgram().getBytes());
    }

    return Paths.get(tempFolder.getAbsolutePath(), sketch.getPrimaryFile().getFileName()).toFile();
  }
コード例 #7
0
  /** Remove a piece of code from the sketch and from the disk. */
  public void handleDeleteCode() throws IOException {
    SketchFile current = editor.getCurrentTab().getSketchFile();
    editor.status.clearState();
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    // if read-only, give an error
    if (isReadOnly(
        BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath())) {
      // if the files are read-only, need to first do a "save as".
      Base.showMessage(
          tr("Sketch is Read-Only"),
          tr(
              "Some files are marked \"read-only\", so you'll\n"
                  + "need to re-save the sketch in another location,\n"
                  + "and try again."));
      return;
    }

    // confirm deletion with user, yes/no
    Object[] options = {tr("OK"), tr("Cancel")};
    String prompt =
        current.isPrimary()
            ? tr("Are you sure you want to delete this sketch?")
            : I18n.format(tr("Are you sure you want to delete \"{0}\"?"), current.getPrettyName());
    int result =
        JOptionPane.showOptionDialog(
            editor,
            prompt,
            tr("Delete"),
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]);
    if (result == JOptionPane.YES_OPTION) {
      if (current.isPrimary()) {
        sketch.delete();
        editor.base.handleClose(editor);
      } else {
        // delete the file
        if (!current.delete(sketch.getBuildPath().toPath())) {
          Base.showMessage(
              tr("Couldn't do it"),
              I18n.format(tr("Could not delete \"{0}\"."), current.getFileName()));
          return;
        }

        // just set current tab to the main tab
        editor.selectTab(0);

        // update the tabs
        editor.header.repaint();
      }
    }
  }
コード例 #8
0
  /**
   * This is called upon return from entering a new file name. (that is, from either newCode or
   * renameCode after the prompt) This code is almost identical for both the newCode and renameCode
   * cases, so they're kept merged except for right in the middle where they diverge.
   */
  protected void nameCode(String newName) {
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    newName = newName.trim();
    if (newName.equals("")) return;

    if (newName.charAt(0) == '.') {
      Base.showWarning(tr("Problem with rename"), tr("The name cannot start with a period."), null);
      return;
    }

    FileUtils.SplitFile split = FileUtils.splitFilename(newName);
    if (split.extension.equals("")) split.extension = Sketch.DEFAULT_SKETCH_EXTENSION;

    if (!Sketch.EXTENSIONS.contains(split.extension)) {
      String msg = I18n.format(tr("\".{0}\" is not a valid extension."), split.extension);
      Base.showWarning(tr("Problem with rename"), msg, null);
      return;
    }

    // Sanitize name
    split.basename = BaseNoGui.sanitizeName(split.basename);
    newName = split.join();

    if (renamingCode) {
      SketchFile current = editor.getCurrentTab().getSketchFile();

      if (current.isPrimary()) {
        if (!split.extension.equals(Sketch.DEFAULT_SKETCH_EXTENSION)) {
          Base.showWarning(
              tr("Problem with rename"), tr("The main file cannot use an extension"), null);
          return;
        }

        // Primary file, rename the entire sketch
        final File parent = sketch.getFolder().getParentFile();
        File newFolder = new File(parent, split.basename);
        try {
          sketch.renameTo(newFolder);
        } catch (IOException e) {
          // This does not pass on e, to prevent showing a backtrace for
          // "normal" errors.
          Base.showWarning(tr("Error"), e.getMessage(), null);
          return;
        }

        editor.base.rebuildSketchbookMenus();
      } else {
        // Non-primary file, rename just that file
        try {
          current.renameTo(newName);
        } catch (IOException e) {
          // This does not pass on e, to prevent showing a backtrace for
          // "normal" errors.
          Base.showWarning(tr("Error"), e.getMessage(), null);
          return;
        }
      }

    } else { // creating a new file
      SketchFile file;
      try {
        file = sketch.addFile(newName);
        editor.addTab(file, "");
      } catch (IOException e) {
        // This does not pass on e, to prevent showing a backtrace for
        // "normal" errors.
        Base.showWarning(tr("Error"), e.getMessage(), null);
        return;
      }
      editor.selectTab(editor.findTabIndex(file));
    }

    // update the tabs
    editor.header.rebuild();
  }