1 /*
   2  * Copyright (c) 2000, 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 
  26 package sun.awt.shell;
  27 
  28 import javax.swing.*;
  29 import java.awt.Image;
  30 import java.awt.Toolkit;
  31 import java.io.*;
  32 import java.io.FileNotFoundException;
  33 import java.nio.file.Files;
  34 import java.nio.file.LinkOption;
  35 import java.nio.file.Path;
  36 import java.util.*;
  37 import java.util.concurrent.Callable;
  38 
  39 /**
  40  * @author Michael Martak
  41  * @since 1.4
  42  */
  43 @SuppressWarnings("serial") // JDK-implementation class
  44 public abstract class ShellFolder extends File {
  45     private static final String COLUMN_NAME = "FileChooser.fileNameHeaderText";
  46     private static final String COLUMN_SIZE = "FileChooser.fileSizeHeaderText";
  47     private static final String COLUMN_DATE = "FileChooser.fileDateHeaderText";
  48 
  49     protected ShellFolder parent;
  50 
  51     /**
  52      * Create a file system shell folder from a file
  53      */
  54     ShellFolder(ShellFolder parent, String pathname) {
  55         super((pathname != null) ? pathname : "ShellFolder");
  56         this.parent = parent;
  57     }
  58 
  59     /**
  60      * @return Whether this is a file system shell folder
  61      */
  62     public boolean isFileSystem() {
  63         return (!getPath().startsWith("ShellFolder"));
  64     }
  65 
  66     /**
  67      * This method must be implemented to make sure that no instances
  68      * of {@code ShellFolder} are ever serialized. If {@code isFileSystem()} returns
  69      * {@code true}, then the object should be representable with an instance of
  70      * {@code java.io.File} instead. If not, then the object is most likely
  71      * depending on some internal (native) state and cannot be serialized.
  72      *
  73      * @return a java.io.File replacement object, or null
  74      *         if no suitable replacement can be found.
  75      */
  76     protected abstract Object writeReplace() throws java.io.ObjectStreamException;
  77 
  78     /**
  79      * Returns the path for this object's parent,
  80      * or {@code null} if this object does not name a parent
  81      * folder.
  82      *
  83      * @return  the path as a String for this object's parent,
  84      * or {@code null} if this object does not name a parent
  85      * folder
  86      *
  87      * @see java.io.File#getParent()
  88      * @since 1.4
  89      */
  90     public String getParent() {
  91         if (parent == null && isFileSystem()) {
  92             return super.getParent();
  93         }
  94         if (parent != null) {
  95             return (parent.getPath());
  96         } else {
  97             return null;
  98         }
  99     }
 100 
 101     /**
 102      * Returns a File object representing this object's parent,
 103      * or {@code null} if this object does not name a parent
 104      * folder.
 105      *
 106      * @return  a File object representing this object's parent,
 107      * or {@code null} if this object does not name a parent
 108      * folder
 109      *
 110      * @see java.io.File#getParentFile()
 111      * @since 1.4
 112      */
 113     public File getParentFile() {
 114         if (parent != null) {
 115             return parent;
 116         } else if (isFileSystem()) {
 117             return super.getParentFile();
 118         } else {
 119             return null;
 120         }
 121     }
 122 
 123     public File[] listFiles() {
 124         return listFiles(true);
 125     }
 126 
 127     public File[] listFiles(boolean includeHiddenFiles) {
 128         File[] files = super.listFiles();
 129 
 130         if (!includeHiddenFiles) {
 131             Vector<File> v = new Vector<>();
 132             int nameCount = (files == null) ? 0 : files.length;
 133             for (int i = 0; i < nameCount; i++) {
 134                 if (!files[i].isHidden()) {
 135                     v.addElement(files[i]);
 136                 }
 137             }
 138             files = v.toArray(new File[v.size()]);
 139         }
 140 
 141         return files;
 142     }
 143 
 144 
 145     /**
 146      * @return Whether this shell folder is a link
 147      */
 148     public abstract boolean isLink();
 149 
 150     /**
 151      * @return The shell folder linked to by this shell folder, or null
 152      * if this shell folder is not a link
 153      */
 154     public abstract ShellFolder getLinkLocation() throws FileNotFoundException;
 155 
 156     /**
 157      * @return The name used to display this shell folder
 158      */
 159     public abstract String getDisplayName();
 160 
 161     /**
 162      * @return The type of shell folder as a string
 163      */
 164     public abstract String getFolderType();
 165 
 166     /**
 167      * @return The executable type as a string
 168      */
 169     public abstract String getExecutableType();
 170 
 171     /**
 172      * Compares this ShellFolder with the specified ShellFolder for order.
 173      *
 174      * @see #compareTo(Object)
 175      */
 176     public int compareTo(File file2) {
 177         if (file2 == null || !(file2 instanceof ShellFolder)
 178             || ((file2 instanceof ShellFolder) && ((ShellFolder)file2).isFileSystem())) {
 179 
 180             if (isFileSystem()) {
 181                 return super.compareTo(file2);
 182             } else {
 183                 return -1;
 184             }
 185         } else {
 186             if (isFileSystem()) {
 187                 return 1;
 188             } else {
 189                 return getName().compareTo(file2.getName());
 190             }
 191         }
 192     }
 193 
 194     /**
 195      * @param getLargeIcon whether to return large icon (ignored in base implementation)
 196      * @return The icon used to display this shell folder
 197      */
 198     public Image getIcon(boolean getLargeIcon) {
 199         return null;
 200     }
 201 
 202 
 203     // Static
 204 
 205     private static final ShellFolderManager shellFolderManager;
 206 
 207     private static final Invoker invoker;
 208 
 209     static {
 210         String managerClassName = (String)Toolkit.getDefaultToolkit().
 211                                       getDesktopProperty("Shell.shellFolderManager");
 212         Class<?> managerClass = null;
 213         try {
 214             managerClass = Class.forName(managerClassName, false, null);
 215             if (!ShellFolderManager.class.isAssignableFrom(managerClass)) {
 216                 managerClass = null;
 217             }
 218         // swallow the exceptions below and use default shell folder
 219         } catch(ClassNotFoundException e) {
 220         } catch(NullPointerException e) {
 221         } catch(SecurityException e) {
 222         }
 223 
 224         if (managerClass == null) {
 225             managerClass = ShellFolderManager.class;
 226         }
 227         try {
 228             shellFolderManager =
 229                 (ShellFolderManager)managerClass.newInstance();
 230         } catch (InstantiationException e) {
 231             throw new Error("Could not instantiate Shell Folder Manager: "
 232             + managerClass.getName());
 233         } catch (IllegalAccessException e) {
 234             throw new Error ("Could not access Shell Folder Manager: "
 235             + managerClass.getName());
 236         }
 237 
 238         invoker = shellFolderManager.createInvoker();
 239     }
 240 
 241     /**
 242      * Return a shell folder from a file object
 243      * @exception FileNotFoundException if file does not exist
 244      */
 245     public static ShellFolder getShellFolder(File file) throws FileNotFoundException {
 246         if (file instanceof ShellFolder) {
 247             return (ShellFolder)file;
 248         }
 249 
 250         if (!Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS)) {
 251             throw new FileNotFoundException();
 252         }
 253         return shellFolderManager.createShellFolder(file);
 254     }
 255 
 256     /**
 257      * @param key a {@code String}
 258      * @return An Object matching the string {@code key}.
 259      * @see ShellFolderManager#get(String)
 260      */
 261     public static Object get(String key) {
 262         return shellFolderManager.get(key);
 263     }
 264 
 265     /**
 266      * Does {@code dir} represent a "computer" such as a node on the network, or
 267      * "My Computer" on the desktop.
 268      */
 269     public static boolean isComputerNode(File dir) {
 270         return shellFolderManager.isComputerNode(dir);
 271     }
 272 
 273     /**
 274      * @return Whether this is a file system root directory
 275      */
 276     public static boolean isFileSystemRoot(File dir) {
 277         return shellFolderManager.isFileSystemRoot(dir);
 278     }
 279 
 280     /**
 281      * Canonicalizes files that don't have symbolic links in their path.
 282      * Normalizes files that do, preserving symbolic links from being resolved.
 283      */
 284     public static File getNormalizedFile(File f) throws IOException {
 285         File canonical = f.getCanonicalFile();
 286         if (f.equals(canonical)) {
 287             // path of f doesn't contain symbolic links
 288             return canonical;
 289         }
 290 
 291         // preserve symbolic links from being resolved
 292         return new File(f.toURI().normalize());
 293     }
 294 
 295     // Override File methods
 296 
 297     public static void sort(final List<? extends File> files) {
 298         if (files == null || files.size() <= 1) {
 299             return;
 300         }
 301 
 302         // To avoid loads of synchronizations with Invoker and improve performance we
 303         // synchronize the whole code of the sort method once
 304         invoke(new Callable<Void>() {
 305             public Void call() {
 306                 // Check that we can use the ShellFolder.sortChildren() method:
 307                 //   1. All files have the same non-null parent
 308                 //   2. All files is ShellFolders
 309                 File commonParent = null;
 310 
 311                 for (File file : files) {
 312                     File parent = file.getParentFile();
 313 
 314                     if (parent == null || !(file instanceof ShellFolder)) {
 315                         commonParent = null;
 316 
 317                         break;
 318                     }
 319 
 320                     if (commonParent == null) {
 321                         commonParent = parent;
 322                     } else {
 323                         if (commonParent != parent && !commonParent.equals(parent)) {
 324                             commonParent = null;
 325 
 326                             break;
 327                         }
 328                     }
 329                 }
 330 
 331                 if (commonParent instanceof ShellFolder) {
 332                     ((ShellFolder) commonParent).sortChildren(files);
 333                 } else {
 334                     Collections.sort(files, FILE_COMPARATOR);
 335                 }
 336 
 337                 return null;
 338             }
 339         });
 340     }
 341 
 342     public void sortChildren(final List<? extends File> files) {
 343         // To avoid loads of synchronizations with Invoker and improve performance we
 344         // synchronize the whole code of the sort method once
 345         invoke(new Callable<Void>() {
 346             public Void call() {
 347                 Collections.sort(files, FILE_COMPARATOR);
 348 
 349                 return null;
 350             }
 351         });
 352     }
 353 
 354     public boolean isAbsolute() {
 355         return (!isFileSystem() || super.isAbsolute());
 356     }
 357 
 358     public File getAbsoluteFile() {
 359         return (isFileSystem() ? super.getAbsoluteFile() : this);
 360     }
 361 
 362     public boolean canRead() {
 363         return (isFileSystem() ? super.canRead() : true);       // ((Fix?))
 364     }
 365 
 366     /**
 367      * Returns true if folder allows creation of children.
 368      * True for the "Desktop" folder, but false for the "My Computer"
 369      * folder.
 370      */
 371     public boolean canWrite() {
 372         return (isFileSystem() ? super.canWrite() : false);     // ((Fix?))
 373     }
 374 
 375     public boolean exists() {
 376         // Assume top-level drives exist, because state is uncertain for
 377         // removable drives.
 378         return (!isFileSystem() || isFileSystemRoot(this) || super.exists()) ;
 379     }
 380 
 381     public boolean isDirectory() {
 382         return (isFileSystem() ? super.isDirectory() : true);   // ((Fix?))
 383     }
 384 
 385     public boolean isFile() {
 386         return (isFileSystem() ? super.isFile() : !isDirectory());      // ((Fix?))
 387     }
 388 
 389     public long lastModified() {
 390         return (isFileSystem() ? super.lastModified() : 0L);    // ((Fix?))
 391     }
 392 
 393     public long length() {
 394         return (isFileSystem() ? super.length() : 0L);  // ((Fix?))
 395     }
 396 
 397     public boolean createNewFile() throws IOException {
 398         return (isFileSystem() ? super.createNewFile() : false);
 399     }
 400 
 401     public boolean delete() {
 402         return (isFileSystem() ? super.delete() : false);       // ((Fix?))
 403     }
 404 
 405     public void deleteOnExit() {
 406         if (isFileSystem()) {
 407             super.deleteOnExit();
 408         } else {
 409             // Do nothing       // ((Fix?))
 410         }
 411     }
 412 
 413     public boolean mkdir() {
 414         return (isFileSystem() ? super.mkdir() : false);
 415     }
 416 
 417     public boolean mkdirs() {
 418         return (isFileSystem() ? super.mkdirs() : false);
 419     }
 420 
 421     public boolean renameTo(File dest) {
 422         return (isFileSystem() ? super.renameTo(dest) : false); // ((Fix?))
 423     }
 424 
 425     public boolean setLastModified(long time) {
 426         return (isFileSystem() ? super.setLastModified(time) : false); // ((Fix?))
 427     }
 428 
 429     public boolean setReadOnly() {
 430         return (isFileSystem() ? super.setReadOnly() : false); // ((Fix?))
 431     }
 432 
 433     public String toString() {
 434         return (isFileSystem() ? super.toString() : getDisplayName());
 435     }
 436 
 437     public static ShellFolderColumnInfo[] getFolderColumns(File dir) {
 438         ShellFolderColumnInfo[] columns = null;
 439 
 440         if (dir instanceof ShellFolder) {
 441             columns = ((ShellFolder) dir).getFolderColumns();
 442         }
 443 
 444         if (columns == null) {
 445             columns = new ShellFolderColumnInfo[]{
 446                     new ShellFolderColumnInfo(COLUMN_NAME, 150,
 447                             SwingConstants.LEADING, true, null,
 448                             FILE_COMPARATOR),
 449                     new ShellFolderColumnInfo(COLUMN_SIZE, 75,
 450                             SwingConstants.RIGHT, true, null,
 451                             DEFAULT_COMPARATOR, true),
 452                     new ShellFolderColumnInfo(COLUMN_DATE, 130,
 453                             SwingConstants.LEADING, true, null,
 454                             DEFAULT_COMPARATOR, true)
 455             };
 456         }
 457 
 458         return columns;
 459     }
 460 
 461     public ShellFolderColumnInfo[] getFolderColumns() {
 462         return null;
 463     }
 464 
 465     public static Object getFolderColumnValue(File file, int column) {
 466         if (file instanceof ShellFolder) {
 467             Object value = ((ShellFolder)file).getFolderColumnValue(column);
 468             if (value != null) {
 469                 return value;
 470             }
 471         }
 472 
 473         if (file == null || !file.exists()) {
 474             return null;
 475         }
 476 
 477         switch (column) {
 478             case 0:
 479                 // By default, file name will be rendered using getSystemDisplayName()
 480                 return file;
 481 
 482             case 1: // size
 483                 return file.isDirectory() ? null : Long.valueOf(file.length());
 484 
 485             case 2: // date
 486                 if (isFileSystemRoot(file)) {
 487                     return null;
 488                 }
 489                 long time = file.lastModified();
 490                 return (time == 0L) ? null : new Date(time);
 491 
 492             default:
 493                 return null;
 494         }
 495     }
 496 
 497     public Object getFolderColumnValue(int column) {
 498         return null;
 499     }
 500 
 501     /**
 502      * Invokes the {@code task} which doesn't throw checked exceptions
 503      * from its {@code call} method. If invokation is interrupted then Thread.currentThread().isInterrupted() will
 504      * be set and result will be {@code null}
 505      */
 506     public static <T> T invoke(Callable<T> task) {
 507         try {
 508             return invoke(task, RuntimeException.class);
 509         } catch (InterruptedException e) {
 510             return null;
 511         }
 512     }
 513 
 514     /**
 515      * Invokes the {@code task} which throws checked exceptions from its {@code call} method.
 516      * If invokation is interrupted then Thread.currentThread().isInterrupted() will
 517      * be set and InterruptedException will be thrown as well.
 518      */
 519     public static <T, E extends Throwable> T invoke(Callable<T> task, Class<E> exceptionClass)
 520             throws InterruptedException, E {
 521         try {
 522             return invoker.invoke(task);
 523         } catch (Exception e) {
 524             if (e instanceof RuntimeException) {
 525                 // Rethrow unchecked exceptions
 526                 throw (RuntimeException) e;
 527             }
 528 
 529             if (e instanceof InterruptedException) {
 530                 // Set isInterrupted flag for current thread
 531                 Thread.currentThread().interrupt();
 532 
 533                 // Rethrow InterruptedException
 534                 throw (InterruptedException) e;
 535             }
 536 
 537             if (exceptionClass.isInstance(e)) {
 538                 throw exceptionClass.cast(e);
 539             }
 540 
 541             throw new RuntimeException("Unexpected error", e);
 542         }
 543     }
 544 
 545     /**
 546      * Interface allowing to invoke tasks in different environments on different platforms.
 547      */
 548     public static interface Invoker {
 549         /**
 550          * Invokes a callable task.
 551          *
 552          * @param task a task to invoke
 553          * @throws Exception {@code InterruptedException} or an exception that was thrown from the {@code task}
 554          * @return the result of {@code task}'s invokation
 555          */
 556         <T> T invoke(Callable<T> task) throws Exception;
 557     }
 558 
 559     /**
 560      * Provides a default comparator for the default column set
 561      */
 562     private static final Comparator<Object> DEFAULT_COMPARATOR = new Comparator<Object>() {
 563         public int compare(Object o1, Object o2) {
 564             int gt;
 565 
 566             if (o1 == null && o2 == null) {
 567                 gt = 0;
 568             } else if (o1 != null && o2 == null) {
 569                 gt = 1;
 570             } else if (o1 == null && o2 != null) {
 571                 gt = -1;
 572             } else if (o1 instanceof Comparable) {
 573                 @SuppressWarnings("unchecked")
 574                 Comparable<Object> o = (Comparable<Object>) o1;
 575                 gt = o.compareTo(o2);
 576             } else {
 577                 gt = 0;
 578             }
 579 
 580             return gt;
 581         }
 582     };
 583 
 584     private static final Comparator<File> FILE_COMPARATOR = new Comparator<File>() {
 585         public int compare(File f1, File f2) {
 586             ShellFolder sf1 = null;
 587             ShellFolder sf2 = null;
 588 
 589             if (f1 instanceof ShellFolder) {
 590                 sf1 = (ShellFolder) f1;
 591                 if (sf1.isFileSystem()) {
 592                     sf1 = null;
 593                 }
 594             }
 595             if (f2 instanceof ShellFolder) {
 596                 sf2 = (ShellFolder) f2;
 597                 if (sf2.isFileSystem()) {
 598                     sf2 = null;
 599                 }
 600             }
 601 
 602             if (sf1 != null && sf2 != null) {
 603                 return sf1.compareTo(sf2);
 604             } else if (sf1 != null) {
 605                 // Non-file shellfolders sort before files
 606                 return -1;
 607             } else if (sf2 != null) {
 608                 return 1;
 609             } else {
 610                 String name1 = f1.getName();
 611                 String name2 = f2.getName();
 612 
 613                 // First ignore case when comparing
 614                 int diff = name1.compareToIgnoreCase(name2);
 615                 if (diff != 0) {
 616                     return diff;
 617                 } else {
 618                     // May differ in case (e.g. "mail" vs. "Mail")
 619                     // We need this test for consistent sorting
 620                     return name1.compareTo(name2);
 621                 }
 622             }
 623         }
 624     };
 625 }
--- EOF ---