Ejemplo n.º 1
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());
    }
  }
Ejemplo n.º 2
0
  /**
   * Returns the parent directory of <code>dir</code>.
   *
   * @param dir the <code>File</code> being queried
   * @return the parent directory of <code>dir</code>, or <code>null</code> if <code>dir</code> is
   *     <code>null</code>
   */
  public File getParentDirectory(File dir) {
    if (dir == null || !dir.exists()) {
      return null;
    }

    ShellFolder sf;

    try {
      sf = getShellFolder(dir);
    } catch (FileNotFoundException e) {
      return null;
    }

    File psf = sf.getParentFile();

    if (psf == null) {
      return null;
    }

    if (isFileSystem(psf)) {
      File f = psf;
      if (!f.exists()) {
        // This could be a node under "Network Neighborhood".
        File ppsf = psf.getParentFile();
        if (ppsf == null || !isFileSystem(ppsf)) {
          // We're mostly after the exists() override for windows below.
          f = createFileSystemRoot(f);
        }
      }
      return f;
    } else {
      return psf;
    }
  }
Ejemplo n.º 3
0
 /**
  * Checks if <code>f</code> represents a real directory or file as opposed to a special folder
  * such as <code>"Desktop"</code>. Used by UI classes to decide if a folder is selectable when
  * doing directory choosing.
  *
  * @param f a <code>File</code> object
  * @return <code>true</code> if <code>f</code> is a real file or directory.
  * @since 1.4
  */
 public boolean isFileSystem(File f) {
   if (f instanceof ShellFolder) {
     ShellFolder sf = (ShellFolder) f;
     // Shortcuts to directories are treated as not being file system objects,
     // so that they are never returned by JFileChooser.
     return sf.isFileSystem() && !(sf.isLink() && sf.isDirectory());
   } else {
     return true;
   }
 }
Ejemplo n.º 4
0
 /**
  * Return the user's default starting directory for the file chooser.
  *
  * @return a <code>File</code> object representing the default starting folder
  * @since 1.4
  */
 public File getDefaultDirectory() {
   File f = (File) ShellFolder.get("fileChooserDefaultFolder");
   if (isFileSystemRoot(f)) {
     f = createFileSystemRoot(f);
   }
   return f;
 }
Ejemplo n.º 5
0
  /**
   * Returns all root partitions on this system. For example, on Windows, this would be the
   * "Desktop" folder, while on DOS this would be the A: through Z: drives.
   */
  public File[] getRoots() {
    // Don't cache this array, because filesystem might change
    File[] roots = (File[]) ShellFolder.get("roots");

    for (int i = 0; i < roots.length; i++) {
      if (isFileSystemRoot(roots[i])) {
        roots[i] = createFileSystemRoot(roots[i]);
      }
    }
    return roots;
  }
Ejemplo n.º 6
0
  public static void main(String[] args) {
    if (OSInfo.getOSType() != OSInfo.OSType.WINDOWS) {
      System.out.println("The test was skipped because it is sensible only for Windows.");

      return;
    }

    for (String key : KEYS) {
      Image image = (Image) ShellFolder.get(key);

      if (image == null) {
        throw new RuntimeException("The image '" + key + "' not found.");
      }

      if (image != ShellFolder.get(key)) {
        throw new RuntimeException("The image '" + key + "' is not cached.");
      }
    }

    System.out.println("The test passed.");
  }
Ejemplo n.º 7
0
  /**
   * Icon for a file, directory, or folder as it would be displayed in a system file browser.
   * Example from Windows: the "M:\" directory displays a CD-ROM icon.
   *
   * <p>The default implementation gets information from the ShellFolder class.
   *
   * @param f a <code>File</code> object
   * @return an icon as it would be displayed by a native file chooser
   * @see JFileChooser#getIcon
   * @since 1.4
   */
  public Icon getSystemIcon(File f) {
    if (f == null) {
      return null;
    }

    ShellFolder sf;

    try {
      sf = getShellFolder(f);
    } catch (FileNotFoundException e) {
      return null;
    }

    Image img = sf.getIcon(false);

    if (img != null) {
      return new ImageIcon(img, sf.getFolderType());
    } else {
      return UIManager.getIcon(f.isDirectory() ? "FileView.directoryIcon" : "FileView.fileIcon");
    }
  }
Ejemplo n.º 8
0
  /** Throws {@code FileNotFoundException} if file not found or current thread was interrupted */
  ShellFolder getShellFolder(File f) throws FileNotFoundException {
    if (!(f instanceof ShellFolder) && !(f instanceof FileSystemRoot) && isFileSystemRoot(f)) {
      f = createFileSystemRoot(f);
    }

    try {
      return ShellFolder.getShellFolder(f);
    } catch (InternalError e) {
      System.err.println("FileSystemView.getShellFolder: f=" + f);
      e.printStackTrace();
      return null;
    }
  }
  private String getSystemDisplayName(File f) {
    String name;

    try {
      name = ShellFolder.getShellFolder(f).getDisplayName();
    } catch (FileNotFoundException e) {
      return null;
    }

    if (name == null || name.length() == 0) {
      name = f.getPath(); // the "/" directory
    }

    return name;
  }
Ejemplo n.º 10
0
  /** Gets the list of shown (i.e. not hidden) files. */
  public File[] getFiles(File dir, boolean useFileHiding) {
    List<File> files = new ArrayList<File>();

    // add all files in dir
    if (!(dir instanceof ShellFolder)) {
      try {
        dir = getShellFolder(dir);
      } catch (FileNotFoundException e) {
        return new File[0];
      }
    }

    File[] names = ((ShellFolder) dir).listFiles(!useFileHiding);

    if (names == null) {
      return new File[0];
    }

    for (File f : names) {
      if (Thread.currentThread().isInterrupted()) {
        break;
      }

      if (!(f instanceof ShellFolder)) {
        if (isFileSystemRoot(f)) {
          f = createFileSystemRoot(f);
        }
        try {
          f = ShellFolder.getShellFolder(f);
        } catch (FileNotFoundException e) {
          // Not a valid file (wouldn't show in native file chooser)
          // Example: C:\pagefile.sys
          continue;
        } catch (InternalError e) {
          // Not a valid file (wouldn't show in native file chooser)
          // Example C:\Winnt\Profiles\joe\history\History.IE5
          continue;
        }
      }
      if (!useFileHiding || !isHiddenFile(f)) {
        files.add(f);
      }
    }

    return files.toArray(new File[files.size()]);
  }
Ejemplo n.º 11
0
    public void mouseClicked(MouseEvent evt) {
      // Note: we can't depend on evt.getSource() because of backward
      // compatability
      if (list != null && SwingUtilities.isLeftMouseButton(evt) && (evt.getClickCount() % 2 == 0)) {

        int index = SwingUtilities2.loc2IndexFileList(list, evt.getPoint());
        if (index >= 0) {
          File f = (File) list.getModel().getElementAt(index);
          try {
            // Strip trailing ".."
            f = ShellFolder.getNormalizedFile(f);
          } catch (IOException ex) {
            // That's ok, we'll use f as is
          }
          if (getFileChooser().isTraversable(f)) {
            list.clearSelection();
            changeDirectory(f);
          } else {
            getFileChooser().approveSelection();
          }
        }
      }
    }
    public void run0() {
      FileSystemView fileSystem = filechooser.getFileSystemView();

      if (loadThread.isInterrupted()) {
        return;
      }

      File[] list = fileSystem.getFiles(currentDirectory, filechooser.isFileHidingEnabled());

      if (loadThread.isInterrupted()) {
        return;
      }

      final Vector<File> newFileCache = new Vector<File>();
      Vector<File> newFiles = new Vector<File>();

      // run through the file list, add directories and selectable files to fileCache
      // Note that this block must be OUTSIDE of Invoker thread because of
      // deadlock possibility with custom synchronized FileSystemView
      for (File file : list) {
        if (filechooser.accept(file)) {
          boolean isTraversable = filechooser.isTraversable(file);

          if (isTraversable) {
            newFileCache.addElement(file);
          } else if (filechooser.isFileSelectionEnabled()) {
            newFiles.addElement(file);
          }

          if (loadThread.isInterrupted()) {
            return;
          }
        }
      }

      // First sort alphabetically by filename
      sort(newFileCache);
      sort(newFiles);

      newFileCache.addAll(newFiles);

      // To avoid loads of synchronizations with Invoker and improve performance we
      // execute the whole block on the COM thread
      DoChangeContents doChangeContents =
          ShellFolder.invoke(
              new Callable<DoChangeContents>() {
                public DoChangeContents call() {
                  int newSize = newFileCache.size();
                  int oldSize = fileCache.size();

                  if (newSize > oldSize) {
                    // see if interval is added
                    int start = oldSize;
                    int end = newSize;
                    for (int i = 0; i < oldSize; i++) {
                      if (!newFileCache.get(i).equals(fileCache.get(i))) {
                        start = i;
                        for (int j = i; j < newSize; j++) {
                          if (newFileCache.get(j).equals(fileCache.get(i))) {
                            end = j;
                            break;
                          }
                        }
                        break;
                      }
                    }
                    if (start >= 0
                        && end > start
                        && newFileCache
                            .subList(end, newSize)
                            .equals(fileCache.subList(start, oldSize))) {
                      if (loadThread.isInterrupted()) {
                        return null;
                      }
                      return new DoChangeContents(
                          newFileCache.subList(start, end), start, null, 0, fid);
                    }
                  } else if (newSize < oldSize) {
                    // see if interval is removed
                    int start = -1;
                    int end = -1;
                    for (int i = 0; i < newSize; i++) {
                      if (!newFileCache.get(i).equals(fileCache.get(i))) {
                        start = i;
                        end = i + oldSize - newSize;
                        break;
                      }
                    }
                    if (start >= 0
                        && end > start
                        && fileCache
                            .subList(end, oldSize)
                            .equals(newFileCache.subList(start, newSize))) {
                      if (loadThread.isInterrupted()) {
                        return null;
                      }
                      return new DoChangeContents(
                          null, 0, new Vector<>(fileCache.subList(start, end)), start, fid);
                    }
                  }
                  if (!fileCache.equals(newFileCache)) {
                    if (loadThread.isInterrupted()) {
                      cancelRunnables(runnables);
                    }
                    return new DoChangeContents(newFileCache, 0, fileCache, 0, fid);
                  }
                  return null;
                }
              });

      if (doChangeContents != null) {
        runnables.addElement(doChangeContents);
        SwingUtilities.invokeLater(doChangeContents);
      }
    }
 /**
  * Sorts a list of files.
  *
  * @param v a list of files
  */
 protected void sort(Vector<? extends File> v) {
   ShellFolder.sort(v);
 }
Ejemplo n.º 14
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();
      }
    }
Ejemplo n.º 15
0
 /**
  * Used by UI classes to decide whether to display a special icon for a computer node, e.g. "My
  * Computer" or a network server.
  *
  * <p>The default implementation has no way of knowing, so always returns false.
  *
  * @param dir a directory
  * @return <code>false</code> always
  * @since 1.4
  */
 public boolean isComputerNode(File dir) {
   return ShellFolder.isComputerNode(dir);
 }
Ejemplo n.º 16
0
 /**
  * Is dir the root of a tree in the file system, such as a drive or partition. Example: Returns
  * true for "C:\" on Windows 98.
  *
  * @param dir a <code>File</code> object representing a directory
  * @return <code>true</code> if <code>f</code> is a root of a filesystem
  * @see #isRoot
  * @since 1.4
  */
 public boolean isFileSystemRoot(File dir) {
   return ShellFolder.isFileSystemRoot(dir);
 }