コード例 #1
0
 public String saveAsFile(boolean accessingAsFile) throws IOException {
   File file = new SikuliIDEFileChooser(SikuliIDE.getInstance(), accessingAsFile).save();
   if (file == null) {
     return null;
   }
   String bundlePath = FileManager.slashify(file.getAbsolutePath(), false);
   if (!file.getAbsolutePath().endsWith(".sikuli")) {
     bundlePath += ".sikuli";
   }
   if (FileManager.exists(bundlePath)) {
     int res =
         JOptionPane.showConfirmDialog(
             null,
             SikuliIDEI18N._I("msgFileExists", bundlePath),
             SikuliIDEI18N._I("dlgFileExists"),
             JOptionPane.YES_NO_OPTION);
     if (res != JOptionPane.YES_OPTION) {
       return null;
     }
   } else {
     FileManager.mkdir(bundlePath);
   }
   try {
     saveAsBundle(bundlePath, (SikuliIDE.getInstance().getCurrentFileTabTitle()));
     if (Settings.isMac()) {
       if (!Settings.handlesMacBundles) {
         makeBundle(bundlePath, accessingAsFile);
       }
     }
   } catch (IOException iOException) {
   }
   return getCurrentShortFilename();
 }
コード例 #2
0
    public void actionPerformed(ActionEvent e) {
      if (readOnly) {
        return;
      }
      JFileChooser fc = getFileChooser();
      File currentDirectory = fc.getCurrentDirectory();

      if (!currentDirectory.exists()) {
        JOptionPane.showMessageDialog(
            fc,
            newFolderParentDoesntExistText,
            newFolderParentDoesntExistTitleText,
            JOptionPane.WARNING_MESSAGE);
        return;
      }

      File newFolder;
      try {
        newFolder = fc.getFileSystemView().createNewFolder(currentDirectory);
        if (fc.isMultiSelectionEnabled()) {
          fc.setSelectedFiles(new File[] {newFolder});
        } else {
          fc.setSelectedFile(newFolder);
        }
      } catch (IOException exc) {
        JOptionPane.showMessageDialog(
            fc,
            newFolderErrorText + newFolderErrorSeparator + exc,
            newFolderErrorText,
            JOptionPane.ERROR_MESSAGE);
        return;
      }

      fc.rescanCurrentDirectory();
    }
コード例 #3
0
 @Override
 public boolean importData(JComponent comp, Transferable t) {
   DataFlavor htmlFlavor = DataFlavor.stringFlavor;
   if (canImport(comp, t.getTransferDataFlavors())) {
     try {
       String transferString = (String) t.getTransferData(htmlFlavor);
       EditorPane targetTextPane = (EditorPane) comp;
       for (Map.Entry<String, String> entry : _copiedImgs.entrySet()) {
         String imgName = entry.getKey();
         String imgPath = entry.getValue();
         File destFile = targetTextPane.copyFileToBundle(imgPath);
         String newName = destFile.getName();
         if (!newName.equals(imgName)) {
           String ptnImgName = "\"" + imgName + "\"";
           newName = "\"" + newName + "\"";
           transferString = transferString.replaceAll(ptnImgName, newName);
           Debug.info(ptnImgName + " exists. Rename it to " + newName);
         }
       }
       targetTextPane.insertString(transferString);
     } catch (Exception e) {
       Debug.error(me + "importData: Problem pasting text\n%s", e.getMessage());
     }
     return true;
   }
   return false;
 }
コード例 #4
0
ファイル: DragAndDrop.java プロジェクト: Jondeen/imagej1
 private void openDirectory(File f, String path) {
   if (path == null) return;
   if (!(path.endsWith(File.separator) || path.endsWith("/"))) path += File.separator;
   String[] names = f.list();
   names = (new FolderOpener()).trimFileList(names);
   if (names == null) return;
   String msg = "Open all " + names.length + " images in \"" + f.getName() + "\" as a stack?";
   GenericDialog gd = new GenericDialog("Open Folder");
   gd.setInsets(10, 5, 0);
   gd.addMessage(msg);
   gd.setInsets(15, 35, 0);
   gd.addCheckbox("Convert to RGB", convertToRGB);
   gd.setInsets(0, 35, 0);
   gd.addCheckbox("Use Virtual Stack", virtualStack);
   gd.enableYesNoCancel();
   gd.showDialog();
   if (gd.wasCanceled()) return;
   if (gd.wasOKed()) {
     convertToRGB = gd.getNextBoolean();
     virtualStack = gd.getNextBoolean();
     String options = " sort";
     if (convertToRGB) options += " convert_to_rgb";
     if (virtualStack) options += " use";
     IJ.run("Image Sequence...", "open=[" + path + "]" + options);
     DirectoryChooser.setDefaultDirectory(path);
   } else {
     for (int k = 0; k < names.length; k++) {
       IJ.redirectErrorMessages();
       if (!names[k].startsWith(".")) (new Opener()).open(path + names[k]);
     }
   }
   IJ.register(DragAndDrop.class);
 }
コード例 #5
0
 public void loadFile(String filename) {
   filename = FileManager.slashify(filename, false);
   setSrcBundle(filename + "/");
   File script = new File(filename);
   _editingFile = FileManager.getScriptFile(script, null, null);
   if (_editingFile != null) {
     editingType =
         _editingFile
             .getAbsolutePath()
             .substring(_editingFile.getAbsolutePath().lastIndexOf(".") + 1);
     initBeforeLoad(editingType);
     try {
       this.read(
           new BufferedReader(new InputStreamReader(new FileInputStream(_editingFile), "UTF8")),
           null);
     } catch (Exception ex) {
       _editingFile = null;
     }
   }
   if (_editingFile != null) {
     updateDocumentListeners();
     setDirty(false);
     _srcBundleTemp = false;
   } else {
     _srcBundlePath = null;
   }
 }
コード例 #6
0
 private String getCurrentShortFilename() {
   if (_srcBundlePath != null) {
     File f = new File(_srcBundlePath);
     return f.getName();
   }
   return "Untitled";
 }
コード例 #7
0
 public String getSrcBundle() {
   if (_srcBundlePath == null) {
     File tmp = FileManager.createTempDir();
     setSrcBundle(FileManager.slashify(tmp.getAbsolutePath(), true));
     _srcBundleTemp = true;
   }
   return _srcBundlePath;
 }
コード例 #8
0
    public void valueChanged(ListSelectionEvent evt) {
      if (!evt.getValueIsAdjusting()) {
        JFileChooser chooser = getFileChooser();
        FileSystemView fsv = chooser.getFileSystemView();
        JList list = (JList) evt.getSource();

        int fsm = chooser.getFileSelectionMode();
        boolean useSetDirectory = usesSingleFilePane && (fsm == JFileChooser.FILES_ONLY);

        if (chooser.isMultiSelectionEnabled()) {
          File[] files = null;
          Object[] objects = list.getSelectedValues();
          if (objects != null) {
            if (objects.length == 1
                && ((File) objects[0]).isDirectory()
                && chooser.isTraversable(((File) objects[0]))
                && (useSetDirectory || !fsv.isFileSystem(((File) objects[0])))) {
              setDirectorySelected(true);
              setDirectory(((File) objects[0]));
            } else {
              ArrayList<File> fList = new ArrayList<File>(objects.length);
              for (Object object : objects) {
                File f = (File) object;
                boolean isDir = f.isDirectory();
                if ((chooser.isFileSelectionEnabled() && !isDir)
                    || (chooser.isDirectorySelectionEnabled() && fsv.isFileSystem(f) && isDir)) {
                  fList.add(f);
                }
              }
              if (fList.size() > 0) {
                files = fList.toArray(new File[fList.size()]);
              }
              setDirectorySelected(false);
            }
          }
          chooser.setSelectedFiles(files);
        } else {
          File file = (File) list.getSelectedValue();
          if (file != null
              && file.isDirectory()
              && chooser.isTraversable(file)
              && (useSetDirectory || !fsv.isFileSystem(file))) {

            setDirectorySelected(true);
            setDirectory(file);
            if (usesSingleFilePane) {
              chooser.setSelectedFile(null);
            }
          } else {
            setDirectorySelected(false);
            if (file != null) {
              chooser.setSelectedFile(file);
            }
          }
        }
      }
    }
コード例 #9
0
 public boolean accept(File f) {
   if (f == null) {
     return false;
   }
   if (f.isDirectory()) {
     return true;
   }
   return pattern.matcher(f.getName()).matches();
 }
コード例 #10
0
 public File reparseBefore() {
   Element e = this.getDocument().getDefaultRootElement();
   if (e.getEndOffset() - e.getStartOffset() == 1) {
     return null;
   }
   File temp = FileManager.createTempFile("reparse");
   try {
     writeFile(temp.getAbsolutePath());
     return temp;
   } catch (IOException ex) {
   }
   return null;
 }
コード例 #11
0
 private void writeSrcFile() throws IOException {
   Debug.log(3, "IDE: writeSrcFile: " + _editingFile.getName());
   writeFile(_editingFile.getAbsolutePath());
   if (PreferencesUser.getInstance().getAtSaveMakeHTML()) {
     convertSrcToHtml(getSrcBundle());
   } else {
     String snameDir = new File(_editingFile.getAbsolutePath()).getParentFile().getName();
     String sname = snameDir.replace(".sikuli", "") + ".html";
     (new File(snameDir, sname)).delete();
   }
   if (PreferencesUser.getInstance().getAtSaveCleanBundle()) {
     cleanBundle(getSrcBundle());
   }
   setDirty(false);
 }
コード例 #12
0
 public File copyFileToBundle(String filename) {
   File f = new File(filename);
   String bundlePath = getSrcBundle();
   if (f.exists()) {
     try {
       File newFile = FileManager.smartCopy(filename, bundlePath);
       return newFile;
     } catch (IOException e) {
       Debug.error(
           me + "copyFileToBundle: Problem while trying to save %s\n%s", filename, e.getMessage());
       return f;
     }
   }
   return null;
 }
コード例 #13
0
ファイル: MainFrame.java プロジェクト: gaurav/taxref
  /**
   * Load a file of a particular type. It's a pretty standard helper function, which uses DarwinCSV
   * and setCurrentCSV(...) to make file loading happen with messaging and whatnot. We can also
   * reset the display: just call loadFile(null).
   *
   * @param file The file to load.
   * @param type The type of file (see DarwinCSV's constants).
   */
  private void loadFile(File file, short type) {
    // If the file was reset, reset the display and keep going.
    if (file == null) {
      mainFrame.setTitle(basicTitle);
      setCurrentCSV(null);
      return;
    }

    // Load up a new DarwinCSV and set current CSV.
    try {
      setCurrentCSV(new DarwinCSV(file, type));

    } catch (IOException ex) {
      MessageBox.messageBox(
          mainFrame,
          "Could not read file '" + file + "'",
          "Unable to read file '" + file + "': " + ex);
    }

    // Set the main frame title, based on the filename and the index.
    mainFrame.setTitle(
        basicTitle
            + ": "
            + file.getName()
            + " ("
            + String.format("%,d", currentCSV.getRowIndex().getRowCount())
            + " rows)");
  }
コード例 #14
0
  private void changeDirectory(File dir) {
    JFileChooser fc = getFileChooser();
    // Traverse shortcuts on Windows
    if (dir != null && FilePane.usesShellFolder(fc)) {
      try {
        ShellFolder shellFolder = ShellFolder.getShellFolder(dir);

        if (shellFolder.isLink()) {
          File linkedTo = shellFolder.getLinkLocation();

          // If linkedTo is null we try to use dir
          if (linkedTo != null) {
            if (fc.isTraversable(linkedTo)) {
              dir = linkedTo;
            } else {
              return;
            }
          } else {
            dir = shellFolder;
          }
        }
      } catch (FileNotFoundException ex) {
        return;
      }
    }
    fc.setCurrentDirectory(dir);
    if (fc.getFileSelectionMode() == JFileChooser.FILES_AND_DIRECTORIES
        && fc.getFileSystemView().isFileSystem(dir)) {

      setFileName(dir.getAbsolutePath());
    }
  }
コード例 #15
0
 public Boolean isHidden(File f) {
   String name = f.getName();
   if (name != null && name.charAt(0) == '.') {
     return Boolean.TRUE;
   } else {
     return Boolean.FALSE;
   }
 }
コード例 #16
0
 // <editor-fold defaultstate="collapsed" desc="file handling">
 public String loadFile(boolean accessingAsFile) throws IOException {
   File file = new SikuliIDEFileChooser(SikuliIDE.getInstance(), accessingAsFile).load();
   if (file == null) {
     return null;
   }
   String fname = FileManager.slashify(file.getAbsolutePath(), false);
   SikuliIDE ide = SikuliIDE.getInstance();
   int i = ide.isAlreadyOpen(fname);
   if (i > -1) {
     Debug.log(2, "Already open in IDE: " + fname);
     return null;
   }
   loadFile(fname);
   if (_editingFile == null) {
     return null;
   }
   return fname;
 }
コード例 #17
0
  public String exportAsZip() throws IOException, FileNotFoundException {
    File file = new SikuliIDEFileChooser(SikuliIDE.getInstance()).export();
    if (file == null) {
      return null;
    }

    String zipPath = file.getAbsolutePath();
    String srcName = file.getName();
    if (!file.getAbsolutePath().endsWith(".skl")) {
      zipPath += ".skl";
    } else {
      srcName = srcName.substring(0, srcName.lastIndexOf('.'));
    }
    writeFile(getSrcBundle() + srcName + ".py");
    FileManager.zip(getSrcBundle(), zipPath);
    Debug.log(2, "export to executable file: " + zipPath);
    return zipPath;
  }
コード例 #18
0
 public String getCurrentSrcDir() {
   if (_srcBundlePath != null) {
     if (_editingFile == null || _srcBundleTemp) {
       return null;
     } else {
       return _editingFile.getParent();
     }
   } else {
     return null;
   }
 }
コード例 #19
0
 public String getTypeDescription(File f) {
   String type = getFileChooser().getFileSystemView().getSystemTypeDescription(f);
   if (type == null) {
     if (f.isDirectory()) {
       type = directoryDescriptionText;
     } else {
       type = fileDescriptionText;
     }
   }
   return type;
 }
コード例 #20
0
ファイル: MainPanel.java プロジェクト: mhcrnl/java-swing-tips
 @Override
 public void drop(DropTargetDropEvent dtde) {
   try {
     if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
       dtde.acceptDrop(DnDConstants.ACTION_COPY);
       Transferable t = dtde.getTransferable();
       List list = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
       for (Object o : list) {
         if (o instanceof File) {
           File f = (File) o;
           System.out.println(f.getAbsolutePath());
         }
       }
       dtde.dropComplete(true);
       return;
     }
   } catch (UnsupportedFlavorException | IOException ex) {
     ex.printStackTrace();
   }
   dtde.rejectDrop();
 }
コード例 #21
0
ファイル: DragAndDrop.java プロジェクト: Jondeen/imagej1
 /**
  * Open a file. If it's a directory, ask to open all images as a sequence in a stack or
  * individually.
  */
 public void openFile(File f) {
   if (IJ.debugMode) IJ.log("DragAndDrop.openFile: " + f);
   try {
     if (null == f) return;
     String path = f.getCanonicalPath();
     if (f.exists()) {
       if (f.isDirectory()) openDirectory(f, path);
       else {
         if (openAsVirtualStack && (path.endsWith(".tif") || path.endsWith(".TIF")))
           (new FileInfoVirtualStack()).run(path);
         else (new Opener()).openAndAddToRecent(path);
         OpenDialog.setLastDirectory(f.getParent() + File.separator);
         OpenDialog.setLastName(f.getName());
       }
     } else {
       IJ.log("File not found: " + path);
     }
   } catch (Throwable e) {
     if (!Macro.MACRO_CANCELED.equals(e.getMessage())) IJ.handleException(e);
   }
 }
コード例 #22
0
 public File getCurrentFile(boolean shouldSave) {
   if (shouldSave && _editingFile == null && isDirty()) {
     try {
       saveAsFile(Settings.isMac());
     } catch (IOException e) {
       Debug.error(
           me + "getCurrentFile: Problem while trying to save %s\n%s",
           _editingFile.getAbsolutePath(),
           e.getMessage());
     }
   }
   return _editingFile;
 }
コード例 #23
0
    public Icon getIcon(File f) {
      Icon icon = getCachedIcon(f);
      if (icon != null) {
        return icon;
      }
      icon = fileIcon;
      if (f != null) {
        FileSystemView fsv = getFileChooser().getFileSystemView();

        if (fsv.isFloppyDrive(f)) {
          icon = floppyDriveIcon;
        } else if (fsv.isDrive(f)) {
          icon = hardDriveIcon;
        } else if (fsv.isComputerNode(f)) {
          icon = computerIcon;
        } else if (f.isDirectory()) {
          icon = directoryIcon;
        }
      }
      cacheIcon(f, icon);
      return icon;
    }
コード例 #24
0
ファイル: ReviewDialog.java プロジェクト: rokstrnisa/RokClock
 /**
  * This function writes the generated relative overview to a file.
  *
  * @param f The file to write to.
  * @throws IOException Thrown if unable to open or write to the file.
  * @throws InsufficientDataException Thrown if unable to generate the overview.
  */
 public void writeToFile(File f) throws IOException, InsufficientDataException {
   f.createNewFile();
   FileWriter fw = new FileWriter(f);
   fw.write(generateOverviewText());
   fw.close();
 }
コード例 #25
0
ファイル: ArtemisMain.java プロジェクト: ambarrio/Artemis
  /** Read the entries given in the uk.ac.sanger.artemis.ini file. */
  private void readDefaultEntries() {
    final EntryInformation artemis_entry_information = Options.getArtemisEntryInformation();

    final String default_sequence_file_name = Options.getOptions().getDefaultSequenceFileName();

    final String default_feature_file_name = Options.getOptions().getDefaultFeatureFileName();

    if (default_sequence_file_name != null) {
      final String default_sequence_file_name_embl = default_sequence_file_name + "_embl";

      uk.ac.sanger.artemis.io.Entry new_embl_entry = null;

      // try opening the default sequence file with "_embl" added to the name
      // if that fails try the plain sequence file name

      final Document entry_document = DocumentFactory.makeDocument(default_sequence_file_name_embl);

      final InputStreamProgressListener progress_listener = getInputStreamProgressListener();

      entry_document.addInputStreamProgressListener(progress_listener);

      if (entry_document.readable()) {
        new_embl_entry =
            EntryFileDialog.getEntryFromFile(
                this, entry_document, artemis_entry_information, false);
      }

      if (new_embl_entry == null
          || new_embl_entry.getSequence() == null
          || new_embl_entry.getSequence().length() == 0) {
        final File entry_file = new File(default_sequence_file_name);

        if (entry_file.exists()) {
          new_embl_entry =
              EntryFileDialog.getEntryFromFile(
                  this, entry_document, artemis_entry_information, false);
        } else {
          // read failed
          System.err.println(
              "file does not exist: " + default_sequence_file_name + "(given in options files)");
          return;
        }
      }

      if (new_embl_entry == null
          || new_embl_entry.getSequence() == null
          || new_embl_entry.getSequence().length() == 0) {
        // read failed
        System.err.println(
            "failed to read " + default_sequence_file_name + "(given in options files)");
        return;
      }

      getStatusLabel().setText("");

      try {
        final Entry entry = new Entry(new_embl_entry);

        final EntryEdit new_entry_edit = makeEntryEdit(entry);

        new_entry_edit.setVisible(true);

        if (default_feature_file_name != null) {
          final Document feature_document = DocumentFactory.makeDocument(default_feature_file_name);

          final uk.ac.sanger.artemis.io.Entry new_embl_table_entry =
              EntryFileDialog.getEntryFromFile(
                  this, feature_document, artemis_entry_information, false);

          if (new_embl_table_entry == null) // open failed
          return;

          final EntryGroup entry_group = new_entry_edit.getEntryGroup();

          final Entry new_table_entry = new Entry(entry.getBases(), new_embl_table_entry);

          entry_group.add(new_table_entry);
        }
      } catch (OutOfRangeException e) {
        new MessageDialog(
            this,
            "read failed: one of the features in "
                + default_feature_file_name
                + " has an out of range location: "
                + e.getMessage());
      } catch (NoSequenceException e) {
        new MessageDialog(
            this, "read failed: " + new_embl_entry.getName() + " contains no sequence");
      }
    }
  }
コード例 #26
0
ファイル: ArtemisMain.java プロジェクト: ambarrio/Artemis
  /** Read the entries named in args and in the diana.ini file. */
  protected void readArgsAndOptions(final String[] args) {
    if (args.length == 0) {
      if (System.getProperty("chado") != null && (args.length < 1 || args[0].indexOf(':') == -1))
        fm = new LocalAndRemoteFileManager(ArtemisMain.this);

      // open the entries given in the options file(diana.ini)
      readDefaultEntries();
      return;
    }

    if (args[0].equals("-biojava")) {
      handleBioJava(args);
      return;
    }

    final EntryInformation artemis_entry_information = Options.getArtemisEntryInformation();

    EntryEdit last_entry_edit = null;
    boolean seen_plus = false;

    for (int i = 0; i < args.length; ++i) {
      String new_entry_name = args[i];

      if (new_entry_name.length() == 0) continue;

      if (new_entry_name.equals("+")) {
        seen_plus = true;
        continue;
      }

      if (new_entry_name.startsWith("+") && last_entry_edit != null || seen_plus) {
        // new feature file

        final Document entry_document;

        if (seen_plus) entry_document = DocumentFactory.makeDocument(new_entry_name);
        else entry_document = DocumentFactory.makeDocument(new_entry_name.substring(1));

        final InputStreamProgressListener progress_listener = getInputStreamProgressListener();

        entry_document.addInputStreamProgressListener(progress_listener);

        final uk.ac.sanger.artemis.io.Entry new_embl_entry =
            EntryFileDialog.getEntryFromFile(
                this, entry_document, artemis_entry_information, false);

        if (new_embl_entry == null) // the read failed
        break;

        try {
          final Entry new_entry =
              new Entry(last_entry_edit.getEntryGroup().getBases(), new_embl_entry);

          last_entry_edit.getEntryGroup().add(new_entry);
        } catch (OutOfRangeException e) {
          new MessageDialog(
              this,
              "read failed: one of the features in "
                  + new_entry_name
                  + " has an out of range "
                  + "location: "
                  + e.getMessage());
        }
      } else if (System.getProperty("chado") != null && new_entry_name.indexOf(':') > -1) {
        // open from database e.g. Pfalciparum:Pf3D7_09:95000..150000
        Splash.logger4j.info("OPEN ENTRY " + new_entry_name);
        getStatusLabel().setText("Connecting ...");
        DatabaseEntrySource entry_source = new DatabaseEntrySource();

        boolean promptUser = true;
        if (System.getProperty("read_only") != null) {
          promptUser = false;
          entry_source.setReadOnly(true);
        }

        if (!entry_source.setLocation(promptUser)) return;

        last_entry_edit =
            DatabaseJPanel.show(
                entry_source, this, getInputStreamProgressListener(), new_entry_name);
      } else {
        // new sequence file

        if (last_entry_edit != null) {
          last_entry_edit.setVisible(true);
          last_entry_edit = null;
        }

        if (new_entry_name.indexOf("://") == -1) {
          File file = new File(new_entry_name);
          if (!file.exists()) {
            JOptionPane.showMessageDialog(
                null,
                "File " + new_entry_name + " not found.\n" + "Check the file name.",
                "File Not Found",
                JOptionPane.WARNING_MESSAGE);
          }
        }

        final Document entry_document = DocumentFactory.makeDocument(new_entry_name);

        entry_document.addInputStreamProgressListener(getInputStreamProgressListener());

        final uk.ac.sanger.artemis.io.Entry new_embl_entry =
            EntryFileDialog.getEntryFromFile(
                this, entry_document, artemis_entry_information, false);

        if (new_embl_entry == null) // the read failed
        break;

        try {
          final Entry entry = new Entry(new_embl_entry);
          last_entry_edit = makeEntryEdit(entry);
          addEntryEdit(last_entry_edit);
          getStatusLabel().setText("");
        } catch (OutOfRangeException e) {
          new MessageDialog(
              this,
              "read failed: one of the features in "
                  + new_entry_name
                  + " has an out of range "
                  + "location: "
                  + e.getMessage());
          break;
        } catch (NoSequenceException e) {
          new MessageDialog(this, "read failed: " + new_entry_name + " contains no sequence");
          break;
        }
      }
    }

    if (System.getProperty("offset") != null)
      last_entry_edit.getGotoEventSource().gotoBase(Integer.parseInt(System.getProperty("offset")));

    last_entry_edit.setVisible(true);
    for (int entry_index = 0; entry_index < entry_edit_objects.size(); ++entry_index) {
      if (System.getProperty("offset") != null)
        entry_edit_objects
            .elementAt(entry_index)
            .getGotoEventSource()
            .gotoBase(Integer.parseInt(System.getProperty("offset")));
    }
  }
コード例 #27
0
    public void actionPerformed(ActionEvent e) {
      if (isDirectorySelected()) {
        File dir = getDirectory();
        if (dir != null) {
          try {
            // Strip trailing ".."
            dir = ShellFolder.getNormalizedFile(dir);
          } catch (IOException ex) {
            // Ok, use f as is
          }
          changeDirectory(dir);
          return;
        }
      }

      JFileChooser chooser = getFileChooser();

      String filename = getFileName();
      FileSystemView fs = chooser.getFileSystemView();
      File dir = chooser.getCurrentDirectory();

      if (filename != null) {
        // Remove whitespaces from end of filename
        int i = filename.length() - 1;

        while (i >= 0 && filename.charAt(i) <= ' ') {
          i--;
        }

        filename = filename.substring(0, i + 1);
      }

      if (filename == null || filename.length() == 0) {
        // no file selected, multiple selection off, therefore cancel the approve action
        resetGlobFilter();
        return;
      }

      File selectedFile = null;
      File[] selectedFiles = null;

      // Unix: Resolve '~' to user's home directory
      if (File.separatorChar == '/') {
        if (filename.startsWith("~/")) {
          filename = System.getProperty("user.home") + filename.substring(1);
        } else if (filename.equals("~")) {
          filename = System.getProperty("user.home");
        }
      }

      if (chooser.isMultiSelectionEnabled()
          && filename.length() > 1
          && filename.charAt(0) == '"'
          && filename.charAt(filename.length() - 1) == '"') {
        List<File> fList = new ArrayList<File>();

        String[] files = filename.substring(1, filename.length() - 1).split("\" \"");
        // Optimize searching files by names in "children" array
        Arrays.sort(files);

        File[] children = null;
        int childIndex = 0;

        for (String str : files) {
          File file = fs.createFileObject(str);
          if (!file.isAbsolute()) {
            if (children == null) {
              children = fs.getFiles(dir, false);
              Arrays.sort(children);
            }
            for (int k = 0; k < children.length; k++) {
              int l = (childIndex + k) % children.length;
              if (children[l].getName().equals(str)) {
                file = children[l];
                childIndex = l + 1;
                break;
              }
            }
          }
          fList.add(file);
        }

        if (!fList.isEmpty()) {
          selectedFiles = fList.toArray(new File[fList.size()]);
        }
        resetGlobFilter();
      } else {
        selectedFile = fs.createFileObject(filename);
        if (!selectedFile.isAbsolute()) {
          selectedFile = fs.getChild(dir, filename);
        }
        // check for wildcard pattern
        FileFilter currentFilter = chooser.getFileFilter();
        if (!selectedFile.exists() && isGlobPattern(filename)) {
          changeDirectory(selectedFile.getParentFile());
          if (globFilter == null) {
            globFilter = new GlobFilter();
          }
          try {
            globFilter.setPattern(selectedFile.getName());
            if (!(currentFilter instanceof GlobFilter)) {
              actualFileFilter = currentFilter;
            }
            chooser.setFileFilter(null);
            chooser.setFileFilter(globFilter);
            return;
          } catch (PatternSyntaxException pse) {
            // Not a valid glob pattern. Abandon filter.
          }
        }

        resetGlobFilter();

        // Check for directory change action
        boolean isDir = (selectedFile != null && selectedFile.isDirectory());
        boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile));
        boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled();
        boolean isFileSelEnabled = chooser.isFileSelectionEnabled();
        boolean isCtrl =
            (e != null
                && (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0);

        if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) {
          changeDirectory(selectedFile);
          return;
        } else if ((isDir || !isFileSelEnabled)
            && (!isDir || !isDirSelEnabled)
            && (!isDirSelEnabled || selectedFile.exists())) {
          selectedFile = null;
        }
      }

      if (selectedFiles != null || selectedFile != null) {
        if (selectedFiles != null || chooser.isMultiSelectionEnabled()) {
          if (selectedFiles == null) {
            selectedFiles = new File[] {selectedFile};
          }
          chooser.setSelectedFiles(selectedFiles);
          // Do it again. This is a fix for bug 4949273 to force the
          // selected value in case the ListSelectionModel clears it
          // for non-existing file names.
          chooser.setSelectedFiles(selectedFiles);
        } else {
          chooser.setSelectedFile(selectedFile);
        }
        chooser.approveSelection();
      } else {
        if (chooser.isMultiSelectionEnabled()) {
          chooser.setSelectedFiles(null);
        } else {
          chooser.setSelectedFile(null);
        }
        chooser.cancelSelection();
      }
    }
コード例 #28
0
 public String getCurrentFilename() {
   if (_editingFile == null) {
     return null;
   }
   return _editingFile.getAbsolutePath();
 }
コード例 #29
0
 public String getDescription(File f) {
   return f.getName();
 }