7. Application Objects
Creating application objects
Before you can communicate with a scriptable application you must create an Application
object, for example:
textedit = app.by_id('com.apple.textedit')
To target an application you must call one of the app
object's by_*
methods with the appropriate argument:
app.by_name(name)
/app(name)
- The application's filename or POSIX path, e.g.
'TextEdit'
,'TextEdit.app'
,'/Applications/TextEdit.app'
. Where a filename is provided, appscript uses LaunchServices to locate the application. An.app
suffix is optional. e.g. Given the name'TextEdit'
, appscript first searches for an application with that exact filename; if none is found, it automatically adds an.app
suffix ('TextEdit.app'
) and tries again. app.by_id(id)
- The application's bundle id, e.g.
'com.apple.textedit'
. Cocoa applications often have unique bundle ids. app.by_creator(creator)
- A four-character string containing the application's creator type, e.g.
'ttxt'
. Older Carbon-based applications and some Cocoa-based applications have unique creator types. app.by_pid(pid)
- A valid Unix process id, e.g.
5687
. app.by_url(url)
- A URL of form
eppc://[user[:password]@host/Application%20Name[?[uid=#]&[pid=#]
, e.g.eppc://johnsmith:foobar@office-mac.local/TextEdit?uid=501
. The host name/IP address and the process name (case-sensitive) are required. The username and password are optional: if omitted, the OS will obtain this information from the user's keychain or display a dialog asking the user to input one or both values. The user id and process id are also optional; if the process id is given, the process name will be ignored. app.by_aem_app(aem_app)
- An
AEM::Application
instance. app.current
- The host application.
Examples:
require "appscript"
include Appscript
ical = app('iCal')
textedit = app('TextEdit.app')
safari = app('/Applications/Safari')
addressbook = app.by_id('com.apple.addressbook')
quicktimeplayer = app.by_creator('TVOD')
finder = app.by_url('eppc://192.168.10.1/Finder')
itunes = app.by_url('eppc://Jan%20Smith@G4.local/iTunes')
Basic commands
All applications should respond to the following commands:
run -- Run an application. Most applications will open an empty,
untitled window.
launch -- Launch an application without sending it a 'run' event.
Applications that normally open a new, empty document
upon launch won't. [1]
activate -- Bring the application to the front.
reopen -- Reactivate a running application. Some applications
will open a new untitled window if no window is open.
open(value) -- Open the specified object(s).
anything -- list of objects to open, typically a list of
MacTypes::Alias
print(value) -- Print the specified object(s).
anything -- list of objects to print, typically a list of
MacTypes::Alias
quit(saving => value) -- Quit an application.
saving : :yes | :ask | :no -- specifies whether to save
currently open documents
[1] The launch
command should be used before constructing references or sending other commands, otherwise appscript will run the application normally.
Some applications may provide their own definitions of some or all of these commands, so check their terminology before use.
Appscript also defines get
and set
commands for any scriptable application that doesn't supply its own definitions:
get(value) -- Get the data for an object.
reference -- the object for the command
Result: anything -- the reply for the command
set(value, :to => value) -- Set an object's data.
reference -- the object for the command
to : anything -- The new value.
Note that these commands are only useful in applications that define an Apple Event Object Model as part of their Apple event interface.
Transaction support
Application objects implement three additional methods, begin_transaction
, end_transaction
and abort_transaction
that allow a sequence of related commands to be handled as a single operation by applications that support transactions, e.g. FileMaker Pro.
Once the application object's begin_transaction
method is called, all subsequent commands to that application will be sent as part of the same transaction until end_transaction
or abort_transaction
is called.
The begin_transaction
method takes an optional session
argument that indicates the specific transaction session to open (in applications that support this).
Remember to call end_transaction
or abort_transaction
at the end of every transaction. (This includes transactions interrupted by a raised exception.) If a transaction is accidentally left open, appscript will try to end it automatically when the application object is garbage-collected, but this is not guaranteed to succeed.
Local application launching notes
Note: the following information only applies to local applications as appscript cannot directly launch applications on a remote Mac. To control a remote application, the application must be running beforehand or else launched indirectly (e.g. by using the remote Mac's Finder to open it).
How applications are identified
When you create an Application object by application name, bundle id or creator type, appscript uses LaunchServices to locate an application matching that description. If you have more than one copy of the same application installed, you can identify the one you want by providing its full path, otherwise LaunchServices will identify the newest copy for you.
Appscript identifies running applications by their process ids so it's possible to control multiple versions of an application running at the same time if their Application objects are created using process ids or eppc URLs.
Checking if an application is running
You can check if the application specified by an Application object is currently running by calling its #is_running?
method. This is useful if you don't want to perform commands on an application that isn't already running. For example:
te = app('TextEdit')
# Only perform TextEdit-related commands if it's already running:
if te.is_running?
# all TextEdit-related code goes here...
end
Remember that appscript automatically launches a non-running application the first time your script makes reference to any of its properties, elements or commands. To avoid accidental launches, all code relating to that application must be included in a conditional block that only executes if #is_running?
returns true
.
Launch errors
If the application can't be launched for some reason (e.g. if it's in the Trash), an Appscript::CantLaunchApplicationError
error will be raised. This provides a description of the problem (if it's a standard LaunchServices error) along with the original OS error number, which you can also obtain via the CantLaunchApplicationError#to_i
method.
Using launch
vs run
When appscript launches a non-running application, it normally sends it a run
command as part of the launching process. If you wish to avoid this, you should start the application by sending it a launch
command before doing anything else. For example:
te = app('TextEdit')
te.launch
# other TextEdit-related code goes here...
This is useful when you want to start an application without it going through its normal startup procedure. For example, the above script will launch TextEdit without causing it to display a new, empty document (its usual behaviour).
launch
is also useful if you need to send a non-running application an open
command as its very first instruction. For example, to send an open
command to a non-stay-open application that batch processes one or more dropped files then quits again, you must first start it using launch
, then send it an open
command with the files to process. If you forget to do this, the application will first receive a run
command and quit again before the open
command can be handled.
Restarting applications
As soon as you start to construct a reference or command using a newly created Application objects, if the application is not already running then appscript will automatically launch it in order to obtain its terminology.
If the target application has stopped running since the Application object was created, trying to send it a command using that Application object will result in an invalid connection error (-609), unless that command is run
or launch
. This restriction prevents appscript accidentally restarting an application that has unexpectedly quit while a script is controlling it. Scripts can restart an application by sending an explicit run
or launch
command, or by creating a new Application object for it.
Note that you can still use Application objects to control applications that have been quit and restarted since the Application object was created. Appscript will automatically update the Application object's process id information as needed.
There is a known problem with quitting and immediately relaunching an application via appscript, where the relaunch instruction is sent to the application before it has actually quit. This timing issue appears to be the OS's fault; the current workaround for scripts that need to quit and restart applications is to insert a few seconds' delay between the quit
and run
/launch
using Ruby's sleep
function.