FilePane.java revision 0
0N/A
4791N/A/*
0N/A * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
2362N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation. Sun designates this
2362N/A * particular file as subject to the "Classpath" exception as provided
0N/A * by Sun in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
2362N/A *
2362N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
2362N/A * CA 95054 USA or visit www.sun.com if you need additional information or
0N/A * have any questions.
0N/A */
0N/Apackage sun.swing;
0N/A
0N/Aimport java.awt.*;
0N/Aimport java.awt.event.*;
0N/Aimport java.beans.PropertyChangeEvent;
0N/Aimport java.beans.PropertyChangeListener;
0N/Aimport java.io.*;
0N/Aimport java.text.DateFormat;
0N/Aimport java.text.MessageFormat;
0N/Aimport java.util.*;
0N/Aimport java.util.List;
0N/A
0N/Aimport javax.swing.*;
0N/Aimport javax.swing.border.*;
0N/Aimport javax.swing.event.*;
0N/Aimport javax.swing.filechooser.*;
0N/Aimport javax.swing.plaf.basic.*;
0N/Aimport javax.swing.table.*;
0N/Aimport javax.swing.text.*;
0N/A
0N/Aimport sun.awt.shell.*;
0N/A
0N/A/**
0N/A * <b>WARNING:</b> This class is an implementation detail and is only
0N/A * public so that it can be used by two packages. You should NOT consider
0N/A * this public API.
0N/A * <p>
0N/A * This component is intended to be used in a subclass of
0N/A * javax.swing.plaf.basic.BasicFileChooserUI. It realies heavily on the
0N/A * implementation of BasicFileChooserUI, and is intended to be API compatible
0N/A * with earlier implementations of MetalFileChooserUI and WindowsFileChooserUI.
0N/A *
0N/A * @author Leif Samuelsson
0N/A */
0N/Apublic class FilePane extends JPanel implements PropertyChangeListener {
0N/A // Constants for actions. These are used for the actions' ACTION_COMMAND_KEY
0N/A // and as keys in the action maps for FilePane and the corresponding UI classes
0N/A
0N/A public final static String ACTION_APPROVE_SELECTION = "approveSelection";
0N/A public final static String ACTION_CANCEL = "cancelSelection";
0N/A public final static String ACTION_EDIT_FILE_NAME = "editFileName";
0N/A public final static String ACTION_REFRESH = "refresh";
0N/A public final static String ACTION_CHANGE_TO_PARENT_DIRECTORY = "Go Up";
0N/A public final static String ACTION_NEW_FOLDER = "New Folder";
0N/A public final static String ACTION_VIEW_LIST = "viewTypeList";
0N/A public final static String ACTION_VIEW_DETAILS = "viewTypeDetails";
0N/A
0N/A private Action[] actions;
0N/A
0N/A // "enums" for setViewType()
0N/A public static final int VIEWTYPE_LIST = 0;
0N/A public static final int VIEWTYPE_DETAILS = 1;
0N/A private static final int VIEWTYPE_COUNT = 2;
0N/A
0N/A private int viewType = -1;
0N/A private JPanel[] viewPanels = new JPanel[VIEWTYPE_COUNT];
0N/A private JPanel currentViewPanel;
0N/A private String[] viewTypeActionNames;
0N/A
0N/A private JPopupMenu contextMenu;
0N/A private JMenu viewMenu;
0N/A
0N/A private String viewMenuLabelText;
0N/A private String refreshActionLabelText;
0N/A private String newFolderActionLabelText;
0N/A
0N/A private String kiloByteString;
0N/A private String megaByteString;
0N/A private String gigaByteString;
0N/A
0N/A private String renameErrorTitleText;
0N/A private String renameErrorText;
0N/A private String renameErrorFileExistsText;
0N/A
0N/A private static final Cursor waitCursor =
0N/A Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
0N/A
0N/A private final KeyListener detailsKeyListener = new KeyAdapter() {
0N/A private final long timeFactor;
0N/A
0N/A private final StringBuilder typedString = new StringBuilder();
0N/A
0N/A private long lastTime = 1000L;
0N/A
0N/A {
0N/A Long l = (Long) UIManager.get("Table.timeFactor");
0N/A timeFactor = (l != null) ? l : 1000L;
0N/A }
0N/A
0N/A /**
0N/A * Moves the keyboard focus to the first element whose prefix matches
0N/A * the sequence of alphanumeric keys pressed by the user with delay
0N/A * less than value of <code>timeFactor</code>. Subsequent same key
0N/A * presses move the keyboard focus to the next object that starts with
0N/A * the same letter until another key is pressed, then it is treated
0N/A * as the prefix with appropriate number of the same letters followed
0N/A * by first typed another letter.
0N/A */
0N/A public void keyTyped(KeyEvent e) {
0N/A BasicDirectoryModel model = getModel();
0N/A int rowCount = model.getSize();
0N/A
0N/A if (detailsTable == null || rowCount == 0 ||
0N/A e.isAltDown() || e.isControlDown() || e.isMetaDown()) {
0N/A return;
0N/A }
0N/A
0N/A InputMap inputMap = detailsTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
0N/A KeyStroke key = KeyStroke.getKeyStrokeForEvent(e);
0N/A
0N/A if (inputMap != null && inputMap.get(key) != null) {
0N/A return;
0N/A }
0N/A
0N/A int startIndex = detailsTable.getSelectionModel().getLeadSelectionIndex();
0N/A
0N/A if (startIndex < 0) {
0N/A startIndex = 0;
0N/A }
0N/A
0N/A if (startIndex >= rowCount) {
0N/A startIndex = rowCount - 1;
0N/A }
0N/A
0N/A char c = e.getKeyChar();
0N/A
0N/A long time = e.getWhen();
0N/A
0N/A if (time - lastTime < timeFactor) {
0N/A if (typedString.length() == 1 && typedString.charAt(0) == c) {
0N/A // Subsequent same key presses move the keyboard focus to the next
0N/A // object that starts with the same letter.
0N/A startIndex++;
0N/A } else {
0N/A typedString.append(c);
0N/A }
0N/A } else {
0N/A startIndex++;
0N/A
0N/A typedString.setLength(0);
0N/A typedString.append(c);
0N/A }
0N/A
0N/A lastTime = time;
0N/A
0N/A if (startIndex >= rowCount) {
0N/A startIndex = 0;
0N/A }
0N/A
0N/A // Find next file
0N/A int index = getNextMatch(startIndex, rowCount - 1);
0N/A
0N/A if (index < 0 && startIndex > 0) { // wrap
0N/A index = getNextMatch(0, startIndex - 1);
0N/A }
0N/A
0N/A if (index >= 0) {
0N/A detailsTable.getSelectionModel().setSelectionInterval(index, index);
0N/A
0N/A Rectangle cellRect = detailsTable.getCellRect(index,
0N/A detailsTable.convertColumnIndexToView(COLUMN_FILENAME), false);
0N/A detailsTable.scrollRectToVisible(cellRect);
0N/A }
0N/A }
0N/A
0N/A private int getNextMatch(int startIndex, int finishIndex) {
0N/A BasicDirectoryModel model = getModel();
0N/A JFileChooser fileChooser = getFileChooser();
0N/A DetailsTableRowSorter rowSorter = getRowSorter();
0N/A
0N/A String prefix = typedString.toString().toLowerCase();
0N/A
0N/A // Search element
0N/A for (int index = startIndex; index <= finishIndex; index++) {
0N/A File file = (File) model.getElementAt(rowSorter.convertRowIndexToModel(index));
0N/A
0N/A String fileName = fileChooser.getName(file).toLowerCase();
0N/A
0N/A if (fileName.startsWith(prefix)) {
0N/A return index;
0N/A }
0N/A }
0N/A
0N/A return -1;
0N/A }
0N/A };
0N/A
0N/A private FocusListener editorFocusListener = new FocusAdapter() {
0N/A public void focusLost(FocusEvent e) {
0N/A if (! e.isTemporary()) {
0N/A applyEdit();
0N/A }
0N/A }
0N/A };
0N/A
0N/A private static FocusListener repaintListener = new FocusListener() {
0N/A public void focusGained(FocusEvent fe) {
0N/A repaintSelection(fe.getSource());
0N/A }
0N/A
0N/A public void focusLost(FocusEvent fe) {
0N/A repaintSelection(fe.getSource());
0N/A }
0N/A
0N/A private void repaintSelection(Object source) {
0N/A if (source instanceof JList) {
0N/A repaintListSelection((JList)source);
0N/A } else if (source instanceof JTable) {
0N/A repaintTableSelection((JTable)source);
0N/A }
0N/A }
0N/A
0N/A private void repaintListSelection(JList list) {
0N/A int[] indices = list.getSelectedIndices();
0N/A for (int i : indices) {
0N/A Rectangle bounds = list.getCellBounds(i, i);
0N/A list.repaint(bounds);
0N/A }
0N/A }
0N/A
0N/A private void repaintTableSelection(JTable table) {
0N/A int minRow = table.getSelectionModel().getMinSelectionIndex();
0N/A int maxRow = table.getSelectionModel().getMaxSelectionIndex();
0N/A if (minRow == -1 || maxRow == -1) {
0N/A return;
0N/A }
0N/A
0N/A int col0 = table.convertColumnIndexToView(COLUMN_FILENAME);
0N/A
0N/A Rectangle first = table.getCellRect(minRow, col0, false);
0N/A Rectangle last = table.getCellRect(maxRow, col0, false);
0N/A Rectangle dirty = first.union(last);
0N/A table.repaint(dirty);
0N/A }
0N/A };
0N/A
0N/A private boolean smallIconsView = false;
0N/A private Border listViewBorder;
0N/A private Color listViewBackground;
0N/A private boolean listViewWindowsStyle;
0N/A private boolean readOnly;
0N/A
0N/A private ListSelectionModel listSelectionModel;
4007N/A private JList list;
0N/A private JTable detailsTable;
0N/A
0N/A private static final int COLUMN_FILENAME = 0;
0N/A
0N/A // Provides a way to recognize a newly created folder, so it can
0N/A // be selected when it appears in the model.
0N/A private File newFolderFile;
0N/A
0N/A // Used for accessing methods in the corresponding UI class
0N/A private FileChooserUIAccessor fileChooserUIAccessor;
0N/A private DetailsTableModel detailsTableModel;
0N/A private DetailsTableRowSorter rowSorter;
0N/A
0N/A public FilePane(FileChooserUIAccessor fileChooserUIAccessor) {
0N/A super(new BorderLayout());
0N/A
0N/A this.fileChooserUIAccessor = fileChooserUIAccessor;
0N/A
0N/A installDefaults();
0N/A createActionMap();
0N/A }
0N/A
0N/A public void uninstallUI() {
0N/A if (getModel() != null) {
0N/A getModel().removePropertyChangeListener(this);
0N/A }
0N/A }
0N/A
0N/A protected JFileChooser getFileChooser() {
0N/A return fileChooserUIAccessor.getFileChooser();
0N/A }
0N/A
0N/A protected BasicDirectoryModel getModel() {
0N/A return fileChooserUIAccessor.getModel();
0N/A }
0N/A
0N/A public int getViewType() {
0N/A return viewType;
0N/A }
0N/A
0N/A public void setViewType(int viewType) {
0N/A int oldValue = this.viewType;
0N/A if (viewType == oldValue) {
0N/A return;
0N/A }
0N/A this.viewType = viewType;
0N/A
0N/A switch (viewType) {
0N/A case VIEWTYPE_LIST:
0N/A if (viewPanels[viewType] == null) {
0N/A JPanel p = fileChooserUIAccessor.createList();
0N/A if (p == null) {
0N/A p = createList();
0N/A }
0N/A setViewPanel(viewType, p);
4007N/A }
4007N/A list.setLayoutOrientation(JList.VERTICAL_WRAP);
4007N/A break;
4007N/A
4007N/A case VIEWTYPE_DETAILS:
0N/A if (viewPanels[viewType] == null) {
0N/A JPanel p = fileChooserUIAccessor.createDetailsView();
0N/A if (p == null) {
0N/A p = createDetailsView();
0N/A }
0N/A setViewPanel(viewType, p);
0N/A }
0N/A break;
0N/A }
0N/A JPanel oldViewPanel = currentViewPanel;
0N/A currentViewPanel = viewPanels[viewType];
0N/A if (currentViewPanel != oldViewPanel) {
0N/A if (oldViewPanel != null) {
0N/A remove(oldViewPanel);
0N/A }
0N/A add(currentViewPanel, BorderLayout.CENTER);
0N/A revalidate();
4007N/A repaint();
4007N/A }
0N/A updateViewMenu();
0N/A firePropertyChange("viewType", oldValue, viewType);
0N/A }
0N/A
0N/A class ViewTypeAction extends AbstractAction {
0N/A private int viewType;
0N/A
0N/A ViewTypeAction(int viewType) {
0N/A super(viewTypeActionNames[viewType]);
0N/A this.viewType = viewType;
0N/A
0N/A String cmd;
0N/A switch (viewType) {
0N/A case VIEWTYPE_LIST: cmd = ACTION_VIEW_LIST; break;
0N/A case VIEWTYPE_DETAILS: cmd = ACTION_VIEW_DETAILS; break;
0N/A default: cmd = (String)getValue(Action.NAME);
0N/A }
0N/A putValue(Action.ACTION_COMMAND_KEY, cmd);
0N/A }
0N/A
0N/A public void actionPerformed(ActionEvent e) {
0N/A setViewType(viewType);
0N/A }
0N/A }
0N/A
4007N/A public Action getViewTypeAction(int viewType) {
4007N/A return new ViewTypeAction(viewType);
4007N/A }
4007N/A
4007N/A private static void recursivelySetInheritsPopupMenu(Container container, boolean b) {
0N/A if (container instanceof JComponent) {
0N/A ((JComponent)container).setInheritsPopupMenu(b);
0N/A }
0N/A int n = container.getComponentCount();
0N/A for (int i = 0; i < n; i++) {
0N/A recursivelySetInheritsPopupMenu((Container)container.getComponent(i), b);
0N/A }
0N/A }
0N/A
0N/A public void setViewPanel(int viewType, JPanel viewPanel) {
0N/A viewPanels[viewType] = viewPanel;
0N/A recursivelySetInheritsPopupMenu(viewPanel, true);
0N/A
0N/A switch (viewType) {
0N/A case VIEWTYPE_LIST:
0N/A list = (JList)findChildComponent(viewPanels[viewType], JList.class);
0N/A if (listSelectionModel == null) {
0N/A listSelectionModel = list.getSelectionModel();
0N/A if (detailsTable != null) {
0N/A detailsTable.setSelectionModel(listSelectionModel);
0N/A }
4007N/A } else {
0N/A list.setSelectionModel(listSelectionModel);
0N/A }
0N/A break;
0N/A
0N/A case VIEWTYPE_DETAILS:
0N/A detailsTable = (JTable)findChildComponent(viewPanels[viewType], JTable.class);
0N/A detailsTable.setRowHeight(Math.max(detailsTable.getFont().getSize() + 4, 16+1));
0N/A if (listSelectionModel != null) {
0N/A detailsTable.setSelectionModel(listSelectionModel);
0N/A }
0N/A break;
0N/A }
0N/A if (this.viewType == viewType) {
0N/A if (currentViewPanel != null) {
0N/A remove(currentViewPanel);
0N/A }
0N/A currentViewPanel = viewPanel;
0N/A add(currentViewPanel, BorderLayout.CENTER);
0N/A revalidate();
0N/A repaint();
0N/A }
0N/A }
0N/A
0N/A protected void installDefaults() {
0N/A Locale l = getFileChooser().getLocale();
0N/A
4007N/A listViewBorder = UIManager.getBorder("FileChooser.listViewBorder");
4007N/A listViewBackground = UIManager.getColor("FileChooser.listViewBackground");
4007N/A listViewWindowsStyle = UIManager.getBoolean("FileChooser.listViewWindowsStyle");
4007N/A readOnly = UIManager.getBoolean("FileChooser.readOnly");
4007N/A
0N/A // TODO: On windows, get the following localized strings from the OS
0N/A
0N/A viewMenuLabelText =
0N/A UIManager.getString("FileChooser.viewMenuLabelText", l);
0N/A refreshActionLabelText =
0N/A UIManager.getString("FileChooser.refreshActionLabelText", l);
0N/A newFolderActionLabelText =
0N/A UIManager.getString("FileChooser.newFolderActionLabelText", l);
0N/A
0N/A viewTypeActionNames = new String[VIEWTYPE_COUNT];
0N/A viewTypeActionNames[VIEWTYPE_LIST] =
0N/A UIManager.getString("FileChooser.listViewActionLabelText", l);
0N/A viewTypeActionNames[VIEWTYPE_DETAILS] =
0N/A UIManager.getString("FileChooser.detailsViewActionLabelText", l);
0N/A
0N/A kiloByteString = UIManager.getString("FileChooser.fileSizeKiloBytes", l);
0N/A megaByteString = UIManager.getString("FileChooser.fileSizeMegaBytes", l);
0N/A gigaByteString = UIManager.getString("FileChooser.fileSizeGigaBytes", l);
0N/A
0N/A renameErrorTitleText = UIManager.getString("FileChooser.renameErrorTitleText", l);
0N/A renameErrorText = UIManager.getString("FileChooser.renameErrorText", l);
4007N/A renameErrorFileExistsText = UIManager.getString("FileChooser.renameErrorFileExistsText", l);
0N/A }
0N/A
0N/A /**
0N/A * Fetches the command list for the FilePane. These commands
0N/A * are useful for binding to events, such as in a keymap.
0N/A *
0N/A * @return the command list
0N/A */
0N/A public Action[] getActions() {
0N/A if (actions == null) {
0N/A class FilePaneAction extends AbstractAction {
0N/A FilePaneAction(String name) {
0N/A this(name, name);
0N/A }
0N/A
0N/A FilePaneAction(String name, String cmd) {
0N/A super(name);
0N/A putValue(Action.ACTION_COMMAND_KEY, cmd);
0N/A }
0N/A
0N/A public void actionPerformed(ActionEvent e) {
0N/A String cmd = (String)getValue(Action.ACTION_COMMAND_KEY);
0N/A
0N/A if (cmd == ACTION_CANCEL) {
0N/A if (editFile != null) {
0N/A cancelEdit();
0N/A } else {
0N/A getFileChooser().cancelSelection();
0N/A }
0N/A } else if (cmd == ACTION_EDIT_FILE_NAME) {
0N/A JFileChooser fc = getFileChooser();
0N/A int index = listSelectionModel.getMinSelectionIndex();
0N/A if (index >= 0 && editFile == null &&
0N/A (!fc.isMultiSelectionEnabled() ||
0N/A fc.getSelectedFiles().length <= 1)) {
0N/A
0N/A editFileName(index);
0N/A }
0N/A } else if (cmd == ACTION_REFRESH) {
0N/A getFileChooser().rescanCurrentDirectory();
0N/A }
0N/A }
0N/A
0N/A public boolean isEnabled() {
0N/A String cmd = (String)getValue(Action.ACTION_COMMAND_KEY);
0N/A if (cmd == ACTION_CANCEL) {
0N/A return getFileChooser().isEnabled();
0N/A } else if (cmd == ACTION_EDIT_FILE_NAME) {
0N/A return !readOnly && getFileChooser().isEnabled();
0N/A } else {
0N/A return true;
0N/A }
0N/A }
0N/A }
0N/A
0N/A ArrayList<Action> actionList = new ArrayList<Action>(8);
0N/A Action action;
0N/A
0N/A actionList.add(new FilePaneAction(ACTION_CANCEL));
0N/A actionList.add(new FilePaneAction(ACTION_EDIT_FILE_NAME));
0N/A actionList.add(new FilePaneAction(refreshActionLabelText, ACTION_REFRESH));
0N/A
0N/A action = fileChooserUIAccessor.getApproveSelectionAction();
0N/A if (action != null) {
0N/A actionList.add(action);
0N/A }
0N/A action = fileChooserUIAccessor.getChangeToParentDirectoryAction();
0N/A if (action != null) {
0N/A actionList.add(action);
0N/A }
0N/A action = getNewFolderAction();
0N/A if (action != null) {
0N/A actionList.add(action);
0N/A }
0N/A action = getViewTypeAction(VIEWTYPE_LIST);
0N/A if (action != null) {
0N/A actionList.add(action);
0N/A }
0N/A action = getViewTypeAction(VIEWTYPE_DETAILS);
0N/A if (action != null) {
0N/A actionList.add(action);
0N/A }
0N/A actions = actionList.toArray(new Action[actionList.size()]);
0N/A }
0N/A
0N/A return actions;
0N/A }
0N/A
0N/A protected void createActionMap() {
0N/A addActionsToMap(super.getActionMap(), getActions());
0N/A }
0N/A
0N/A
0N/A public static void addActionsToMap(ActionMap map, Action[] actions) {
0N/A if (map != null && actions != null) {
0N/A for (int i = 0; i < actions.length; i++) {
0N/A Action a = actions[i];
0N/A String cmd = (String)a.getValue(Action.ACTION_COMMAND_KEY);
0N/A if (cmd == null) {
0N/A cmd = (String)a.getValue(Action.NAME);
0N/A }
0N/A map.put(cmd, a);
0N/A }
0N/A }
0N/A }
0N/A
0N/A
0N/A private void updateListRowCount(JList list) {
0N/A if (smallIconsView) {
0N/A list.setVisibleRowCount(getModel().getSize() / 3);
0N/A } else {
0N/A list.setVisibleRowCount(-1);
4007N/A }
4007N/A }
4007N/A
0N/A public JPanel createList() {
0N/A JPanel p = new JPanel(new BorderLayout());
0N/A final JFileChooser fileChooser = getFileChooser();
0N/A final JList list = new JList() {
0N/A public int getNextMatch(String prefix, int startIndex, Position.Bias bias) {
0N/A ListModel model = getModel();
0N/A int max = model.getSize();
0N/A if (prefix == null || startIndex < 0 || startIndex >= max) {
0N/A throw new IllegalArgumentException();
0N/A }
0N/A // start search from the next element before/after the selected element
0N/A boolean backwards = (bias == Position.Bias.Backward);
0N/A for (int i = startIndex; backwards ? i >= 0 : i < max; i += (backwards ? -1 : 1)) {
0N/A String filename = fileChooser.getName((File)model.getElementAt(i));
0N/A if (filename.regionMatches(true, 0, prefix, 0, prefix.length())) {
0N/A return i;
0N/A }
0N/A }
0N/A return -1;
0N/A }
0N/A };
0N/A list.setCellRenderer(new FileRenderer());
0N/A list.setLayoutOrientation(JList.VERTICAL_WRAP);
0N/A
0N/A // 4835633 : tell BasicListUI that this is a file list
0N/A list.putClientProperty("List.isFileList", Boolean.TRUE);
0N/A
4007N/A if (listViewWindowsStyle) {
4007N/A list.addFocusListener(repaintListener);
4007N/A }
0N/A
0N/A updateListRowCount(list);
0N/A
0N/A getModel().addListDataListener(new ListDataListener() {
0N/A public void intervalAdded(ListDataEvent e) {
0N/A updateListRowCount(list);
0N/A }
0N/A public void intervalRemoved(ListDataEvent e) {
0N/A updateListRowCount(list);
0N/A }
0N/A public void contentsChanged(ListDataEvent e) {
0N/A if (isShowing()) {
0N/A clearSelection();
0N/A }
0N/A updateListRowCount(list);
4007N/A }
4007N/A });
4007N/A
0N/A getModel().addPropertyChangeListener(this);
0N/A
0N/A if (fileChooser.isMultiSelectionEnabled()) {
0N/A list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
0N/A } else {
0N/A list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
0N/A }
0N/A list.setModel(new SortableListModel());
0N/A
0N/A list.addListSelectionListener(createListSelectionListener());
0N/A list.addMouseListener(getMouseHandler());
0N/A
0N/A JScrollPane scrollpane = new JScrollPane(list);
0N/A if (listViewBackground != null) {
0N/A list.setBackground(listViewBackground);
0N/A }
0N/A if (listViewBorder != null) {
0N/A scrollpane.setBorder(listViewBorder);
0N/A }
0N/A p.add(scrollpane, BorderLayout.CENTER);
0N/A return p;
0N/A }
0N/A
0N/A /**
0N/A * This model allows for sorting JList
0N/A */
0N/A private class SortableListModel extends AbstractListModel
0N/A implements TableModelListener, RowSorterListener {
0N/A
0N/A public SortableListModel() {
0N/A getDetailsTableModel().addTableModelListener(this);
0N/A getRowSorter().addRowSorterListener(this);
0N/A }
0N/A
0N/A public int getSize() {
0N/A return getModel().getSize();
4007N/A }
4007N/A
4007N/A public Object getElementAt(int index) {
0N/A // JList doesn't support RowSorter so far, so we put it into the list model
0N/A return getModel().getElementAt(getRowSorter().convertRowIndexToModel(index));
0N/A }
0N/A
0N/A public void tableChanged(TableModelEvent e) {
0N/A fireContentsChanged(this, 0, getSize());
0N/A }
0N/A
0N/A public void sorterChanged(RowSorterEvent e) {
0N/A fireContentsChanged(this, 0, getSize());
0N/A }
0N/A }
0N/A
0N/A private DetailsTableModel getDetailsTableModel() {
4007N/A if(detailsTableModel == null) {
4007N/A detailsTableModel = new DetailsTableModel(getFileChooser());
4007N/A }
4007N/A return detailsTableModel;
4007N/A }
0N/A
0N/A class DetailsTableModel extends AbstractTableModel implements ListDataListener {
0N/A JFileChooser chooser;
0N/A BasicDirectoryModel directoryModel;
0N/A
0N/A ShellFolderColumnInfo[] columns;
0N/A int[] columnMap;
0N/A
0N/A DetailsTableModel(JFileChooser fc) {
0N/A this.chooser = fc;
0N/A directoryModel = getModel();
0N/A directoryModel.addListDataListener(this);
0N/A
0N/A updateColumnInfo();
0N/A }
0N/A
0N/A void updateColumnInfo() {
0N/A File dir = chooser.getCurrentDirectory();
0N/A if (dir != null && fileChooserUIAccessor.usesShellFolder()) {
0N/A try {
0N/A dir = ShellFolder.getShellFolder(dir);
0N/A } catch (FileNotFoundException e) {
0N/A // Leave dir without changing
0N/A }
0N/A }
0N/A
0N/A ShellFolderColumnInfo[] allColumns = ShellFolder.getFolderColumns(dir);
0N/A
0N/A ArrayList<ShellFolderColumnInfo> visibleColumns =
0N/A new ArrayList<ShellFolderColumnInfo>();
0N/A columnMap = new int[allColumns.length];
0N/A for (int i = 0; i < allColumns.length; i++) {
0N/A ShellFolderColumnInfo column = allColumns[i];
0N/A if (column.isVisible()) {
0N/A columnMap[visibleColumns.size()] = i;
0N/A visibleColumns.add(column);
4007N/A }
4007N/A }
4007N/A
0N/A columns = new ShellFolderColumnInfo[visibleColumns.size()];
0N/A visibleColumns.toArray(columns);
0N/A columnMap = Arrays.copyOf(columnMap, columns.length);
0N/A
0N/A List<RowSorter.SortKey> sortKeys =
0N/A (rowSorter == null) ? null : rowSorter.getSortKeys();
0N/A fireTableStructureChanged();
0N/A restoreSortKeys(sortKeys);
0N/A }
0N/A
0N/A private void restoreSortKeys(List<RowSorter.SortKey> sortKeys) {
0N/A if (sortKeys != null) {
0N/A // check if preserved sortKeys are valid for this folder
0N/A for (int i = 0; i < sortKeys.size(); i++) {
0N/A RowSorter.SortKey sortKey = sortKeys.get(i);
0N/A if (sortKey.getColumn() >= columns.length) {
0N/A sortKeys = null;
0N/A break;
0N/A }
0N/A }
0N/A if (sortKeys != null) {
0N/A rowSorter.setSortKeys(sortKeys);
0N/A }
0N/A }
0N/A }
0N/A
0N/A public int getRowCount() {
0N/A return directoryModel.getSize();
0N/A }
0N/A
0N/A public int getColumnCount() {
0N/A return columns.length;
0N/A }
0N/A
0N/A public Object getValueAt(int row, int col) {
0N/A // Note: It is very important to avoid getting info on drives, as
0N/A // this will trigger "No disk in A:" and similar dialogs.
0N/A //
0N/A // Use (f.exists() && !chooser.getFileSystemView().isFileSystemRoot(f)) to
0N/A // determine if it is safe to call methods directly on f.
0N/A return getFileColumnValue((File)directoryModel.getElementAt(row), col);
0N/A }
0N/A
0N/A private Object getFileColumnValue(File f, int col) {
0N/A return (col == COLUMN_FILENAME)
0N/A ? f // always return the file itself for the 1st column
0N/A : ShellFolder.getFolderColumnValue(f, columnMap[col]);
0N/A }
0N/A
0N/A public void setValueAt(Object value, int row, int col) {
0N/A if (col == COLUMN_FILENAME) {
0N/A JFileChooser chooser = getFileChooser();
0N/A File f = (File)getValueAt(row, col);
0N/A if (f != null) {
0N/A String oldDisplayName = chooser.getName(f);
0N/A String oldFileName = f.getName();
0N/A String newDisplayName = ((String)value).trim();
0N/A String newFileName;
0N/A
0N/A if (!newDisplayName.equals(oldDisplayName)) {
0N/A newFileName = newDisplayName;
0N/A //Check if extension is hidden from user
0N/A int i1 = oldFileName.length();
0N/A int i2 = oldDisplayName.length();
4791N/A if (i1 > i2 && oldFileName.charAt(i2) == '.') {
0N/A newFileName = newDisplayName + oldFileName.substring(i2);
0N/A }
0N/A
0N/A // rename
0N/A FileSystemView fsv = chooser.getFileSystemView();
0N/A File f2 = fsv.createFileObject(f.getParentFile(), newFileName);
0N/A if (f2.exists()) {
0N/A JOptionPane.showMessageDialog(chooser, MessageFormat.format(renameErrorFileExistsText,
0N/A oldFileName), renameErrorTitleText, JOptionPane.ERROR_MESSAGE);
0N/A } else {
0N/A if (FilePane.this.getModel().renameFile(f, f2)) {
4791N/A if (fsv.isParent(chooser.getCurrentDirectory(), f2)) {
0N/A if (chooser.isMultiSelectionEnabled()) {
0N/A chooser.setSelectedFiles(new File[]{f2});
0N/A } else {
0N/A chooser.setSelectedFile(f2);
0N/A }
0N/A } else {
0N/A // Could be because of delay in updating Desktop folder
0N/A // chooser.setSelectedFile(null);
0N/A }
0N/A } else {
0N/A JOptionPane.showMessageDialog(chooser, MessageFormat.format(renameErrorText, oldFileName),
0N/A renameErrorTitleText, JOptionPane.ERROR_MESSAGE);
0N/A }
0N/A }
0N/A }
0N/A }
4791N/A }
0N/A }
0N/A
0N/A public boolean isCellEditable(int row, int column) {
0N/A File currentDirectory = getFileChooser().getCurrentDirectory();
0N/A return (!readOnly && column == COLUMN_FILENAME && canWrite(currentDirectory));
0N/A }
0N/A
0N/A public void contentsChanged(ListDataEvent e) {
0N/A // Update the selection after the model has been updated
0N/A new DelayedSelectionUpdater();
0N/A fireTableDataChanged();
0N/A }
0N/A
0N/A public void intervalAdded(ListDataEvent e) {
0N/A int i0 = e.getIndex0();
0N/A int i1 = e.getIndex1();
0N/A if (i0 == i1) {
0N/A File file = (File)getModel().getElementAt(i0);
0N/A if (file.equals(newFolderFile)) {
0N/A new DelayedSelectionUpdater(file);
0N/A newFolderFile = null;
0N/A }
0N/A }
0N/A
0N/A fireTableRowsInserted(e.getIndex0(), e.getIndex1());
0N/A }
0N/A public void intervalRemoved(ListDataEvent e) {
0N/A fireTableRowsDeleted(e.getIndex0(), e.getIndex1());
0N/A }
4791N/A
0N/A public ShellFolderColumnInfo[] getColumns() {
0N/A return columns;
0N/A }
0N/A }
0N/A
0N/A
0N/A private void updateDetailsColumnModel(JTable table) {
0N/A if (table != null) {
0N/A ShellFolderColumnInfo[] columns = detailsTableModel.getColumns();
0N/A
0N/A TableColumnModel columnModel = new DefaultTableColumnModel();
0N/A for (int i = 0; i < columns.length; i++) {
0N/A ShellFolderColumnInfo dataItem = columns[i];
0N/A TableColumn column = new TableColumn(i);
0N/A
0N/A String title = dataItem.getTitle();
0N/A if (title != null && title.startsWith("FileChooser.") && title.endsWith("HeaderText")) {
0N/A // the column must have a string resource that we try to get
0N/A String uiTitle = UIManager.getString(title, table.getLocale());
0N/A if (uiTitle != null) {
0N/A title = uiTitle;
0N/A }
0N/A }
0N/A column.setHeaderValue(title);
0N/A
0N/A Integer width = dataItem.getWidth();
0N/A if (width != null) {
0N/A column.setPreferredWidth(width);
0N/A // otherwise we let JTable to decide the actual width
0N/A }
0N/A
0N/A columnModel.addColumn(column);
0N/A }
0N/A
0N/A // Install cell editor for editing file name
0N/A if (!readOnly && columnModel.getColumnCount() > COLUMN_FILENAME) {
0N/A columnModel.getColumn(COLUMN_FILENAME).
0N/A setCellEditor(getDetailsTableCellEditor());
0N/A }
0N/A
0N/A table.setColumnModel(columnModel);
0N/A }
0N/A }
0N/A
0N/A private DetailsTableRowSorter getRowSorter() {
0N/A if (rowSorter == null) {
0N/A rowSorter = new DetailsTableRowSorter();
0N/A }
0N/A return rowSorter;
0N/A }
0N/A
0N/A private class DetailsTableRowSorter extends TableRowSorter {
0N/A public DetailsTableRowSorter() {
0N/A setModelWrapper(new SorterModelWrapper());
0N/A }
0N/A
0N/A public void updateComparators(ShellFolderColumnInfo [] columns) {
0N/A for (int i = 0; i < columns.length; i++) {
0N/A Comparator c = columns[i].getComparator();
0N/A if (c != null) {
0N/A c = new DirectoriesFirstComparatorWrapper(i, c);
0N/A }
0N/A setComparator(i, c);
0N/A }
0N/A }
0N/A
0N/A public void modelStructureChanged() {
0N/A super.modelStructureChanged();
0N/A updateComparators(detailsTableModel.getColumns());
0N/A }
0N/A
0N/A private class SorterModelWrapper extends ModelWrapper {
0N/A public Object getModel() {
0N/A return getDetailsTableModel();
0N/A }
0N/A
0N/A public int getColumnCount() {
0N/A return getDetailsTableModel().getColumnCount();
0N/A }
0N/A
0N/A public int getRowCount() {
0N/A return getDetailsTableModel().getRowCount();
0N/A }
0N/A
0N/A public Object getValueAt(int row, int column) {
0N/A return FilePane.this.getModel().getElementAt(row);
0N/A }
0N/A
0N/A public Object getIdentifier(int row) {
0N/A return row;
4007N/A }
4007N/A }
4007N/A }
4007N/A
4007N/A /**
4007N/A * This class sorts directories before files, comparing directory to
4007N/A * directory and file to file using the wrapped comparator.
4007N/A */
4007N/A private class DirectoriesFirstComparatorWrapper implements Comparator<File> {
4007N/A private Comparator comparator;
4007N/A private int column;
4007N/A
4007N/A public DirectoriesFirstComparatorWrapper(int column, Comparator comparator) {
4007N/A this.column = column;
4007N/A this.comparator = comparator;
4007N/A }
4007N/A
4007N/A public int compare(File f1, File f2) {
4007N/A if (f1 != null && f2 != null) {
4007N/A boolean traversable1 = getFileChooser().isTraversable(f1);
4007N/A boolean traversable2 = getFileChooser().isTraversable(f2);
4007N/A // directories go first
4007N/A if (traversable1 && !traversable2) {
4007N/A return -1;
4007N/A }
4007N/A if (!traversable1 && traversable2) {
4007N/A return 1;
4007N/A }
4007N/A }
4007N/A if (detailsTableModel.getColumns()[column].isCompareByColumn()) {
4007N/A return comparator.compare(
4007N/A getDetailsTableModel().getFileColumnValue(f1, column),
4007N/A getDetailsTableModel().getFileColumnValue(f2, column)
4007N/A );
4007N/A }
4007N/A // For this column we need to pass the file itself (not a
4007N/A // column value) to the comparator
4007N/A return comparator.compare(f1, f2);
4007N/A }
4007N/A }
4007N/A
4007N/A private DetailsTableCellEditor tableCellEditor;
4007N/A
4007N/A private DetailsTableCellEditor getDetailsTableCellEditor() {
4007N/A if (tableCellEditor == null) {
4007N/A tableCellEditor = new DetailsTableCellEditor(new JTextField());
4007N/A }
4007N/A return tableCellEditor;
4007N/A }
4007N/A
4007N/A private class DetailsTableCellEditor extends DefaultCellEditor {
4007N/A private final JTextField tf;
4007N/A
4007N/A public DetailsTableCellEditor(JTextField tf) {
4007N/A super(tf);
4007N/A this.tf = tf;
4007N/A tf.addFocusListener(editorFocusListener);
4007N/A }
4007N/A
4007N/A public Component getTableCellEditorComponent(JTable table, Object value,
4007N/A boolean isSelected, int row, int column) {
4007N/A Component comp = super.getTableCellEditorComponent(table, value,
4007N/A isSelected, row, column);
0N/A if (value instanceof File) {
tf.setText(getFileChooser().getName((File) value));
tf.selectAll();
}
return comp;
}
}
class DetailsTableCellRenderer extends DefaultTableCellRenderer {
JFileChooser chooser;
DateFormat df;
DetailsTableCellRenderer(JFileChooser chooser) {
this.chooser = chooser;
df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
chooser.getLocale());
}
public void setBounds(int x, int y, int width, int height) {
if (getHorizontalAlignment() == SwingConstants.LEADING) {
// Restrict width to actual text
width = Math.min(width, this.getPreferredSize().width+4);
} else {
x -= 4;
}
super.setBounds(x, y, width, height);
}
public Insets getInsets(Insets i) {
// Provide some space between columns
i = super.getInsets(i);
i.left += 4;
i.right += 4;
return i;
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (table.convertColumnIndexToModel(column) != COLUMN_FILENAME ||
(listViewWindowsStyle && !table.isFocusOwner())) {
isSelected = false;
}
super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
setIcon(null);
int modelColumn = table.convertColumnIndexToModel(column);
ShellFolderColumnInfo columnInfo = detailsTableModel.getColumns()[modelColumn];
Integer alignment = columnInfo.getAlignment();
if (alignment == null) {
alignment = (value instanceof Number)
? SwingConstants.RIGHT
: SwingConstants.LEADING;
}
setHorizontalAlignment(alignment);
// formatting cell text
// TODO: it's rather a temporary trick, to be revised
String text;
if (value == null) {
text = "";
} else if (value instanceof File) {
File file = (File)value;
text = chooser.getName(file);
Icon icon = chooser.getIcon(file);
setIcon(icon);
} else if (value instanceof Long) {
long len = ((Long) value) / 1024L;
if (listViewWindowsStyle) {
text = MessageFormat.format(kiloByteString, len + 1);
} else if (len < 1024L) {
text = MessageFormat.format(kiloByteString, (len == 0L) ? 1L : len);
} else {
len /= 1024L;
if (len < 1024L) {
text = MessageFormat.format(megaByteString, len);
} else {
len /= 1024L;
text = MessageFormat.format(gigaByteString, len);
}
}
} else if (value instanceof Date) {
text = df.format((Date)value);
} else {
text = value.toString();
}
setText(text);
return this;
}
}
public JPanel createDetailsView() {
final JFileChooser chooser = getFileChooser();
JPanel p = new JPanel(new BorderLayout());
final JTable detailsTable = new JTable(getDetailsTableModel()) {
// Handle Escape key events here
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE && getCellEditor() == null) {
// We are not editing, forward to filechooser.
chooser.dispatchEvent(e);
return true;
}
return super.processKeyBinding(ks, e, condition, pressed);
}
public void tableChanged(TableModelEvent e) {
super.tableChanged(e);
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
// update header with possibly changed column set
updateDetailsColumnModel(this);
}
}
};
detailsTable.setRowSorter(getRowSorter());
detailsTable.setAutoCreateColumnsFromModel(false);
detailsTable.setComponentOrientation(chooser.getComponentOrientation());
detailsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
detailsTable.setShowGrid(false);
detailsTable.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);
detailsTable.addKeyListener(detailsKeyListener);
Font font = list.getFont();
detailsTable.setFont(font);
detailsTable.setIntercellSpacing(new Dimension(0, 0));
TableCellRenderer headerRenderer =
new AlignableTableHeaderRenderer(detailsTable.getTableHeader().getDefaultRenderer());
detailsTable.getTableHeader().setDefaultRenderer(headerRenderer);
TableCellRenderer cellRenderer = new DetailsTableCellRenderer(chooser);
detailsTable.setDefaultRenderer(Object.class, cellRenderer);
// So that drag can be started on a mouse press
detailsTable.getColumnModel().getSelectionModel().
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
detailsTable.addMouseListener(getMouseHandler());
// No need to addListSelectionListener because selections are forwarded
// to our JList.
// 4835633 : tell BasicTableUI that this is a file list
detailsTable.putClientProperty("Table.isFileList", Boolean.TRUE);
if (listViewWindowsStyle) {
detailsTable.addFocusListener(repaintListener);
}
// TAB/SHIFT-TAB should transfer focus and ENTER should select an item.
// We don't want them to navigate within the table
ActionMap am = SwingUtilities.getUIActionMap(detailsTable);
am.remove("selectNextRowCell");
am.remove("selectPreviousRowCell");
am.remove("selectNextColumnCell");
am.remove("selectPreviousColumnCell");
detailsTable.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
null);
detailsTable.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
null);
JScrollPane scrollpane = new JScrollPane(detailsTable);
scrollpane.setComponentOrientation(chooser.getComponentOrientation());
LookAndFeel.installColors(scrollpane.getViewport(), "Table.background", "Table.foreground");
// Adjust width of first column so the table fills the viewport when
// first displayed (temporary listener).
scrollpane.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
JScrollPane sp = (JScrollPane)e.getComponent();
fixNameColumnWidth(sp.getViewport().getSize().width);
sp.removeComponentListener(this);
}
});
// 4835633.
// If the mouse is pressed in the area below the Details view table, the
// event is not dispatched to the Table MouseListener but to the
// scrollpane. Listen for that here so we can clear the selection.
scrollpane.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JScrollPane jsp = ((JScrollPane)e.getComponent());
JTable table = (JTable)jsp.getViewport().getView();
if (!e.isShiftDown() || table.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) {
clearSelection();
TableCellEditor tce = table.getCellEditor();
if (tce != null) {
tce.stopCellEditing();
}
}
}
});
detailsTable.setForeground(list.getForeground());
detailsTable.setBackground(list.getBackground());
if (listViewBorder != null) {
scrollpane.setBorder(listViewBorder);
}
p.add(scrollpane, BorderLayout.CENTER);
detailsTableModel.fireTableStructureChanged();
return p;
} // createDetailsView
private class AlignableTableHeaderRenderer implements TableCellRenderer {
TableCellRenderer wrappedRenderer;
public AlignableTableHeaderRenderer(TableCellRenderer wrappedRenderer) {
this.wrappedRenderer = wrappedRenderer;
}
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component c = wrappedRenderer.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
int modelColumn = table.convertColumnIndexToModel(column);
ShellFolderColumnInfo columnInfo = detailsTableModel.getColumns()[modelColumn];
Integer alignment = columnInfo.getAlignment();
if (alignment == null) {
alignment = SwingConstants.CENTER;
}
if (c instanceof JLabel) {
((JLabel) c).setHorizontalAlignment(alignment);
}
return c;
}
}
private void fixNameColumnWidth(int viewWidth) {
TableColumn nameCol = detailsTable.getColumnModel().getColumn(COLUMN_FILENAME);
int tableWidth = detailsTable.getPreferredSize().width;
if (tableWidth < viewWidth) {
nameCol.setPreferredWidth(nameCol.getPreferredWidth() + viewWidth - tableWidth);
}
}
private class DelayedSelectionUpdater implements Runnable {
File editFile;
DelayedSelectionUpdater() {
this(null);
}
DelayedSelectionUpdater(File editFile) {
this.editFile = editFile;
if (isShowing()) {
SwingUtilities.invokeLater(this);
}
}
public void run() {
setFileSelected();
if (editFile != null) {
editFileName(getRowSorter().convertRowIndexToView(
getModel().indexOf(editFile)));
editFile = null;
}
}
}
/**
* Creates a selection listener for the list of files and directories.
*
* @return a <code>ListSelectionListener</code>
*/
public ListSelectionListener createListSelectionListener() {
return fileChooserUIAccessor.createListSelectionListener();
}
int lastIndex = -1;
File editFile = null;
int editX = 20;
private int getEditIndex() {
return lastIndex;
}
private void setEditIndex(int i) {
lastIndex = i;
}
private void resetEditIndex() {
lastIndex = -1;
}
private void cancelEdit() {
if (editFile != null) {
editFile = null;
list.remove(editCell);
repaint();
} else if (detailsTable != null && detailsTable.isEditing()) {
detailsTable.getCellEditor().cancelCellEditing();
}
}
JTextField editCell = null;
/**
* @param index visual index of the file to be edited
*/
private void editFileName(int index) {
File currentDirectory = getFileChooser().getCurrentDirectory();
if (readOnly || !canWrite(currentDirectory)) {
return;
}
ensureIndexIsVisible(index);
switch (viewType) {
case VIEWTYPE_LIST:
editFile = (File)getModel().getElementAt(getRowSorter().convertRowIndexToModel(index));
Rectangle r = list.getCellBounds(index, index);
if (editCell == null) {
editCell = new JTextField();
editCell.addActionListener(new EditActionListener());
editCell.addFocusListener(editorFocusListener);
editCell.setNextFocusableComponent(list);
}
list.add(editCell);
editCell.setText(getFileChooser().getName(editFile));
ComponentOrientation orientation = list.getComponentOrientation();
editCell.setComponentOrientation(orientation);
if (orientation.isLeftToRight()) {
editCell.setBounds(editX + r.x, r.y, r.width - editX, r.height);
} else {
editCell.setBounds(r.x, r.y, r.width - editX, r.height);
}
editCell.requestFocus();
editCell.selectAll();
break;
case VIEWTYPE_DETAILS:
detailsTable.editCellAt(index, COLUMN_FILENAME);
break;
}
}
class EditActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
applyEdit();
}
}
private void applyEdit() {
if (editFile != null && editFile.exists()) {
JFileChooser chooser = getFileChooser();
String oldDisplayName = chooser.getName(editFile);
String oldFileName = editFile.getName();
String newDisplayName = editCell.getText().trim();
String newFileName;
if (!newDisplayName.equals(oldDisplayName)) {
newFileName = newDisplayName;
//Check if extension is hidden from user
int i1 = oldFileName.length();
int i2 = oldDisplayName.length();
if (i1 > i2 && oldFileName.charAt(i2) == '.') {
newFileName = newDisplayName + oldFileName.substring(i2);
}
// rename
FileSystemView fsv = chooser.getFileSystemView();
File f2 = fsv.createFileObject(editFile.getParentFile(), newFileName);
if (f2.exists()) {
JOptionPane.showMessageDialog(chooser, MessageFormat.format(renameErrorFileExistsText, oldFileName),
renameErrorTitleText, JOptionPane.ERROR_MESSAGE);
} else {
if (getModel().renameFile(editFile, f2)) {
if (fsv.isParent(chooser.getCurrentDirectory(), f2)) {
if (chooser.isMultiSelectionEnabled()) {
chooser.setSelectedFiles(new File[]{f2});
} else {
chooser.setSelectedFile(f2);
}
} else {
//Could be because of delay in updating Desktop folder
//chooser.setSelectedFile(null);
}
} else {
JOptionPane.showMessageDialog(chooser, MessageFormat.format(renameErrorText, oldFileName),
renameErrorTitleText, JOptionPane.ERROR_MESSAGE);
}
}
}
}
if (detailsTable != null && detailsTable.isEditing()) {
detailsTable.getCellEditor().stopCellEditing();
}
cancelEdit();
}
protected Action newFolderAction;
public Action getNewFolderAction() {
if (!readOnly && newFolderAction == null) {
newFolderAction = new AbstractAction(newFolderActionLabelText) {
private Action basicNewFolderAction;
// Initializer
{
putValue(Action.ACTION_COMMAND_KEY, FilePane.ACTION_NEW_FOLDER);
File currentDirectory = getFileChooser().getCurrentDirectory();
if (currentDirectory != null) {
setEnabled(canWrite(currentDirectory));
}
}
public void actionPerformed(ActionEvent ev) {
if (basicNewFolderAction == null) {
basicNewFolderAction = fileChooserUIAccessor.getNewFolderAction();
}
JFileChooser fc = getFileChooser();
File oldFile = fc.getSelectedFile();
basicNewFolderAction.actionPerformed(ev);
File newFile = fc.getSelectedFile();
if (newFile != null && !newFile.equals(oldFile) && newFile.isDirectory()) {
newFolderFile = newFile;
}
}
};
}
return newFolderAction;
}
protected class FileRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected,
boolean cellHasFocus) {
if (listViewWindowsStyle && !list.isFocusOwner()) {
isSelected = false;
}
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
File file = (File) value;
String fileName = getFileChooser().getName(file);
setText(fileName);
setFont(list.getFont());
Icon icon = getFileChooser().getIcon(file);
if (icon != null) {
setIcon(icon);
if (isSelected) {
// PENDING - grab padding (4) below from defaults table.
editX = icon.getIconWidth() + 4;
}
} else {
if (getFileChooser().getFileSystemView().isTraversable(file)) {
setText(fileName+File.separator);
}
}
return this;
}
}
void setFileSelected() {
if (getFileChooser().isMultiSelectionEnabled() && !isDirectorySelected()) {
File[] files = getFileChooser().getSelectedFiles(); // Should be selected
Object[] selectedObjects = list.getSelectedValues(); // Are actually selected
listSelectionModel.setValueIsAdjusting(true);
try {
int lead = listSelectionModel.getLeadSelectionIndex();
int anchor = listSelectionModel.getAnchorSelectionIndex();
Arrays.sort(files);
Arrays.sort(selectedObjects);
int shouldIndex = 0;
int actuallyIndex = 0;
// Remove files that shouldn't be selected and add files which should be selected
// Note: Assume files are already sorted in compareTo order.
while (shouldIndex < files.length &&
actuallyIndex < selectedObjects.length) {
int comparison = files[shouldIndex].compareTo((File)selectedObjects[actuallyIndex]);
if (comparison < 0) {
doSelectFile(files[shouldIndex++]);
} else if (comparison > 0) {
doDeselectFile(selectedObjects[actuallyIndex++]);
} else {
// Do nothing
shouldIndex++;
actuallyIndex++;
}
}
while (shouldIndex < files.length) {
doSelectFile(files[shouldIndex++]);
}
while (actuallyIndex < selectedObjects.length) {
doDeselectFile(selectedObjects[actuallyIndex++]);
}
// restore the anchor and lead
if (listSelectionModel instanceof DefaultListSelectionModel) {
((DefaultListSelectionModel)listSelectionModel).
moveLeadSelectionIndex(lead);
listSelectionModel.setAnchorSelectionIndex(anchor);
}
} finally {
listSelectionModel.setValueIsAdjusting(false);
}
} else {
JFileChooser chooser = getFileChooser();
File f;
if (isDirectorySelected()) {
f = getDirectory();
} else {
f = chooser.getSelectedFile();
}
int i;
if (f != null && (i = getModel().indexOf(f)) >= 0) {
int viewIndex = getRowSorter().convertRowIndexToView(i);
listSelectionModel.setSelectionInterval(viewIndex, viewIndex);
ensureIndexIsVisible(viewIndex);
} else {
clearSelection();
}
}
}
private void doSelectFile(File fileToSelect) {
int index = getModel().indexOf(fileToSelect);
// could be missed in the current directory if it changed
if (index >= 0) {
index = getRowSorter().convertRowIndexToView(index);
listSelectionModel.addSelectionInterval(index, index);
}
}
private void doDeselectFile(Object fileToDeselect) {
int index = getRowSorter().convertRowIndexToView(
getModel().indexOf(fileToDeselect));
listSelectionModel.removeSelectionInterval(index, index);
}
/* The following methods are used by the PropertyChange Listener */
private void doSelectedFileChanged(PropertyChangeEvent e) {
applyEdit();
File f = (File) e.getNewValue();
JFileChooser fc = getFileChooser();
if (f != null
&& ((fc.isFileSelectionEnabled() && !f.isDirectory())
|| (f.isDirectory() && fc.isDirectorySelectionEnabled()))) {
setFileSelected();
}
}
private void doSelectedFilesChanged(PropertyChangeEvent e) {
applyEdit();
File[] files = (File[]) e.getNewValue();
JFileChooser fc = getFileChooser();
if (files != null
&& files.length > 0
&& (files.length > 1 || fc.isDirectorySelectionEnabled() || !files[0].isDirectory())) {
setFileSelected();
}
}
private void doDirectoryChanged(PropertyChangeEvent e) {
getDetailsTableModel().updateColumnInfo();
JFileChooser fc = getFileChooser();
FileSystemView fsv = fc.getFileSystemView();
applyEdit();
resetEditIndex();
ensureIndexIsVisible(0);
File currentDirectory = fc.getCurrentDirectory();
if (currentDirectory != null) {
if (!readOnly) {
getNewFolderAction().setEnabled(canWrite(currentDirectory));
}
fileChooserUIAccessor.getChangeToParentDirectoryAction().setEnabled(!fsv.isRoot(currentDirectory));
}
if (list != null) {
list.clearSelection();
}
}
private void doFilterChanged(PropertyChangeEvent e) {
applyEdit();
resetEditIndex();
clearSelection();
}
private void doFileSelectionModeChanged(PropertyChangeEvent e) {
applyEdit();
resetEditIndex();
clearSelection();
}
private void doMultiSelectionChanged(PropertyChangeEvent e) {
if (getFileChooser().isMultiSelectionEnabled()) {
listSelectionModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
} else {
listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
clearSelection();
getFileChooser().setSelectedFiles(null);
}
}
/*
* Listen for filechooser property changes, such as
* the selected file changing, or the type of the dialog changing.
*/
public void propertyChange(PropertyChangeEvent e) {
if (viewType == -1) {
setViewType(VIEWTYPE_LIST);
}
String s = e.getPropertyName();
if (s.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
doSelectedFileChanged(e);
} else if (s.equals(JFileChooser.SELECTED_FILES_CHANGED_PROPERTY)) {
doSelectedFilesChanged(e);
} else if (s.equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
doDirectoryChanged(e);
} else if (s.equals(JFileChooser.FILE_FILTER_CHANGED_PROPERTY)) {
doFilterChanged(e);
} else if (s.equals(JFileChooser.FILE_SELECTION_MODE_CHANGED_PROPERTY)) {
doFileSelectionModeChanged(e);
} else if (s.equals(JFileChooser.MULTI_SELECTION_ENABLED_CHANGED_PROPERTY)) {
doMultiSelectionChanged(e);
} else if (s.equals(JFileChooser.CANCEL_SELECTION)) {
applyEdit();
} else if (s.equals("busy")) {
setCursor((Boolean)e.getNewValue() ? waitCursor : null);
} else if (s.equals("componentOrientation")) {
ComponentOrientation o = (ComponentOrientation)e.getNewValue();
JFileChooser cc = (JFileChooser)e.getSource();
if (o != e.getOldValue()) {
cc.applyComponentOrientation(o);
}
if (detailsTable != null) {
detailsTable.setComponentOrientation(o);
detailsTable.getParent().getParent().setComponentOrientation(o);
}
}
}
private void ensureIndexIsVisible(int i) {
if (i >= 0) {
if (list != null) {
list.ensureIndexIsVisible(i);
}
if (detailsTable != null) {
detailsTable.scrollRectToVisible(detailsTable.getCellRect(i, COLUMN_FILENAME, true));
}
}
}
public void ensureFileIsVisible(JFileChooser fc, File f) {
int modelIndex = getModel().indexOf(f);
if (modelIndex >= 0) {
ensureIndexIsVisible(getRowSorter().convertRowIndexToView(modelIndex));
}
}
public void rescanCurrentDirectory() {
getModel().validateFileCache();
}
public void clearSelection() {
if (listSelectionModel != null) {
listSelectionModel.clearSelection();
if (listSelectionModel instanceof DefaultListSelectionModel) {
((DefaultListSelectionModel)listSelectionModel).moveLeadSelectionIndex(0);
listSelectionModel.setAnchorSelectionIndex(0);
}
}
}
public JMenu getViewMenu() {
if (viewMenu == null) {
viewMenu = new JMenu(viewMenuLabelText);
ButtonGroup viewButtonGroup = new ButtonGroup();
for (int i = 0; i < VIEWTYPE_COUNT; i++) {
JRadioButtonMenuItem mi =
new JRadioButtonMenuItem(new ViewTypeAction(i));
viewButtonGroup.add(mi);
viewMenu.add(mi);
}
updateViewMenu();
}
return viewMenu;
}
private void updateViewMenu() {
if (viewMenu != null) {
Component[] comps = viewMenu.getMenuComponents();
for (int i = 0; i < comps.length; i++) {
if (comps[i] instanceof JRadioButtonMenuItem) {
JRadioButtonMenuItem mi = (JRadioButtonMenuItem)comps[i];
if (((ViewTypeAction)mi.getAction()).viewType == viewType) {
mi.setSelected(true);
}
}
}
}
}
public JPopupMenu getComponentPopupMenu() {
JPopupMenu popupMenu = getFileChooser().getComponentPopupMenu();
if (popupMenu != null) {
return popupMenu;
}
JMenu viewMenu = getViewMenu();
if (contextMenu == null) {
contextMenu = new JPopupMenu();
if (viewMenu != null) {
contextMenu.add(viewMenu);
if (listViewWindowsStyle) {
contextMenu.addSeparator();
}
}
ActionMap actionMap = getActionMap();
Action refreshAction = actionMap.get(ACTION_REFRESH);
Action newFolderAction = actionMap.get(ACTION_NEW_FOLDER);
if (refreshAction != null) {
contextMenu.add(refreshAction);
if (listViewWindowsStyle && newFolderAction != null) {
contextMenu.addSeparator();
}
}
if (newFolderAction != null) {
contextMenu.add(newFolderAction);
}
}
if (viewMenu != null) {
viewMenu.getPopupMenu().setInvoker(viewMenu);
}
return contextMenu;
}
private Handler handler;
protected Handler getMouseHandler() {
if (handler == null) {
handler = new Handler();
}
return handler;
}
private class Handler implements MouseListener {
private MouseListener doubleClickListener;
public void mouseClicked(MouseEvent evt) {
JComponent source = (JComponent)evt.getSource();
int index;
if (source instanceof JList) {
index = SwingUtilities2.loc2IndexFileList(list, evt.getPoint());
} else if (source instanceof JTable) {
JTable table = (JTable)source;
Point p = evt.getPoint();
index = table.rowAtPoint(p);
if (SwingUtilities2.pointOutsidePrefSize(table,
index,
table.columnAtPoint(p), p)) {
return;
}
// Translate point from table to list
if (index >= 0 && list != null &&
listSelectionModel.isSelectedIndex(index)) {
// Make a new event with the list as source, placing the
// click in the corresponding list cell.
Rectangle r = list.getCellBounds(index, index);
evt = new MouseEvent(list, evt.getID(),
evt.getWhen(), evt.getModifiers(),
r.x + 1, r.y + r.height/2,
evt.getXOnScreen(),
evt.getYOnScreen(),
evt.getClickCount(), evt.isPopupTrigger(),
evt.getButton());
}
} else {
return;
}
if (index >= 0 && SwingUtilities.isLeftMouseButton(evt)) {
JFileChooser fc = getFileChooser();
// For single click, we handle editing file name
if (evt.getClickCount() == 1 && source instanceof JList) {
if ((!fc.isMultiSelectionEnabled() || fc.getSelectedFiles().length <= 1)
&& index >= 0 && listSelectionModel.isSelectedIndex(index)
&& getEditIndex() == index && editFile == null) {
editFileName(index);
} else {
if (index >= 0) {
setEditIndex(index);
} else {
resetEditIndex();
}
}
} else if (evt.getClickCount() == 2) {
// on double click (open or drill down one directory) be
// sure to clear the edit index
resetEditIndex();
}
}
// Forward event to Basic
if (getDoubleClickListener() != null) {
getDoubleClickListener().mouseClicked(evt);
}
}
public void mouseEntered(MouseEvent evt) {
JComponent source = (JComponent)evt.getSource();
if (source instanceof JTable) {
JTable table = (JTable)evt.getSource();
TransferHandler th1 = getFileChooser().getTransferHandler();
TransferHandler th2 = table.getTransferHandler();
if (th1 != th2) {
table.setTransferHandler(th1);
}
boolean dragEnabled = getFileChooser().getDragEnabled();
if (dragEnabled != table.getDragEnabled()) {
table.setDragEnabled(dragEnabled);
}
} else if (source instanceof JList) {
// Forward event to Basic
if (getDoubleClickListener() != null) {
getDoubleClickListener().mouseEntered(evt);
}
}
}
public void mouseExited(MouseEvent evt) {
if (evt.getSource() instanceof JList) {
// Forward event to Basic
if (getDoubleClickListener() != null) {
getDoubleClickListener().mouseExited(evt);
}
}
}
public void mousePressed(MouseEvent evt) {
if (evt.getSource() instanceof JList) {
// Forward event to Basic
if (getDoubleClickListener() != null) {
getDoubleClickListener().mousePressed(evt);
}
}
}
public void mouseReleased(MouseEvent evt) {
if (evt.getSource() instanceof JList) {
// Forward event to Basic
if (getDoubleClickListener() != null) {
getDoubleClickListener().mouseReleased(evt);
}
}
}
private MouseListener getDoubleClickListener() {
// Lazy creation of Basic's listener
if (doubleClickListener == null && list != null) {
doubleClickListener =
fileChooserUIAccessor.createDoubleClickListener(list);
}
return doubleClickListener;
}
}
/**
* Property to remember whether a directory is currently selected in the UI.
*
* @return <code>true</code> iff a directory is currently selected.
*/
protected boolean isDirectorySelected() {
return fileChooserUIAccessor.isDirectorySelected();
}
/**
* Property to remember the directory that is currently selected in the UI.
*
* @return the value of the <code>directory</code> property
* @see javax.swing.plaf.basic.BasicFileChooserUI#setDirectory
*/
protected File getDirectory() {
return fileChooserUIAccessor.getDirectory();
}
private Component findChildComponent(Container container, Class cls) {
int n = container.getComponentCount();
for (int i = 0; i < n; i++) {
Component comp = container.getComponent(i);
if (cls.isInstance(comp)) {
return comp;
} else if (comp instanceof Container) {
Component c = findChildComponent((Container)comp, cls);
if (c != null) {
return c;
}
}
}
return null;
}
public boolean canWrite(File f) {
// Return false for non FileSystem files or if file doesn't exist.
if (!f.exists()) {
return false;
}
if (f instanceof ShellFolder) {
return ((ShellFolder) f).isFileSystem();
} else {
if (fileChooserUIAccessor.usesShellFolder()) {
try {
return ShellFolder.getShellFolder(f).isFileSystem();
} catch (FileNotFoundException ex) {
// File doesn't exist
return false;
}
} else {
// Ordinary file
return true;
}
}
}
// This interface is used to access methods in the FileChooserUI
// that are not public.
public interface FileChooserUIAccessor {
public JFileChooser getFileChooser();
public BasicDirectoryModel getModel();
public JPanel createList();
public JPanel createDetailsView();
public boolean isDirectorySelected();
public File getDirectory();
public Action getApproveSelectionAction();
public Action getChangeToParentDirectoryAction();
public Action getNewFolderAction();
public MouseListener createDoubleClickListener(JList list);
public ListSelectionListener createListSelectionListener();
public boolean usesShellFolder();
}
}