Next Page > Hide TOC

Legacy Documentclose button

Important: The information in this document is obsolete and should not be used for new development.

NSWorkspace

Inherits from
Package
com.apple.cocoa.application
Companion guide

Overview

An NSWorkspace object responds to application requests to perform a variety of services:

There is one shared NSWorkspace object per application. You use the static method sharedWorkspace to access it.

Tasks

Constructors

Accessing the Shared NSWorkspace

Accessing the NSWorkspace Notification Center

Opening Files

Manipulating Applications

Manipulating Files

Requesting Information

Requesting Additional Time Before Logout

Tracking Changes to the File System

Updating Registered Services and File Types

Tracking Changes to the Defaults Database

Tracking Status Changes for Applications and Devices

Unmounting a Device

Working with Bundles

Constructors

NSWorkspace

Creates an empty NSWorkspace.

public NSWorkspace()

Static Methods

sharedWorkspace

Returns the shared NSWorkspace instance.

public static NSWorkspace sharedWorkspace()

Instance Methods

absolutePathForAppBundleWithIdentifier

Returns the absolute file-system path of an application bundle.

public String absolutePathForAppBundleWithIdentifier(String bundleIdentifier)

Discussion

The bundleIdentifier parameter identifies the desired application and corresponds to the value from the CFBundleIdentifier key in the application’s Info.plist file. For example, the bundle identifier of the TextEdit application is com.apple.TextEdit.

Availability

activeApplication

Returns a dictionary with information about the current active application.

public NSDictionary activeApplication()

Discussion

The dictionary contains as many of the keys described in the constants section as are available.

Availability
See Also

applicationForFile

Returns the full path to the application that the system would use to open the document pathToFile.

public String applicationForFile(String pathToFile)

Discussion

Returns null if the file cannot be found or if the file is of an unknown type.

checkForRemovableMedia

Polls the system’s drives for any disks that have been inserted but not yet mounted.

public void checkForRemovableMedia()

Discussion

checkForRemovableMedia doesn’t wait until such disks are mounted; instead, it requests that the disk be mounted asynchronously and returns immediately. Currently has no effect.

See Also

extendPowerOffBy

Requests requested milliseconds more time before the power goes off or the user logs out.

public int extendPowerOffBy(int requested)

Discussion

Returns the number of additional milliseconds granted. Currently unimplemented.

fileSystemChanged

Returns true if a change to the file system has been registered with a noteFileSystemChanged message since the last fileSystemChanged message; false otherwise.

public boolean fileSystemChanged()

Discussion

Currently always returns false.

findApplications

Examines all applications in the normal places (/Network/Applications, /Applications, /Developer/Applications) and updates the records of registered services and file types.

public void findApplications()

fullPathForApplication

Returns the full path for the application appName, or null if appName isn’t in one of the normal places.

public String fullPathForApplication(String appName)

hideOtherApplications

Hides all applications other than the sender.

public void hideOtherApplications()

Discussion

The user can hide all applications except the current one by Command-Option-clicking on an application’s Dock icon.

iconForFile

Returns an NSImage with the icon for the single file specified by fullPath, with an initial size of 32 pixels by 32 pixels.

public NSImage iconForFile(String fullPath)

See Also

iconForFiles

Returns an NSImage with the icon for the files specified in fullPaths, an array of Strings.

public NSImage iconForFiles(NSArray fullPaths)

Discussion

If fullPaths specifies one file, its icon is returned. If fullPaths specifies more than one file, an icon representing the multiple selection is returned.

See Also

iconForFileType

Returns an NSImage with the icon for the file type specified by fileType, with an initial size of 32 pixels by 32 pixels.

public NSImage iconForFileType(String fileType)

Discussion

fileType may be either a filename extension or an encoded HFS file type.

See Also

isFilePackageAtPath

Determines whether fullPath is a file package.

public boolean isFilePackageAtPath(String fullPath)

Discussion

Returns false if fullPath does not exist or is not a directory.

launchApplication

Launches the application appName.

public boolean launchApplication(String appName, boolean showIcon, boolean autoLaunch)

Discussion

If showIcon is false, the application’s icon won’t be placed on the screen. (The icon still exists, though.) If autolaunch is true, the autolaunch default will be set as though the application were autolaunched at startup. This method is provided to enable daemon-like applications that lack a normal user interface. Its use is not generally encouraged.

Returns true if the application is successfully launched or already running, and false if it can’t be launched.

Before this method begins, it posts an WorkspaceWillLaunchApplicationNotification to the NSWorkspace’s notification center. When the operation is complete, it posts an WorkspaceDidLaunchApplicationNotification.

Launches the application appName.

public boolean launchApplication(String appName)

Discussion

appName need not be specified with a full path and, in the case of an application wrapper, may be specified with or without the .app extension, as described in “Use of .app Extension”. Returns true if the application is successfully launched or already running, false if it can’t be launched.

Before this method begins, it posts an WorkspaceWillLaunchApplicationNotification to the NSWorkspace’s notification center. When the operation is complete, it posts an WorkspaceDidLaunchApplicationNotification.

launchedApplications

Returns an array of dictionaries, one entry for each running application.

public NSArray launchedApplications()

Discussion

The dictionary contains as many of the keys described in the constants section as are available.

Availability
See Also

mountedLocalVolumePaths

Returns an array containing the mount points of all local volumes, not just the removable ones returned by mountedRemovableMedia.

public NSArray mountedLocalVolumePaths()

mountedRemovableMedia

Returns an NSArray of Strings containing the full pathnames of all currently mounted removable disks.

public NSArray mountedRemovableMedia()

Discussion

If the computer provides an interrupt or other notification when the user inserts a disk into a drive, the Finder will mount the disk immediately. However, if no notification is given, the Finder won’t be aware that a disk needs to be mounted. On such systems, an application should invoke either mountNewRemovableMedia or checkForRemovableMedia before invoking mountedRemovableMedia. Either of these methods cause the Finder to poll the drives to see if a disk is present. If a disk has been inserted but not yet mounted, these methods will cause the Finder to mount it.

The Disk button in an Open or Save panel invokes mountedRemovableMedia and mountNewRemovableMedia as part of its operation, so most applications won’t need to invoke these methods directly.

See Also

mountNewRemovableMedia

Polls the system’s drives for any disks that have been inserted but not yet mounted, waits until the new disks have been mounted, and returns an NSArray of Strings containing full pathnames to all newly mounted disks.

public NSArray mountNewRemovableMedia()

Discussion

This method posts a WorkspaceDidMountNotification to the NSWorkspace’s notification center when it is finished. Currently provides the same functionality as mountedRemovableMedia.

See Also

noteFileSystemChanged

Informs NSWorkspace that the file system has changed.

public void noteFileSystemChanged()

Discussion

NSWorkspace then gets the status of all the files and directories it is interested in and updates itself appropriately. This method is used by many objects that write or delete files.

NSDocument and NSSavePanel use this method when saving a file. If you create a file directly, you should call noteFileSystemChanged so that the Finder can update the folder if it is open.

See Also

noteFileSystemChangedAtPath

Informs NSWorkspace that the file system specified by path has changed.

public void noteFileSystemChangedAtPath(String path)

Discussion

NSWorkspace then gets the status of all the files and directories it is interested in and updates itself appropriately. This method is used by many objects that write or delete files.

See Also

noteUserDefaultsChanged

Informs NSWorkspace that the defaults database has changed.

public void noteUserDefaultsChanged()

Discussion

NSWorkspace then reads all the defaults it is interested in and reconfigures itself appropriately. For example, this method is used by the Preferences application to notify the Finder whether the user prefers to see hidden files. Currently has no effect.

See Also

notificationCenter

Returns the notification center for workspace notifications.

public NSNotificationCenter notificationCenter()

openFile

Opens the file specified by fullPath using the appName application.

public boolean openFile(String fullPath, String appName, boolean flag)

Discussion

appName need not be specified with a full path and, in the case of an application wrapper, may be specified with or without the .app extension, as described in “Use of .app Extension”. If appName is null, the default application for the file’s type is used. If flag is true, the sending application is deactivated before the request is sent, allowing the opening application to become the active application. Returns true if the file is successfully opened, false otherwise.

Opens the file specified by fullPath using the appName application.

public boolean openFile(String fullPath, String appName)

Discussion

appName need not be specified with a full path and, in the case of an application wrapper, may be specified with or without the .app extension, as described in “Use of .app Extension”. The sending application is deactivated before the request is sent. Returns true if the file is successfully opened, false otherwise.

Opens the file specified by fullPath using the default application for its type.

public boolean openFile(String fullPath, NSImage anImage, NSPoint point, NSView aView)

Discussion

The Finder provides animation before opening the file to give the user feedback that the file is to be opened. To provide this animation, anImage should contain an icon for the file, and its image should be displayed at point, specified in the coordinates of aView.

The sending application is deactivated before the request is sent. Returns true if the file is successfully opened, false otherwise.

Opens the file specified by fullPath using the default application for its type; returns true if the file was successfully opened, false otherwise.

public boolean openFile(String fullPath)

Discussion

The sending application is deactivated before the request is sent.

openTempFile

Opens the temporary file specified by fullPath using the default application for its type.

public boolean openTempFile(String fullPath)

Discussion

The sending application is deactivated before the request is sent. Using this method instead of openFile lets the receiving application know that it should delete the file when it no longer needs it. Returns true if the file is successfully opened, false otherwise. Currently provides the same functionality as openFile.

See Also

openURL

Opens the location specified by url; returns true if the location was successfully opened, false otherwise.

public boolean openURL(java.net.URL url)

openURLs

Opens one or more files from an array of URLs.

public boolean openURLs(NSArray urls, String bundleIdentifier, int options, NSAppleEventDescriptor descriptor, NSMutableArray launchIdentifiers)

Discussion

The urls parameter contains an array of NSURL objects, each identifying one URL to open. The bundleIdentifier parameter contains the bundle identifier of the application to use to open the URLs, or NULL to use the default system bindings. Possible values for the options parameter are described in the constants section. To specify additional options using an AppleEvent-style descriptor, specify a value for the additionalEventParamDescriptor parameter.

If you specify a parameter for launchIdentifier, the method returns an array of unique identifiers (one for each URL) for this launch attempt. You can use these values to distinguish individual launch requests.

Availability

performFileOperation

Performs a file operation on a set of files in a particular directory.

public int performFileOperation(String operation, String source, String destination, NSArray files)

Discussion

operation is some file operation, such as compressing or moving files. files contains Strings specifying the names of the files to be manipulated. The filenames are given relative to the source directory. The list can contain both files and directories; all of them must be located directly within source (not in one of its subdirectories).

Some operations—such as moving, copying, and linking files—require a destination directory to be specified. If not, destination should be the empty string ("").

The possible values for operation are described in the "Constants" section.

This method returns a negative integer if the operation fails, 0 if the operation is performed synchronously and succeeds, and a positive integer if the operation is performed asynchronously. The positive integer identifies the requested file operation. Before this method returns, it posts a WorkspaceDidPerformFileOperationNotification to NSWorkspace’s notification center.

selectFile

Selects the file specified by fullPath.

public boolean selectFile(String fullPath, String rootFullPath)

Discussion

If a path is specified by rootFullPath, a new file viewer is opened. If rootFullPath is an empty string (""), the file is selected in the main viewer. Returns true if the file is successfully selected, false otherwise.

unmountAndEjectDeviceAtPath

Unmounts and ejects the device at path.

public boolean unmountAndEjectDeviceAtPath(String path)

Discussion

Returns true if the unmount operation succeeded, false otherwise. When this method begins, it posts a WorkspaceWillUnmountNotification to NSWorkspace’s notification center. When it is finished, it posts a WorkspaceDidUnmountNotification.

userDefaultsChanged

Returns whether a change to the defaults database has been registered with a noteUserDefaultsChanged message since the last userDefaultsChanged message.

public boolean userDefaultsChanged()

Discussion

Currently always returns false.

Constants

These constants specify different types of files:

Constant

Description

PlainFileType

Plain (untyped) file

DirectoryFileType

Directory

ApplicationFileType

Cocoa application

FilesystemFileType

File-system mount point

ShellCommandFileType

Executable shell command

The constants specify different types of file operations. They’re used by performFileOperation.

Constant

Description

MoveOperation

Move file to destination.

CopyOperation

Copy file to destination.

LinkOperation

Create hard link to file in destination.

CompressOperation

Compress file. Currently unavailable.

DecompressOperation

Decompress file. Currently unavailable.

EncryptOperation

Encrypt file. Currently unavailable.

DecryptOperation

Decrypt file. Currently unavailable.

DestroyOperation

Destroy file.

RecycleOperation

Move file to recycler.

DuplicateOperation

Duplicate file in source directory.

The following describes keys for an NSDictionary containing information about an application. This dictionary is returned by activeApplication and launchedApplications, and is also provided in the userInfo of NSWorkspace notifications for application launch and termination.

Key

Value

"NSApplicationPath"

The full path to the application, as a string.

"NSApplicationName"

The application's name, as a string.

"NSApplicationBundleIdentifier"

The application’s bundle identifier., as a string.

"NSApplicationProcessIdentifier"

The application's process id, as an integer.

"NSApplicationProcessSerialNumberHigh"

The high long of the process serial number (PSN), as an integer.

"NSApplicationProcessSerialNumberLow"

The low long of the process serial number (PSN), as an integer.

The following table describes launch options you can pass to openURLs.

Constant

Description

LaunchAndPrint

Print items instead of opening them.

LaunchInhibitingBackgroundOnly

Causes launch to fail if the target is background-only.

LaunchWithoutAddingToRecents

Do not add the application or documents to the Recents menu.

LaunchWithoutActivation

Launch the application but do not bring it into the foreground.

LaunchAsync

Launch the application and return the results asynchronously.

LaunchAllowingClassicStartup

Start up the Classic compatibility environment, if it is required by the application.

LaunchPreferringClassic

Force the application to launch in the Classic compatibility environment.

LaunchNewInstance

Create a new instance of the application, even if one is already running.

LaunchAndHide

Tell the application to hide itself as soon as it has finished launching.

LaunchAndHideOthers

Hide all applications except the newly launched one.

LaunchDefault

Launch the application asynchronously and launch it in the Classic environment, if required.

The following table describes the NSWorkspaceIconCreationOptions values. These values are combined using the C bitwise OR operator.

Constant

Description

NSExcludeQuickDrawElementsIconCreationOption

Supress generation of the QuickDraw format icon representations that are used Mac OS X v10.0 through v10.4.

Available in Mac OS X v10.4 and later.

NSExclude10_4ElementsIconCreationOption

Supress generation of the new higher resolution icon representations that are supported in Mac OS X v10.4.

Available in Mac OS X v10.4 and later.

Notifications

All NSWorkspace notifications are posted to NSWorkspace’s own notification center, not the application’s default notification center. Access this center using NSWorkspace’s notificationCenter method.

WorkspaceDidLaunchApplicationNotification

Posted when a new application has started up.

The notification object is the shared NSWorkspace instance. The userInfo dictionary contains the keys and values described in the constants section.

WorkspaceDidMountNotification

Posted when a new device has been mounted.

The notification object is the shared NSWorkspace instance. The userInfo dictionary contains the following information:

Key

Value

"NSDevicePath"

The path where the device was mounted, as a string.

WorkspaceDidPerformFileOperationNotification

Posted when a file operation has been performed in the receiving application.

The notification object is the shared NSWorkspace instance. The userInfo dictionary contains the following information:

Key

Value

"NSOperationNumber"

An integer indicating the type of file operation completed.

WorkspaceDidTerminateApplicationNotification

Posted when an application finishes executing.

The notification object is the shared NSWorkspace instance. The userInfo dictionary contains the keys and values described in the constants section.

WorkspaceDidWakeNotification

Posted when the machine wakes from sleep.

The notification object is the shared NSWorkspace instance. The notification does not contain a userInfo dictionary.

Availability

WorkspaceDidUnmountNotification

Posted when the Finder has unmounted a device.

The notification object is the shared NSWorkspace instance. The userInfo dictionary contains the following information:

Key

Value

"NSDevicePath"

The path where the device was previously mounted, as a string.

WorkspaceSessionDidBecomeActiveNotification

Posted after a user session is switched in. This allows an application to reenable some processing when a switched out session gets switched back in, for example.

The notification object is the shared NSWorkspace instance. The notification does not contain a userInfo dictionary.

Availability

WorkspaceSessionDidResignActiveNotification

Posted before a user session is switched out. This allows an application to disable some processing when its user session is switched out, and reenable when that session gets switched back in, for example.

The notification object is the shared NSWorkspace instance. The notification does not contain a userInfo dictionary.

If an application is launched in an inactive session, WorkspaceSessionDidResignActiveNotification is sent after ApplicationWillFinishLaunchingNotification and before sending ApplicationDidFinishLaunchingNotification.

Availability

WorkspaceWillLaunchApplicationNotification

Posted when the Finder is about to launch an application.

The notification object is the shared NSWorkspace instance. The userInfo dictionary contains the keys and values described in the constants section.

WorkspaceWillPowerOffNotification

Posted when the user has requested a logout or that the machine be powered off.

The notification object is the shared NSWorkspace instance. This notification does not contain a userInfo dictionary.

WorkspaceWillSleepNotification

Posted before the machine goes to sleep. An observer of this message can delay sleep for up to 30 seconds while handling this notification.

The notification object is the shared NSWorkspace instance. The notification does not contain a userInfo dictionary.

Availability

WorkspaceWillUnmountNotification

Posted when the Finder is about to unmount a device. This notification will not be delivered if a volume was forcibly and immediately made unavailable, such as when a FireWire drive is simply unplugged, because there is no chance to deliver it before the volume becomes unavailable.

The notification object is the shared NSWorkspace instance. The userInfo dictionary contains the following information:

Key

Value

"NSDevicePath"

The path where the device is mounted, as a string.



Next Page > Hide TOC


© 1997, 2007 Apple Inc. All Rights Reserved. (Last updated: 2007-02-01)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.