Win32ShellFolderManager2.java 21.9 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27
 */

package sun.awt.shell;

28 29
import java.awt.*;
import java.awt.image.BufferedImage;
D
duke 已提交
30 31 32 33 34

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.AccessController;
35
import java.security.PrivilegedAction;
D
duke 已提交
36
import java.util.*;
37
import java.util.List;
38
import java.util.concurrent.*;
39
import java.util.stream.Stream;
40

D
duke 已提交
41 42
import static sun.awt.shell.Win32ShellFolder2.*;
import sun.awt.OSInfo;
43
import sun.misc.ThreadGroupUtils;
D
duke 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

// NOTE: This class supersedes Win32ShellFolderManager, which was removed
//       from distribution after version 1.4.2.

/**
 * @author Michael Martak
 * @author Leif Samuelsson
 * @author Kenneth Russell
 * @since 1.4
 */

public class Win32ShellFolderManager2 extends ShellFolderManager {

    static {
        // Load library here
59
        sun.awt.windows.WToolkit.loadLibraries();
D
duke 已提交
60 61 62
    }

    public ShellFolder createShellFolder(File file) throws FileNotFoundException {
63 64 65 66 67
        try {
            return createShellFolder(getDesktop(), file);
        } catch (InterruptedException e) {
            throw new FileNotFoundException("Execution was interrupted");
        }
D
duke 已提交
68 69
    }

70 71
    static Win32ShellFolder2 createShellFolder(Win32ShellFolder2 parent, File file)
            throws FileNotFoundException, InterruptedException {
D
duke 已提交
72 73 74 75 76 77 78 79 80 81
        long pIDL;
        try {
            pIDL = parent.parseDisplayName(file.getCanonicalPath());
        } catch (IOException ex) {
            pIDL = 0;
        }
        if (pIDL == 0) {
            // Shouldn't happen but watch for it anyway
            throw new FileNotFoundException("File " + file.getAbsolutePath() + " not found");
        }
82 83 84 85 86 87

        try {
            return createShellFolderFromRelativePIDL(parent, pIDL);
        } finally {
            Win32ShellFolder2.releasePIDL(pIDL);
        }
D
duke 已提交
88 89
    }

90 91
    static Win32ShellFolder2 createShellFolderFromRelativePIDL(Win32ShellFolder2 parent, long pIDL)
            throws InterruptedException {
D
duke 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105
        // Walk down this relative pIDL, creating new nodes for each of the entries
        while (pIDL != 0) {
            long curPIDL = Win32ShellFolder2.copyFirstPIDLEntry(pIDL);
            if (curPIDL != 0) {
                parent = new Win32ShellFolder2(parent, curPIDL);
                pIDL = Win32ShellFolder2.getNextPIDLEntry(pIDL);
            } else {
                // The list is empty if the parent is Desktop and pIDL is a shortcut to Desktop
                break;
            }
        }
        return parent;
    }

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    private static final int VIEW_LIST = 2;
    private static final int VIEW_DETAILS = 3;
    private static final int VIEW_PARENTFOLDER = 8;
    private static final int VIEW_NEWFOLDER = 11;

    private static final Image[] STANDARD_VIEW_BUTTONS = new Image[12];

    private static Image getStandardViewButton(int iconIndex) {
        Image result = STANDARD_VIEW_BUTTONS[iconIndex];

        if (result != null) {
            return result;
        }

        BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);

        img.setRGB(0, 0, 16, 16, Win32ShellFolder2.getStandardViewButton0(iconIndex), 0, 16);

        STANDARD_VIEW_BUTTONS[iconIndex] = img;

        return img;
    }

D
duke 已提交
129 130 131 132 133 134 135 136 137 138 139
    // Special folders
    private static Win32ShellFolder2 desktop;
    private static Win32ShellFolder2 drives;
    private static Win32ShellFolder2 recent;
    private static Win32ShellFolder2 network;
    private static Win32ShellFolder2 personal;

    static Win32ShellFolder2 getDesktop() {
        if (desktop == null) {
            try {
                desktop = new Win32ShellFolder2(DESKTOP);
140 141
            } catch (SecurityException e) {
                // Ignore error
D
duke 已提交
142
            } catch (IOException e) {
143 144 145
                // Ignore error
            } catch (InterruptedException e) {
                // Ignore error
D
duke 已提交
146 147 148 149 150 151 152 153 154
            }
        }
        return desktop;
    }

    static Win32ShellFolder2 getDrives() {
        if (drives == null) {
            try {
                drives = new Win32ShellFolder2(DRIVES);
155 156
            } catch (SecurityException e) {
                // Ignore error
D
duke 已提交
157
            } catch (IOException e) {
158 159 160
                // Ignore error
            } catch (InterruptedException e) {
                // Ignore error
D
duke 已提交
161 162 163 164 165 166 167 168 169 170 171 172
            }
        }
        return drives;
    }

    static Win32ShellFolder2 getRecent() {
        if (recent == null) {
            try {
                String path = Win32ShellFolder2.getFileSystemPath(RECENT);
                if (path != null) {
                    recent = createShellFolder(getDesktop(), new File(path));
                }
173 174
            } catch (SecurityException e) {
                // Ignore error
175 176
            } catch (InterruptedException e) {
                // Ignore error
D
duke 已提交
177
            } catch (IOException e) {
178
                // Ignore error
D
duke 已提交
179 180 181 182 183 184 185 186 187
            }
        }
        return recent;
    }

    static Win32ShellFolder2 getNetwork() {
        if (network == null) {
            try {
                network = new Win32ShellFolder2(NETWORK);
188 189
            } catch (SecurityException e) {
                // Ignore error
D
duke 已提交
190
            } catch (IOException e) {
191 192 193
                // Ignore error
            } catch (InterruptedException e) {
                // Ignore error
D
duke 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
            }
        }
        return network;
    }

    static Win32ShellFolder2 getPersonal() {
        if (personal == null) {
            try {
                String path = Win32ShellFolder2.getFileSystemPath(PERSONAL);
                if (path != null) {
                    Win32ShellFolder2 desktop = getDesktop();
                    personal = desktop.getChildByPath(path);
                    if (personal == null) {
                        personal = createShellFolder(getDesktop(), new File(path));
                    }
                    if (personal != null) {
                        personal.setIsPersonal();
                    }
                }
213 214
            } catch (SecurityException e) {
                // Ignore error
215 216
            } catch (InterruptedException e) {
                // Ignore error
D
duke 已提交
217
            } catch (IOException e) {
218
                // Ignore error
D
duke 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
            }
        }
        return personal;
    }


    private static File[] roots;

    /**
     * @param key a <code>String</code>
     *  "fileChooserDefaultFolder":
     *    Returns a <code>File</code> - the default shellfolder for a new filechooser
     *  "roots":
     *    Returns a <code>File[]</code> - containing the root(s) of the displayable hierarchy
     *  "fileChooserComboBoxFolders":
     *    Returns a <code>File[]</code> - an array of shellfolders representing the list to
     *    show by default in the file chooser's combobox
     *   "fileChooserShortcutPanelFolders":
     *    Returns a <code>File[]</code> - an array of shellfolders representing well-known
     *    folders, such as Desktop, Documents, History, Network, Home, etc.
     *    This is used in the shortcut panel of the filechooser on Windows 2000
     *    and Windows Me.
241 242 243
     *  "fileChooserIcon <icon>":
     *    Returns an <code>Image</code> - icon can be ListView, DetailsView, UpFolder, NewFolder or
     *    ViewMenu (Windows only).
D
duke 已提交
244 245 246 247 248 249 250 251 252 253 254
     *  "optionPaneIcon iconName":
     *    Returns an <code>Image</code> - icon from the system icon list
     *
     * @return An Object matching the key string.
     */
    public Object get(String key) {
        if (key.equals("fileChooserDefaultFolder")) {
            File file = getPersonal();
            if (file == null) {
                file = getDesktop();
            }
255
            return checkFile(file);
D
duke 已提交
256 257 258 259 260 261 262 263 264 265
        } else if (key.equals("roots")) {
            // Should be "History" and "Desktop" ?
            if (roots == null) {
                File desktop = getDesktop();
                if (desktop != null) {
                    roots = new File[] { desktop };
                } else {
                    roots = (File[])super.get(key);
                }
            }
266
            return checkFiles(roots);
D
duke 已提交
267 268 269
        } else if (key.equals("fileChooserComboBoxFolders")) {
            Win32ShellFolder2 desktop = getDesktop();

270
            if (desktop != null && checkFile(desktop) != null) {
D
duke 已提交
271 272 273 274 275 276 277 278 279 280
                ArrayList<File> folders = new ArrayList<File>();
                Win32ShellFolder2 drives = getDrives();

                Win32ShellFolder2 recentFolder = getRecent();
                if (recentFolder != null && OSInfo.getWindowsVersion().compareTo(OSInfo.WINDOWS_2000) >= 0) {
                    folders.add(recentFolder);
                }

                folders.add(desktop);
                // Add all second level folders
281
                File[] secondLevelFolders = checkFiles(desktop.listFiles());
D
duke 已提交
282 283 284
                Arrays.sort(secondLevelFolders);
                for (File secondLevelFolder : secondLevelFolders) {
                    Win32ShellFolder2 folder = (Win32ShellFolder2) secondLevelFolder;
285
                    if (!folder.isFileSystem() || (folder.isDirectory() && !folder.isLink())) {
D
duke 已提交
286 287 288
                        folders.add(folder);
                        // Add third level for "My Computer"
                        if (folder.equals(drives)) {
289
                            File[] thirdLevelFolders = checkFiles(folder.listFiles());
290 291 292 293 294
                            if (thirdLevelFolders != null && thirdLevelFolders.length > 0) {
                                List<File> thirdLevelFoldersList = Arrays.asList(thirdLevelFolders);

                                folder.sortChildren(thirdLevelFoldersList);
                                folders.addAll(thirdLevelFoldersList);
D
duke 已提交
295 296 297 298
                            }
                        }
                    }
                }
299
                return checkFiles(folders);
D
duke 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
            } else {
                return super.get(key);
            }
        } else if (key.equals("fileChooserShortcutPanelFolders")) {
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            ArrayList<File> folders = new ArrayList<File>();
            int i = 0;
            Object value;
            do {
                value = toolkit.getDesktopProperty("win.comdlg.placesBarPlace" + i++);
                try {
                    if (value instanceof Integer) {
                        // A CSIDL
                        folders.add(new Win32ShellFolder2((Integer)value));
                    } else if (value instanceof String) {
                        // A path
                        folders.add(createShellFolder(new File((String)value)));
                    }
                } catch (IOException e) {
                    // Skip this value
320 321 322
                } catch (InterruptedException e) {
                    // Return empty result
                    return new File[0];
D
duke 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335
                }
            } while (value != null);

            if (folders.size() == 0) {
                // Use default list of places
                for (File f : new File[] {
                    getRecent(), getDesktop(), getPersonal(), getDrives(), getNetwork()
                }) {
                    if (f != null) {
                        folders.add(f);
                    }
                }
            }
336
            return checkFiles(folders);
D
duke 已提交
337
        } else if (key.startsWith("fileChooserIcon ")) {
338 339 340 341 342 343 344 345 346 347 348 349 350 351
            String name = key.substring(key.indexOf(" ") + 1);

            int iconIndex;

            if (name.equals("ListView") || name.equals("ViewMenu")) {
                iconIndex = VIEW_LIST;
            } else if (name.equals("DetailsView")) {
                iconIndex = VIEW_DETAILS;
            } else if (name.equals("UpFolder")) {
                iconIndex = VIEW_PARENTFOLDER;
            } else if (name.equals("NewFolder")) {
                iconIndex = VIEW_NEWFOLDER;
            } else {
                return null;
D
duke 已提交
352
            }
353 354

            return getStandardViewButton(iconIndex);
D
duke 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368
        } else if (key.startsWith("optionPaneIcon ")) {
            Win32ShellFolder2.SystemIcon iconType;
            if (key == "optionPaneIcon Error") {
                iconType = Win32ShellFolder2.SystemIcon.IDI_ERROR;
            } else if (key == "optionPaneIcon Information") {
                iconType = Win32ShellFolder2.SystemIcon.IDI_INFORMATION;
            } else if (key == "optionPaneIcon Question") {
                iconType = Win32ShellFolder2.SystemIcon.IDI_QUESTION;
            } else if (key == "optionPaneIcon Warning") {
                iconType = Win32ShellFolder2.SystemIcon.IDI_EXCLAMATION;
            } else {
                return null;
            }
            return Win32ShellFolder2.getSystemIcon(iconType);
369 370
        } else if (key.startsWith("shell32Icon ") || key.startsWith("shell32LargeIcon ")) {
            String name = key.substring(key.indexOf(" ") + 1);
D
duke 已提交
371
            try {
372
                int i = Integer.parseInt(name);
D
duke 已提交
373
                if (i >= 0) {
374
                    return Win32ShellFolder2.getShell32Icon(i, key.startsWith("shell32LargeIcon "));
D
duke 已提交
375 376 377 378 379 380 381
                }
            } catch (NumberFormatException ex) {
            }
        }
        return null;
    }

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    private File checkFile(File file) {
        SecurityManager sm = System.getSecurityManager();
        return (sm == null || file == null) ? file : checkFile(file, sm);
    }

    private File checkFile(File file, SecurityManager sm) {
        try {
            sm.checkRead(file.getPath());
            return file;
        } catch (SecurityException se) {
            return null;
        }
    }

    private File[] checkFiles(File[] files) {
        SecurityManager sm = System.getSecurityManager();
        if (sm == null || files == null || files.length == 0) {
            return files;
        }
        return checkFiles(Arrays.stream(files), sm);
    }

    private File[] checkFiles(List<File> files) {
        SecurityManager sm = System.getSecurityManager();
        if (sm == null || files.isEmpty()) {
            return files.toArray(new File[files.size()]);
        }
        return checkFiles(files.stream(), sm);
    }

    private File[] checkFiles(Stream<File> filesStream, SecurityManager sm) {
        return filesStream.filter((file) -> checkFile(file, sm) != null)
                .toArray(File[]::new);
    }

D
duke 已提交
417 418 419 420
    /**
     * Does <code>dir</code> represent a "computer" such as a node on the network, or
     * "My Computer" on the desktop.
     */
421
    public boolean isComputerNode(final File dir) {
D
duke 已提交
422 423 424
        if (dir != null && dir == getDrives()) {
            return true;
        } else {
425 426 427 428 429 430
            String path = AccessController.doPrivileged(new PrivilegedAction<String>() {
                public String run() {
                    return dir.getAbsolutePath();
                }
            });

D
duke 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
            return (path.startsWith("\\\\") && path.indexOf("\\", 2) < 0);      //Network path
        }
    }

    public boolean isFileSystemRoot(File dir) {
        //Note: Removable drives don't "exist" but are listed in "My Computer"
        if (dir != null) {
            Win32ShellFolder2 drives = getDrives();
            if (dir instanceof Win32ShellFolder2) {
                Win32ShellFolder2 sf = (Win32ShellFolder2)dir;
                if (sf.isFileSystem()) {
                    if (sf.parent != null) {
                        return sf.parent.equals(drives);
                    }
                    // else fall through ...
                } else {
                    return false;
                }
            }
            String path = dir.getPath();
451 452 453 454 455 456 457 458

            if (path.length() != 3 || path.charAt(1) != ':') {
                return false;
            }

            File[] files = drives.listFiles();

            return files != null && Arrays.asList(files).contains(dir);
D
duke 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
        }
        return false;
    }

    private static List topFolderList = null;
    static int compareShellFolders(Win32ShellFolder2 sf1, Win32ShellFolder2 sf2) {
        boolean special1 = sf1.isSpecial();
        boolean special2 = sf2.isSpecial();

        if (special1 || special2) {
            if (topFolderList == null) {
                ArrayList tmpTopFolderList = new ArrayList();
                tmpTopFolderList.add(Win32ShellFolderManager2.getPersonal());
                tmpTopFolderList.add(Win32ShellFolderManager2.getDesktop());
                tmpTopFolderList.add(Win32ShellFolderManager2.getDrives());
                tmpTopFolderList.add(Win32ShellFolderManager2.getNetwork());
                topFolderList = tmpTopFolderList;
            }
            int i1 = topFolderList.indexOf(sf1);
            int i2 = topFolderList.indexOf(sf2);
            if (i1 >= 0 && i2 >= 0) {
                return (i1 - i2);
            } else if (i1 >= 0) {
                return -1;
            } else if (i2 >= 0) {
                return 1;
            }
        }

        // Non-file shellfolders sort before files
        if (special1 && !special2) {
            return -1;
        } else if (special2 && !special1) {
            return  1;
        }

        return compareNames(sf1.getAbsolutePath(), sf2.getAbsolutePath());
    }

    static int compareNames(String name1, String name2) {
        // First ignore case when comparing
500
        int diff = name1.compareToIgnoreCase(name2);
D
duke 已提交
501 502 503 504 505 506 507 508
        if (diff != 0) {
            return diff;
        } else {
            // May differ in case (e.g. "mail" vs. "Mail")
            // We need this test for consistent sorting
            return name1.compareTo(name2);
        }
    }
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

    @Override
    protected Invoker createInvoker() {
        return new ComInvoker();
    }

    private static class ComInvoker extends ThreadPoolExecutor implements ThreadFactory, ShellFolder.Invoker {
        private static Thread comThread;

        private ComInvoker() {
            super(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>());
            allowCoreThreadTimeOut(false);
            setThreadFactory(this);
            final Runnable shutdownHook = new Runnable() {
                public void run() {
                    AccessController.doPrivileged(new PrivilegedAction<Void>() {
                        public Void run() {
                            shutdownNow();
                            return null;
                        }
                    });
                }
            };
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                public Void run() {
                    Runtime.getRuntime().addShutdownHook(
                        new Thread(shutdownHook)
                    );
                    return null;
                }
            });
        }

        public synchronized Thread newThread(final Runnable task) {
            final Runnable comRun = new Runnable() {
                public void run() {
                    try {
                        initializeCom();
                        task.run();
                    } finally {
                        uninitializeCom();
                    }
                }
            };
553
            comThread =  AccessController.doPrivileged((PrivilegedAction<Thread>) () -> {
554 555 556 557
                            /* The thread must be a member of a thread group
                             * which will not get GCed before VM exit.
                             * Make its parent the top-level thread group.
                             */
558 559
                            ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
                            Thread thread = new Thread(rootTG, comRun, "Swing-Shell");
560 561 562 563 564 565 566
                            thread.setDaemon(true);
                            return thread;
                        }
                );
            return comThread;
        }

567 568 569 570 571 572
        public <T> T invoke(Callable<T> task) throws Exception {
            if (Thread.currentThread() == comThread) {
                // if it's already called from the COM
                // thread, we don't need to delegate the task
                return task.call();
            } else {
573
                final Future<T> future;
574 575 576 577 578

                try {
                    future = submit(task);
                } catch (RejectedExecutionException e) {
                    throw new InterruptedException(e.getMessage());
579
                }
580 581 582 583

                try {
                    return future.get();
                } catch (InterruptedException e) {
584 585 586 587 588 589 590
                    AccessController.doPrivileged(new PrivilegedAction<Void>() {
                        public Void run() {
                            future.cancel(true);

                            return null;
                        }
                    });
591 592 593 594 595 596 597 598 599 600 601 602 603 604

                    throw e;
                } catch (ExecutionException e) {
                    Throwable cause = e.getCause();

                    if (cause instanceof Exception) {
                        throw (Exception) cause;
                    }

                    if (cause instanceof Error) {
                        throw (Error) cause;
                    }

                    throw new RuntimeException("Unexpected error", cause);
605 606 607 608 609 610 611 612
                }
            }
        }
    }

    static native void initializeCom();

    static native void uninitializeCom();
D
duke 已提交
613
}