1 /*
   2  * Copyright (c) 2011, 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 com.apple.eio;
  27 
  28 import java.io.*;
  29 
  30 /**
  31  * Provides functionality to query and modify Mac-specific file attributes. The methods in this class are based on Finder
  32  * attributes. These attributes in turn are dependent on HFS and HFS+ file systems. As such, it is important to recognize
  33  * their limitation when writing code that must function well across multiple platforms.<p>
  34  *
  35  * In addition to file name suffixes, Mac OS X can use Finder attributes like file <code>type</code> and <code>creator</code> codes to
  36  * identify and handle files. These codes are unique 4-byte identifiers. The file <code>type</code> is a string that describes the
  37  * contents of a file. For example, the file type <code>APPL</code> identifies the file as an application and therefore
  38  * executable. A file type of <code>TEXT</code>  means that the file contains raw text. Any application that can read raw
  39  * text can open a file of type <code>TEXT</code>. Applications that use proprietary file types might assign their files a proprietary
  40  * file <code>type</code> code.
  41  * <p>
  42  * To identify the application that can handle a document, the Finder can look at the <code>creator</code>. For example, if a user
  43  * double-clicks on a document with the <code>ttxt</code> <code>creator</code>, it opens up in Text Edit, the application registered
  44  * with the <code>ttxt</code> <code>creator</code> code. Note that the <code>creator</code>
  45  * code can be set to any application, not necessarily the application that created it. For example, if you
  46  * use an editor to create an HTML document, you might want to assign a browser's <code>creator</code> code for the file rather than
  47  * the HTML editor's <code>creator</code> code. Double-clicking on the document then opens the appropriate browser rather than the
  48  *HTML editor.
  49  *<p>
  50  * If you plan to publicly distribute your application, you must register its creator and any proprietary file types with the Apple
  51  * Developer Connection to avoid collisions with codes used by other developers. You can register a codes online at the
  52  * <a target=_blank href=http://developer.apple.com/dev/cftype/>Creator Code Registration</a> site.
  53  *
  54  * @since 1.4
  55  */
  56 public class FileManager {
  57     static {
  58         java.security.AccessController.doPrivileged(
  59             new java.security.PrivilegedAction<Void>() {
  60                 public Void run() {
  61                     System.loadLibrary("osx");
  62                     return null;
  63                 }
  64             });
  65     }
  66 
  67     /**
  68      * The default
  69      * @since Java for Mac OS X 10.5 - 1.5
  70          * @since Java for Mac OS X 10.5 Update 1 - 1.6
  71      */
  72     public final static short kOnAppropriateDisk = -32767;
  73     /**
  74      * Read-only system hierarchy.
  75      * @since Java for Mac OS X 10.5 - 1.5
  76          * @since Java for Mac OS X 10.5 Update 1 - 1.6
  77      */
  78     public final static short kSystemDomain = -32766;
  79     /**
  80      * All users of a single machine have access to these resources.
  81      * @since Java for Mac OS X 10.5 - 1.5
  82          * @since Java for Mac OS X 10.5 Update 1 - 1.6
  83      */
  84     public final static short kLocalDomain = -32765;
  85     /**
  86      * All users configured to use a common network server has access to these resources.
  87      * @since Java for Mac OS X 10.5 - 1.5
  88          * @since Java for Mac OS X 10.5 Update 1 - 1.6
  89      */
  90     public final static short kNetworkDomain = -32764;
  91     /**
  92      * Read/write. Resources that are private to the user.
  93      * @since Java for Mac OS X 10.5 - 1.5
  94          * @since Java for Mac OS X 10.5 Update 1 - 1.6
  95      */
  96     public final static short kUserDomain = -32763;
  97 
  98 
  99         /**
 100          * Converts an OSType (e.g. "macs" from <CarbonCore/Folders.h>) into an int.
 101          *
 102          * @param type the 4 character type to convert.
 103          * @return an int representing the 4 character value
 104          *
 105          * @since Java for Mac OS X 10.5 - 1.5
 106          * @since Java for Mac OS X 10.5 Update 1 - 1.6
 107          */
 108     @SuppressWarnings("deprecation")
 109         public static int OSTypeToInt(String type) {
 110         int result = 0;
 111 
 112                 byte b[] = { (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
 113                 int len = type.length();
 114                 if (len > 0) {
 115                         if (len > 4) len = 4;
 116                         type.getBytes(0, len, b, 4 - len);
 117                 }
 118 
 119                 for (int i = 0;  i < len;  i++)  {
 120                         if (i > 0) result <<= 8;
 121                         result |= (b[i] & 0xff);
 122                 }
 123 
 124         return result;
 125     }
 126 
 127     /**
 128          * Sets the file <code>type</code> and <code>creator</code> codes for a file or folder.
 129          *
 130          * @since 1.4
 131          */
 132     public static void setFileTypeAndCreator(String filename, int type, int creator) throws IOException {
 133         SecurityManager security = System.getSecurityManager();
 134         if (security != null) {
 135             security.checkWrite(filename);
 136         }
 137         _setFileTypeAndCreator(filename, type, creator);
 138     }
 139         private static native void _setFileTypeAndCreator(String filename, int type, int creator) throws IOException;
 140 
 141     /**
 142          * Sets the file <code>type</code> code for a file or folder.
 143          *
 144          * @since 1.4
 145          */
 146     public static void setFileType(String filename, int type) throws IOException {
 147         SecurityManager security = System.getSecurityManager();
 148         if (security != null) {
 149             security.checkWrite(filename);
 150         }
 151         _setFileType(filename, type);
 152         }
 153     private static native void _setFileType(String filename, int type) throws IOException;
 154 
 155     /**
 156          * Sets the file <code>creator</code> code for a file or folder.
 157          *
 158          * @since 1.4
 159          */
 160     public static void setFileCreator(String filename, int creator) throws IOException {
 161         SecurityManager security = System.getSecurityManager();
 162         if (security != null) {
 163             security.checkWrite(filename);
 164         }
 165         _setFileCreator(filename, creator);
 166     }
 167     private static native void _setFileCreator(String filename, int creator) throws IOException;
 168 
 169     /**
 170          * Obtains the file <code>type</code> code for a file or folder.
 171          *
 172          * @since 1.4
 173          */
 174     public static int getFileType(String filename) throws IOException {
 175         SecurityManager security = System.getSecurityManager();
 176         if (security != null) {
 177             security.checkRead(filename);
 178         }
 179         return _getFileType(filename);
 180     }
 181     private static native int _getFileType(String filename) throws IOException;
 182 
 183     /**
 184          * Obtains the file <code>creator</code> code for a file or folder.
 185          *
 186          * @since 1.4
 187          */
 188     public static int getFileCreator(String filename) throws IOException {
 189         SecurityManager security = System.getSecurityManager();
 190         if (security != null) {
 191             security.checkRead(filename);
 192         }
 193         return _getFileCreator(filename);
 194     }
 195     private static native int _getFileCreator(String filename) throws IOException;
 196 
 197 
 198     /**
 199          * Locates a folder of a particular type. Mac OS X recognizes certain specific folders that have distinct purposes.
 200          * For example, the user's desktop or temporary folder. These folders have corresponding codes. Given one of these codes,
 201          * this method returns the path to that particular folder. Certain folders of a given type may appear in more than
 202          * one domain. For example, although there is only one <code>root</code> folder, there are multiple <code>pref</code>
 203          * folders. If this method is called to find the <code>pref</code> folder, it will return the first one it finds,
 204          * the user's preferences folder in <code>~/Library/Preferences</code>. To explicitly locate a folder in a certain
 205          * domain use <code>findFolder(short domain, int folderType)</code> or <code>findFolder(short domain, int folderType,
 206          * boolean createIfNeeded)</code>.
 207          *
 208          * @return the path to the folder searched for
 209          *
 210          * @since 1.4
 211          */
 212         public static String findFolder(int folderType) throws FileNotFoundException {
 213                 return findFolder(kOnAppropriateDisk, folderType);
 214         }
 215 
 216     /**
 217          * Locates a folder of a particular type, within a given domain. Similar to <code>findFolder(int folderType)</code>
 218          * except that the domain to look in can be specified. Valid values for <code>domain</code>include:
 219          * <dl>
 220          * <dt>user</dt>
 221          * <dd>The User domain contains resources specific to the user who is currently logged in</dd>
 222          * <dt>local</dt>
 223          * <dd>The Local domain contains resources shared by all users of the system but are not needed for the system
 224          * itself to run.</dd>
 225          * <dt>network</dt>
 226          * <dd>The Network domain contains resources shared by users of a local area network.</dd>
 227          * <dt>system</dt>
 228          * <dd>The System domain contains the operating system resources installed by Apple.</dd>
 229          * </dl>
 230          *
 231          * @return the path to the folder searched for
 232          *
 233          * @since 1.4
 234          */
 235         public static String findFolder(short domain, int folderType) throws FileNotFoundException {
 236                 return findFolder(domain, folderType, false);
 237         }
 238 
 239     /**
 240          * Locates a folder of a particular type within a given domain and optionally creating the folder if it does
 241          * not exist. The behavior is similar to <code>findFolder(int folderType)</code> and
 242          * <code>findFolder(short domain, int folderType)</code> except that it can create the folder if it does not already exist.
 243          *
 244          * @param createIfNeeded
 245          *            set to <code>true</code>, by setting to <code>false</code> the behavior will be the
 246          *            same as <code>findFolder(short domain, int folderType, boolean createIfNeeded)</code>
 247          * @return the path to the folder searched for
 248          *
 249          * @since 1.4
 250          */
 251     public static String findFolder(short domain, int folderType, boolean createIfNeeded) throws FileNotFoundException {
 252         final SecurityManager security = System.getSecurityManager();
 253         if (security != null) {
 254             security.checkPermission(new RuntimePermission("canExamineFileSystem"));
 255         }
 256 
 257         final String foundFolder = _findFolder(domain, folderType, createIfNeeded);
 258         if (foundFolder == null) throw new FileNotFoundException("Can't find folder: " + Integer.toHexString(folderType));
 259         return foundFolder;
 260     }
 261     private static native String _findFolder(short domain, int folderType, boolean createIfNeeded);
 262 
 263 
 264     /**
 265          * Opens the path specified by a URL in the appropriate application for that URL. HTTP URL's (<code>http://</code>)
 266          * open in the default browser as set in the Internet pane of System Preferences. File (<code>file://</code>) and
 267          * FTP URL's (<code>ftp://</code>) open in the Finder. Note that opening an FTP URL will prompt the user for where
 268          * they want to save the downloaded file(s).
 269          *
 270          * @param url
 271          *            the URL for the file you want to open, it can either be an HTTP, FTP, or file url
 272          *
 273          * @deprecated this functionality has been superseded by java.awt.Desktop.browse() and java.awt.Desktop.open()
 274          *
 275          * @since 1.4
 276          */
 277     @Deprecated
 278     public static void openURL(String url) throws IOException {
 279         SecurityManager security = System.getSecurityManager();
 280         if (security != null) {
 281             security.checkPermission(new RuntimePermission("canOpenURLs"));
 282         }
 283         _openURL(url);
 284     }
 285     private static native void _openURL(String url) throws IOException;
 286 
 287     /**
 288          * @return full pathname for the resource identified by a given name.
 289          *
 290          * @since 1.4
 291          */
 292         public static String getResource(String resourceName) throws FileNotFoundException {
 293                 return getResourceFromBundle(resourceName, null, null);
 294         }
 295 
 296         /**
 297          * @return full pathname for the resource identified by a given name and located in the specified bundle subdirectory.
 298          *
 299          * @since 1.4
 300          */
 301         public static String getResource(String resourceName, String subDirName) throws FileNotFoundException {
 302                 return getResourceFromBundle(resourceName, subDirName, null);
 303         }
 304 
 305         /**
 306          * Returns the full pathname for the resource identified by the given name and file extension
 307          * and located in the specified bundle subdirectory.
 308          *
 309          * If extension is an empty string or null, the returned pathname is the first one encountered where the
 310          * file name exactly matches name.
 311          *
 312          * If subpath is null, this method searches the top-level nonlocalized resource directory (typically Resources)
 313          * and the top-level of any language-specific directories. For example, suppose you have a modern bundle and
 314          * specify "Documentation" for the subpath parameter. This method would first look in the
 315          * Contents/Resources/Documentation directory of the bundle, followed by the Documentation subdirectories of
 316          * each language-specific .lproj directory. (The search order for the language-specific directories
 317          * corresponds to the user's preferences.) This method does not recurse through any other subdirectories at
 318          * any of these locations. For more details see the AppKit NSBundle documentation.
 319          *
 320          * @return full pathname for the resource identified by the given name and file extension and located in the specified bundle subdirectory.
 321          *
 322          * @since 1.4
 323          */
 324         public static String getResource(String resourceName, String subDirName, String type) throws FileNotFoundException {
 325                 return getResourceFromBundle(resourceName, subDirName, type);
 326         }
 327 
 328         private static native String getNativeResourceFromBundle(String resourceName, String subDirName, String type) throws FileNotFoundException;
 329         private static String getResourceFromBundle(String resourceName, String subDirName, String type) throws FileNotFoundException {
 330                 final SecurityManager security = System.getSecurityManager();
 331                 if (security != null) security.checkPermission(new RuntimePermission("canReadBundle"));
 332 
 333                 final String resourceFromBundle = getNativeResourceFromBundle(resourceName, subDirName, type);
 334                 if (resourceFromBundle == null) throw new FileNotFoundException(resourceName);
 335                 return resourceFromBundle;
 336         }
 337 
 338         /**
 339          * Obtains the path to the current application's NSBundle, may not
 340          * return a valid path if Java was launched from the command line.
 341          *
 342          * @return full pathname of the NSBundle of the current application executable.
 343          *
 344          * @since Java for Mac OS X 10.5 Update 1 - 1.6
 345          * @since Java for Mac OS X 10.5 Update 2 - 1.5
 346          */
 347         public static String getPathToApplicationBundle() {
 348                 SecurityManager security = System.getSecurityManager();
 349                 if (security != null) security.checkPermission(new RuntimePermission("canReadBundle"));
 350                 return getNativePathToApplicationBundle();
 351         }
 352 
 353         private static native String getNativePathToApplicationBundle();
 354 
 355         /**
 356          * Moves the specified file to the Trash
 357          *
 358          * @param file
 359          * @return returns true if the NSFileManager successfully moved the file to the Trash.
 360          * @throws FileNotFoundException
 361          *
 362          * @since Java for Mac OS X 10.6 Update 1 - 1.6
 363          * @since Java for Mac OS X 10.5 Update 6 - 1.6, 1.5
 364          */
 365         public static boolean moveToTrash(final File file) throws FileNotFoundException {
 366                 if (file == null || !file.exists()) throw new FileNotFoundException();
 367                 final String fileName = file.getAbsolutePath();
 368 
 369                 final SecurityManager security = System.getSecurityManager();
 370                 if (security != null) security.checkWrite(fileName);
 371 
 372                 return _moveToTrash(fileName);
 373         }
 374 
 375         private static native boolean _moveToTrash(String fileName);
 376 
 377         /**
 378          * Reveals the specified file in the Finder
 379          *
 380          * @param file
 381          *            the file to reveal
 382          * @return returns true if the NSFileManager successfully revealed the file in the Finder.
 383          * @throws FileNotFoundException
 384          *
 385          * @since Java for Mac OS X 10.6 Update 1 - 1.6
 386          * @since Java for Mac OS X 10.5 Update 6 - 1.6, 1.5
 387          */
 388         public static boolean revealInFinder(final File file) throws FileNotFoundException {
 389                 if (file == null || !file.exists()) throw new FileNotFoundException();
 390                 final String fileName = file.getAbsolutePath();
 391 
 392                 final SecurityManager security = System.getSecurityManager();
 393                 if (security != null) security.checkRead(fileName);
 394 
 395                 return _revealInFinder(fileName);
 396         }
 397 
 398         private static native boolean _revealInFinder(String fileName);
 399 }