ADOBE® CREATIVE SUITE® 5 JAVASCRIPT TOOLS GUIDE
© 2010 Adobe Systems Incorporated. All rights reserved. Adobe® Creative Suite® 5 JavaScript Tools Guide for Windows® and Macintosh®. NOTICE: All information contained herein is the property of Adobe Systems Incorporated. No part of this publication (whether in hardcopy or electronic form) may be reproduced or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written consent of Adobe Systems Incorporated.
Contents 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 ExtendScript overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Example code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Development and debugging tools . .
File error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 File access error messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 File- and Folder-supported encoding names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Additional encodings . . . . . . . . . . . . .
The AutoLayoutManager algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Automatic layout restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Managing control titles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Title alignment and orientation . . . . . . . . . . . . . . . .
AutoLayoutManager object functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 5 Interapplication Communication with Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 Communications overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 Remote function calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Defining entry points for indirect access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Shared-library function API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 Support structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 8 ExtendScript Tools and Features . . . . . . . . . . . .
XMPScript object reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 XMPAliasInfo object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 XMPConst object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 XMPDateTime object . . . . . . . . . . . . .
1 Introduction JavaScript is a platform-independent scripting language that you can use to control many features and automate many tasks in Adobe® applications. Scripting is easier to learn and use than many other kinds of programming, and provides a convenient way of automating repetitive tasks or extending applications to provide additional tools for other users.
CHAPTER 1: Introduction ExtendScript overview 10 The samples are located under the ExtendScript SDK root directory: SDKroot/Samples/javascript/ SDKroot/Samples//javascript/resources/ sample scripts resources, such as image or flash files Development and debugging tools For help in developing, debugging, and testing scripts, Adobe provides the ExtendScript Toolkit, an interactive development and testing environment for ExtendScript, which is installed with all JavaScript-enabled applications.
CHAPTER 1: Introduction ExtendScript overview 11 In addition to the basic set of common functions, some applications provide more extensive sets of exported JavaScript functions to other applications. X The interapplication messaging framework is an application programming interface (API) that allows extensive control over communication between applications.
CHAPTER 1: Introduction Scripting for specific applications 12 Scripting for specific applications On startup, all Adobe JavaScript-enabled applications execute JSX files that they find in their startup directories; some of these are installed by applications, and some can be installed by scripters. The policies of different applications vary as to the locations, write access, and loading order.
2 The ExtendScript Toolkit The ExtendScript Toolkit provides an interactive development and testing environment for ExtendScript in all JavaScript-enabled Adobe applications. It includes a full-featured, syntax-highlighting text editor with Unicode capabilities and multiple undo/redo support. The Toolkit is the default editor for ExtendScript files, which use the extension .jsx.
CHAPTER 2: The ExtendScript Toolkit Configuring the Toolkit window 14 You can, for example, adjust the relative sizes of the panels by dragging the separators up or down, or right or left, and can rearrange the groupings. To move a tabbed panel, drag the tab into another pane. If you drag a tab so that the entire destination group is highlighted, it becomes another stacked panel in that group.
CHAPTER 2: The ExtendScript Toolkit Configuring the Toolkit window 15 Document windows When you open scripts or text files, each file appears in its own Script Editor document window. By default, the document windows are docked; that is, shown as tabbed panes in the main window. However, like the panels, you can drag any document window out of the frame to make it an independent floating window.
CHAPTER 2: The ExtendScript Toolkit Configuring the Toolkit window 16 Workspaces The Toolkit saves the current layout when you exit, and restores it at the next startup. It saves and restores the open documents, the current positions within the documents, any breakpoints that have been set, and other preferences that have been set in the Preferences dialog.
CHAPTER 2: The ExtendScript Toolkit Selecting scripts 17 Selecting scripts You can open multiple scripts (or text files, including programs in other languages). You can find and open scripts in a number of ways: X Use File > Open to bring up the platform-specific file browser. X Choose from recently opened files using File > Recent files. X Create a new script using File > New JavaScript. X Drop files from the Explorer or the Finder onto the Toolkit to open them in a document window.
CHAPTER 2: The ExtendScript Toolkit The Script Editor 18 The favorite script locations that you define are also available to the Find and Replace dialog; see “Searching in text” on page 24. You can also examine and set favorite locations using the Favorites page of the Preferences dialog (Edit > Preferences). Use the Add, Modify, and Remove buttons to edit the list of folders. Adobe Scripts folder On first launch, the Toolkit creates a folder named Adobe Scripts in the user's Documents folder.
CHAPTER 2: The ExtendScript Toolkit The Script Editor X A full-featured text search tool that can search in multiple files; see “Searching in text” on page 24. X Syntax marking (color and font styles for specific syntactic structures) for JavaScript and for many other computer languages. The marking styles are configurable; see “Syntax marking” on page 26.
CHAPTER 2: The ExtendScript Toolkit The Script Editor 20 Bookmarks The Edit > Bookmarks menu allows you to set and clear navigation points in your text. The F2 function key is the default shortcut key for the bookmark commands: X Toggle the bookmark for the current line using CTRL-F2. X Move the cursor to the next bookmark with F2, or to the previous one with SHIFT-F2. The bookmarks wrap, so that the first follows the last. X Use SHIFT-CTRL-F2 to clear all bookmarks in the current text.
CHAPTER 2: The ExtendScript Toolkit The Script Editor 21 line numbers bookmark collapsible code sections bookmark and breakpoint Mouse navigation and selection You can use the mouse or special keyboard shortcuts to move the insertion point or to select text in the document window. Click the left mouse button in the document window to move the position caret. To select text with the mouse, click in unselected text, then drag over the text to be selected.
CHAPTER 2: The ExtendScript Toolkit The Script Editor Right arrow Move insertion point right one character Up arrow Move insertion point up one line; stay in column if possible Down arrow Move insertion point down one line; stay in column if possible Page up Move insertion point one page up Page down Move insertion point one page down CTRL + Up arrow Scroll up one line without moving the insertion point CTRL + Down arrow Scroll down one line without moving the insertion point CTRL + Page up
CHAPTER 2: The ExtendScript Toolkit The Script Editor 23 You can use the flyout menu at the upper right corner of the document window to choose an object-model dictionary to use for completion. Available dictionaries depend on which applications are loaded. See “Inspecting object models” on page 36.
CHAPTER 2: The ExtendScript Toolkit The Script Editor 24 /** * @@@BUILDINFO@@@ SnpCreateDialog.jsx !Version! Tue Dec 05 2006 08:03:38 GMT-0800 */ You are responsible for manually updating the !Version! portion with your own version information. Undo and redo Choose Undo or Redo from the Edit menu or from the document window’s right-click context menu to revoke and reinstate multiple editing changes sequentially.
CHAPTER 2: The ExtendScript Toolkit The Script Editor 25 X All scripts made public by the current target application X Folders that you have defined as favorite locations; see “The Scripts panel and favorite script locations” on page 17. The results of a search are listed in the Find Results tab; by default, this is stacked with the Find and Replace panel, but you can drag it to another stack, or display it as an independent floating panel.
CHAPTER 2: The ExtendScript Toolkit The Script Editor \x Escapes a character x that would otherwise have a special meaning. For example, \[ is interpreted as a left bracket, rather than the start of a character set. [...] A set of characters; for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character. [^...] The complement of the characters in a set. For example, [^A-Za-z] means any character except an alphabetic character.
CHAPTER 2: The ExtendScript Toolkit Debugging in the Toolkit 27 Select language for syntax highlighting in Script Editor Customize highlighting styles in Preferences dialog Debugging in the Toolkit You can debug the code in the currently active document window. Select one of the debugging commands to either run or to single-step through the program. When you run code from the document window, it runs in the current target application’s selected JavaScript engine.
CHAPTER 2: The ExtendScript Toolkit Debugging in the Toolkit 28 executing code, is halted at a breakpoint, or, having executed all scripts, is waiting to receive events. An icon by each engine name indicates whether it is running, halted, or waiting for input: running halted waiting The current engine is the one whose data and state is displayed in the Toolkit’s panes. If an application has only one engine, its engine becomes current when you select the application as the target.
CHAPTER 2: The ExtendScript Toolkit Debugging in the Toolkit 29 The console is a JavaScript listener, that expects input text to be JavaScript code. You can use the console to evaluate expressions or call functions. Enter any JavaScript statement and execute it by pressing ENTER. The statement executes within the stack scope of the line highlighted in the Call Stack panel, and the result appears in the next line.
CHAPTER 2: The ExtendScript Toolkit Debugging in the Toolkit 30 Visual indication of execution states When the execution of a script halts because the script reached a breakpoint, or when the script reaches the next line when stepping line by line, the document window displays the current script with the current line highlighted in yellow.
CHAPTER 2: The ExtendScript Toolkit Debugging in the Toolkit 31 Setting breakpoints When debugging a script, it is often helpful to make it stop at certain lines so that you can inspect the state of the environment, whether function calls are nested properly, or whether all variables contain the expected data. X To stop execution of a script at a given line, click to the left of the line number to set a breakpoint. A red dot indicates the breakpoint.
CHAPTER 2: The ExtendScript Toolkit Debugging in the Toolkit condition statement. You can also specify a hit count, which allows you to skip the breakpoint some number of times before entering the debugger. The default is 1, which breaks at the first execution. When execution reaches this breakpoint after the specified number of hits, the debugger evaluates this condition. If it does not evaluate to true, the breakpoint is ignored and execution continues.
CHAPTER 2: The ExtendScript Toolkit Debugging in the Toolkit 33 Evaluation in help tips If you let your mouse pointer rest over a variable or function in a document window, the result of evaluating that variable or function is displayed as a help tip. When you are not debugging the program, this is helpful only if the variables and functions are already known to the JavaScript engine.
CHAPTER 2: The ExtendScript Toolkit Debugging in the Toolkit 34 Boolean Number String Object Method null You can inspect the contents of an object by clicking its icon. The list expands to show the object’s properties (and methods, if Functions display is enabled), and the triangle points down to indicate that the object is open. The call stack The Call Stack panel is active while debugging a program.
CHAPTER 2: The ExtendScript Toolkit Code profiling for optimization 35 Switching between the functions in the call hierarchy allows you to trace how the current function was called. The Console and Data Browser panels coordinate with the Call Stack panel. When you select a function in the Call Stack: X The Console panel switches its scope to the execution context of that function, so you can inspect and modify its local variables.
CHAPTER 2: The ExtendScript Toolkit Inspecting object models Show Hit Count When selected, display hit counts. Show Timing When selected, display timing data. Erase Profiler Data Clear all profiling data. Save Data As Save profiling data as comma-separated values in a CSV file that can be loaded into a spreadsheet program such as Excel. 36 When execution halts (at termination, at a breakpoint, or due to a runtime error), the Toolkit displays this information in the Document Window, line by line.
CHAPTER 2: The ExtendScript Toolkit Inspecting object models 37 The Object Model Viewer (OMV) comes up as a separate, floating window. The OMV allows you to browse through the object hierarchy and inspect the type and description of each property, and the description and parameters for each method. The drop-down menu in the Browser section at the top left allows you to choose from any loaded dictionary of objects. A dictionary provides access to the object model for one application or subsystem.
CHAPTER 2: The ExtendScript Toolkit X Inspecting object models 38 Each Adobe application defines a dictionary for that application’s Document Object Model (DOM). The dictionary for a particular application may not be available until you launch that application, or until you select it as a target in the Toolkit. To inspect an object model, select the appropriate dictionary from the Browser menu. The classes defined in that model appear in the Classes panel.
3 File System Access Adobe ExtendScript defines classes that simplify cross-platform file-system access. These classes are available to all applications that support a JavaScript interface. X The first part of this chapter, Using File and Folder objects, describes how to use these classes and provides details of pathname syntax. X “File object” on page 47 and “Folder object” on page 56 provide reference details of the objects, properties, methods, and creation parameters.
CHAPTER 3: File System Access Using File and Folder objects 40 Absolute and relative path names An absolute path name in URI notation describes the full path from a root directory down to a specific file or folder. It starts with one or two slashes (/), and a slash separates path elements. For example, the following describes an absolute location for the file myFile.jsx: /dir1/dir2/mydir/myFile.
CHAPTER 3: File System Access Using File and Folder objects 41 The home directory A path name can start with a tilde (~) to indicate the user’s home directory. It corresponds to the platform’s HOME environment variable. UNIX and Mac OS assign the HOME environment variable according to the user login. On Mac OS, the default home directory is /Users/username. In UNIX, it is typically /home/username or /users/username. ExtendScript assigns the home directory value directly from the platform value.
CHAPTER 3: File System Access Using File and Folder objects 42 a folder C:\C on Windows. A path starting with /c always addresses the drive C:, so in this case, to access the folder by name, you must use both the drive name and the folder name, for example /c/c for C:\C. If the current drive contains a root folder with the same name as another drive letter, that name is considered to be a folder.
CHAPTER 3: File System Access Using File and Folder objects 43 As an example, suppose you use the UNIX machine myServer for data storage. If you set up an alias share in the root directory of myServer, and if you set up a Windows-accessible share at share pointing to the same data location, the path name //myServer/share/file would work for all three platforms. Unicode I/O When doing file I/O, Adobe applications convert 8-bit character encoding to Unicode.
CHAPTER 3: File System Access File access error messages File access error messages The following messages can be returned in the error property. File or folder does not exist The file or folder does not exist, but the parent folder exists. File or folder already exists The file or folder already exists. I/O device is not open An I/O operation was attempted on a file that was closed. Read past EOF Attempt to read beyond the end of a file.
CHAPTER 3: File System Access File- and Folder-supported encoding names 45 File- and Folder-supported encoding names The following list of names is a basic set of encoding names supported by the File object. Some of the character encoders are built in, while the operating system is queried for most of the other encoders. Depending on the language packs installed, some of the encodings may not be available. Names that refer to the same encoding are listed in one line.
CHAPTER 3: File System Access File- and Folder-supported encoding names Common encoding names The following encoding names are implemented both in Windows and in Mac OS: UTF-7,UTF7,UNICODE-1-1-UTF-7,X-UNICODE-2-0-UTF-7 ISO-8859-2,ISO-8859-2,ISO-8859-2:1987,ISO-IR-101,LATIN2 ISO-8859-3,ISO-8859-3,ISO-8859-3:1988,ISO-IR-109,LATIN3 ISO-8859-4,ISO-8859-4,ISO-8859-4:1988,ISO-IR-110,LATIN4,BALTIC ISO-8859-5,ISO-8859-5,ISO-8859-5:1988,ISO-IR-144,CYRILLIC ISO-8859-6,ISO-8859-6,ISO-8859-6:1987,ISO-IR-127,ECMA-114,
CHAPTER 3: File System Access File object 47 Additional Mac OS encoding names These names are alias names for encodings that Mac OS might know. TIS-620,TIS620,TIS620-0,TIS620.2529-1,TIS620.2533-0,TIS620.2533-1,ISO-IR-166 CP874,WINDOWS-874 JP,JIS-C6220-1969-RO,ISO646-JP,ISO-IR-14 JIS-X0201,JISX0201-1976,X0201 JIS-X0208,JIS-X0208-1983,JIS-X0208-1990,JIS0208,X0208,ISO-IR-87 JIS-X0212,JIS-X0212.
CHAPTER 3: File System Access File object 48 File class properties This property is available as a static property of the File class. It is not necessary to create an instance to access it. fs String The name of the file system. Read only. One of Windows, Macintosh, or Unix. File class functions These functions are available as static methods of the File class. It is not necessary to create an instance to call them. decode() File.decode (uri) uri String. The encoded string to decode.
CHAPTER 3: File System Access File object 49 openDialog() File.openDialog ([prompt, filter, multiSelect]) prompt Optional. A string containing the prompt text, if the dialog allows a prompt. filter Optional. A filter that limits the types of files displayed in the dialog. multiSelect X In Windows, a filter expression, such as "JavaScript:*.jsx;All files:*.
CHAPTER 3: File System Access encoding File object String Gets or sets the encoding for subsequent read/write operations. One of the encoding constants listed in “File- and Folder-supported encoding names” on page 45. If the value is not recognized, uses the system default encoding. A special encoder, BINARY, is used to read binary files. It stores each byte of the file as one Unicode character regardless of any encoding.
CHAPTER 3: File System Access File object relativeURI String The path name for the referenced file in URI notation, relative to the current folder. Read only. type String The file type as a four-character string. X In Mac OS, the Mac OS file type. X In Windows, "appl" for .EXE files, "shlb" for .DLL files and "TEXT" for any other file. If the file does not exist, the value is "????". Read only. File object functions These functions are available for File objects. changePath() fileObj.
CHAPTER 3: File System Access File object 52 execute() fileObj.execute () Opens this file using the appropriate application, as if it had been double-clicked in a file browser. You can use this method to run scripts, launch applications, and so on. Returns true immediately if the application launch was successful. getRelativeURI() fileObj.getRelativeURI ([basePath]) basePath Optional. A string containing the base path for the relative URI. Default is the current folder.
CHAPTER 3: File System Access File object openDlg() fileObj.OpenDlg ([prompt][,filter][,multiSelect]) prompt Optional. A string containing the prompt text, if the dialog allows a prompt. filter Optional. A filter that limits the types of files displayed in the dialog. multiSelect X In Windows, a filter expression, such as "JavaScript:*.jsx;All files:*.*" X In Mac OS, a filter function that takes a File instance and returns true if the file should be included in the display, false if it should not.
CHAPTER 3: File System Access File object remove() fileObj.remove () Deletes the file associated with this object from disk, immediately, without moving it to the system trash. Does not resolve aliases; instead, deletes the referenced alias or shortcut file itself. NOTE: Cannot be undone. It is recommended that you prompt the user for permission before deleting. Returns true if the file is deleted successfully. rename() fileObj.rename (newName) newName The new file name, with no path.
CHAPTER 3: File System Access File object seek() fileObj.seek (pos[, mode]) pos The new current position in the file as an offset in bytes from the start, current position, or end, depending on the mode. mode Optional. The seek mode, one of: X 0: Seek to absolute position, where pos=0 is the first byte of the file. This is the default. X 1: Seek relative to the current position. X 2: Seek backward from the end of the file. Seeks to the specified position in the file.
CHAPTER 3: File System Access Folder object Folder object Represents a file-system folder or directory in a platform-independent manner. All properties and methods resolve file system aliases automatically and act on the original file unless otherwise noted. Folder object constructors To create a Folder object, use the Folder function or the new operator. The constructor accepts full or partial path names, and returns the new object.
CHAPTER 3: File System Access desktop Folder object Folder A Folder object for the folder that contains the user’s desktop. Read only. X In Windows, C:\Documents and Settings\username\Desktop X In Mac OS, ~/Desktop fs String The name of the file system. Read only. One of Windows, Macintosh, or Unix. myDocuments Folder A Folder object for the user’s default document folder. Read only.
CHAPTER 3: File System Access Folder object Folder class functions These functions are available as a static methods of the Folder class. It is not necessary to create an instance in order to call them. decode() Folder.decode (uri) uri String. The encoded string to decode. All special characters must be encoded in UTF-8 and stored as escaped characters starting with the percent sign followed by two hexadecimal digits. For example, the string "my%20file" is decoded as "my file".
CHAPTER 3: File System Access Folder object Folder object properties These properties are available for Folder objects. absoluteURI String The full path name for the referenced folder in URI notation. Read only. alias Boolean When true, the object refers to a file system alias or shortcut. Read only. created Date The creation date of the referenced folder, or null if the object does not refer to a folder on disk. Read only.
CHAPTER 3: File System Access Folder object create() folderObj.create () Creates a folder at the location given by this object’s path property. Returns true if the folder was created successfully. execute() folderObj.execute () Opens this folder in the platform-specific file browser (as if it had been double-clicked in the file browser). Returns true immediately if the folder was opened successfully. getFiles() folderObj.getFiles ([mask]) mask Optional. A search mask for file names.
CHAPTER 3: File System Access Folder object rename() folderObj.rename (newName) newName The new folder name, with no path. Renames the associated folder. Does not resolve aliases; instead, renames the referenced alias or shortcut file itself. Returns true on success. resolve() folderObj.
4 User-Interface Tools Adobe provides the ScriptUI component, which works with the ExtendScript JavaScript interpreter to provide JavaScript scripts with the ability to create and interact with user interface elements. It provides an object model for windows and user-interface control elements within an Adobe application. X The first part of this chapter describes the features and programming model, with details of how you can use JavaScript to build a user interface with ScriptUI objects.
CHAPTER 4: User-Interface Tools ScriptUI programming model SnpCreateDynamicScriptUI.jsx Shows how to use automatic layout, switching component layout between “row” and “stack” orientation. AlertBoxBuilder1.jsx Shows a way to use resource specifications. Uses the add() method to build a dialog that collects values from the user, and creates a resource string from those values. Saves the string to a file, then uses it to build a new dialog. See “Using resource strings” on page 79. AlertBoxBuilder2.
CHAPTER 4: User-Interface Tools ScriptUI programming model 64 Container elements All Windows are containers—that is, they contain other elements within their bounds. Within a Window, you can create other types of container elements: Panels and Groups. These can contain control elements, and can also contain other Panel and Group containers. However, a Window cannot be added to any container. X A Group is the simplest container used to visually organize related controls.
CHAPTER 4: User-Interface Tools ScriptUI programming model 65 The following examples show equivalent ways of changing an existing window’s width and height to 200 and 100: win.size = [200, 100]; win.size = {width:200, height:100}; win.size = "width:200, height:100"; This example shows how to change a window’s height to 100, leaving its location and width unchanged: win.size.
CHAPTER 4: User-Interface Tools ScriptUI programming model 66 The order of optional parameters must be maintained. Use the value undefined for a parameter you do not wish to set. For example, if you want to use automatic layout to determine the bounds, but still set the title and text in a panel and button, the following creates Panel and Button elements with an initial text value, but no bounds value: dlg.btnPnl = dlg.add(’panel’, undefined, ’Build it’); dlg.btnPnl.testBtn = dlg.btnPnl.
CHAPTER 4: User-Interface Tools Types of controls 67 If you use a creation property to assign a name to a newly created element, you can access that child by its name, either in the children array of its parent, or directly as a property of its parent. For example, the Button in a previous example was named ok, so it can be referenced as follows: dlg.btnPnl.children['ok'].text = "Build"; dlg.btnPnl.ok.
CHAPTER 4: User-Interface Tools Types of controls Group Used to visually organize related controls. Unlike Panels, Groups have no title or visible border. You can use them to create hierarchies of controls, and for fine control over layout attributes of certain groups of controls within a larger panel. For examples, see “Creating more complex arrangements” on page 92. TabbedPanel A panel that contains only Tab objects as its immediate children.
CHAPTER 4: User-Interface Tools Image StaticText Types of controls Displays an iconic image. X The image property identifies the icon image; see “Displaying images” on page 72. X The title property provides an optional label; the titleLayout property places the label with respect to the image. Typically used to display text strings that are not intended for direct manipulation by a user, such as informative messages or labels.
CHAPTER 4: User-Interface Tools Checkbox Types of controls Allows the user to set a boolean state. X Set the text property to assign an identifying text string that appears next to the clickable box. X The user can click to select or deselect the box, which shows a checkmark when selected. The value is true when it is selected (checked) and false when it is not. When you create a Checkbox, you can set its value property to specify its initial state and appearance.
CHAPTER 4: User-Interface Tools Scrollbar Types of controls Like a slider, the scrollbar is a bar with a draggable indicator. It also has “stepper” buttons at each end, that you can click to jump the indicator by the amount in the stepdelta property. If you click a point on the bar outside the indicator, the indicator jumps by the amount in the jumpdelta property.
CHAPTER 4: User-Interface Tools ListItem FlashPlayer Types of controls 72 Items added to or inserted into any type of list control are ListItem objects, with properties that can be manipulated from a script. ListItem elements can be of the following types: X item: the typical item in any type of list. It displays text or an image, and can be selected. To display an image, set the item object’s image property; see “Displaying images” on page 72.
CHAPTER 4: User-Interface Tools Types of controls 73 If a script does not explicitly set the preferredSize or size property of an element that displays a icon image, the value of preferredSize is determined by the dimensions of the iconic image. If the size values are explicitly set to dimensions smaller than those of the actual image graphic, the displayed image is clipped. If they are set to dimensions larger than those of the image graphic, the displayed image is centered in the larger space.
CHAPTER 4: User-Interface Tools Types of controls 74 Notice that the columns have headers, and the label in the second column of the second row has both text and an image. Prompts and alerts Static functions on the Window class are globally available to display short messages in standard dialogs. The host application controls the appearance of these simple dialogs, so they are consistent with other alert and message boxes displayed by the application.
CHAPTER 4: User-Interface Tools Types of controls 75 closed. If the function returns true, the window is closed, but if it returns false, the close operation is cancelled and the window remains open. Your onClose handler can examine the states of any controls in the dialog to determine their correctness, and can show alert messages or use other modal dialogs to alert the user to any errors that must be corrected.
CHAPTER 4: User-Interface Tools Size and location objects 76 a button whose name or text value is "cancel" (disregarding case). Because it looks at the name value first, this works even if the text value is localized. If there is no suitable button in the dialog, the property value remains null, which means that the keyboard shortcut has no effect in that dialog.
CHAPTER 4: User-Interface Tools Bounds Drawing objects 77 Defines the boundaries of a window within the screen’s coordinate space, or of a user-interface element within the container’s coordinate space. Contains an array, [left, top, right, bottom], that defines the coordinates of the upper left and lower right corners of the element. A Bounds object is created when you set an element’s bounds property, and this property returns a Bounds object.
CHAPTER 4: User-Interface Tools Resource specifications ScriptUIGraphics Encapsulates the drawing methods. The graphics object is associated with each control is found in the control object’s graphics property. ScriptUIBrush Describes the brush used to paint textures in a control. ScriptUIFont Describes the font used to write text into a control. ScriptUIImage Describes an image to be drawn in a control. ScriptUIPath Describes a drawing path for a figure to be drawn into a control.
CHAPTER 4: User-Interface Tools Resource specifications 79 testBtn: Button { text: ’Test’ } The following resource string specifies a panel that contains grouped StaticText and EditText controls: "msgPnl: Panel { orientation:’column’, alignChildren:[’right’, ’top’],\ text: ’Messages’, \ title: Group { \ st: StaticText { text:’Alert box title:’ }, \ et: EditText { text:’Sample Alert’, characters:35 } \ } msg: Group { \ st: StaticText { text:’Alert message:’ }, \ et: EditText { properties:{multiline:true}
CHAPTER 4: User-Interface Tools Defining behavior with event callbacks and listeners 80 The Build button event handler builds a resource string from the collected values, and returns it from the dialog invocation function; the script then saves the resource string to a file. That resource string can later be used to create and display the user-configured alert box. The resource specification format can also be used to create a single element or container and its child elements.
CHAPTER 4: User-Interface Tools Defining behavior with event callbacks and listeners 81 X Button, RadioButton, and Checkbox controls generate events when the user clicks within the control bounds. To handle the event, define a callback function for onClick. X EditText, Scrollbar, and Slider controls generate events when the content or value changes—that is, when the user types into an edit field, or moves the scroll or slider indicator.
CHAPTER 4: User-Interface Tools Defining behavior with event callbacks and listeners 82 Simulating user events You can simulate user actions by sending an event notification directly to a window or control with the notify method. A script can use this method to generate events in the controls of a window, as if a user was clicking buttons, entering text, or moving the window. If you have defined an event-handler callback for the element, the notify method invokes it.
CHAPTER 4: User-Interface Tools Defining behavior with event callbacks and listeners 83 myButton.addEventListener( ’click’, myFunction ); X A locally defined handler function that takes one argument, the event object. For example: myButton.addEventListener( ’click’, ’function(e){/*handler code*/}’); The handler or registered code statement is executed when the specified event occurs in the target. A script can programmatically simulate an event by creating an event objects with ScriptUI.events.events.
CHAPTER 4: User-Interface Tools Defining behavior with event callbacks and listeners 84 The ScriptUI implementation of W3C mouse events follows the W3C DOM level 3 functional specification (http://www.w3.org/TR/DOM-Level-3-Events/events.html#Events-eventgroupings-mouseevents), with these differences: X To create a MouseEvent instance, call ScriptUI.events.createEvent('MouseEvent'), rather than DocumentEvent.createEvent('MouseEvent').
CHAPTER 4: User-Interface Tools Communicating with the Flash application 85 the bubbling phase. For example, the following click handler, registered with the parent dialog object, responds only in the capture phase: myDialog.addEventListener("click", handleAllItems, true); This value is false by default, so if it is not supplied, the handler can respond only in the bubbling phase when the object’s descendent is the target, or when the object is itself the target of the event (the at-target phase).
CHAPTER 4: User-Interface Tools Automatic layout 86 You do not need to register the ExtendScript function in the ActionScript environment. Your ActionScript script can simply call the external function using the ExternalInterface.call() method: var res = ExternalInterface.call("myJavaScriptFunction"); When the Flash Player executes the ExternalInterface call, ScriptUI looks for a function with the same name as a method of the FlashPlayer element, and invokes it with the specified arguments.
CHAPTER 4: User-Interface Tools Automatic layout 87 The script programmer has considerable control over the automatic layout process. Each container has an associated layout manager object, specified in the layout property. The layout manager controls the sizes and positions of the contained elements, and also sizes the container itself. There is a default layout manager object, or you can create a new one: myWin.
CHAPTER 4: User-Interface Tools Automatic layout 88 et: EditText { characters:4, justify:’right’ } \ }"); w.show(); Each example shows the effects of setting particular layout properties in various ways. In each window, w. text is set so that the window title shows which property is being varied, and w.st.text is set to display the particular property value being demonstrated. Container orientation The orientation property of a container specifies the organization of child elements within it.
CHAPTER 4: User-Interface Tools Automatic layout 89 If you set the alignment value using a constant and then query the property, it returns an index number corresponding to the constant, rather than a string value. Elements in a row can be aligned along the vertical axis, in these ways: X top — The element’s top edge is located at the top margin of its container. X bottom — element’s bottom edge is located at the bottom margin of its container.
CHAPTER 4: User-Interface Tools Automatic layout 90 You can override the container’s child alignment, as specified by alignChildren, by setting the alignment property of a particular child element.
CHAPTER 4: User-Interface Tools Automatic layout 91 Setting margins The margins property of a container specifies the number of pixels between the edges of a container and the outermost edges of the child elements. You can set this property to a simple number to specify equal margins, or using a Margins object, which allows you to specify different margins for each edge of the container.
CHAPTER 4: User-Interface Tools Automatic layout 92 Determining a preferred size Each element has a preferredSize property, which is initially defined with reasonable default dimensions for the element. The default value is calculated by ScriptUI, and is based on constant characteristics of each type of element, and variable characteristics such as the text string to be displayed in a button or text element.
CHAPTER 4: User-Interface Tools Automatic layout 93 info: Panel { orientation: ’column’, \ text: ’Personal Info’, \ name: Group { orientation: ’row’, \ s: StaticText { text:’Name:’ }, \ e: EditText { characters: 30 } \ }, \ addr: Group { orientation: ’row’, \ s: StaticText { text:’Street / City:’ }, \ e: EditText { characters: 30 } \ } \ }, \ buttons: Group { orientation: ’row’, \ okBtn: Button { text:’OK’, properties:{name:’ok’} }, \ cancelBtn: Button { text:’Cancel’, properties:{name:’cancel’} } \ } \
CHAPTER 4: User-Interface Tools Automatic layout 94 } \ }, \ workInfo: Panel { orientation: ’column’, \ text: ’Work Info’, \ name: Group { orientation: ’row’, \ s: StaticText { text:’Company name:’ }, \ e: EditText { characters: 30 } \ } \ }, \ buttons: Group { orientation: ’row’, alignment: ’right’, \ okBtn: Button { text:’OK’, properties:{name:’ok’} }, \ cancelBtn: Button { text:’Cancel’, properties:{name:’cancel’} } \ } \ }"; win = new Window (res); win.center(); win.
CHAPTER 4: User-Interface Tools Automatic layout 95 res = "dialog { \ whichInfo: DropDownList { alignment:’left’ }, \ allGroups: Panel { orientation:’stack’, \ info: Group { orientation: ’column’, \ name: Group { orientation: ’row’, \ s: StaticText { text:’Name:’ }, \ e: EditText { characters: 30 } \ } \ }, \ workInfo: Group { orientation: ’column’, \ name: Group { orientation: ’row’, \ s: StaticText { text:’Company name:’ }, \ e: EditText { characters: 30 } \ } \ }, \ }, \ buttons: Group { orientation:
CHAPTER 4: User-Interface Tools Automatic layout /* Define a custom layout manager that arranges the children ** of ’container’ in a stair-step fashion.*/ function StairStepButtonLayout (container) { this.initSelf(container); } // Define its ’method’ functions function SSBL_initSelf (container) { this.container = container; } function SSBL_layout() { var top = 0, left = 0; var width; var vspacing = 10, hspacing = 20; for (i = 0; i < this.container.children.length; i++) { var child = this.container.
CHAPTER 4: User-Interface Tools Automatic layout 97 // Create window using resource spec win = new Window (res); // Create list items, select first one win.whichInfo.onChange = function () { if (this.selection != null) { for (var g = 0; g < this.items.length; g++) this.items[g].group.visible = false; this.selection.group.visible = true; } } var item = win.whichInfo.add (’item’, ’Personal Info’); item.group = win.allGroups.info; item = win.whichInfo.add (’item’, ’Work Info’); item.group = win.allGroups.
CHAPTER 4: User-Interface Tools Managing control titles 98 5. Determine the column, row, or stack dimensions, based on the dimensions of the children. 6. Using the desired alignment for each child element, adjust its trial location relative to the edges of its container. 7. Set the bounds property for each child element. 8. Set the container’s preferredSize property, based on the margins and dimensions of the row or column of child elements.
CHAPTER 4: User-Interface Tools Managing control titles 99 X The title property is a String that defines a text label for a UI element. The title can appear to the left or right of the graphic element, above or below it, or superimposed over the center of the graphic element; the placement is controlled by the titleLayout property.
CHAPTER 4: User-Interface Tools X Managing control titles 100 To achieve a column orientation where the title appears above or below the graphic element, define vertical alignment as top or bottom, and horizontal alignment as center: image.titleLayout = { alignment: ['center', 'bottom'] }; X To achieve a stack orientation where the title appears superimposed upon the graphic element, define both vertical and horizontal alignment as center.
CHAPTER 4: User-Interface Tools X Managing control titles 101 Use spacing to override the default number of pixels separating the title from the graphic element. In this example, titleLayout is configured to place the title 15 pixels above the panel: panel.title = 'Image format'; panel.titleLayout = { alignment: ['center', 'top'], spacing: 15 }; Title character width and justification X To override the automatically calculated title width, define a positive non-zero value for the characters property.
CHAPTER 4: User-Interface Tools X Managing control titles 102 This example demonstrates using characters and justify to vertically align the colons at the ends of all the dropdownlist control titles in a group. The same characters value is used for each element's title, and all are right-justified: w.ddl1 = w.add("dropdownlist { title: 'Image format:' }"); w.ddl2 = w.add("dropdownlist { title: 'Background color:' }"); w.ddl3 = w.add("dropdownlist { title: 'Text color:' }"); w.ddl1.
CHAPTER 4: User-Interface Tools Localization in ScriptUI objects 103 Margins around the title and graphic object The margins property specifies the number of pixels separating each edge of an element from the visible content within that element. This value overrides the default margin settings (no margins for most element types, 6 pixels at each edge for iconbutton). X For iconbutton, the margins value controls the padding between the button's frame and its title and icon image.
CHAPTER 4: User-Interface Tools Localization in ScriptUI objects 104 standard. In this example, a btnText object contains localized text strings for several locales. This object supplies the text for a Button to be added to a window w: btnText = { en: "Yes", de: "Ja", fr: "Oui" }; b1 = w.add ("button", undefined, localize (btnText)); The localize function extracts the proper string for the current locale.
CHAPTER 4: User-Interface Tools ScriptUI object reference 105 ScriptUI object reference ScriptUI is a component that works with the ExtendScript JavaScript interpreter to provide JavaScript programs with the ability to create and interact with user interface elements. It provides an object model for windows and user-interface control elements within an application. This section provides the details of the ScriptUI classes and objects with their properties, methods, and creation parameters.
CHAPTER 4: User-Interface Tools ScriptUI class 106 compatability Object An object whose properties are the names of compatibility modes supported by the host application. For example, the presence of ScriptUI.compatability.su1PanelCoordinates means that the application allows backward compatibility with the coordinate system of Panel elements in ScriptUI version 1. coreVersion String The internal core version number of the ScriptUI components. Read only.
CHAPTER 4: User-Interface Tools ScriptUI class 107 ScriptUI class functions events.createEvent() ScriptUi.events.createEvent (eventType) eventType The type of event, one of: UIEvent KeyboardEvent MouseEvent This function is in the JavaScript object contained in the events property. It returns an event object of the appropriate type: X A UIEvent base class encapsulates input event information for an event that propagates through a container and control hierarchy.
CHAPTER 4: User-Interface Tools Common properties 108 newImage() ScriptUI.newImage ( normal, disabled, pressed, rollover ); normal The resource name or path to the image to use for the normal or default state. disabled The resource name or path to the image to use for the disabled state, shown when the control containing the image is disabled (enabled=false). pressed The resource name or path to the image to use for the pressed state, shown when the user clicks on the image.
FlashPlayer IconButton Image ListBox x x x x x x x TreeView EditText x StaticText DropDownList x Slider CheckBox x Scrollbar Button x RadioButton Group x 109 ProgressBar Tab x ListItem TabbedPanel children Panel Property Common properties Window CHAPTER 4: User-Interface Tools x x x x x x x x x x x x x columns defaultElement x enabled x x x x x x x x x x x x x x x expanded frameBounds x frameLocation x frameSize x graphics x x x x
resizeable TreeView StaticText Slider 110 x x selected x selection x shortcutKey x size x x x x x spacing x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x stepdelta x subitems x x text Scrollbar RadioButton ProgressBar ListItem ListBox Image IconButton FlashPlayer EditText DropDownList CheckBox Button Group Tab TabbedPanel Panel Property Window class Window CHAPTER 4: User-Interface Tools x x x x te
CHAPTER 4: User-Interface Tools Window class 111 Window class functions Access these function through the class. For example: Window.alert(“Notification to user”); alert() Window.alert (message[, title, errorIcon]); message The string for the displayed message. title Optional. A string to appear as the title of the dialog, if the platform supports a title. Mac OS does not support titles for alert dialogs. The default title string is “Script Alert.” errorIcon Optional.
CHAPTER 4: User-Interface Tools Window object 112 prompt() Window.prompt (message, preset[, title ]); message The string for the displayed message. preset The initial value to be displayed in the text edit field. title Optional. A string to appear as the title of the dialog. In Windows, this appears in the window’s frame; in Mac OS it appears above the message. The default title string is “Script Prompt.” Displays a modal dialog that returns the user’s text input.
CHAPTER 4: User-Interface Tools Window object X 113 maximizeButton — When true, the title bar includes a button to expand the window to its maximum size (typically, the entire screen), if the platform and window type allow it. When false, it does not. Default is false for type palette, true for type window. Not used for dialogs. X minimizeButton — When true, the title bar includes a button to minimize or iconify the window, if the platform and window type allow it. When false, it does not.
CHAPTER 4: User-Interface Tools Window object 114 maximized Boolean When true, the window is expanded. minimized Boolean When true, the window is minimized or iconified. opacity Number The opacity of the window, in the range [0..1]. A value of 1.0 (the default) makes the window completely opaque, a value of 0 makes it completely transparent. Intermediate values make it partially transparent to any degree.
CHAPTER 4: User-Interface Tools Window object 115 Container properties The following table shows properties that apply to Window objects and container objects (controls of type panel, tabbedpanel, tab, and group). alignChildren String, or Array of 2 Strings Tells the layout manager how unlike-sized children of a container should be aligned within a column or row.
CHAPTER 4: User-Interface Tools alignment Window object String, or Array of 2 Strings 116 Applies to child elements of a container. If defined, this value overrides the alignChildren setting for the parent container. For a single string value, allowed values depend on the orientation value.
CHAPTER 4: User-Interface Tools Window object 117 margins Margins A Margins object describing the number of pixels between the edges of this container and the outermost child elements. You can specify different margins for each edge of the container. The default value is based on the type of container, and is chosen to match the standard Adobe user-interface guidelines.
CHAPTER 4: User-Interface Tools Window object 118 text String The title, label, or displayed text. Does not apply to containers of type group or tabbedpanel. This is a localizable string: see “Localization in ScriptUI objects” on page 103. visible Boolean When true, the element is shown, when false it is hidden. When a container is hidden, its children are also hidden, but they retain their own visibility values, and are shown or hidden accordingly when the parent is next shown.
CHAPTER 4: User-Interface Tools Window object 119 addEventListener() windowObj.addEventListener (eventName, handler[, capturePhase]); eventName The event name string. Predefined event names include: change changing move moving resize resizing show enterKey focus blur mousedown mouseup mousemove mouseover mouseout click (detail = 1 for single, 2 for double) handler The function to register for the specified event in this target.
CHAPTER 4: User-Interface Tools Window object findElement() windowOrContainerObj.findElement (name) name The name of the element, as specified in the name creation property. Searches for the named element among the children of this window or container, and returns the object if found. Returns the control object or null. hide() windowObj.hide() Hides this window. When a window is hidden, its children are also hidden, but when it is shown again, the children retain their own visibility states.
CHAPTER 4: User-Interface Tools Window object 121 removeEventListener() windowObj.removeEventListener (eventName, handler[, capturePhase]); eventName The event name string. handler The function that was registered to handle the event. capturePhase Optional. Whether the handler was to respond only in the capture phase. Unregisters an event handler for a particular type of event occurring in this window. All arguments must be identical to those that were used to register the event handler.
CHAPTER 4: User-Interface Tools Window object 122 Window event-handling callbacks The following callback functions can be defined to respond to events in windows. To respond to an event, define a function with the corresponding name in the Window instance. These callbacks are not available for other container types (controls of type panel or group). Callback Description onActivate Called when the user make the window active by clicking it or otherwise making it the keyboard focus.
CHAPTER 4: User-Interface Tools Control objects 123 Control objects UI elements that belong to windows can be containers or controls. Containers share some aspects of top-level windows, and some aspects of controls, and so are described here with controls. Control object constructors Use the add method to create new containers and controls. The add method is available on window and container (panel and group) objects. (See also add() for dropdownlist and listbox controls.) add() containerObj.
CHAPTER 4: User-Interface Tools Control objects 124 Control types and creation parameters The following keywords can be used in string literals as the type specifier for the add method, available on Window and container (Panel and Group) objects. The class names can be used in resource specifications to define controls within a container element (Window, Panel, or Group).
CHAPTER 4: User-Interface Tools Control objects Type keyword Class name dropdownlist DropDownList A drop-down list with zero or more items. Calls the onChange 125 Description callback if the item selection is changed by a script or the user, or if the object’s notify() method is called. To add to a window w: w.add ("dropdownlist", bounds [, items, {creation_properties}]); bounds: The control’s position and size. items: Optional. Supply this argument or the creation_properties argument, not both.
CHAPTER 4: User-Interface Tools Type keyword Control objects Class name edittext (cont’d) 126 Description enterKeySignalsOnChange: When false (the default), the control signals an onChange event when the editable text is changed and the control loses the keyboard focus (that is, the user tabs to another control, clicks outside the control, or types ENTER).
CHAPTER 4: User-Interface Tools Control objects 127 Type keyword Class name Description group Group A container for other controls. Containers have additional properties that control the children; see “Container properties” on page 115. Hiding a group hides all its children. Making it visible makes visible those children that are not individually hidden. To add to a window w: w.add (“group” [, bounds, {creation_properties}]); bounds: Optional. The element’s position and size.
CHAPTER 4: User-Interface Tools Control objects Type keyword Class name Description image Image Displays an icon or image. 128 To add to a window w: w.add (“image” [, bounds, icon, {creation_properties}]); bounds: Optional. The control’s position and size. icon: Optional. The named resource for the icon or family of icons displayed in the image control, or a pathname or File object for an image file. Images must be in PNG format. creation_properties: Optional.
CHAPTER 4: User-Interface Tools Type keyword Control objects Class name listbox (cont’d) 129 Description creation_properties: Optional. An object that contains any of the following properties: name: A unique name for the control. multiselect: When false (the default), only one item can be selected. When true, multiple items can be selected. items: An array of strings for the text of each list item. A ListItem object is created for each item. An item with the text string "-" creates a separator item.
CHAPTER 4: User-Interface Tools Type keyword Control objects Class name panel (cont’d) 130 Description creation_properties: Optional. An object that contains the following property: name: A unique name for the control. borderStyle: A string that specifies the appearance of the border drawn around the panel. One of black, etched, gray, raised, sunken. Default is etched. su1PanelCoordinates: When true, this panel automatically adjusts the positions of its children for compatability with Photoshop CS.
CHAPTER 4: User-Interface Tools Control objects 131 Type keyword Class name Description radiobutton RadioButton A dual-state control, grouped with other radiobuttons, of which only one can be in the selected state. Shows the selected state when value is true, empty when value is false. Calls the onClick callback if the control is clicked or if its notify() method is called. All radiobuttons in a group must be created sequentially, with no intervening creation of other element types.
CHAPTER 4: User-Interface Tools Type keyword Control objects Class name scrollbar (cont’d) 132 Description To add to a window w: w.add (“scrollbar” [, bounds, value, minvalue, maxvalue, {creation_properties}]); bounds: Optional. The control’s position and size. value: Optional. The initial position of the scroll indicator. Default is 0. minvalue: Optional. The minimum value that the value property can be set to. Default is 0. Together with maxvalue, defines the scrolling range. maxvalue: Optional.
CHAPTER 4: User-Interface Tools Control objects Type keyword Class name Description statictext StaticText A text field that the user cannot change. 133 To add to a window w: w.add (“statictext” [, bounds, text, {creation_properties}]); bounds: Optional. The control’s position and size. text: Optional. The text displayed in the control. creation_properties: Optional. An object that contains any of the following properties: name: A unique name for the control.
CHAPTER 4: User-Interface Tools Type keyword Control objects Class name tab (cont’d) 134 Description creation_properties: Optional. An object that contains the following property: name: A unique name for the control. tabbedpanel TabbedPanel A container for selectable Tab containers. Differs from a Panel element in that it can contain only Tab elements as direct children. Containers have additional properties that control the children; see “Container properties” on page 115.
CHAPTER 4: User-Interface Tools Type keyword Control objects Class name 135 Description treeview (cont’d) creation_properties: Optional. An object that contains any of the following properties: name: A unique name for the control. items: An array of strings for the text of each top-level list item. A ListItem object is created for each item. An item with the type node can contain child items. Supply this property, or the items argument, not both.
CHAPTER 4: User-Interface Tools Control objects alignment (cont’d) 136 For an array value, the first string element defines the horizontal alignment and the second element defines the vertical alignment. The horizontal alignment value must be one of left, right, center or fill. The vertical alignment value must be one of top, bottom, center, or fill. Values are not case sensitive.
CHAPTER 4: User-Interface Tools image Control objects Object 137 A ScriptUIImage object, or the name of an icon resource, or the pathname or File object for a file that contains a platform-specific image in PNG or JPEG format, or for a shortcut or alias to such a file. X For an IconButton, the icon appears as the content of the button. X For an Image, the image is the entire content of the image element. X For a ListItem, the image is displayed to the left of the text.
CHAPTER 4: User-Interface Tools location Control objects Point 138 A Point object describing the location of the element as an array, [x, y], representing the coordinates of the upper left corner of the element. These are screen coordinates for Window elements, and parent-relative coordinates for other elements. The location is defined as [bounds.x, bounds.y]. Setting an element’s location changes its bounds property, and vice-versa.
CHAPTER 4: User-Interface Tools selection (ListBox) Control objects Array of ListItem 139 For a ListBox, an array of ListItem objects for the current selection in a multi-selection list. Setting this value causes the selected item to be highlighted and to be scrolled into view if necessary. If no items are selected, the value is null. Set to null to deselect all items.
CHAPTER 4: User-Interface Tools subitems Control objects Array 140 For ListItem objects only. When the parent is a multi-column ListBox, the ListItem.text and ListItem.image values describe the label in the first column, and this specifies additional labels for that row in the remaining columns. This contains an array of JavaScript objects, whose length is one less than the number of columns.
CHAPTER 4: User-Interface Tools titleLayout Control objects Object 141 For a DropDownList, FlashPlayer, IconButton, Image, or TabbedPanel with a title value, the way the text label is shown in relation to the element. A JavaScript object with these properties: alignment —The position of the title relative to the element, an array of [horizontal_alignment, vertical_alignment]. For possible alignment values, see “alignment” on page 116.
CHAPTER 4: User-Interface Tools Control objects 142 window Window The Window object that contains this control. Read only. windowBounds Bounds A Bounds object that contains the bounds of this control in the containing window’s coordinates. Compare bounds, in which coordinates are relative to the immediate parent container. Read only. function_name Function For the FlashPlayer control, a function definition for a callback from the Flash ActionScript environment.
CHAPTER 4: User-Interface Tools Control objects 143 dispatchEvent() controlObj.dispatchEvent (eventObj) eventObj An object of the UIEvent base class. Simulates the occurrence of an event in this target. A script can create an event object for a specific event, using ScriptUI.events.events.createEvent(), and pass it to this method to start the event propagation for the event.
CHAPTER 4: User-Interface Tools Control objects 144 show() controlObj.show() Shows this container or control. When a window or container is hidden, its children are also hidden, but when it is shown again, the children retain their own visibility states. Returns undefined. toString() listItemObj.toString() For ListItem controls only. Retrieves the value of this item’s text property as a string. Returns a String. valueOf() listItemObj.valueOf() For ListItem controls only.
CHAPTER 4: User-Interface Tools Control objects 145 remove() containerObj.remove(index) containerObj.remove(text) containerObj.remove(child) index text child The item or child to remove, specified by 0-based index, text value, or as a control object. For containers (Panel, Group), removes the specified child control from the container’s children array. For list objects (ListBox, DropDownList or TreeView) only, removes the specified item from this object’s items array.
CHAPTER 4: User-Interface Tools Control objects 146 invokePlayerFunction() flashPlayerObj.invokePlayerFunction(fnName, [arg1[,...argn]] ) fnName String. The name of a Flash ActionScript function that has been registered with the ExternalInterface object by the currently loaded SWF file; see “Calling ActionScript functions from a ScriptUI script” on page 86. args Optional.
CHAPTER 4: User-Interface Tools Control objects 147 Control event-handling callbacks The following events are signalled in certain types of controls. To handle the event, define a function with the corresponding name in the control object. Handler functions take no arguments and have no expected return values; see “Defining behavior with event callbacks and listeners” on page 80. onActivate Called when the user gives a control the keyboard focus by clicking it or tabbing into it.
CHAPTER 4: User-Interface Tools Control objects 148 onExpand Called when the user expands (opens) a node in a TreeView control. The parameter to this function is the ListItem node object that was expanded. onShortcutKey (In Windows only) Called when a shortcut-key sequence is typed that matches the shortcutKey value for an element in the active window. DrawState object A helper object that describes an input state at the time of the triggering onDraw event.
CHAPTER 4: User-Interface Tools Event handling 149 Event handling Several helper classes provide low-level event-handling capabilities. X Event objects are normally created by ScriptUI and passed to your event handler. However, you can simulate a user action by constructing an event object using ScriptUI.events.events.createEvent(), and sending it to a target object’s dispatchEvent() function.
CHAPTER 4: User-Interface Tools Event handling 150 UIEvent object functions initUIEvent() eventObj.initUIEvent (eventName, bubble, isCancelable, view, detail) eventName The event name string. bubble When true, the event should be triggered in ancestors of the target object during the bubbling phase. isCancelable When true, the event can be cancelled. view The container or control object that dispatched the event. detail Details of the event, which vary according to the event type.
CHAPTER 4: User-Interface Tools Event handling 151 KeyboardEvent object This type of object is passed to your registered event handler when a keyboard-input event occurs. The properties reflect the keypress and key modifier state at the time the keyboard event was generated. All properties are read-only. KeyboardEvent object properties In addition to the properties defined for UIEvent base class, a keyboard event has these properties. All properties are read-only.
CHAPTER 4: User-Interface Tools Event handling 152 KeyboardEvent object functions In addition to the functions defined for UIEvent base class, a keyboard event has these functions. getModifierState() eventObj.getModifierState (keyIdentifier) keyIdentifier A string containing a modifier key identifier, one of: Alt CapsLock Control Meta NumLock Scroll Shift Returns true if the given modifier was active when the event occurred, false otherwise. initKeyboardEvent() eventObj.
CHAPTER 4: User-Interface Tools Event handling 153 MouseEvent object This type of object is passed to your registered event handler when a mouse-input event occurs. The properties reflect the button and modifier-key state and pointer position at the time the event was generated. In the case of nested elements, mouse event types are always targeted at the most deeply nested element.
CHAPTER 4: User-Interface Tools Event handling shiftKey Boolean When true, the SHIFT key was active. Value is undefined if the keyIdentifier is for a modifier key. type String 154 The name of the event that occurred. Mouse events types are: mousedown mouseup mousemove mouseover mouseout click (detail = 1 for single, 2 for double) The sequence of click events is: mousedown, mouseup, click.
CHAPTER 4: User-Interface Tools Graphic customization objects button Sets the mouse button. relatedTarget Optional. Sets the related target, if any, for a mouseover or mouseout event. 155 Reinitializes the object, allowing you to change the event properties after construction. Arguments set the corresponding properties. Returns undefined.
CHAPTER 4: User-Interface Tools Graphic customization objects 156 ScriptUIGraphics class properties These static properties provide color type constants with which to create Pen and Brush objects. BrushType Object Contains the enumerated constants for the type argument of newBrush(). Types are: SOLID_COLOR THEME_COLOR PenType Object Contains the enumerated constants for the type argument of newPen().
CHAPTER 4: User-Interface Tools Graphic customization objects 157 ScriptUIGraphics object functions These functions directly customize the appearance of the associated element by drawing on the screen, or create the Pen and Brush objects used to populate the graphics object or pass to the drawing methods: closePath() controlObj.graphics.closePath ( ) Defines a line from the current position to the start point of the current path (the value of currentPath), which closes the path. Returns undefined.
CHAPTER 4: User-Interface Tools Graphic customization objects drawString() controlObj.graphics.drawString (text, pen, x, y, font) text The text string. pen The ScriptUIPen object for the drawing pen to use. x, y The origin point of the drawn text, in the coordinate system of the control that contains this graphics object. font Optional. The ScriptUIFont object for the font to use. Default is the font value in this object.
CHAPTER 4: User-Interface Tools Graphic customization objects 159 measureString() controlObj.graphics.measureString (text, font[, boundingWidth]) text The text string to measure. font Optional. The ScriptUIFont object for the font to use. Default is the font value in this object. boundingWidth Optional. A number that specifies the maximum width in pixels of the area in which the text might be placed. Use when wrapping a long string of text across multiple lines.
CHAPTER 4: User-Interface Tools Graphic customization objects 160 newPen() controlObj.graphics.newPen( type, color, lineWidth); type The pen type, one of these constants: ScriptUIGraphics.PenType.SOLID_COLOR ScriptUIGraphics.PenType.THEME_COLOR color lineWidth The pen color. X If type is SOLID_COLOR, the color expressed as an array of three or four values, in the form [R, B, G, A] specifying the red, green, and blue values of the color and, optionally, the opacity (alpha channel).
CHAPTER 4: User-Interface Tools Graphic customization objects 161 ScriptUIBrush object A helper object that encapsulates the qualities of a brush used to paint fill into a path in a control. Create with the newBrush() method of the ScriptUIGraphics object. X Used as a value of backgroundColor and disabledBackgroundColor. X Passed as an argument to fillPath().
CHAPTER 4: User-Interface Tools style Graphic customization objects Object 162 The font style. One of these constants: ScriptUI.FontStyle.REGULAR ScriptUI.FontStyle.BOLD ScriptUI.FontStyle.ITALIC ScriptUI.FontStyle.BOLDITALIC substitute String The name of a substitution font, a fallback font to substitute for this font if the requested font family or style is not available. ScriptUIImage object A helper object that encapsulates a set of images that can be drawn into a control.
CHAPTER 4: User-Interface Tools Graphic customization objects 163 ScriptUIPen object A helper object that encapsulates the qualities of a pen used to stroke path segments in a control. Create with the newPen() method of the ScriptUIGraphics object. X Used as a value of foregroundColor and disabledForegroundColor. X Passed as an argument to drawString() and strokePath().
CHAPTER 4: User-Interface Tools customBoundedValue Graphic customization objects 164 Can be used to implement controls whose 'value' can vary within minimum and maximum bounds, like the Progressbar, Slider, and Scrollbar. Has the same additional properties as those controls: value minvalue maxvalue shortcutKey If the value property is changed, the control receives an onChange event notification, followed by an onDraw event notification, so the element can redraw itself with the changed state.
CHAPTER 4: User-Interface Tools LayoutManager object 165 } } function drawButton (drawingState) { ... } LayoutManager object Controls the automatic layout behavior for a window or container. The subclass AutoLayoutManager implements the default automatic layout behavior. AutoLayoutManager object constructor Create an instance of the AutoLayoutManager class with the new operator: myWin.
5 Interapplication Communication with Scripts The Adobe scripting environment provides an interapplication messaging framework, a way for to send and receive information and scripts from one Adobe application to another. An application that supports the messaging framework is said to be message enabled. Code samples that demonstrate various techniques are provided with the Adobe ExtendScript SDK, and referenced by name in the relevant sections.
CHAPTER 5: Interapplication Communication with Scripts Cross-DOM functions 167 Identifying applications When calling external functions or exchanging messages, you must identify particular applications using namespace specifiers. A specifier consists of a specific name string (such as photoshop), and optional additions that identify a particular release or locale version. Application specifiers are used occasionally in other contexts as well.
CHAPTER 5: Interapplication Communication with Scripts Cross-DOM functions 168 of application-specific functions. Each application determines the extent of its exported functionality. Some applications provide extensive support for exported functions, others less. For details of additional functions that are exported by individual applications, refer to the startup scripts for those applications. The application startup scripts are named appname-n.
CHAPTER 5: Interapplication Communication with Scripts Cross-DOM functions 169 openAsNew() appspec.openAsNew([options]) options Optional. Application-specific creation options: Adobe Bridge: none Photoshop: none InDesign: creation options are: (Boolean:showingWindow, ObjectOrString:documentPresets) See the arguments for documents.add() in the Adobe InDesign CS5 Scripting Reference.
CHAPTER 5: Interapplication Communication with Scripts Communicating through messages 170 Communicating through messages Adobe Bridge provides an application programming interface (API) that defines a communication protocol between Adobe ExtendScript- and message-enabled applications. This provides the most general mechanism for communication between applications. A messaging-enabled application can launch another messaging-enabled application, and send or receive scripts to effect certain actions.
CHAPTER 5: Interapplication Communication with Scripts Communicating through messages 171 var bt = new BridgeTalk; // send this msg to the Adobe Bridge CS4 application var targetApp = BridgeTalk.getSpecifier( "bridge-3.0"); bt.target = targetApp; // the script to evaluate is contained in a string in the "body" property bt.body = "new Document(’C:\\BridgeScripts’); app.document.target.children.
CHAPTER 5: Interapplication Communication with Scripts Communicating through messages 172 var targetApp = BridgeTalk.getSpecifier( "bridge-3.0"); if( targetApp ) { // construct a message object var bt = new BridgeTalk; // the message is intended for Adobe Bridge CS4 bt.target = targetApp; // the script to evaluate is contained in a string in the "body" property bt.body = "new Document(’C:\\BridgeScripts’); app.document.target.children.length;" // define result handler callback bt.
CHAPTER 5: Interapplication Communication with Scripts Communicating through messages 173 To change the default behavior set the BridgeTalk.onReceive property to a function definition in the following form: BridgeTalk.onReceive = function( bridgeTalkObject ) { // callback definition here }; The body property of the received message object contains the received data. The function can return any type. The function that you define does not need to explicitly create and return a BridgeTalk message object.
CHAPTER 5: Interapplication Communication with Scripts Communicating through messages 174 A response message can be: X The result of an error in processing the message. This is handled by the onError callback. If an error occurs in processing the message body (as the result of a JavaScript syntax error, for instance), the target application invokes the onError callback, passing a response message that contains the error code and error message.
CHAPTER 5: Interapplication Communication with Scripts Communicating through messages 175 bt.send(); Example: Handling any error In this example, the onError handler re-throws the error message within the sending application. var bt = new BridgeTalk; bt.onError = function (btObj) { var errorCode = parseInt (btObj.headers ["Error-Code"]); throw new Error (errorCode, btObj.
CHAPTER 5: Interapplication Communication with Scripts Communicating through messages 176 } } Example: Setting up a sender to receive multiple responses This example sends a message of the type iterator, to be handled by the onReceive handler in the previous example, and processes the responses received from that target.
CHAPTER 5: Interapplication Communication with Scripts Communicating through messages 177 Passing simple types When your message object’s onResult callback receives a response, it must interpret the string it finds in the body of the response message to obtain a result of the correct type. Results of various types can be identified and processed as follows: Number JavaScript allows you to access a string that contains a number directly as a number, without doing any type conversion.
CHAPTER 5: Interapplication Communication with Scripts Communicating through messages 178 // now you can access the returned array for (i=0; i< arr.length(); i++) doSomething(arr[i]); } // send the message bt.send(); Passing an object with toSource and eval This technique is the only way to pass objects between applications. For example, this code sends a script that returns an object containing some of the metadata for a specific file and defines an onResult callback that receives the object.
CHAPTER 5: Interapplication Communication with Scripts Messaging framework API reference 179 Messaging framework API reference This application programming interface (API) defines a communication protocol between message-enabled applications. These objects are available to all ExtendScript scripts when any of the applications is loaded. The messaging protocol is extensible. Although it is primarily designed to send scripts, you can use it to send other kinds of data.
CHAPTER 5: Interapplication Communication with Scripts BridgeTalk class 180 BridgeTalk class properties The BridgeTalk class provides these static properties, which are available in the global namespace: appInstance String The instance identifier of an application launched by the messaging framework, the instance portion of an application specifier; see “Application specifiers” on page 191. Read only.
CHAPTER 5: Interapplication Communication with Scripts BridgeTalk class 181 BridgeTalk class functions The BridgeTalk class provides these static methods, which are available in the global namespace: bringToFront() BridgeTalk.bringToFront (app) app A specifier for the target application; see “Application specifiers” on page 191. Brings all windows of the specified application to the front of the screen. In Mac OS, an application can be running but have no windows open.
CHAPTER 5: Interapplication Communication with Scripts BridgeTalk class 182 getSpecifier() BridgeTalk.getSpecifier (appName,[version],[locale]) appName The base name of the application to search for. version Optional. The specific version number to search for. If 0 or not supplied, returns the most recent version. If negative, returns the highest version up to and including the absolute value. If a major version is specified, returns the highest minor-version variation.
CHAPTER 5: Interapplication Communication with Scripts BridgeTalk class 183 getStatus() BridgeTalk.getStatus (targetSpec) targetSpec Optional, a specifier for the target application; see “Application specifiers” on page 191. If not supplied, returns the processing status of the current application. Retrieves the processing status of an application. Returns a string, one of: X BUSY: The application is currently busy, but not processing messages.
CHAPTER 5: Interapplication Communication with Scripts X BridgeTalk class 184 If neither version nor locale is supplied, returns base specifiers with neither version nor locale information, but tries to find the most appropriate version and locale; see “Application specifiers” on page 191. For example, assuming installed applications include Photoshop CS3 10.0 en_US, Photoshop CS4 11.0 en_us, and Illustrator CS4 14.0 de_de: BridgeTalk.getTargets(); => [photoshop,illustrator] BridgeTalk.getTargets( "10.
CHAPTER 5: Interapplication Communication with Scripts BridgeTalk message object 185 ping() BridgeTalk.ping (specifier, pingRequest) specifier A specifier for the target application; see “Application specifiers” on page 191. pingRequest An identifying key string for a specific type of return value. One of: X STATUS: Returns the processing status; see getStatus(). X DIAGNOSTICS: Returns a diagnostic report that includes a list of valid ping keys.
CHAPTER 5: Interapplication Communication with Scripts BridgeTalk message object 186 BridgeTalk message object properties body headers String Object The data payload of the message. Read/write. X If this is an unsolicited message to another application, typically contains a script packaged as a string. The target application’s full document object model (DOM) is available within the script.
CHAPTER 5: Interapplication Communication with Scripts type String BridgeTalk message object 187 The message type, which indicates what type of data the body contains. Read/write. Default is ExtendScript. You can define a type for script-defined data. If you do so, the target application must have a static BridgeTalk onReceive method that checks for and processes that type.
CHAPTER 5: Interapplication Communication with Scripts onResult Function BridgeTalk message object 188 A callback function that the target application invokes to return a response to the sender. This can be an intermediate response or the final result of processing the message. To handle the response, set this to a function definition in the following form: bridgeTalkObj.
CHAPTER 5: Interapplication Communication with Scripts BridgeTalk message object 189 BridgeTalk message object functions send() bridgeTalkObj.send ([timoutInSecs[, launchParameters]]) timoutInSecs Optional. A maximum number of seconds to wait for a result before returning from this function. The message is sent synchronously, and the function does not return until the target has processed the message or this number of seconds have passed.
CHAPTER 5: Interapplication Communication with Scripts Messaging error codes Messaging error codes The interapplication messaging protocol defines the following error codes, which are compatible with ExtendScript error codes. Negative values indicate unrecoverable errors that cause ExtendScript to terminate a running script.
CHAPTER 5: Interapplication Communication with Scripts Application and namespace specifiers 191 Application and namespace specifiers All forms of interapplication communication use Application specifiers to identify Adobe applications. X In all ExtendScript scripts, the #target directive can use an specifier to identify the application that should run that script. See “Preprocessor directives” on page 233.
CHAPTER 5: Interapplication Communication with Scripts version Application and namespace specifiers 192 Optional. A number indicating at least a major version. The number should include a minor version separated from the major version number by a dot; for example, 1.5. If not supplied, assumes the same suite version as the sending application, if possible; otherwise, the highest available version number.
CHAPTER 5: Interapplication Communication with Scripts Application and namespace specifiers 193 Namespace specifiers When calling cross-DOM and exported functions from other applications, a namespace specifier qualifies the function call, directing it to the appropriate application. Namespace specifiers consist of an application name, as used in an application specifier, with an optional major version number. Use it as a prefix to an exported function name, with the JavaScript dot notation.
6 External Communication Tools ExtendScript offers tools for communicating with other computers or the Internet using standard protocols. X The Socket object supports low-level TCP connections. It is available in the following applications: Z Adobe Bridge CS5 Z Adobe InDesign CS5 Z Adobe InCopy® CS5 Z Adobe After Effects® CS5 Z Adobe Photoshop CS5 Socket object TCP connections are the basic transport layer of the Internet.
CHAPTER 6: External Communication Tools Socket object 195 incoming connections and then return immediately. If there is a connection request, the call to poll() would return another Socket object containing the brand new connection. Use this connection object to talk to the calling client; when finished, close the connection and discard the connection object. Before a Socket object is able to check for an incoming connection, it must be told to listen on a specific port, like port 80 for HTTP requests.
CHAPTER 6: External Communication Tools // poll for a new connection var connection = tcp.poll(); if (connection != null) { writeln ("Connection from " + connection.host); // we have a new connection, so welcome and chat // until client terminates the session connection.writeln ("Welcome to a little chat!"); chat (connection); connection.writeln ( "*** Goodbye ***"); connection.
CHAPTER 6: External Communication Tools Socket object reference 197 Socket object reference This section provides details of the object’s properties and methods. Socket object constructor [new] Socket (); Creates and returns a new Socket object. Socket object properties connected Boolean When true, the connection is active. Read only. encoding String eof Boolean When true, the receive buffer is empty. Read only. error String A message describing the most recent error.
CHAPTER 6: External Communication Tools Socket object reference 198 listen() socketObj.listen (port [, encoding]); port Number. The TCP/IP port number to listen on. Valid port numbers are 1 to 65535. Typical values are 80 for a Web server, 23 for a Telnet server and so on. encoding Optional. String. The encoding to be used for the connection. Typical values are “ASCII,” “binary,” or “UTF-8.” Default is “ASCII.” Instructs the object to start listening for an incoming connection.
CHAPTER 6: External Communication Tools Socket object reference readln() socketObj.readln (); Reads one line of text up to the next line feed. Line feeds are recognized as LF or CRLF pairs. CR characters are ignored. Returns a string. write() socketObj.write (text[, text...]); text String. Any number of string values. All arguments are concatenated to form the string to be written. Concatenates all arguments into a single string and writes that string to the connection.
7 Integrating External Libraries You can extend the JavaScript DOM for an application by writing a C or C++ shared library, compiling it for the platform you are using, and loading it into JavaScript as an ExternalObject object. A shared library is implemented by a DLL in Windows, a bundle or framework in Mac OS, or a SharedObject in UNIX.
CHAPTER 7: Integrating External Libraries ExternalObject object 201 automatically defined, and you can access the properties and methods through an instance of that class. For example: anotherlib= new ExternalObject ("lib:" + filespec); // load the library alert(anotherlib.version) ; // instantiate library-defined class var myObject = new MyNewClass() ; // access functions from instance var a = myObject.method_abc(1,2.0,true,"this is data") ; alert(a) ; anotherlib.
CHAPTER 7: Integrating External Libraries ExternalObject object 202 ExternalObject class properties The ExternalObject class provides these static properties: log Boolean Set to true to write status information to standard output (the JavaScript Console in the ExtendScript Toolkit). Set to false to turn logging off. Default is false.
CHAPTER 7: Integrating External Libraries Defining entry points for direct access Defining entry points for direct access A library to be loaded and accessed directly through an ExternalObject instance must publish the following entry points. These must be exported as C functions, not C++ functions: ESInitialize() char* ESInitialize (TaggedData* argv, long argc); argv, argc The pointer to and number of arguments passed to the constructor, in the form of TaggedData.
CHAPTER 7: Integrating External Libraries X Defining entry points for direct access 204 string — Must be UTF-8 encoded. The library must define an entry point ESFreeMem(), which ExtendScript calls to release a returned string pointer. If this entry point is missing, ExtendScript does not attempt to release any returned string data. X Script — A string to be evaluated by ExtendScript. Use to return small JavaScript scripts that define arbitrarily complex data.
CHAPTER 7: Integrating External Libraries Defining entry points for direct access 205 For example, suppose your library defines these two entry points: One (Integer a, String b); Two (); The signature strings for these two functions would be "One_ds", "Two". NOTE: You cannot define function overloading by returning multiple different signatures for one function. Attempting to do so produces undefined results.
CHAPTER 7: Integrating External Libraries Defining entry points for indirect access 206 Defining entry points for indirect access The C-client object interface for external libraries allows your C or C++ shared-library code to define, create, use, and manage JavaScript objects.
CHAPTER 7: Integrating External Libraries Defining entry points for indirect access 207 SoServerInterface SoServerInterface is a structure of function pointers which enable the shared-library code to call JavaScript objects. It is passed to the global ESClientInterface() function for initialization when the library is loaded, and again for cleanup when the library is unloaded. Between these calls, your shared-library code must store the structure and use it to access the communication functions.
CHAPTER 7: Integrating External Libraries Defining entry points for indirect access addClass() ESerror_t addClass (SoHServer hServer, char* name, SoObjectInterface_p pObjectInterface); hServer The SoHServer reference for this shared library, as passed to your global ESClientInterface() function on initialization. name String. The unique name of the new class. The name must begin with an uppercase alphabetic character. pObjectInterface A pointer to an SoObjectInterface.
CHAPTER 7: Integrating External Libraries Defining entry points for indirect access addProperties() ESerror_t addProperties (SoHObject hObject, SoCClientName_p pNames); hObject The SoHObject reference for an instance of this class. pNames[] SoCClientName. A structure containing the names and identifiers of properties to be added. Adds a set of new properties to an instance. Returns an error code, kESErrOK on success.
CHAPTER 7: Integrating External Libraries Defining entry points for indirect access 210 eval() ESerror_t eval (SohServer hServer, char* string, TaggedData* pTaggedData); hServer The SoHServer reference for this shared library, as passed to your global ESClientInterface() function on initialization. string A string containing the JavaScript expression to evaluate. pTaggedData A pointer to a TaggedData object in which to return the result of evaluation.
CHAPTER 7: Integrating External Libraries Defining entry points for indirect access 211 All SoObjectInterface members must be valid function pointers, or NULL. You must implement initialize() and finalize(). The functions must conform to the following type definitions. initialize() ESerror_t initialize (SoHObject hObject, int argc, TaggedData* argv); hObject The SoHObject reference for this instance.
CHAPTER 7: Integrating External Libraries Defining entry points for indirect access 212 call() ESerror_t call (SoHObject hObject, SoCClientName* name, int argc, TaggedData* argv, TaggedData* pResult); hObject The SoHObject reference for this instance. name The name of the method, an SoCClientName. argc, argv The number and pointer to arguments passed to the call, in the form of TaggedDatas. pResult A buffer in which to return the result of the call, in the form of TaggedDatas.
CHAPTER 7: Integrating External Libraries Defining entry points for indirect access 213 Support structures These support structures are passed to functions that you define for your JavaScript interface: SoHObject An opaque pointer (long *) to the C/C++ representation of a JavaScript object. SoHServer An opaque pointer (long *) to the server object, which acts as an object factory for the shared library. SoCClientName A structure that uniquely identifies methods and properties.
CHAPTER 7: Integrating External Libraries Defining entry points for indirect access 214 TaggedData The TaggedData structure is used to communicate data values between JavaScript and shared-library C/C++ code. Types are automatically converted as appropriate. typedef struct { union { long intval; double fltval; char* string; SoHObject* hObject; } data; long type; long filler; } TaggedData; intval Integer and boolean data values. Type is kTypeInteger, kTypeUInteger, or kTypeBool.
CHAPTER 7: Integrating External Libraries type Defining entry points for indirect access The data type tag. One of: X kTypeUndefined: a null value, equivalent of JavaScript undefined. The return value for a function is always set to this by default. X kTypeBool: a boolean value, 0 for false, 1 for true. X kTypeDouble: a 64-bit floating-point number. X kTypeString: a character string. X kTypeLiveObject: a pointer to an internal representation of an object (SoHObject).
8 ExtendScript Tools and Features In addition to the specific functional modules and development tools, ExtendScript provides these tools and features: X Global objects that support debugging and object inspection; these include the Dollar ($) object and the ExtendScript reflection interface. X A localization utility for providing user-interface string values in different languages. See Localizing ExtendScript strings. X Global functions for displaying short messages in dialog boxes.
CHAPTER 8: ExtendScript Tools and Features Dollar ($) object engineName String The name of the current JavaScript engine, if set. Read only. error Error String The most recent run-time error information, contained in a JavaScript Error object. 217 Assigning error text to this property generates a run-time error; however, the preferred way to generate a run-time error is to throw an Error object. fileName String The file name of the current script. Read only.
CHAPTER 8: ExtendScript Tools and Features locale String Dollar ($) object 218 Gets or sets the current locale. The string contains five characters in the form LL_RR, where LL is an ISO 639 language specifier, and RR is an ISO 3166 region specifier. Initially, this is the value that the application or the platform returns for the current user. You can set it to temporarily change the locale for testing. To return to the application or platform setting, set to undefined, null, or the empty string.
CHAPTER 8: ExtendScript Tools and Features Dollar ($) object 219 Function Return type colorPicker() $.colorPicker (name) Number Invokes the platform-specific color selection dialog, and returns the selected color as a hexadecimal RGB value: 0xRRGGBB. name: The color to be preselected in the dialog, as a hexadecimal RGB value (0xRRGGBB), or -1 for the platform default. evalFile() $.
CHAPTER 8: ExtendScript Tools and Features Dollar ($) object 220 Function Return type write() $.write (text[, text...]...) undefined Writes the specified text to the JavaScript Console. text: One or more strings to write, which are concatenated to form a single string. writeln() $.writeln (text[, text...]...) Writes the specified text to the JavaScript Console and appends a linefeed sequence. text: One or more strings to write, which are concatenated to form a single string.
CHAPTER 8: ExtendScript Tools and Features ExtendScript reflection interface 221 ExtendScript reflection interface ExtendScript provides a reflection interface that allows you to find out everything about an object, including its name, a description, the expected data type for properties, the arguments and return value for methods, and any default values or limitations to the input values.
CHAPTER 8: ExtendScript Tools and Features ExtendScript reflection interface 222 Examples This code determines the class name of an object: obj = new String ("hi"); obj.reflect.name; // => String This code gets a list of all methods: obj = new String ("hi"); obj.reflect.methods; //=> indexOf,slice,... obj.reflect.find ("indexOf"); // => the method info This code gets a list of properties: Math.reflect.properties; //=> PI,LOG10,... This code gets the data type of a property: Math.reflect.find ("PI").
CHAPTER 8: ExtendScript Tools and Features ExtendScript reflection interface 223 ReflectionInfo object properties arguments Array of For a reflected method, an array of ReflectionInfo objects describing ReflectionInfo each method argument. dataType String The data type of the reflected element. One of: boolean number string Classname: The class name of an object. NOTE: Class names start with a capital letter.
CHAPTER 8: ExtendScript Tools and Features Localizing ExtendScript strings 224 Localizing ExtendScript strings Localization is the process of translating and otherwise manipulating an interface so it looks as if it were originally designed for a particular language. ExtendScript enables you to localize the strings in your script’s user interface. The language is chosen by the application at startup, according to the current locale provided by the operating system.
CHAPTER 8: ExtendScript Tools and Features Localizing ExtendScript strings 225 To use automatic translation of localization objects, you must enable localization in your script with this statement: $.localize = true; The localize function always performs its translation, regardless of the setting of the $.localize variable; for example: msg = { en: "Yes", de: "Ja", fr: "Oui" }; //Only works if the $.localize=true alert (msg); //Always works, regardless of $.
CHAPTER 8: ExtendScript Tools and Features Localizing ExtendScript strings 226 5. If not found, it removes the region identifier (for example, en) and retries. 6. If not found, it tries the identifier en (that is, the default language is English). 7. If not found, it returns the entire localizer object. Testing localization ExtendScript stores the current locale in the variable $.locale. This variable is updated whenever the locale of the hosting application changes.
CHAPTER 8: ExtendScript Tools and Features User notification dialogs 227 For example: today = { en: "Today is %1/%2", de: "Heute ist der %2.%1." }; d = new Date(); alert (localize (today, d.getMonth()+1, d.getDate())); User notification dialogs ExtendScript provides a set of globally available functions that allow you to display short messages to the user in platform-standard dialog boxes. There are three types of message dialogs: X Alert — Displays a dialog containing a short message and an OK button.
CHAPTER 8: ExtendScript Tools and Features User notification dialogs 228 This figure shows alert dialogs with error icons. Global confirm function Displays a platform-standard dialog containing a short message and two buttons labeled Yes and No. confirm() confirm (message[,noAsDflt ,title ]); message The string for the displayed message. noAsDflt Optional. When true, the No button is the default choice, selected when the user types ENTER. Default is false, meaning that Yes is the default choice.
CHAPTER 8: ExtendScript Tools and Features User notification dialogs 229 Global prompt function Displays a platform-standard dialog containing a short message, a text edit field, and two buttons labeled OK and Cancel. prompt() prompt (message, preset[, title ]); message The string for the displayed message. preset The initial value to be displayed in the text edit field. title Optional. A string to appear as the title of the dialog.
CHAPTER 8: ExtendScript Tools and Features Specifying measurement values 230 Specifying measurement values ExtendScript provides the UnitValue object to represent measurement values. The properties and methods of the UnitValue object make it easy to change the value, the unit, or both, or to perform conversions from one unit to another. UnitValue object Represents measurement values that contain both the numeric magnitude and the unit of measurement.
CHAPTER 8: ExtendScript Tools and Features Specifying measurement values 231 For example, all the following formats are equivalent: myVal = new UnitValue (12, "cm"); myVal = new UnitValue ("12 cm"); myVal = UnitValue ("12 centimeters"); UnitValue object properties baseUnit UnitValue A UnitValue object that defines the size of one pixel, or a total size to use as a base for percentage values.
CHAPTER 8: ExtendScript Tools and Features X Specifying measurement values Percentage values are relative to a total measurement. For example, 10% of 100 inches is 10 inches, while 10% of 1 meter is 0.1 meters. The conversion base of a percentage is the unit value corresponding to 100%. The default baseUnit of a unitValue object is 0.013889 inches, the base for pixels at 72 dpi. If the unitValue is for pixels at any other dpi, or for a percentage value, you must set the baseUnit value accordingly.
CHAPTER 8: ExtendScript Tools and Features X +unitValue Result is the numeric value. -unitValue Result is the negated numeric value. Preprocessor directives 233 Binary operators (+, -, *, /, %) If one operand is unitValue object and the other is a number, the operation is applied to the number and the numeric value of the object. The expression returns a new unitValue object with the result as its value.
CHAPTER 8: ExtendScript Tools and Features #include file Preprocessor directives 234 Includes a JavaScript source file from another location. Inserts the contents of the named file into this file at the location of this statement. The file argument is an Adobe portable file specification. See Specifying paths. As a convention, use the file extension .jsxinc for JavaScript include files. For example: #include "../include/lib.
CHAPTER 8: ExtendScript Tools and Features #target name Operator overloading 235 Defines the target application for this JSX file. The name value is an application specifier; see Application and namespace specifiers. Enclosing quotes are optional. If the Toolkit is registered as the handler for files with the .jsx extension (as it is by default), opening the file opens the target application to run the script. If this directive is not present, the Toolkit loads and displays the script.
CHAPTER 8: ExtendScript Tools and Features Operator overloading 236 You can override the following operators: Unary +, ~ Binary +, *, /, %, ^ <, <=, == <<, >>, >>> &, |, === X The operators > and >= are implemented by executing NOT operator <= and NOT operator <. X Combined assignment operators such as *= are not supported. All operator overload implementations must return the result of the operation. To perform the default operation, return undefined.
9 Integrating XML into JavaScript ExtendScript defines the XML object, which allows you to process XML with your JavaScript scripts. This feature offers a subset of the functionality specified by the ECMA-357 specification (E4X). For more information on this standard, see: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf The XML Object The XML object represents an XML element node in an XML tree. The topmost XML object for an XML file represents the root node.
CHAPTER 9: Integrating XML into JavaScript The XML Object 238 If an element is empty in the XML, the corresponding property exists and contains an empty XML object; it is never null or undefined. Accessing XML elements This sample XML code is used for examples throughout this chapter: The Boston Cooking-School Cookbook Fannie Merrit Farmer 1896 49.
CHAPTER 9: Integrating XML into JavaScript The XML Object 239 Accessing XML attributes Attribute are properties of their parent elements. In ExtendScript, access an attribute name by using a preceding at-sign (@). An attribute property is a one-element list, which contains an XML object for the value of the attribute. For example: bookstoreXML.book [0].@category; This returns the category attribute of the first book, whose value is the string “COOKING”.
CHAPTER 9: Integrating XML into JavaScript The XML Object 240 Modifying XML elements and attributes You can change an element by assigning a value to the corresponding property. X If the value assigned is an XML element, the element is simply replaced. If there are multiple elements of the same type, the first element is replaced, and all other elements are deleted. X If the value assigned is not XML, it is converted to a string, and the content of the element is replaced with that string.
CHAPTER 9: Integrating XML into JavaScript The XML Object 241 The result is this XML: The Wonderful Wizard of Oz ... Deleting elements and attributes To delete an element or attribute in the XML, use the JavaScript delete operator to delete the corresponding element or attribute property. If there are multiple instances of an element, you can delete all, or refer to a single one by its index.
CHAPTER 9: Integrating XML into JavaScript X The XML Object 242 The result of XML.children() contains 3 elements, the direct child tags and , and the directly contained text of the tag: > x.children() one text two text inside text top text > x.children().length() 3 X The result of XML.elements() contains 2 elements, the direct child tags and : > x.elements() one text two text inside text > x.
CHAPTER 9: Integrating XML into JavaScript The XML Object 243 The Boston Cooking-School Cookbook Fannie Merrit Farmer 1896 49.99 The Wonderful Wizard of Oz L. Frank Baum 1900 39.95 ... When this namespace is defined, the simple statement bookstoreXML.
CHAPTER 9: Integrating XML into JavaScript X The XML Object 244 If you have assigned an element to a namespace, and have not made it the default, you must use a Namespace object to access those elements. For example: var ns = new Namespace ("http://kids.mybookstore.com"); bookstoreXML.ns::book; This returns all books that have been assigned to the "kids" namespace.
CHAPTER 9: Integrating XML into JavaScript The XML Object 245 All XML statements and functions that collect XML return the result as an XMLList, which can be empty if there is no match. For example, the following statement returns an empty list: bookstoreXML.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 246 XML Object Reference This section provides reference details for the properties and methods of the XML object itself, and for the related utility objects and global functions that you use to work with namespaces: X “XML object” on page 246 X “Namespace object” on page 255 X “QName object” on page 255 X “Global functions” on page 254 XML object The XML object provides both static properties and functions, available through the XML
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 247 prettyIndent Number The number of spaces to use for indenting when pretty-printing. Default is 2. prettyPrinting Boolean When true, toXMLString() uses indenting and line feeds to create the XML string. Default is true. XML class functions These static functions are available through the XML class, and provide information about the global settings of the XML parser. defaultSettings() XML.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 248 XML object functions addNamespace() xmlObj.addNamespace (ns); ns A Namespace object. Adds a namespace declaration to this node. Returns this XML object. appendChild() xmlObj.appendChild (child); child An XML object or any value that can be converted to a String with toString(). Appends a child element to this node, after any existing children.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 249 contains() xmlObj.contains (element); element An XML object. Reports whether an element is contained in this node at any level of nesting. Returns true if the element is contained in this XML tree. copy() xmlObj.copy(); Creates a copy of this node. Returns the new XML object. descendants() xmlObj.descendants ([name]); name Optional. A String, the element name to match. If not provided, matches all elements.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 250 inScopeNamespaces() xmlObj.inScopeNamespaces (); Retrieves the current list of valid namespaces in this element. Returns an Array of Namespace objects, in which the last member is the default namespace. insertChildAfter() xmlObj.insertChildAfter (child1, child2); child1 An XML object, the existing child element after which to place the new child, or null to insert the new child at the beginning.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 251 namespace() xmlObj.namespace (); Retrieves the namespace URI of this element. Returns a String. nodeKind() xmlObj.nodeKind (); Reports the type of this node. Returns a String, one of: element attribute comment processing-instruction text namespaceDeclarations() xmlObj.namespaceDeclarations (); Retrieves all of the namespace declarations contained in this node. Returns an Array of Namespace objects. normalize() xmlObj.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 252 processingInstructions() xmlObj.processingInstructions ([name]); name A String, the name of a processing instruction, or null to get all processing instructions. Retrieves processing instructions contained in this node. Returns an XML object containing the children of this object that are processing instructions, matching the name if supplied. replace() xmlObj.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 253 setNamespace() xmlObj.setNamespace(ns); A Namespace object for a namespace that has been declared in the tree above this element. ns Sets the namespace for this XML element. If the namespace has not been declared in the tree above this element, add a namespace declaration instead. Returns this XML object. text() xmlObj.text(); Retrieves text nodes from this element.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 254 xpath() xmlObj.xpath (expression[, variables]); expression A String containing an XPath expression. NOTE: In this context, include the actual top level element. For example, an expression for the example XML must start with “/bookstore”. This is unlike JavaScript property access, where the top level element is implied. variables Optional. A JavaScript object containing variable definitions.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 255 QName object This object encapsulates a fully qualified XML name, the combination of a local XML name and its namespace URI. QName object constructors The constructor takes several forms: new new new new QName QName QName QName () (name) (ns) (uri, name) When no arguments are supplies, creates a QName object with an empty local name and no URI.
CHAPTER 9: Integrating XML into JavaScript XML Object Reference 256 Namespace object constructors The Namespace constructor takes several forms: new new new new new Namespace() Namespace (String uri) Namespace (QName prefix) Namespace (Namespace ns) Namespace (String prefix, String uri) When no argument is supplied, creates a namespace with an empty prefix and URI. uri String Creates a Namespace object with an empty prefix and the given URI.
10 Scripting Access to XMP Metadata XMPScript, the XMP ExtendScript API, offers JavaScript access to the Adobe XMP Core and XMP Files libraries. This chapter provides reference information for the JavaScript objects related to XMP, with their properties and methods. This chapter is not intended to provide complete details of the XMP metadata technology. For more information about XMP metadata, see the XMP Specification at Adobe Developer Center, http://www.adobe.com/devnet/.
CHAPTER 10: Scripting Access to XMP Metadata Accessing the XMP scripting API 258 Using the XMP scripting API The XMPMeta object is the primary means of access to the namespaces and properties of an XMP metadata packet. Through this object, you can create and delete namespaces and properties, and examine and modify property values. You can obtain or create an XMPMeta object in several ways: X You can use an XMPFile object to retrieve existing metadata directly from a file. The XMPFile.
CHAPTER 10: Scripting Access to XMP Metadata Accessing the XMP scripting API 259 // retrieve property prop = xmp.getProperty(XMPConst.NS_XMP, "CreatorTool"); $.writeln("namespace: " + prop.namespace + \n + "property path + name: " + prop.path + \n + "value: " + prop); // same as prop.value Modifying existing metadata This code accesses an existing XMP packet, assuming the location has been assigned to a string variable.
CHAPTER 10: Scripting Access to XMP Metadata Accessing the XMP scripting API 260 Integrating XMPScript with Adobe Bridge This script adds a command to the context menu for Thumbnails that shows some of the XMP properties. It demonstrates how to retrieve the XMP metadata that is stored with the Thumbnail object, and use it to create an XMPMeta object, then use that object to retrieve different types of property values.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 261 XMPScript object reference The classes defined for the XMP JavaScript API, with their properties and methods, are listed here in alphabetical order. After the library has been loaded, these XMP classes are available in the global JavaScript namespace: XMPMeta object Provides the core services of the XMP Toolkit. XMPFile object Provides convenient I/O access to the main, or document level, XMP for a file.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 262 XMPAliasInfo object This object is returned by XMPMeta.resolveAlias(). The read-only properties describe an XMP metadata alias. XMPAliasInfo object properties arrayForm Number A constant that describes the property type of the resolved alias, 0 for a simple property. Constants are: X XMPConst.ALIAS_TO_SIMPLE_PROP: A direct mapping. It can be simple-to-simple, array-to-array, or structure-to-structure. X XMPConst.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 263 NS_XMP_MM The XML namespace for the XMP digital asset management schema. NS_XMP_BJ The XML namespace for the job management schema. NS_XMP_NOTE The XML namespace for the XMP note schema. An Adobe private namespace; do not create new properties. NS_PDF The XML namespace for the PDF schema. NS_PDFX The XML namespace for the PDFX schema. An Adobe private namespace; do not create new properties.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference TYPE_RESOURCE_EVENT The XML namespace for fields of the ResourceEvent type. TYPE_RESOURCE_REF The XML namespace for fields of the ResourceRef type. TYPE_ST_VERSION The XML namespace for fields of the Version type. TYPE_ST_JOB The XML namespace for fields of the JobRef type. TYPE_MANIFEST_ITEM The XML namespace for the elements of a manifest array.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference FILE_MPEG2 MP2 FILE_MPEG4 MP4 FILE_WMAV WMAV, Windows Media Audio and Video FILE_AIFF AIFF FILE_HTML HTML FILE_XML XML FILE_TEXT TEXT FILE_PHOTOSHOP PSD, Photoshop FILE_ILLUSTRATOR AI, Illustrator FILE_INDESIGN INDD, Indesign FILE_AE_PROJECT AE, After Effects FILE_AE_PROJECT_TEMPLATE AET, After Effects Project Template FILE_AE_FILTER_PRESET FFX, After Effects Filter Preset file FILE_ENCORE_PROJECT NCOR, Enco
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 266 XMPDateTime object properties All properties are read-write, and allow you to modify the date-time value. If values are set outside the allowed range, they are automatically set to the minimum or maximum allowed value. year Number The year, in the range [0000...9999]. month Number The month, in the range [1...12]. day Number The day, in the range [1...31]. hour Number The hour, in the range [1...23].
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 267 getDate() XMPDateTimeObj.getDate() Converts this date-time value to a JavaScript Date. The time zone is normalized (time zones are not supported in the JavaScript format), and the accuracy is reduced to milliseconds. Returns a JavaScript Date object. setLocalTimeZone() XMPDateTimeObj.setLocalTimeZone() Sets the time zone in this object to the current operation-system value, replacing any existing value.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 268 XMPFile object constructors new XMPFile( filePath, format, openFlags) filePath A string containing the file path of a document. format The file format constant. See “File format numeric constants” on page 264. openFlags The open options for the file. One of these constants: X XMPConst.OPEN_FOR_READ Open for read-only access. X XMPConst.OPEN_FOR_UPDATE Open for reading and writing. X XMPConst.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 269 XMPFile class functions This function is available as a static method of the XMPFile class. It is not necessary to create an instance to call it. getFormatInfo() XMPFile.getFormatInfo(format) format The file format constant. See “File format numeric constants” on page 264. Reports the supported features for the given file format. Returns a logical OR of bit-flag constants, or 0 if the format is not handled.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 270 closeFile() XMPFileObj.closeFile(closeFlags) closeFlags A close-option constant, or 0. Close options are: X XMPConst.CLOSE_UPDATE_SAFELY Write into a temporary file then swap for crash safety. Closes this open file, after writing to it as necessary; that is, if the file was opened for update, and if the XMP metadata was updated or injected.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 271 XMPFileInfo object This object is returned by XMPFile.getFileInfo(). The read-only properties describe the file represented by the XMPFile object. NOTE: This object is not related to the XMP File Info dialog that Adobe Creative Suite 4 applications use to display metadata. XMPFileInfo object properties filePath String The absolute path of the file, in JavaScript notation. format Number One of the file-format constants.
CHAPTER 10: Scripting Access to XMP Metadata openFlags XMPScript object reference 272 Number The options with which this file was opened. One of these constants: XMPConst.OPEN_FOR_READ — Open for read-only access. XMPConst.OPEN_FOR_UPDATE — Open for reading and writing. XMPConst.OPEN_ONLY_XMP — Only the XMP is wanted, allows space/time optimizations. XMPConst.OPEN_STRICTLY — Be strict about locating XMP and reconciling with other forms. XMPConst.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 273 There is one static property on the class that provides XMP version information; there are no JavaScript properties in the instance. The object encapsulates a set of metadata properties, which you access through the object functions. The generic functions getProperty(), setProperty(), and deleteProperty() allow you to manipulate all types of properties, when used with appropriately composed path expressions.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference deleteNamespace() XMPMeta.deleteNamespace (namespaceURI) namespaceURI The namespace URI string. See “Schema namespace string constants” on page 262. Deletes a registered prefix - namespace URI pair. NOTE: Not yet implemented in the XMP Toolkit. Returns undefined. dumpAliases() XMPMeta.dumpAliases ( ) Creates and returns a human-readable string containing the list of registered aliases and their targets. Returns a String.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 275 registerAlias() XMPMeta.registerAlias (aliasNS, aliasProp, actualNS, actualProp, arrayForm ) aliasNS The alias namespace string. See “Schema namespace string constants” on page 262. aliasProp The alias property, a simple name string. actualNS The namespace string of the aliased property. See “Schema namespace string constants” on page 262. actualProp The aliased property, a simple name string. arrayForm Number.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 276 resolveAlias() XMPMeta.resolveAlias (aliasNS, aliasProp) schemaNS The alias namespace URI string. See “Schema namespace string constants” on page 262. aliasProp The alias property string. Retrieves information about the actual property to which an alias is mapped. Returns an XMPAliasInfo object. XMPMeta object functions appendArrayItem() XMPMetaObj.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 277 deleteArrayItem() XMPMetaObj.deleteArrayItem(schemaNS, arrayName,itemIndex) schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. arrayName The array-type property name string. Can be a general path expression. itemIndex Number. The 1-based position index of the item. Use XMPConst.ARRAY_LAST_ITEM to reference the last existing item in the array.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference doesArrayItemExist() XMPMetaObj.doesArrayItemExist(schemaNS, arrayName, itemIndex) schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. arrayName The array name string. Can be a general path expression. itemIndex Number. The 1-based position index of the item. Reports whether an array item with a given index currently exists in an existing array in the metadata.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 279 dumpObject() XMPMetaObj.dumpObject ( ) Creates and returns a string containing the metadata content of this object as RDF. Returns a String. getArrayItem() XMPMetaObj.getArrayItem(schemaNS, arrayName, itemIndex) schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. arrayName The array name string. Can be a general path expression. itemIndex Number. The 1-based position index of the item.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 280 getProperty() XMPMetaObj.getProperty(schemaNS, propName[, valueType]) schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. propName The property name string. Can be a general path expression. valueType Optional, String. The property data type, one of: XMPConst.STRING XMPConst.INTEGER XMPConst.NUMBER XMPConst.BOOLEAN XMPConst.XMPDATE Retrieves the value and options of a metadata property.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 281 insertArrayItem() XMPMetaObj.insertArrayItem(schemaNS, arrayName, itemIndex, itemValue[, itemOptions]) schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. arrayName String. The name of an existing array. Can be a general path expression. itemIndex Number. The 1-based position index at which to insert the new item. Use XMPConst.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 282 serialize() XMPMetaObj.serialize([options, padding, indent, newline, baseIndent]) options Optional. The set of options that control how the serialization is performed. The options must be logically consistent; if they conflict, the function throws an exception. A logical OR of these bit-flag constants: XMPConst.SERIALIZE_OMIT_PACKET_WRAPPER — Do not include an XML packet wrapper. XMPConst.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 283 serializeToArray() XMPMetaObj.serializeToArray([options, padding, indent, newline, baseIndent]) options Optional. The set of options that control how the serialization is performed. The options must be logically consistent; if they conflict, the function throws an exception. A logical OR of these bit-flag constants: XMPConst.SERIALIZE_OMIT_PACKET_WRAPPER: — Do not include an XML packet wrapper. XMPConst.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 284 setArrayItem() XMPMetaObj.setArrayItem(schemaNS, arrayName, itemIndex, itemValue[, itemOptions]) schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. arrayName The name string of an existing array. Can be a general path expression. itemIndex Number. The 1-based position index of the item. Use XMPConst.ARRAY_LAST_ITEM to replace the last existing item in the array.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 285 setStructField() XMPMetaObj.setStructField(schemaNS, structName, fieldNS, fieldName, fieldValue[, options]) schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. structName The name string of an existing structure. Can be a general path expression. fieldNS The field type namespace string. See “Type namespace string constants” on page 263. fieldName The field name string.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 286 setProperty() XMPMetaObj.setProperty(schemaNS, propName, propValue[, setOptions, valueType]) schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. propName The property name string. Can be a general path expression. propValue The new property value string. Pass null to create an array or non-leaf level structure property. setOptions Optional.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 287 XMPPacketInfo object This object is returned by XMPFile.getPacketInfo(). The read-only properties describe the XMP packet for the file represented by the XMPFile object.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 288 path String The property path, including the property name. For a simple property, the entire path is the property name. value Variant The value of the property, if any. Arrays and non-leaf levels of structures do not have values. XMPUtils object This class provides additional utility functions for the XMP Toolkit, layered upon the functionality of the XMPMeta object.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 289 catenateArrayItems() XMPUtils.catenateArrayItems(xmpObj, schemaNS, arrayName, separator, quotes, options) xmpObj The XMPMeta object containing the array. schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. arrayName The array property name string. Can be a general path expression. Each item in the array must be a simple string value.
CHAPTER 10: Scripting Access to XMP Metadata fieldNS The field namespace URI string. fieldName The field name. Must be a simple XML name. fieldValue The desired field value. XMPScript object reference 290 Creates and returns a string containing the path expression to select an alternate item by a field’s value, using the registered prefixes for the namespaces, in the form: schemaNS:arrayName[fieldNS:fieldName=’fieldValue’] Returns a String. composeLanguageSelector() XMPUtils.
CHAPTER 10: Scripting Access to XMP Metadata qualName XMPScript object reference 291 The qualifier name. Must be a simple XML name. Creates and returns a string containing the path expression for a qualifier attached to a property, using the registered prefix for the namespace, in the form: schemaNS:propName/?qualNS:qualName Returns a String. duplicateSubtree() XMPUtils.duplicateSubtree(source, dest, sourceNS, sourceRoot, destNS, destRoot, options) source The source XMPMeta object.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 292 removeProperties() XMPUtils.removeProperties(xmpObj, schemaNS, propName, options) xmpObj The XMPMeta object. schemaNS Optional. The namespace URI string. See “Schema namespace string constants” on page 262. Must be supplied if a property name is supplied. propName Optional. The property name string. Can be a general path expression. options Option flags that control the deletion operation.
CHAPTER 10: Scripting Access to XMP Metadata XMPScript object reference 293 separateArrayItems() XMPUtils.separateArrayItems(xmpObj, schemaNS, arrayName, arrayOptions, concatString) xmpObj The XMPMeta object containing the array. schemaNS The namespace URI string. See “Schema namespace string constants” on page 262. arrayName The array property name string. Can be a general path expression. Each item in the array must be a simple string value.
11 Porting Guide This chapter briefly describes changes between this release and the previous release of ExtendScript, to aid you in porting applications to current versions. X ExtendScript Toolkit Z X X This version of ExtendScript Toolkit comes with a number of improvements related to its usability. For complete details, see the README file.
Index A absolute paths, 40 ActionScript, calling foreign functions, 85 active engine status, 27 addition operator, 235 alerts about, 74 creating, 110 dialogs, 227 aliases, referencing, 42 alignment, child elements, 88 applications as script execution targets, 235 calling exported functions, 193 communication between, 166, 191 debugging, 27 identifying, 167 messaging framework, 170, 179 specifiers, 191 status indicators, 27 arrow marker, 20 AutoLayoutManager algorithm, 97 automatic layout about, 86 user-inte
Index 296 interapplication, See interapplication communication overview, 166 TCP connections, 194 comparison operators, 233 complex data types, passing, 177 computational expressions, unit values, 232 configuration ExtendScript Toolkit window, 14 layouts, 16 script display, 17 shortcut keys, 16 view options, 19 confirmation dialogs, 74, 110, 227 console, JavaScript, 28 containers, 127, 129, 134 about, 64 adding, 123 adding elements, 65 automatic layout, 165 common properties, 108 complex arrangements, 92–
Index 297 E editing features, 18 EditText objects, 69 creating, 125 encoding binary, 43 common names, 46 specific platform features, 45 supported names, 45 Unicode, 43 engines, JavaScript, 27 entry points direct library access, 203 indirect library access, 206 error handling example code, 175 filesystem, 43 list of error codes, 190 list of messages, 44 messaging framework, 190 setting strict, 234 syntax checking, 24 event callbacks, UIE event types, 83 event handlers calling rules, 84 calling sequence, 84
Index 298 object references, 39, 47, 56 Flash communicating with, 85 control functions, 145 examples, 86 FlashPlayer objects, 72 floating palettes, 63 Folder class functions, 58 properties, 56 Folder object about, 56 constructors, 56 functions, 59 properties, 59 folders distinguishing from files, 39 platform-independent objects, 39 startup locations, 168 supported encoding names, 45 fonts, customizing, 155, 161 frames, user-interface controls, 64 FTP protocol, using, 194 function pointers SoObjectInterfac
Index 299 list of object types, 76 objects, 76 L layout AutoLayoutManager algorithm, 97 automatic, 86, 165 custom example, 95 default behavior, 87 preferred size of elements, 92 properties, 87 restrictions, 98 setting margins, 91 user-interface controls, 64, 165 user-interface elements, 86 LayoutManager object, 165 libraries accessing functions, 200 additional functions, 203 calling JS objects, 207 defining entry points for direct access, 203 defining entry points for indirect access, 206 initializing, 2
Index 300 MouseEvent object, 153 multi-column lists, 73 N Namespace object, 255 namespace specifiers about, 193 accessing cross-DOM functions, 167 identifying applications with, 167 namespaces for external functions, 167 global functions, 254 XML definitions, 255 namespaces in XML, 242 naming scripts, 234 navigation about, 19 bookmarks, 20 mouse and keyboard, 21 view options, 19 nested container elements, 64 notification dialogs, 227 O object models, inspecting, 36 objects BridgeTalk message, 170 Contro
Index 301 platform-independent paths, 39 Point object, 77 portability of file references, 42 porting guide, 294 preferences keyboard shortcuts, 21 saving settings, 16 view options, 19 preprocessor directives, 233 Profiling tool about, 35 color coding, 36 program execution, optimizing, 35 Progressbar objects, 70 creating, 130 prompts, 74, 227 properties, common, 108 Q QName object, 255 R RadioButton objects, 70 creating, 131 reflection object, 221 ReflectionInfo object, 222 relative paths, 40 release not
Index 302 shortcut keys for user-interface elements, 81 shortcuts bookmarks, 20 configuring, 16 dismissing dialogs, 75 keyboard list, 21 mouse and keyboard, 21 setting keyboard preferences, 15 signatures, function, 204 size assigning automatically, 97 list of object types, 76 objects, 76 preferred, 92 setting preferences, 92 slashes in paths, 40 Slider objects, 70 creating, 132 SoCClientName data structure, 213 Socket object about, 194 availability, 194 constructor, 197 functions, 197 properties, 197 refe
Index 303 fonts, 161 graphic customization objects, 155 grouping, 64, 67 methods, 142 pens, 163 placing, 76 properties, 135 registering listeners, 82 removing, 67 responding to user interaction, 147 size and location, 64 tools, 10, 62 types, 67 user-interface elements common properties, 108 object reference, 105 UTF encoding, 43 V variables defining, 12 examining values, 33 version comments, 23 view options, 19 volumes, specifying in paths, 41 W waiting status, 27 Window class, 110 Window object about,
Index 304 XMPMeta object, 272 using, 258 XMPProperty object, 287 XMPScript, 257 API reference, 261 constant values, 262 integrating with Adobe Bridge, 258 loading, 257 usage, 258 XMPUtils object, 288