1 /*
   2  * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package sun.swing;
  26 
  27 import java.awt.*;
  28 import java.awt.event.*;
  29 import java.beans.PropertyChangeEvent;
  30 import java.beans.PropertyChangeListener;
  31 import java.io.*;
  32 import java.text.DateFormat;
  33 import java.text.MessageFormat;
  34 import java.util.*;
  35 import java.util.List;
  36 import java.util.concurrent.Callable;
  37 
  38 import javax.accessibility.AccessibleContext;
  39 import javax.swing.*;
  40 import javax.swing.border.*;
  41 import javax.swing.event.*;
  42 import javax.swing.filechooser.*;
  43 import javax.swing.plaf.basic.*;
  44 import javax.swing.table.*;
  45 import javax.swing.text.*;
  46 
  47 import sun.awt.shell.*;
  48 
  49 /**
  50  * <b>WARNING:</b> This class is an implementation detail and is only
  51  * public so that it can be used by two packages. You should NOT consider
  52  * this public API.
  53  * <p>
  54  * This component is intended to be used in a subclass of
  55  * javax.swing.plaf.basic.BasicFileChooserUI. It realies heavily on the
  56  * implementation of BasicFileChooserUI, and is intended to be API compatible
  57  * with earlier implementations of MetalFileChooserUI and WindowsFileChooserUI.
  58  *
  59  * @author Leif Samuelsson
  60  */
  61 @SuppressWarnings("serial") // JDK-implementation class
  62 public class FilePane extends JPanel implements PropertyChangeListener {
  63     // Constants for actions. These are used for the actions' ACTION_COMMAND_KEY
  64     // and as keys in the action maps for FilePane and the corresponding UI classes
  65 
  66     public final static String ACTION_APPROVE_SELECTION = "approveSelection";
  67     public final static String ACTION_CANCEL            = "cancelSelection";
  68     public final static String ACTION_EDIT_FILE_NAME    = "editFileName";
  69     public final static String ACTION_REFRESH           = "refresh";
  70     public final static String ACTION_CHANGE_TO_PARENT_DIRECTORY = "Go Up";
  71     public final static String ACTION_NEW_FOLDER        = "New Folder";
  72     public final static String ACTION_VIEW_LIST         = "viewTypeList";
  73     public final static String ACTION_VIEW_DETAILS      = "viewTypeDetails";
  74 
  75     private Action[] actions;
  76 
  77     // "enums" for setViewType()
  78     public  static final int VIEWTYPE_LIST     = 0;
  79     public  static final int VIEWTYPE_DETAILS  = 1;
  80     private static final int VIEWTYPE_COUNT    = 2;
  81 
  82     private int viewType = -1;
  83     private JPanel[] viewPanels = new JPanel[VIEWTYPE_COUNT];
  84     private JPanel currentViewPanel;
  85     private String[] viewTypeActionNames;
  86 
  87     private String filesListAccessibleName = null;
  88     private String filesDetailsAccessibleName = null;
  89 
  90     private JPopupMenu contextMenu;
  91     private JMenu viewMenu;
  92 
  93     private String viewMenuLabelText;
  94     private String refreshActionLabelText;
  95     private String newFolderActionLabelText;
  96 
  97     private String kiloByteString;
  98     private String megaByteString;
  99     private String gigaByteString;
 100 
 101     private String renameErrorTitleText;
 102     private String renameErrorText;
 103     private String renameErrorFileExistsText;
 104 
 105     private static final Cursor waitCursor =
 106         Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
 107 
 108     private final KeyListener detailsKeyListener = new KeyAdapter() {
 109         private final long timeFactor;
 110 
 111         private final StringBuilder typedString = new StringBuilder();
 112 
 113         private long lastTime = 1000L;
 114 
 115         {
 116             Long l = (Long) UIManager.get("Table.timeFactor");
 117             timeFactor = (l != null) ? l : 1000L;
 118         }
 119 
 120         /**
 121          * Moves the keyboard focus to the first element whose prefix matches
 122          * the sequence of alphanumeric keys pressed by the user with delay
 123          * less than value of <code>timeFactor</code>. Subsequent same key
 124          * presses move the keyboard focus to the next object that starts with
 125          * the same letter until another key is pressed, then it is treated
 126          * as the prefix with appropriate number of the same letters followed
 127          * by first typed another letter.
 128          */
 129         public void keyTyped(KeyEvent e) {
 130             BasicDirectoryModel model = getModel();
 131             int rowCount = model.getSize();
 132 
 133             if (detailsTable == null || rowCount == 0 ||
 134                     e.isAltDown() || e.isControlDown() || e.isMetaDown()) {
 135                 return;
 136             }
 137 
 138             InputMap inputMap = detailsTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
 139             KeyStroke key = KeyStroke.getKeyStrokeForEvent(e);
 140 
 141             if (inputMap != null && inputMap.get(key) != null) {
 142                 return;
 143             }
 144 
 145             int startIndex = detailsTable.getSelectionModel().getLeadSelectionIndex();
 146 
 147             if (startIndex < 0) {
 148                 startIndex = 0;
 149             }
 150 
 151             if (startIndex >= rowCount) {
 152                 startIndex = rowCount - 1;
 153             }
 154 
 155             char c = e.getKeyChar();
 156 
 157             long time = e.getWhen();
 158 
 159             if (time - lastTime < timeFactor) {
 160                 if (typedString.length() == 1 && typedString.charAt(0) == c) {
 161                     // Subsequent same key presses move the keyboard focus to the next
 162                     // object that starts with the same letter.
 163                     startIndex++;
 164                 } else {
 165                     typedString.append(c);
 166                 }
 167             } else {
 168                 startIndex++;
 169 
 170                 typedString.setLength(0);
 171                 typedString.append(c);
 172             }
 173 
 174             lastTime = time;
 175 
 176             if (startIndex >= rowCount) {
 177                 startIndex = 0;
 178             }
 179 
 180             // Find next file
 181             int index = getNextMatch(startIndex, rowCount - 1);
 182 
 183             if (index < 0 && startIndex > 0) { // wrap
 184                 index = getNextMatch(0, startIndex - 1);
 185             }
 186 
 187             if (index >= 0) {
 188                 detailsTable.getSelectionModel().setSelectionInterval(index, index);
 189 
 190                 Rectangle cellRect = detailsTable.getCellRect(index,
 191                         detailsTable.convertColumnIndexToView(COLUMN_FILENAME), false);
 192                 detailsTable.scrollRectToVisible(cellRect);
 193             }
 194         }
 195 
 196         private int getNextMatch(int startIndex, int finishIndex) {
 197             BasicDirectoryModel model = getModel();
 198             JFileChooser fileChooser = getFileChooser();
 199             DetailsTableRowSorter rowSorter = getRowSorter();
 200 
 201             String prefix = typedString.toString().toLowerCase();
 202 
 203             // Search element
 204             for (int index = startIndex; index <= finishIndex; index++) {
 205                 File file = (File) model.getElementAt(rowSorter.convertRowIndexToModel(index));
 206 
 207                 String fileName = fileChooser.getName(file).toLowerCase();
 208 
 209                 if (fileName.startsWith(prefix)) {
 210                     return index;
 211                 }
 212             }
 213 
 214             return -1;
 215         }
 216     };
 217 
 218     private FocusListener editorFocusListener = new FocusAdapter() {
 219         public void focusLost(FocusEvent e) {
 220             if (! e.isTemporary()) {
 221                 applyEdit();
 222             }
 223         }
 224     };
 225 
 226     private static FocusListener repaintListener = new FocusListener() {
 227         public void focusGained(FocusEvent fe) {
 228             repaintSelection(fe.getSource());
 229         }
 230 
 231         public void focusLost(FocusEvent fe) {
 232             repaintSelection(fe.getSource());
 233         }
 234 
 235         private void repaintSelection(Object source) {
 236             if (source instanceof JList) {
 237                 repaintListSelection((JList)source);
 238             } else if (source instanceof JTable) {
 239                 repaintTableSelection((JTable)source);
 240             }
 241         }
 242 
 243         private void repaintListSelection(JList list) {
 244             int[] indices = list.getSelectedIndices();
 245             for (int i : indices) {
 246                 Rectangle bounds = list.getCellBounds(i, i);
 247                 list.repaint(bounds);
 248             }
 249         }
 250 
 251         private void repaintTableSelection(JTable table) {
 252             int minRow = table.getSelectionModel().getMinSelectionIndex();
 253             int maxRow = table.getSelectionModel().getMaxSelectionIndex();
 254             if (minRow == -1 || maxRow == -1) {
 255                 return;
 256             }
 257 
 258             int col0 = table.convertColumnIndexToView(COLUMN_FILENAME);
 259 
 260             Rectangle first = table.getCellRect(minRow, col0, false);
 261             Rectangle last = table.getCellRect(maxRow, col0, false);
 262             Rectangle dirty = first.union(last);
 263             table.repaint(dirty);
 264         }
 265     };
 266 
 267     private boolean smallIconsView = false;
 268     private Border  listViewBorder;
 269     private Color   listViewBackground;
 270     private boolean listViewWindowsStyle;
 271     private boolean readOnly;
 272     private boolean fullRowSelection = false;
 273 
 274     private ListSelectionModel listSelectionModel;
 275     private JList list;
 276     private JTable detailsTable;
 277 
 278     private static final int COLUMN_FILENAME = 0;
 279 
 280     // Provides a way to recognize a newly created folder, so it can
 281     // be selected when it appears in the model.
 282     private File newFolderFile;
 283 
 284     // Used for accessing methods in the corresponding UI class
 285     private FileChooserUIAccessor fileChooserUIAccessor;
 286     private DetailsTableModel detailsTableModel;
 287     private DetailsTableRowSorter rowSorter;
 288 
 289     public FilePane(FileChooserUIAccessor fileChooserUIAccessor) {
 290         super(new BorderLayout());
 291 
 292         this.fileChooserUIAccessor = fileChooserUIAccessor;
 293 
 294         installDefaults();
 295         createActionMap();
 296     }
 297 
 298     public void uninstallUI() {
 299         if (getModel() != null) {
 300             getModel().removePropertyChangeListener(this);
 301         }
 302     }
 303 
 304     protected JFileChooser getFileChooser() {
 305         return fileChooserUIAccessor.getFileChooser();
 306     }
 307 
 308     protected BasicDirectoryModel getModel() {
 309         return fileChooserUIAccessor.getModel();
 310     }
 311 
 312     public int getViewType() {
 313         return viewType;
 314     }
 315 
 316     public void setViewType(int viewType) {
 317         if (viewType == this.viewType) {
 318             return;
 319         }
 320 
 321         int oldValue = this.viewType;
 322         this.viewType = viewType;
 323 
 324         JPanel createdViewPanel = null;
 325         Component newFocusOwner = null;
 326 
 327         switch (viewType) {
 328           case VIEWTYPE_LIST:
 329             if (viewPanels[viewType] == null) {
 330                 createdViewPanel = fileChooserUIAccessor.createList();
 331                 if (createdViewPanel == null) {
 332                     createdViewPanel = createList();
 333                 }
 334 
 335                 list = (JList) findChildComponent(createdViewPanel, JList.class);
 336                 if (listSelectionModel == null) {
 337                     listSelectionModel = list.getSelectionModel();
 338                     if (detailsTable != null) {
 339                         detailsTable.setSelectionModel(listSelectionModel);
 340                     }
 341                 } else {
 342                     list.setSelectionModel(listSelectionModel);
 343                 }
 344             }
 345             list.setLayoutOrientation(JList.VERTICAL_WRAP);
 346             newFocusOwner = list;
 347             break;
 348 
 349           case VIEWTYPE_DETAILS:
 350             if (viewPanels[viewType] == null) {
 351                 createdViewPanel = fileChooserUIAccessor.createDetailsView();
 352                 if (createdViewPanel == null) {
 353                     createdViewPanel = createDetailsView();
 354                 }
 355 
 356                 detailsTable = (JTable) findChildComponent(createdViewPanel, JTable.class);
 357                 detailsTable.setRowHeight(Math.max(detailsTable.getFont().getSize() + 4, 16 + 1));
 358                 if (listSelectionModel != null) {
 359                     detailsTable.setSelectionModel(listSelectionModel);
 360                 }
 361             }
 362             newFocusOwner = detailsTable;
 363             break;
 364         }
 365 
 366         if (createdViewPanel != null) {
 367             viewPanels[viewType] = createdViewPanel;
 368             recursivelySetInheritsPopupMenu(createdViewPanel, true);
 369         }
 370 
 371         boolean isFocusOwner = false;
 372 
 373         if (currentViewPanel != null) {
 374             Component owner = DefaultKeyboardFocusManager.
 375                     getCurrentKeyboardFocusManager().getPermanentFocusOwner();
 376 
 377             isFocusOwner = owner == detailsTable || owner == list;
 378 
 379             remove(currentViewPanel);
 380         }
 381 
 382         currentViewPanel = viewPanels[viewType];
 383         add(currentViewPanel, BorderLayout.CENTER);
 384 
 385         if (isFocusOwner && newFocusOwner != null) {
 386             newFocusOwner.requestFocusInWindow();
 387         }
 388 
 389         revalidate();
 390         repaint();
 391         updateViewMenu();
 392         firePropertyChange("viewType", oldValue, viewType);
 393     }
 394 
 395     @SuppressWarnings("serial") // JDK-implementation class
 396     class ViewTypeAction extends AbstractAction {
 397         private int viewType;
 398 
 399         ViewTypeAction(int viewType) {
 400             super(viewTypeActionNames[viewType]);
 401             this.viewType = viewType;
 402 
 403             String cmd;
 404             switch (viewType) {
 405                 case VIEWTYPE_LIST:    cmd = ACTION_VIEW_LIST;    break;
 406                 case VIEWTYPE_DETAILS: cmd = ACTION_VIEW_DETAILS; break;
 407                 default:               cmd = (String)getValue(Action.NAME);
 408             }
 409             putValue(Action.ACTION_COMMAND_KEY, cmd);
 410         }
 411 
 412         public void actionPerformed(ActionEvent e) {
 413             setViewType(viewType);
 414         }
 415     }
 416 
 417     public Action getViewTypeAction(int viewType) {
 418         return new ViewTypeAction(viewType);
 419     }
 420 
 421     private static void recursivelySetInheritsPopupMenu(Container container, boolean b) {
 422         if (container instanceof JComponent) {
 423             ((JComponent)container).setInheritsPopupMenu(b);
 424         }
 425         int n = container.getComponentCount();
 426         for (int i = 0; i < n; i++) {
 427             recursivelySetInheritsPopupMenu((Container)container.getComponent(i), b);
 428         }
 429     }
 430 
 431     protected void installDefaults() {
 432         Locale l = getFileChooser().getLocale();
 433 
 434         listViewBorder       = UIManager.getBorder("FileChooser.listViewBorder");
 435         listViewBackground   = UIManager.getColor("FileChooser.listViewBackground");
 436         listViewWindowsStyle = UIManager.getBoolean("FileChooser.listViewWindowsStyle");
 437         readOnly             = UIManager.getBoolean("FileChooser.readOnly");
 438 
 439         // TODO: On windows, get the following localized strings from the OS
 440 
 441         viewMenuLabelText =
 442                         UIManager.getString("FileChooser.viewMenuLabelText", l);
 443         refreshActionLabelText =
 444                         UIManager.getString("FileChooser.refreshActionLabelText", l);
 445         newFolderActionLabelText =
 446                         UIManager.getString("FileChooser.newFolderActionLabelText", l);
 447 
 448         viewTypeActionNames = new String[VIEWTYPE_COUNT];
 449         viewTypeActionNames[VIEWTYPE_LIST] =
 450                         UIManager.getString("FileChooser.listViewActionLabelText", l);
 451         viewTypeActionNames[VIEWTYPE_DETAILS] =
 452                         UIManager.getString("FileChooser.detailsViewActionLabelText", l);
 453 
 454         kiloByteString = UIManager.getString("FileChooser.fileSizeKiloBytes", l);
 455         megaByteString = UIManager.getString("FileChooser.fileSizeMegaBytes", l);
 456         gigaByteString = UIManager.getString("FileChooser.fileSizeGigaBytes", l);
 457         fullRowSelection = UIManager.getBoolean("FileView.fullRowSelection");
 458 
 459         filesListAccessibleName = UIManager.getString("FileChooser.filesListAccessibleName", l);
 460         filesDetailsAccessibleName = UIManager.getString("FileChooser.filesDetailsAccessibleName", l);
 461 
 462         renameErrorTitleText = UIManager.getString("FileChooser.renameErrorTitleText", l);
 463         renameErrorText = UIManager.getString("FileChooser.renameErrorText", l);
 464         renameErrorFileExistsText = UIManager.getString("FileChooser.renameErrorFileExistsText", l);
 465     }
 466 
 467     /**
 468      * Fetches the command list for the FilePane. These commands
 469      * are useful for binding to events, such as in a keymap.
 470      *
 471      * @return the command list
 472      */
 473     public Action[] getActions() {
 474         if (actions == null) {
 475             @SuppressWarnings("serial") // JDK-implementation class
 476             class FilePaneAction extends AbstractAction {
 477                 FilePaneAction(String name) {
 478                     this(name, name);
 479                 }
 480 
 481                 FilePaneAction(String name, String cmd) {
 482                     super(name);
 483                     putValue(Action.ACTION_COMMAND_KEY, cmd);
 484                 }
 485 
 486                 public void actionPerformed(ActionEvent e) {
 487                     String cmd = (String)getValue(Action.ACTION_COMMAND_KEY);
 488 
 489                     if (cmd == ACTION_CANCEL) {
 490                         if (editFile != null) {
 491                            cancelEdit();
 492                         } else {
 493                            getFileChooser().cancelSelection();
 494                         }
 495                     } else if (cmd == ACTION_EDIT_FILE_NAME) {
 496                         JFileChooser fc = getFileChooser();
 497                         int index = listSelectionModel.getMinSelectionIndex();
 498                         if (index >= 0 && editFile == null &&
 499                             (!fc.isMultiSelectionEnabled() ||
 500                              fc.getSelectedFiles().length <= 1)) {
 501 
 502                             editFileName(index);
 503                         }
 504                     } else if (cmd == ACTION_REFRESH) {
 505                         getFileChooser().rescanCurrentDirectory();
 506                     }
 507                 }
 508 
 509                 public boolean isEnabled() {
 510                     String cmd = (String)getValue(Action.ACTION_COMMAND_KEY);
 511                     if (cmd == ACTION_CANCEL) {
 512                         return getFileChooser().isEnabled();
 513                     } else if (cmd == ACTION_EDIT_FILE_NAME) {
 514                         return !readOnly && getFileChooser().isEnabled();
 515                     } else {
 516                         return true;
 517                     }
 518                 }
 519             }
 520 
 521             ArrayList<Action> actionList = new ArrayList<Action>(8);
 522             Action action;
 523 
 524             actionList.add(new FilePaneAction(ACTION_CANCEL));
 525             actionList.add(new FilePaneAction(ACTION_EDIT_FILE_NAME));
 526             actionList.add(new FilePaneAction(refreshActionLabelText, ACTION_REFRESH));
 527 
 528             action = fileChooserUIAccessor.getApproveSelectionAction();
 529             if (action != null) {
 530                 actionList.add(action);
 531             }
 532             action = fileChooserUIAccessor.getChangeToParentDirectoryAction();
 533             if (action != null) {
 534                 actionList.add(action);
 535             }
 536             action = getNewFolderAction();
 537             if (action != null) {
 538                 actionList.add(action);
 539             }
 540             action = getViewTypeAction(VIEWTYPE_LIST);
 541             if (action != null) {
 542                 actionList.add(action);
 543             }
 544             action = getViewTypeAction(VIEWTYPE_DETAILS);
 545             if (action != null) {
 546                 actionList.add(action);
 547             }
 548             actions = actionList.toArray(new Action[actionList.size()]);
 549         }
 550 
 551         return actions;
 552     }
 553 
 554     protected void createActionMap() {
 555         addActionsToMap(super.getActionMap(), getActions());
 556     }
 557 
 558 
 559     public static void addActionsToMap(ActionMap map, Action[] actions) {
 560         if (map != null && actions != null) {
 561             for (Action a : actions) {
 562                 String cmd = (String)a.getValue(Action.ACTION_COMMAND_KEY);
 563                 if (cmd == null) {
 564                     cmd = (String)a.getValue(Action.NAME);
 565                 }
 566                 map.put(cmd, a);
 567             }
 568         }
 569     }
 570 
 571 
 572     private void updateListRowCount(JList list) {
 573         if (smallIconsView) {
 574             list.setVisibleRowCount(getModel().getSize() / 3);
 575         } else {
 576             list.setVisibleRowCount(-1);
 577         }
 578     }
 579 
 580     public JPanel createList() {
 581         JPanel p = new JPanel(new BorderLayout());
 582         final JFileChooser fileChooser = getFileChooser();
 583 
 584         @SuppressWarnings("serial") // anonymous class
 585         final JList<Object> list = new JList<Object>() {
 586             public int getNextMatch(String prefix, int startIndex, Position.Bias bias) {
 587                 ListModel model = getModel();
 588                 int max = model.getSize();
 589                 if (prefix == null || startIndex < 0 || startIndex >= max) {
 590                     throw new IllegalArgumentException();
 591                 }
 592                 // start search from the next element before/after the selected element
 593                 boolean backwards = (bias == Position.Bias.Backward);
 594                 for (int i = startIndex; backwards ? i >= 0 : i < max; i += (backwards ?  -1 : 1)) {
 595                     String filename = fileChooser.getName((File)model.getElementAt(i));
 596                     if (filename.regionMatches(true, 0, prefix, 0, prefix.length())) {
 597                         return i;
 598                     }
 599                 }
 600                 return -1;
 601             }
 602         };
 603         list.setCellRenderer(new FileRenderer());
 604         list.setLayoutOrientation(JList.VERTICAL_WRAP);
 605 
 606         // 4835633 : tell BasicListUI that this is a file list
 607         list.putClientProperty("List.isFileList", Boolean.TRUE);
 608 
 609         if (listViewWindowsStyle) {
 610             list.addFocusListener(repaintListener);
 611         }
 612 
 613         updateListRowCount(list);
 614 
 615         getModel().addListDataListener(new ListDataListener() {
 616             public void intervalAdded(ListDataEvent e) {
 617                 updateListRowCount(list);
 618             }
 619             public void intervalRemoved(ListDataEvent e) {
 620                 updateListRowCount(list);
 621             }
 622             public void contentsChanged(ListDataEvent e) {
 623                 if (isShowing()) {
 624                     clearSelection();
 625                 }
 626                 updateListRowCount(list);
 627             }
 628         });
 629 
 630         getModel().addPropertyChangeListener(this);
 631 
 632         if (fileChooser.isMultiSelectionEnabled()) {
 633             list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
 634         } else {
 635             list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
 636         }
 637         list.setModel(new SortableListModel());
 638 
 639         list.addListSelectionListener(createListSelectionListener());
 640         list.addMouseListener(getMouseHandler());
 641 
 642         JScrollPane scrollpane = new JScrollPane(list);
 643         if (listViewBackground != null) {
 644             list.setBackground(listViewBackground);
 645         }
 646         if (listViewBorder != null) {
 647             scrollpane.setBorder(listViewBorder);
 648         }
 649 
 650         list.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, filesListAccessibleName);
 651 
 652         p.add(scrollpane, BorderLayout.CENTER);
 653         return p;
 654     }
 655 
 656     /**
 657      * This model allows for sorting JList
 658      */
 659     @SuppressWarnings("serial") // JDK-implementation class
 660     private class SortableListModel extends AbstractListModel<Object>
 661             implements TableModelListener, RowSorterListener {
 662 
 663         public SortableListModel() {
 664             getDetailsTableModel().addTableModelListener(this);
 665             getRowSorter().addRowSorterListener(this);
 666         }
 667 
 668         public int getSize() {
 669             return getModel().getSize();
 670         }
 671 
 672         public Object getElementAt(int index) {
 673             // JList doesn't support RowSorter so far, so we put it into the list model
 674             return getModel().getElementAt(getRowSorter().convertRowIndexToModel(index));
 675         }
 676 
 677         public void tableChanged(TableModelEvent e) {
 678             fireContentsChanged(this, 0, getSize());
 679         }
 680 
 681         public void sorterChanged(RowSorterEvent e) {
 682             fireContentsChanged(this, 0, getSize());
 683         }
 684     }
 685 
 686     private DetailsTableModel getDetailsTableModel() {
 687         if(detailsTableModel == null) {
 688             detailsTableModel = new DetailsTableModel(getFileChooser());
 689         }
 690         return detailsTableModel;
 691     }
 692 
 693     @SuppressWarnings("serial") // JDK-implementation class
 694     class DetailsTableModel extends AbstractTableModel implements ListDataListener {
 695         JFileChooser chooser;
 696         BasicDirectoryModel directoryModel;
 697 
 698         ShellFolderColumnInfo[] columns;
 699         int[] columnMap;
 700 
 701         DetailsTableModel(JFileChooser fc) {
 702             this.chooser = fc;
 703             directoryModel = getModel();
 704             directoryModel.addListDataListener(this);
 705 
 706             updateColumnInfo();
 707         }
 708 
 709         void updateColumnInfo() {
 710             File dir = chooser.getCurrentDirectory();
 711             if (dir != null && usesShellFolder(chooser)) {
 712                 try {
 713                     dir = ShellFolder.getShellFolder(dir);
 714                 } catch (FileNotFoundException e) {
 715                     // Leave dir without changing
 716                 }
 717             }
 718 
 719             ShellFolderColumnInfo[] allColumns = ShellFolder.getFolderColumns(dir);
 720 
 721             ArrayList<ShellFolderColumnInfo> visibleColumns =
 722                     new ArrayList<ShellFolderColumnInfo>();
 723             columnMap = new int[allColumns.length];
 724             for (int i = 0; i < allColumns.length; i++) {
 725                 ShellFolderColumnInfo column = allColumns[i];
 726                 if (column.isVisible()) {
 727                     columnMap[visibleColumns.size()] = i;
 728                     visibleColumns.add(column);
 729                 }
 730             }
 731 
 732             columns = new ShellFolderColumnInfo[visibleColumns.size()];
 733             visibleColumns.toArray(columns);
 734             columnMap = Arrays.copyOf(columnMap, columns.length);
 735 
 736             List<? extends RowSorter.SortKey> sortKeys =
 737                     (rowSorter == null) ? null : rowSorter.getSortKeys();
 738             fireTableStructureChanged();
 739             restoreSortKeys(sortKeys);
 740         }
 741 
 742         private void restoreSortKeys(List<? extends RowSorter.SortKey> sortKeys) {
 743             if (sortKeys != null) {
 744                 // check if preserved sortKeys are valid for this folder
 745                 for (int i = 0; i < sortKeys.size(); i++) {
 746                     RowSorter.SortKey sortKey = sortKeys.get(i);
 747                     if (sortKey.getColumn() >= columns.length) {
 748                         sortKeys = null;
 749                         break;
 750                     }
 751                 }
 752                 if (sortKeys != null) {
 753                     rowSorter.setSortKeys(sortKeys);
 754                 }
 755             }
 756         }
 757 
 758         public int getRowCount() {
 759             return directoryModel.getSize();
 760         }
 761 
 762         public int getColumnCount() {
 763             return columns.length;
 764         }
 765 
 766         public Object getValueAt(int row, int col) {
 767             // Note: It is very important to avoid getting info on drives, as
 768             // this will trigger "No disk in A:" and similar dialogs.
 769             //
 770             // Use (f.exists() && !chooser.getFileSystemView().isFileSystemRoot(f)) to
 771             // determine if it is safe to call methods directly on f.
 772             return getFileColumnValue((File)directoryModel.getElementAt(row), col);
 773         }
 774 
 775         private Object getFileColumnValue(File f, int col) {
 776             return (col == COLUMN_FILENAME)
 777                     ? f // always return the file itself for the 1st column
 778                     : ShellFolder.getFolderColumnValue(f, columnMap[col]);
 779         }
 780 
 781         public void setValueAt(Object value, int row, int col) {
 782             if (col == COLUMN_FILENAME) {
 783                 final JFileChooser chooser = getFileChooser();
 784                 File f = (File)getValueAt(row, col);
 785                 if (f != null) {
 786                     String oldDisplayName = chooser.getName(f);
 787                     String oldFileName = f.getName();
 788                     String newDisplayName = ((String)value).trim();
 789                     String newFileName;
 790 
 791                     if (!newDisplayName.equals(oldDisplayName)) {
 792                         newFileName = newDisplayName;
 793                         //Check if extension is hidden from user
 794                         int i1 = oldFileName.length();
 795                         int i2 = oldDisplayName.length();
 796                         if (i1 > i2 && oldFileName.charAt(i2) == '.') {
 797                             newFileName = newDisplayName + oldFileName.substring(i2);
 798                         }
 799 
 800                         // rename
 801                         FileSystemView fsv = chooser.getFileSystemView();
 802                         final File f2 = fsv.createFileObject(f.getParentFile(), newFileName);
 803                         if (f2.exists()) {
 804                             JOptionPane.showMessageDialog(chooser, MessageFormat.format(renameErrorFileExistsText,
 805                                     oldFileName), renameErrorTitleText, JOptionPane.ERROR_MESSAGE);
 806                         } else {
 807                             if (FilePane.this.getModel().renameFile(f, f2)) {
 808                                 if (fsv.isParent(chooser.getCurrentDirectory(), f2)) {
 809                                     // The setSelectedFile method produces a new setValueAt invocation while the JTable
 810                                     // is editing. Postpone file selection to be sure that edit mode of the JTable
 811                                     // is completed
 812                                     SwingUtilities.invokeLater(new Runnable() {
 813                                         public void run() {
 814                                             if (chooser.isMultiSelectionEnabled()) {
 815                                                 chooser.setSelectedFiles(new File[]{f2});
 816                                             } else {
 817                                                 chooser.setSelectedFile(f2);
 818                                             }
 819                                         }
 820                                     });
 821                                 } else {
 822                                     // Could be because of delay in updating Desktop folder
 823                                     // chooser.setSelectedFile(null);
 824                                 }
 825                             } else {
 826                                 JOptionPane.showMessageDialog(chooser, MessageFormat.format(renameErrorText, oldFileName),
 827                                         renameErrorTitleText, JOptionPane.ERROR_MESSAGE);
 828                             }
 829                         }
 830                     }
 831                 }
 832             }
 833         }
 834 
 835         public boolean isCellEditable(int row, int column) {
 836             File currentDirectory = getFileChooser().getCurrentDirectory();
 837             return (!readOnly && column == COLUMN_FILENAME && canWrite(currentDirectory));
 838         }
 839 
 840         public void contentsChanged(ListDataEvent e) {
 841             // Update the selection after the model has been updated
 842             new DelayedSelectionUpdater();
 843             fireTableDataChanged();
 844         }
 845 
 846         public void intervalAdded(ListDataEvent e) {
 847             int i0 = e.getIndex0();
 848             int i1 = e.getIndex1();
 849             if (i0 == i1) {
 850                 File file = (File)getModel().getElementAt(i0);
 851                 if (file.equals(newFolderFile)) {
 852                     new DelayedSelectionUpdater(file);
 853                     newFolderFile = null;
 854                 }
 855             }
 856 
 857             fireTableRowsInserted(e.getIndex0(), e.getIndex1());
 858         }
 859         public void intervalRemoved(ListDataEvent e) {
 860             fireTableRowsDeleted(e.getIndex0(), e.getIndex1());
 861         }
 862 
 863         public ShellFolderColumnInfo[] getColumns() {
 864             return columns;
 865         }
 866     }
 867 
 868 
 869     private void updateDetailsColumnModel(JTable table) {
 870         if (table != null) {
 871             ShellFolderColumnInfo[] columns = detailsTableModel.getColumns();
 872 
 873             TableColumnModel columnModel = new DefaultTableColumnModel();
 874             for (int i = 0; i < columns.length; i++) {
 875                 ShellFolderColumnInfo dataItem = columns[i];
 876                 TableColumn column = new TableColumn(i);
 877 
 878                 String title = dataItem.getTitle();
 879                 if (title != null && title.startsWith("FileChooser.") && title.endsWith("HeaderText")) {
 880                     // the column must have a string resource that we try to get
 881                     String uiTitle = UIManager.getString(title, table.getLocale());
 882                     if (uiTitle != null) {
 883                         title = uiTitle;
 884                     }
 885                 }
 886                 column.setHeaderValue(title);
 887 
 888                 Integer width = dataItem.getWidth();
 889                 if (width != null) {
 890                     column.setPreferredWidth(width);
 891                     // otherwise we let JTable to decide the actual width
 892                 }
 893 
 894                 columnModel.addColumn(column);
 895             }
 896 
 897             // Install cell editor for editing file name
 898             if (!readOnly && columnModel.getColumnCount() > COLUMN_FILENAME) {
 899                 columnModel.getColumn(COLUMN_FILENAME).
 900                         setCellEditor(getDetailsTableCellEditor());
 901             }
 902 
 903             table.setColumnModel(columnModel);
 904         }
 905     }
 906 
 907     private DetailsTableRowSorter getRowSorter() {
 908         if (rowSorter == null) {
 909             rowSorter = new DetailsTableRowSorter();
 910         }
 911         return rowSorter;
 912     }
 913 
 914     private class DetailsTableRowSorter extends TableRowSorter<TableModel> {
 915         public DetailsTableRowSorter() {
 916             setModelWrapper(new SorterModelWrapper());
 917         }
 918 
 919         public void updateComparators(ShellFolderColumnInfo [] columns) {
 920             for (int i = 0; i < columns.length; i++) {
 921                 Comparator c = columns[i].getComparator();
 922                 if (c != null) {
 923                     c = new DirectoriesFirstComparatorWrapper(i, c);
 924                 }
 925                 setComparator(i, c);
 926             }
 927         }
 928 
 929         @Override
 930         public void sort() {
 931             ShellFolder.invoke(new Callable<Void>() {
 932                 public Void call() {
 933                     DetailsTableRowSorter.super.sort();
 934                     return null;
 935                 }
 936             });
 937         }
 938 
 939         public void modelStructureChanged() {
 940             super.modelStructureChanged();
 941             updateComparators(detailsTableModel.getColumns());
 942         }
 943 
 944         private class SorterModelWrapper extends ModelWrapper<TableModel, Integer> {
 945             public TableModel getModel() {
 946                 return getDetailsTableModel();
 947             }
 948 
 949             public int getColumnCount() {
 950                 return getDetailsTableModel().getColumnCount();
 951             }
 952 
 953             public int getRowCount() {
 954                 return getDetailsTableModel().getRowCount();
 955             }
 956 
 957             public Object getValueAt(int row, int column) {
 958                 return FilePane.this.getModel().getElementAt(row);
 959             }
 960 
 961             public Integer getIdentifier(int row) {
 962                 return row;
 963             }
 964         }
 965     }
 966 
 967     /**
 968      * This class sorts directories before files, comparing directory to
 969      * directory and file to file using the wrapped comparator.
 970      */
 971     private class DirectoriesFirstComparatorWrapper implements Comparator<File> {
 972         private Comparator comparator;
 973         private int column;
 974 
 975         public DirectoriesFirstComparatorWrapper(int column, Comparator comparator) {
 976             this.column = column;
 977             this.comparator = comparator;
 978         }
 979 
 980         public int compare(File f1, File f2) {
 981             if (f1 != null && f2 != null) {
 982                 boolean traversable1 = getFileChooser().isTraversable(f1);
 983                 boolean traversable2 = getFileChooser().isTraversable(f2);
 984                 // directories go first
 985                 if (traversable1 && !traversable2) {
 986                     return -1;
 987                 }
 988                 if (!traversable1 && traversable2) {
 989                     return 1;
 990                 }
 991             }
 992             if (detailsTableModel.getColumns()[column].isCompareByColumn()) {
 993                 return comparator.compare(
 994                         getDetailsTableModel().getFileColumnValue(f1, column),
 995                         getDetailsTableModel().getFileColumnValue(f2, column)
 996                 );
 997             }
 998             // For this column we need to pass the file itself (not a
 999             // column value) to the comparator
1000             return comparator.compare(f1, f2);
1001         }
1002     }
1003 
1004     private DetailsTableCellEditor tableCellEditor;
1005 
1006     private DetailsTableCellEditor getDetailsTableCellEditor() {
1007         if (tableCellEditor == null) {
1008             tableCellEditor = new DetailsTableCellEditor(new JTextField());
1009         }
1010         return tableCellEditor;
1011     }
1012 
1013     @SuppressWarnings("serial") // JDK-implementation class
1014     private class DetailsTableCellEditor extends DefaultCellEditor {
1015         private final JTextField tf;
1016 
1017         public DetailsTableCellEditor(JTextField tf) {
1018             super(tf);
1019             this.tf = tf;
1020             tf.setName("Table.editor");
1021             tf.addFocusListener(editorFocusListener);
1022         }
1023 
1024         public Component getTableCellEditorComponent(JTable table, Object value,
1025                                                      boolean isSelected, int row, int column) {
1026             Component comp = super.getTableCellEditorComponent(table, value,
1027                     isSelected, row, column);
1028             if (value instanceof File) {
1029                 tf.setText(getFileChooser().getName((File) value));
1030                 tf.selectAll();
1031             }
1032             return comp;
1033         }
1034     }
1035 
1036     @SuppressWarnings("serial") // JDK-implementation class
1037     class DetailsTableCellRenderer extends DefaultTableCellRenderer {
1038         JFileChooser chooser;
1039         DateFormat df;
1040 
1041         DetailsTableCellRenderer(JFileChooser chooser) {
1042             this.chooser = chooser;
1043             df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
1044                                                 chooser.getLocale());
1045         }
1046 
1047         public void setBounds(int x, int y, int width, int height) {
1048         if (getHorizontalAlignment() == SwingConstants.LEADING &&
1049                     !fullRowSelection) {
1050                 // Restrict width to actual text
1051                 width = Math.min(width, this.getPreferredSize().width+4);
1052             } else {
1053                 x -= 4;
1054             }
1055             super.setBounds(x, y, width, height);
1056         }
1057 
1058 
1059         public Insets getInsets(Insets i) {
1060             // Provide some space between columns
1061             i = super.getInsets(i);
1062             i.left  += 4;
1063             i.right += 4;
1064             return i;
1065         }
1066 
1067         public Component getTableCellRendererComponent(JTable table, Object value,
1068                               boolean isSelected, boolean hasFocus, int row, int column) {
1069 
1070             if ((table.convertColumnIndexToModel(column) != COLUMN_FILENAME ||
1071                     (listViewWindowsStyle && !table.isFocusOwner())) &&
1072                     !fullRowSelection) {
1073                 isSelected = false;
1074             }
1075 
1076             super.getTableCellRendererComponent(table, value, isSelected,
1077                                                        hasFocus, row, column);
1078 
1079             setIcon(null);
1080 
1081             int modelColumn = table.convertColumnIndexToModel(column);
1082             ShellFolderColumnInfo columnInfo = detailsTableModel.getColumns()[modelColumn];
1083 
1084             Integer alignment = columnInfo.getAlignment();
1085             if (alignment == null) {
1086                 alignment = (value instanceof Number)
1087                         ? SwingConstants.RIGHT
1088                         : SwingConstants.LEADING;
1089             }
1090 
1091             setHorizontalAlignment(alignment);
1092 
1093             // formatting cell text
1094             // TODO: it's rather a temporary trick, to be revised
1095             String text;
1096 
1097             if (value == null) {
1098                 text = "";
1099 
1100             } else if (value instanceof File) {
1101                 File file = (File)value;
1102                 text = chooser.getName(file);
1103                 Icon icon = chooser.getIcon(file);
1104                 setIcon(icon);
1105 
1106             } else if (value instanceof Long) {
1107                 long len = ((Long) value) / 1024L;
1108                 if (listViewWindowsStyle) {
1109                     text = MessageFormat.format(kiloByteString, len + 1);
1110                 } else if (len < 1024L) {
1111                     text = MessageFormat.format(kiloByteString, (len == 0L) ? 1L : len);
1112                 } else {
1113                     len /= 1024L;
1114                     if (len < 1024L) {
1115                         text = MessageFormat.format(megaByteString, len);
1116                     } else {
1117                         len /= 1024L;
1118                         text = MessageFormat.format(gigaByteString, len);
1119                     }
1120                 }
1121 
1122             } else if (value instanceof Date) {
1123                 text = df.format((Date)value);
1124 
1125             } else {
1126                 text = value.toString();
1127             }
1128 
1129             setText(text);
1130 
1131             return this;
1132         }
1133     }
1134 
1135     public JPanel createDetailsView() {
1136         final JFileChooser chooser = getFileChooser();
1137 
1138         JPanel p = new JPanel(new BorderLayout());
1139 
1140         @SuppressWarnings("serial") // anonymous class
1141         final JTable detailsTable = new JTable(getDetailsTableModel()) {
1142             // Handle Escape key events here
1143             protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
1144                 if (e.getKeyCode() == KeyEvent.VK_ESCAPE && getCellEditor() == null) {
1145                     // We are not editing, forward to filechooser.
1146                     chooser.dispatchEvent(e);
1147                     return true;
1148                 }
1149                 return super.processKeyBinding(ks, e, condition, pressed);
1150             }
1151 
1152             public void tableChanged(TableModelEvent e) {
1153                 super.tableChanged(e);
1154 
1155                 if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
1156                     // update header with possibly changed column set
1157                     updateDetailsColumnModel(this);
1158                 }
1159             }
1160         };
1161 
1162         detailsTable.setRowSorter(getRowSorter());
1163         detailsTable.setAutoCreateColumnsFromModel(false);
1164         detailsTable.setComponentOrientation(chooser.getComponentOrientation());
1165         detailsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
1166         detailsTable.setShowGrid(false);
1167         detailsTable.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);
1168         detailsTable.addKeyListener(detailsKeyListener);
1169 
1170         Font font = list.getFont();
1171         detailsTable.setFont(font);
1172         detailsTable.setIntercellSpacing(new Dimension(0, 0));
1173 
1174         TableCellRenderer headerRenderer =
1175                 new AlignableTableHeaderRenderer(detailsTable.getTableHeader().getDefaultRenderer());
1176         detailsTable.getTableHeader().setDefaultRenderer(headerRenderer);
1177         TableCellRenderer cellRenderer = new DetailsTableCellRenderer(chooser);
1178         detailsTable.setDefaultRenderer(Object.class, cellRenderer);
1179 
1180         // So that drag can be started on a mouse press
1181         detailsTable.getColumnModel().getSelectionModel().
1182             setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1183 
1184         detailsTable.addMouseListener(getMouseHandler());
1185         // No need to addListSelectionListener because selections are forwarded
1186         // to our JList.
1187 
1188         // 4835633 : tell BasicTableUI that this is a file list
1189         detailsTable.putClientProperty("Table.isFileList", Boolean.TRUE);
1190 
1191         if (listViewWindowsStyle) {
1192             detailsTable.addFocusListener(repaintListener);
1193         }
1194 
1195         // TAB/SHIFT-TAB should transfer focus and ENTER should select an item.
1196         // We don't want them to navigate within the table
1197         ActionMap am = SwingUtilities.getUIActionMap(detailsTable);
1198         am.remove("selectNextRowCell");
1199         am.remove("selectPreviousRowCell");
1200         am.remove("selectNextColumnCell");
1201         am.remove("selectPreviousColumnCell");
1202         detailsTable.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
1203                      null);
1204         detailsTable.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
1205                      null);
1206 
1207         JScrollPane scrollpane = new JScrollPane(detailsTable);
1208         scrollpane.setComponentOrientation(chooser.getComponentOrientation());
1209         LookAndFeel.installColors(scrollpane.getViewport(), "Table.background", "Table.foreground");
1210 
1211         // Adjust width of first column so the table fills the viewport when
1212         // first displayed (temporary listener).
1213         scrollpane.addComponentListener(new ComponentAdapter() {
1214             public void componentResized(ComponentEvent e) {
1215                 JScrollPane sp = (JScrollPane)e.getComponent();
1216                 fixNameColumnWidth(sp.getViewport().getSize().width);
1217                 sp.removeComponentListener(this);
1218             }
1219         });
1220 
1221         // 4835633.
1222         // If the mouse is pressed in the area below the Details view table, the
1223         // event is not dispatched to the Table MouseListener but to the
1224         // scrollpane.  Listen for that here so we can clear the selection.
1225         scrollpane.addMouseListener(new MouseAdapter() {
1226             public void mousePressed(MouseEvent e) {
1227                 JScrollPane jsp = ((JScrollPane)e.getComponent());
1228                 JTable table = (JTable)jsp.getViewport().getView();
1229 
1230                 if (!e.isShiftDown() || table.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) {
1231                     clearSelection();
1232                     TableCellEditor tce = table.getCellEditor();
1233                     if (tce != null) {
1234                         tce.stopCellEditing();
1235                     }
1236                 }
1237             }
1238         });
1239 
1240         detailsTable.setForeground(list.getForeground());
1241         detailsTable.setBackground(list.getBackground());
1242 
1243         if (listViewBorder != null) {
1244             scrollpane.setBorder(listViewBorder);
1245         }
1246         p.add(scrollpane, BorderLayout.CENTER);
1247 
1248         detailsTableModel.fireTableStructureChanged();
1249 
1250         detailsTable.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, filesDetailsAccessibleName);
1251 
1252         return p;
1253     } // createDetailsView
1254 
1255     private class AlignableTableHeaderRenderer implements TableCellRenderer {
1256         TableCellRenderer wrappedRenderer;
1257 
1258         public AlignableTableHeaderRenderer(TableCellRenderer wrappedRenderer) {
1259             this.wrappedRenderer = wrappedRenderer;
1260         }
1261 
1262         public Component getTableCellRendererComponent(
1263                                 JTable table, Object value, boolean isSelected,
1264                                 boolean hasFocus, int row, int column) {
1265 
1266             Component c = wrappedRenderer.getTableCellRendererComponent(
1267                                 table, value, isSelected, hasFocus, row, column);
1268 
1269             int modelColumn = table.convertColumnIndexToModel(column);
1270             ShellFolderColumnInfo columnInfo = detailsTableModel.getColumns()[modelColumn];
1271 
1272             Integer alignment = columnInfo.getAlignment();
1273             if (alignment == null) {
1274                 alignment = SwingConstants.CENTER;
1275             }
1276             if (c instanceof JLabel) {
1277                 ((JLabel) c).setHorizontalAlignment(alignment);
1278             }
1279 
1280             return c;
1281         }
1282     }
1283 
1284     private void fixNameColumnWidth(int viewWidth) {
1285         TableColumn nameCol = detailsTable.getColumnModel().getColumn(COLUMN_FILENAME);
1286         int tableWidth = detailsTable.getPreferredSize().width;
1287 
1288         if (tableWidth < viewWidth) {
1289             nameCol.setPreferredWidth(nameCol.getPreferredWidth() + viewWidth - tableWidth);
1290         }
1291     }
1292 
1293     private class DelayedSelectionUpdater implements Runnable {
1294         File editFile;
1295 
1296         DelayedSelectionUpdater() {
1297             this(null);
1298         }
1299 
1300         DelayedSelectionUpdater(File editFile) {
1301             this.editFile = editFile;
1302             if (isShowing()) {
1303                 SwingUtilities.invokeLater(this);
1304             }
1305         }
1306 
1307         public void run() {
1308             setFileSelected();
1309             if (editFile != null) {
1310                 editFileName(getRowSorter().convertRowIndexToView(
1311                         getModel().indexOf(editFile)));
1312                 editFile = null;
1313             }
1314         }
1315     }
1316 
1317 
1318     /**
1319      * Creates a selection listener for the list of files and directories.
1320      *
1321      * @return a <code>ListSelectionListener</code>
1322      */
1323     public ListSelectionListener createListSelectionListener() {
1324         return fileChooserUIAccessor.createListSelectionListener();
1325     }
1326 
1327     int lastIndex = -1;
1328     File editFile = null;
1329 
1330     private int getEditIndex() {
1331         return lastIndex;
1332     }
1333 
1334     private void setEditIndex(int i) {
1335         lastIndex = i;
1336     }
1337 
1338     private void resetEditIndex() {
1339         lastIndex = -1;
1340     }
1341 
1342     private void cancelEdit() {
1343         if (editFile != null) {
1344             editFile = null;
1345             list.remove(editCell);
1346             repaint();
1347         } else if (detailsTable != null && detailsTable.isEditing()) {
1348             detailsTable.getCellEditor().cancelCellEditing();
1349         }
1350     }
1351 
1352     JTextField editCell = null;
1353 
1354     /**
1355      * @param index visual index of the file to be edited
1356      */
1357     private void editFileName(int index) {
1358         JFileChooser chooser = getFileChooser();
1359         File currentDirectory = chooser.getCurrentDirectory();
1360 
1361         if (readOnly || !canWrite(currentDirectory)) {
1362             return;
1363         }
1364 
1365         ensureIndexIsVisible(index);
1366         switch (viewType) {
1367           case VIEWTYPE_LIST:
1368             editFile = (File)getModel().getElementAt(getRowSorter().convertRowIndexToModel(index));
1369             Rectangle r = list.getCellBounds(index, index);
1370             if (editCell == null) {
1371                 editCell = new JTextField();
1372                 editCell.setName("Tree.cellEditor");
1373                 editCell.addActionListener(new EditActionListener());
1374                 editCell.addFocusListener(editorFocusListener);
1375                 editCell.setNextFocusableComponent(list);
1376             }
1377             list.add(editCell);
1378             editCell.setText(chooser.getName(editFile));
1379             ComponentOrientation orientation = list.getComponentOrientation();
1380             editCell.setComponentOrientation(orientation);
1381 
1382             Icon icon = chooser.getIcon(editFile);
1383 
1384             // PENDING - grab padding (4) below from defaults table.
1385             int editX = icon == null ? 20 : icon.getIconWidth() + 4;
1386 
1387             if (orientation.isLeftToRight()) {
1388                 editCell.setBounds(editX + r.x, r.y, r.width - editX, r.height);
1389             } else {
1390                 editCell.setBounds(r.x, r.y, r.width - editX, r.height);
1391             }
1392             editCell.requestFocus();
1393             editCell.selectAll();
1394             break;
1395 
1396           case VIEWTYPE_DETAILS:
1397             detailsTable.editCellAt(index, COLUMN_FILENAME);
1398             break;
1399         }
1400     }
1401 
1402 
1403     class EditActionListener implements ActionListener {
1404         public void actionPerformed(ActionEvent e) {
1405             applyEdit();
1406         }
1407     }
1408 
1409     private void applyEdit() {
1410         if (editFile != null && editFile.exists()) {
1411             JFileChooser chooser = getFileChooser();
1412             String oldDisplayName = chooser.getName(editFile);
1413             String oldFileName = editFile.getName();
1414             String newDisplayName = editCell.getText().trim();
1415             String newFileName;
1416 
1417             if (!newDisplayName.equals(oldDisplayName)) {
1418                 newFileName = newDisplayName;
1419                 //Check if extension is hidden from user
1420                 int i1 = oldFileName.length();
1421                 int i2 = oldDisplayName.length();
1422                 if (i1 > i2 && oldFileName.charAt(i2) == '.') {
1423                     newFileName = newDisplayName + oldFileName.substring(i2);
1424                 }
1425 
1426                 // rename
1427                 FileSystemView fsv = chooser.getFileSystemView();
1428                 File f2 = fsv.createFileObject(editFile.getParentFile(), newFileName);
1429                 if (f2.exists()) {
1430                     JOptionPane.showMessageDialog(chooser, MessageFormat.format(renameErrorFileExistsText, oldFileName),
1431                             renameErrorTitleText, JOptionPane.ERROR_MESSAGE);
1432                 } else {
1433                     if (getModel().renameFile(editFile, f2)) {
1434                         if (fsv.isParent(chooser.getCurrentDirectory(), f2)) {
1435                             if (chooser.isMultiSelectionEnabled()) {
1436                                 chooser.setSelectedFiles(new File[]{f2});
1437                             } else {
1438                                 chooser.setSelectedFile(f2);
1439                             }
1440                         } else {
1441                             //Could be because of delay in updating Desktop folder
1442                             //chooser.setSelectedFile(null);
1443                         }
1444                     } else {
1445                         JOptionPane.showMessageDialog(chooser, MessageFormat.format(renameErrorText, oldFileName),
1446                                 renameErrorTitleText, JOptionPane.ERROR_MESSAGE);
1447                     }
1448                 }
1449             }
1450         }
1451         if (detailsTable != null && detailsTable.isEditing()) {
1452             detailsTable.getCellEditor().stopCellEditing();
1453         }
1454         cancelEdit();
1455     }
1456 
1457     protected Action newFolderAction;
1458 
1459     @SuppressWarnings("serial") // anonymous class inside
1460     public Action getNewFolderAction() {
1461         if (!readOnly && newFolderAction == null) {
1462             newFolderAction = new AbstractAction(newFolderActionLabelText) {
1463                 private Action basicNewFolderAction;
1464 
1465                 // Initializer
1466                 {
1467                     putValue(Action.ACTION_COMMAND_KEY, FilePane.ACTION_NEW_FOLDER);
1468 
1469                     File currentDirectory = getFileChooser().getCurrentDirectory();
1470                     if (currentDirectory != null) {
1471                         setEnabled(canWrite(currentDirectory));
1472                     }
1473                 }
1474 
1475                 public void actionPerformed(ActionEvent ev) {
1476                     if (basicNewFolderAction == null) {
1477                         basicNewFolderAction = fileChooserUIAccessor.getNewFolderAction();
1478                     }
1479                     JFileChooser fc = getFileChooser();
1480                     File oldFile = fc.getSelectedFile();
1481                     basicNewFolderAction.actionPerformed(ev);
1482                     File newFile = fc.getSelectedFile();
1483                     if (newFile != null && !newFile.equals(oldFile) && newFile.isDirectory()) {
1484                         newFolderFile = newFile;
1485                     }
1486                 }
1487             };
1488         }
1489         return newFolderAction;
1490     }
1491 
1492     @SuppressWarnings("serial") // JDK-implementation class
1493     protected class FileRenderer extends DefaultListCellRenderer  {
1494 
1495         public Component getListCellRendererComponent(JList list, Object value,
1496                                                       int index, boolean isSelected,
1497                                                       boolean cellHasFocus) {
1498 
1499             if (listViewWindowsStyle && !list.isFocusOwner()) {
1500                 isSelected = false;
1501             }
1502 
1503             super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
1504             File file = (File) value;
1505             String fileName = getFileChooser().getName(file);
1506             setText(fileName);
1507             setFont(list.getFont());
1508 
1509             Icon icon = getFileChooser().getIcon(file);
1510             if (icon != null) {
1511                 setIcon(icon);
1512             } else {
1513                 if (getFileChooser().getFileSystemView().isTraversable(file)) {
1514                     setText(fileName+File.separator);
1515                 }
1516             }
1517 
1518             return this;
1519         }
1520     }
1521 
1522 
1523     void setFileSelected() {
1524         if (getFileChooser().isMultiSelectionEnabled() && !isDirectorySelected()) {
1525             File[] files = getFileChooser().getSelectedFiles(); // Should be selected
1526             Object[] selectedObjects = list.getSelectedValues(); // Are actually selected
1527 
1528             listSelectionModel.setValueIsAdjusting(true);
1529             try {
1530                 int lead = listSelectionModel.getLeadSelectionIndex();
1531                 int anchor = listSelectionModel.getAnchorSelectionIndex();
1532 
1533                 Arrays.sort(files);
1534                 Arrays.sort(selectedObjects);
1535 
1536                 int shouldIndex = 0;
1537                 int actuallyIndex = 0;
1538 
1539                 // Remove files that shouldn't be selected and add files which should be selected
1540                 // Note: Assume files are already sorted in compareTo order.
1541                 while (shouldIndex < files.length &&
1542                        actuallyIndex < selectedObjects.length) {
1543                     int comparison = files[shouldIndex].compareTo((File)selectedObjects[actuallyIndex]);
1544                     if (comparison < 0) {
1545                         doSelectFile(files[shouldIndex++]);
1546                     } else if (comparison > 0) {
1547                         doDeselectFile(selectedObjects[actuallyIndex++]);
1548                     } else {
1549                         // Do nothing
1550                         shouldIndex++;
1551                         actuallyIndex++;
1552                     }
1553 
1554                 }
1555 
1556                 while (shouldIndex < files.length) {
1557                     doSelectFile(files[shouldIndex++]);
1558                 }
1559 
1560                 while (actuallyIndex < selectedObjects.length) {
1561                     doDeselectFile(selectedObjects[actuallyIndex++]);
1562                 }
1563 
1564                 // restore the anchor and lead
1565                 if (listSelectionModel instanceof DefaultListSelectionModel) {
1566                     ((DefaultListSelectionModel)listSelectionModel).
1567                         moveLeadSelectionIndex(lead);
1568                     listSelectionModel.setAnchorSelectionIndex(anchor);
1569                 }
1570             } finally {
1571                 listSelectionModel.setValueIsAdjusting(false);
1572             }
1573         } else {
1574             JFileChooser chooser = getFileChooser();
1575             File f;
1576             if (isDirectorySelected()) {
1577                 f = getDirectory();
1578             } else {
1579                 f = chooser.getSelectedFile();
1580             }
1581             int i;
1582             if (f != null && (i = getModel().indexOf(f)) >= 0) {
1583                 int viewIndex = getRowSorter().convertRowIndexToView(i);
1584                 listSelectionModel.setSelectionInterval(viewIndex, viewIndex);
1585                 ensureIndexIsVisible(viewIndex);
1586             } else {
1587                 clearSelection();
1588             }
1589         }
1590     }
1591 
1592     private void doSelectFile(File fileToSelect) {
1593         int index = getModel().indexOf(fileToSelect);
1594         // could be missed in the current directory if it changed
1595         if (index >= 0) {
1596             index = getRowSorter().convertRowIndexToView(index);
1597             listSelectionModel.addSelectionInterval(index, index);
1598         }
1599     }
1600 
1601     private void doDeselectFile(Object fileToDeselect) {
1602         int index = getRowSorter().convertRowIndexToView(
1603                                 getModel().indexOf(fileToDeselect));
1604         listSelectionModel.removeSelectionInterval(index, index);
1605     }
1606 
1607     /* The following methods are used by the PropertyChange Listener */
1608 
1609     private void doSelectedFileChanged(PropertyChangeEvent e) {
1610         applyEdit();
1611         File f = (File) e.getNewValue();
1612         JFileChooser fc = getFileChooser();
1613         if (f != null
1614             && ((fc.isFileSelectionEnabled() && !f.isDirectory())
1615                 || (f.isDirectory() && fc.isDirectorySelectionEnabled()))) {
1616 
1617             setFileSelected();
1618         }
1619     }
1620 
1621     private void doSelectedFilesChanged(PropertyChangeEvent e) {
1622         applyEdit();
1623         File[] files = (File[]) e.getNewValue();
1624         JFileChooser fc = getFileChooser();
1625         if (files != null
1626             && files.length > 0
1627             && (files.length > 1 || fc.isDirectorySelectionEnabled() || !files[0].isDirectory())) {
1628             setFileSelected();
1629         }
1630     }
1631 
1632     private void doDirectoryChanged(PropertyChangeEvent e) {
1633         getDetailsTableModel().updateColumnInfo();
1634 
1635         JFileChooser fc = getFileChooser();
1636         FileSystemView fsv = fc.getFileSystemView();
1637 
1638         applyEdit();
1639         resetEditIndex();
1640         ensureIndexIsVisible(0);
1641         File currentDirectory = fc.getCurrentDirectory();
1642         if (currentDirectory != null) {
1643             if (!readOnly) {
1644                 getNewFolderAction().setEnabled(canWrite(currentDirectory));
1645             }
1646             fileChooserUIAccessor.getChangeToParentDirectoryAction().setEnabled(!fsv.isRoot(currentDirectory));
1647         }
1648         if (list != null) {
1649             list.clearSelection();
1650         }
1651     }
1652 
1653     private void doFilterChanged(PropertyChangeEvent e) {
1654         applyEdit();
1655         resetEditIndex();
1656         clearSelection();
1657     }
1658 
1659     private void doFileSelectionModeChanged(PropertyChangeEvent e) {
1660         applyEdit();
1661         resetEditIndex();
1662         clearSelection();
1663     }
1664 
1665     private void doMultiSelectionChanged(PropertyChangeEvent e) {
1666         if (getFileChooser().isMultiSelectionEnabled()) {
1667             listSelectionModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
1668         } else {
1669             listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1670             clearSelection();
1671             getFileChooser().setSelectedFiles(null);
1672         }
1673     }
1674 
1675     /*
1676      * Listen for filechooser property changes, such as
1677      * the selected file changing, or the type of the dialog changing.
1678      */
1679     public void propertyChange(PropertyChangeEvent e) {
1680             if (viewType == -1) {
1681                 setViewType(VIEWTYPE_LIST);
1682             }
1683 
1684         String s = e.getPropertyName();
1685         if (s.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
1686             doSelectedFileChanged(e);
1687         } else if (s.equals(JFileChooser.SELECTED_FILES_CHANGED_PROPERTY)) {
1688             doSelectedFilesChanged(e);
1689         } else if (s.equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
1690             doDirectoryChanged(e);
1691         } else if (s.equals(JFileChooser.FILE_FILTER_CHANGED_PROPERTY)) {
1692             doFilterChanged(e);
1693         } else if (s.equals(JFileChooser.FILE_SELECTION_MODE_CHANGED_PROPERTY)) {
1694             doFileSelectionModeChanged(e);
1695         } else if (s.equals(JFileChooser.MULTI_SELECTION_ENABLED_CHANGED_PROPERTY)) {
1696             doMultiSelectionChanged(e);
1697         } else if (s.equals(JFileChooser.CANCEL_SELECTION)) {
1698             applyEdit();
1699         } else if (s.equals("busy")) {
1700             setCursor((Boolean)e.getNewValue() ? waitCursor : null);
1701         } else if (s.equals("componentOrientation")) {
1702             ComponentOrientation o = (ComponentOrientation)e.getNewValue();
1703             JFileChooser cc = (JFileChooser)e.getSource();
1704             if (o != e.getOldValue()) {
1705                 cc.applyComponentOrientation(o);
1706             }
1707             if (detailsTable != null) {
1708                 detailsTable.setComponentOrientation(o);
1709                 detailsTable.getParent().getParent().setComponentOrientation(o);
1710             }
1711         }
1712     }
1713 
1714     private void ensureIndexIsVisible(int i) {
1715         if (i >= 0) {
1716             if (list != null) {
1717                 list.ensureIndexIsVisible(i);
1718             }
1719             if (detailsTable != null) {
1720                 detailsTable.scrollRectToVisible(detailsTable.getCellRect(i, COLUMN_FILENAME, true));
1721             }
1722         }
1723     }
1724 
1725     public void ensureFileIsVisible(JFileChooser fc, File f) {
1726         int modelIndex = getModel().indexOf(f);
1727         if (modelIndex >= 0) {
1728             ensureIndexIsVisible(getRowSorter().convertRowIndexToView(modelIndex));
1729         }
1730     }
1731 
1732     public void rescanCurrentDirectory() {
1733         getModel().validateFileCache();
1734     }
1735 
1736     public void clearSelection() {
1737         if (listSelectionModel != null) {
1738             listSelectionModel.clearSelection();
1739             if (listSelectionModel instanceof DefaultListSelectionModel) {
1740                 ((DefaultListSelectionModel)listSelectionModel).moveLeadSelectionIndex(0);
1741                 listSelectionModel.setAnchorSelectionIndex(0);
1742             }
1743         }
1744     }
1745 
1746     public JMenu getViewMenu() {
1747         if (viewMenu == null) {
1748             viewMenu = new JMenu(viewMenuLabelText);
1749             ButtonGroup viewButtonGroup = new ButtonGroup();
1750 
1751             for (int i = 0; i < VIEWTYPE_COUNT; i++) {
1752                 JRadioButtonMenuItem mi =
1753                     new JRadioButtonMenuItem(new ViewTypeAction(i));
1754                 viewButtonGroup.add(mi);
1755                 viewMenu.add(mi);
1756             }
1757             updateViewMenu();
1758         }
1759         return viewMenu;
1760     }
1761 
1762     private void updateViewMenu() {
1763         if (viewMenu != null) {
1764             Component[] comps = viewMenu.getMenuComponents();
1765             for (Component comp : comps) {
1766                 if (comp instanceof JRadioButtonMenuItem) {
1767                     JRadioButtonMenuItem mi = (JRadioButtonMenuItem) comp;
1768                     if (((ViewTypeAction)mi.getAction()).viewType == viewType) {
1769                         mi.setSelected(true);
1770                     }
1771                 }
1772             }
1773         }
1774     }
1775 
1776     public JPopupMenu getComponentPopupMenu() {
1777         JPopupMenu popupMenu = getFileChooser().getComponentPopupMenu();
1778         if (popupMenu != null) {
1779             return popupMenu;
1780         }
1781 
1782         JMenu viewMenu = getViewMenu();
1783         if (contextMenu == null) {
1784             contextMenu = new JPopupMenu();
1785             if (viewMenu != null) {
1786                 contextMenu.add(viewMenu);
1787                 if (listViewWindowsStyle) {
1788                     contextMenu.addSeparator();
1789                 }
1790             }
1791             ActionMap actionMap = getActionMap();
1792             Action refreshAction   = actionMap.get(ACTION_REFRESH);
1793             Action newFolderAction = actionMap.get(ACTION_NEW_FOLDER);
1794             if (refreshAction != null) {
1795                 contextMenu.add(refreshAction);
1796                 if (listViewWindowsStyle && newFolderAction != null) {
1797                     contextMenu.addSeparator();
1798                 }
1799             }
1800             if (newFolderAction != null) {
1801                 contextMenu.add(newFolderAction);
1802             }
1803         }
1804         if (viewMenu != null) {
1805             viewMenu.getPopupMenu().setInvoker(viewMenu);
1806         }
1807         return contextMenu;
1808     }
1809 
1810 
1811     private Handler handler;
1812 
1813     protected Handler getMouseHandler() {
1814         if (handler == null) {
1815             handler = new Handler();
1816         }
1817         return handler;
1818     }
1819 
1820     private class Handler implements MouseListener {
1821         private MouseListener doubleClickListener;
1822 
1823         public void mouseClicked(MouseEvent evt) {
1824             JComponent source = (JComponent)evt.getSource();
1825 
1826             int index;
1827             if (source instanceof JList) {
1828                 index = SwingUtilities2.loc2IndexFileList(list, evt.getPoint());
1829             } else if (source instanceof JTable) {
1830                 JTable table = (JTable)source;
1831                 Point p = evt.getPoint();
1832                 index = table.rowAtPoint(p);
1833 
1834                 boolean pointOutsidePrefSize =
1835                         SwingUtilities2.pointOutsidePrefSize(
1836                             table, index, table.columnAtPoint(p), p);
1837 
1838                 if (pointOutsidePrefSize && !fullRowSelection) {
1839                     return;
1840                 }
1841 
1842                 // Translate point from table to list
1843                 if (index >= 0 && list != null &&
1844                     listSelectionModel.isSelectedIndex(index)) {
1845 
1846                     // Make a new event with the list as source, placing the
1847                     // click in the corresponding list cell.
1848                     Rectangle r = list.getCellBounds(index, index);
1849                     evt = new MouseEvent(list, evt.getID(),
1850                                          evt.getWhen(), evt.getModifiers(),
1851                                          r.x + 1, r.y + r.height/2,
1852                                          evt.getXOnScreen(),
1853                                          evt.getYOnScreen(),
1854                                          evt.getClickCount(), evt.isPopupTrigger(),
1855                                          evt.getButton());
1856                 }
1857             } else {
1858                 return;
1859             }
1860 
1861             if (index >= 0 && SwingUtilities.isLeftMouseButton(evt)) {
1862                 JFileChooser fc = getFileChooser();
1863 
1864                 // For single click, we handle editing file name
1865                 if (evt.getClickCount() == 1 && source instanceof JList) {
1866                     if ((!fc.isMultiSelectionEnabled() || fc.getSelectedFiles().length <= 1)
1867                         && index >= 0 && listSelectionModel.isSelectedIndex(index)
1868                         && getEditIndex() == index && editFile == null) {
1869 
1870                         editFileName(index);
1871                     } else {
1872                         if (index >= 0) {
1873                             setEditIndex(index);
1874                         } else {
1875                             resetEditIndex();
1876                         }
1877                     }
1878                 } else if (evt.getClickCount() == 2) {
1879                     // on double click (open or drill down one directory) be
1880                     // sure to clear the edit index
1881                     resetEditIndex();
1882                 }
1883             }
1884 
1885             // Forward event to Basic
1886             if (getDoubleClickListener() != null) {
1887                 getDoubleClickListener().mouseClicked(evt);
1888             }
1889         }
1890 
1891         public void mouseEntered(MouseEvent evt) {
1892             JComponent source = (JComponent)evt.getSource();
1893             if (source instanceof JTable) {
1894                 JTable table = (JTable)evt.getSource();
1895 
1896                 TransferHandler th1 = getFileChooser().getTransferHandler();
1897                 TransferHandler th2 = table.getTransferHandler();
1898                 if (th1 != th2) {
1899                     table.setTransferHandler(th1);
1900                 }
1901 
1902                 boolean dragEnabled = getFileChooser().getDragEnabled();
1903                 if (dragEnabled != table.getDragEnabled()) {
1904                     table.setDragEnabled(dragEnabled);
1905                 }
1906             } else if (source instanceof JList) {
1907                 // Forward event to Basic
1908                 if (getDoubleClickListener() != null) {
1909                     getDoubleClickListener().mouseEntered(evt);
1910                 }
1911             }
1912         }
1913 
1914         public void mouseExited(MouseEvent evt) {
1915             if (evt.getSource() instanceof JList) {
1916                 // Forward event to Basic
1917                 if (getDoubleClickListener() != null) {
1918                     getDoubleClickListener().mouseExited(evt);
1919                 }
1920             }
1921         }
1922 
1923         public void mousePressed(MouseEvent evt) {
1924             if (evt.getSource() instanceof JList) {
1925                 // Forward event to Basic
1926                 if (getDoubleClickListener() != null) {
1927                     getDoubleClickListener().mousePressed(evt);
1928                 }
1929             }
1930         }
1931 
1932         public void mouseReleased(MouseEvent evt) {
1933             if (evt.getSource() instanceof JList) {
1934                 // Forward event to Basic
1935                 if (getDoubleClickListener() != null) {
1936                     getDoubleClickListener().mouseReleased(evt);
1937                 }
1938             }
1939         }
1940 
1941         private MouseListener getDoubleClickListener() {
1942             // Lazy creation of Basic's listener
1943             if (doubleClickListener == null && list != null) {
1944                 doubleClickListener =
1945                     fileChooserUIAccessor.createDoubleClickListener(list);
1946             }
1947             return doubleClickListener;
1948         }
1949     }
1950 
1951     /**
1952      * Property to remember whether a directory is currently selected in the UI.
1953      *
1954      * @return <code>true</code> iff a directory is currently selected.
1955      */
1956     protected boolean isDirectorySelected() {
1957         return fileChooserUIAccessor.isDirectorySelected();
1958     }
1959 
1960 
1961     /**
1962      * Property to remember the directory that is currently selected in the UI.
1963      *
1964      * @return the value of the <code>directory</code> property
1965      * @see javax.swing.plaf.basic.BasicFileChooserUI#setDirectory
1966      */
1967     protected File getDirectory() {
1968         return fileChooserUIAccessor.getDirectory();
1969     }
1970 
1971     private Component findChildComponent(Container container, Class cls) {
1972         int n = container.getComponentCount();
1973         for (int i = 0; i < n; i++) {
1974             Component comp = container.getComponent(i);
1975             if (cls.isInstance(comp)) {
1976                 return comp;
1977             } else if (comp instanceof Container) {
1978                 Component c = findChildComponent((Container)comp, cls);
1979                 if (c != null) {
1980                     return c;
1981                 }
1982             }
1983         }
1984         return null;
1985     }
1986 
1987     public boolean canWrite(File f) {
1988         // Return false for non FileSystem files or if file doesn't exist.
1989         if (!f.exists()) {
1990             return false;
1991         }
1992 
1993         if (f instanceof ShellFolder) {
1994             return f.canWrite();
1995         } else {
1996             if (usesShellFolder(getFileChooser())) {
1997                 try {
1998                     return ShellFolder.getShellFolder(f).canWrite();
1999                 } catch (FileNotFoundException ex) {
2000                     // File doesn't exist
2001                     return false;
2002                 }
2003             } else {
2004                 // Ordinary file
2005                 return f.canWrite();
2006             }
2007         }
2008     }
2009 
2010     /**
2011      * Returns true if specified FileChooser should use ShellFolder
2012      */
2013     public static boolean usesShellFolder(JFileChooser chooser) {
2014         Boolean prop = (Boolean) chooser.getClientProperty("FileChooser.useShellFolder");
2015 
2016         return prop == null ? chooser.getFileSystemView().equals(FileSystemView.getFileSystemView())
2017                 : prop.booleanValue();
2018     }
2019 
2020     // This interface is used to access methods in the FileChooserUI
2021     // that are not public.
2022     public interface FileChooserUIAccessor {
2023         public JFileChooser getFileChooser();
2024         public BasicDirectoryModel getModel();
2025         public JPanel createList();
2026         public JPanel createDetailsView();
2027         public boolean isDirectorySelected();
2028         public File getDirectory();
2029         public Action getApproveSelectionAction();
2030         public Action getChangeToParentDirectoryAction();
2031         public Action getNewFolderAction();
2032         public MouseListener createDoubleClickListener(JList list);
2033         public ListSelectionListener createListSelectionListener();
2034     }
2035 }