Adobe CS2 Photoshop graphics software JavaScript Scripting Reference

Adobe CS2 Photoshop graphics software JavaScript Scripting Reference
Add to My manuals

Below you will find brief information for graphics software CS2 Photoshop. This document provides a reference for using JavaScript to automate Photoshop tasks. You can use the scripting engine to create custom scripts to automate repetitive tasks, extend Photoshop's functionality, and integrate Photoshop into workflows.

advertisement

Assistant Bot

Need help? Our chatbot has already read the manual and is ready to assist you. Feel free to ask any questions about the device, but providing details will make the conversation more productive.

Adobe Photoshop CS2 JavaScript Scripting Reference - Adobe | Manualzz

JavaScript Scripting Reference

c

© 2005 Adobe Systems Incorporated. All rights reserved.

Adobe® Creative Suite 2 Photoshop

®

JavaScript Scripting Reference 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. The software described in this document is furnished under license and may only be used or copied in accordance with the terms of such license.

This publication and the information herein is furnished AS IS, is subject to change without notice, and should not be construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies, makes no warranty of any kind (express, implied, or statutory) with respect to this publication, and expressly disclaims any and all warranties of merchantability, fitness for particular purposes, and noninfringement of third party rights.

Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any actual organization.

Adobe, the Adobe logo, Acrobat, GoLive, Illustrator, Photoshop are either registered trademarks or trademarks of Adobe Systems

Incorporated in the United States and/or other countries.

Apple, Mac OS, and Macintosh are trademarks of Apple Computer, Inc., registered in the United States and other countries. Microsoft, and

Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and other countries. JavaScript and all

Java-related marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. UNIX is a registered trademark of The Open Group.

All other trademarks are the property of their respective owners.

If this guide is distributed with software that includes an end user agreement, this guide, as well as the software described in it, is furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end user license agreement.

The content of this guide is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies that may appear in the informational content contained in this guide.

Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA.

Contents

1 Introduction ............................................................................................................................... 37

Script Support in Adobe Photoshop CS2 ............................................................................................................................37

JavaScript support .................................................................................................................................................................38

Executing scripts ....................................................................................................................................................................38

Installing scripts ...............................................................................................................................................................38

Executing other scripts ..................................................................................................................................................38

Startup scripts .........................................................................................................................................................................38

Changes Since Earlier Versions................................................................................................................................................39

Changes in ScriptUI ...............................................................................................................................................................39

2 JavaScript Object Reference ..................................................................................................... 41

Working with the Properties Tables ......................................................................................................................................41

displayDialogs.................................................................................................................................................................41

Working with the Methods Tables .........................................................................................................................................41

executeAction.................................................................................................................................................................42

Working with Method Parameters ..................................................................................................................................42

ActionDescriptor ..........................................................................................................................................................................43

Properties..................................................................................................................................................................................43

count ..................................................................................................................................................................................43

typename .........................................................................................................................................................................43

Methods ....................................................................................................................................................................................43

clear ....................................................................................................................................................................................43

erase ...................................................................................................................................................................................43

fromStream......................................................................................................................................................................43

getBoolean.......................................................................................................................................................................43

getClass .............................................................................................................................................................................43

getData..............................................................................................................................................................................43

getDouble ........................................................................................................................................................................43

getEnumerationType ...................................................................................................................................................43

getEnumerationValue..................................................................................................................................................43

getInteger.........................................................................................................................................................................43

getKey................................................................................................................................................................................43

getList ................................................................................................................................................................................43

getObjectType................................................................................................................................................................44

getObjectValue...............................................................................................................................................................44

getPath ..............................................................................................................................................................................44

getReference ...................................................................................................................................................................44

getString ...........................................................................................................................................................................44

getType .............................................................................................................................................................................44

getUnitDoubleType ......................................................................................................................................................44

getUnitDoubleValue.....................................................................................................................................................44

hasKey................................................................................................................................................................................44

isEqual................................................................................................................................................................................44

putBoolean ......................................................................................................................................................................44

putClass.............................................................................................................................................................................44

putData .............................................................................................................................................................................44

3

Adobe Photoshop CS2

JavaScript Scripting Reference 4

putDouble ........................................................................................................................................................................44

putEnumerated ..............................................................................................................................................................44

putInteger ........................................................................................................................................................................44

putList ................................................................................................................................................................................45

putObject..........................................................................................................................................................................45

putPath..............................................................................................................................................................................45

putReference...................................................................................................................................................................45

putString...........................................................................................................................................................................45

putUnitDouble................................................................................................................................................................45

toStream ...........................................................................................................................................................................45

ActionList.........................................................................................................................................................................................46

count ..................................................................................................................................................................................46

typename .........................................................................................................................................................................46

clear ....................................................................................................................................................................................46

getBoolean.......................................................................................................................................................................46

getClass .............................................................................................................................................................................46

getData..............................................................................................................................................................................46

getDouble ........................................................................................................................................................................46

getEnumerationType ...................................................................................................................................................46

getEnumerationValue..................................................................................................................................................46

getInteger.........................................................................................................................................................................46

getList ................................................................................................................................................................................46

getObjectType................................................................................................................................................................46

getObjectValue...............................................................................................................................................................47

getPath ..............................................................................................................................................................................47

getReference ...................................................................................................................................................................47

getString ...........................................................................................................................................................................47

getType .............................................................................................................................................................................47

getUnitDoubleType ......................................................................................................................................................47

getUnitDoubleValue.....................................................................................................................................................47

putBoolean ......................................................................................................................................................................47

putClass.............................................................................................................................................................................47

putData .............................................................................................................................................................................47

putDouble ........................................................................................................................................................................47

putEnumerated ..............................................................................................................................................................47

putInteger ........................................................................................................................................................................47

putList ................................................................................................................................................................................47

putObject..........................................................................................................................................................................47

putPath..............................................................................................................................................................................47

putReference...................................................................................................................................................................48

putString...........................................................................................................................................................................48

putUnitDouble................................................................................................................................................................48

ActionReference ...........................................................................................................................................................................49

Properties..................................................................................................................................................................................49

typename .........................................................................................................................................................................49

Methods ....................................................................................................................................................................................49

getContainer ...................................................................................................................................................................49

getDesiredClass..............................................................................................................................................................49

getEnumeratedType.....................................................................................................................................................49

getEnumeratedValue ...................................................................................................................................................49

getForm.............................................................................................................................................................................49

Adobe Photoshop CS2

JavaScript Scripting Reference 5

getIdentifier .....................................................................................................................................................................49

getIndex ............................................................................................................................................................................49

getName ...........................................................................................................................................................................49

getOffset ...........................................................................................................................................................................49

getProperty......................................................................................................................................................................49

putClass.............................................................................................................................................................................49

putEnumerated ..............................................................................................................................................................50

putIdentifier.....................................................................................................................................................................50

putIndex............................................................................................................................................................................50

putName ...........................................................................................................................................................................50

putOffset...........................................................................................................................................................................50

putProperty......................................................................................................................................................................50

Application .....................................................................................................................................................................................51

Properties..................................................................................................................................................................................51

activeDocument.............................................................................................................................................................51

backgroundColor...........................................................................................................................................................51

colorSettings ...................................................................................................................................................................51

displayDialogs.................................................................................................................................................................51

documents .......................................................................................................................................................................51

fonts....................................................................................................................................................................................51

foregroundColor ............................................................................................................................................................51

freeMemory .....................................................................................................................................................................51

locale ..................................................................................................................................................................................51

macintoshFileTypes ......................................................................................................................................................51

name...................................................................................................................................................................................51

notifiers .............................................................................................................................................................................52

notifiersEnabled .............................................................................................................................................................52

path.....................................................................................................................................................................................52

playbackDisplayDialogs ..............................................................................................................................................52

playbackParameters .....................................................................................................................................................52

preferences ......................................................................................................................................................................52

preferencesFolder .........................................................................................................................................................52

scriptingVersion .............................................................................................................................................................52

typename .........................................................................................................................................................................52

version ...............................................................................................................................................................................52

windowsFileTypes.........................................................................................................................................................52

Methods ....................................................................................................................................................................................53

batch ..................................................................................................................................................................................53

beep....................................................................................................................................................................................53

bringToFront ...................................................................................................................................................................53

charIDToTypeID..............................................................................................................................................................53

doAction ...........................................................................................................................................................................53

executeAction.................................................................................................................................................................53

executeActionGet..........................................................................................................................................................53

load .....................................................................................................................................................................................53

makeContactSheet........................................................................................................................................................53

makePDFPresentation .................................................................................................................................................53

makePhotoGallery.........................................................................................................................................................53

makePhotomerge..........................................................................................................................................................54

makePicturePackage ....................................................................................................................................................54

open ...................................................................................................................................................................................54

Adobe Photoshop CS2

JavaScript Scripting Reference 6

purge..................................................................................................................................................................................54

stringIDToTypeID...........................................................................................................................................................54

typeIDToCharID..............................................................................................................................................................54

typeIDToStringID ...........................................................................................................................................................54

Second Sample Script...........................................................................................................................................................56

ArtLayer............................................................................................................................................................................................57

Properties..................................................................................................................................................................................57

allLocked...........................................................................................................................................................................57

blendMode.......................................................................................................................................................................57

bounds...............................................................................................................................................................................57

fillOpacity..........................................................................................................................................................................57

grouped ............................................................................................................................................................................57

isBackgroundLayer........................................................................................................................................................57

kind .....................................................................................................................................................................................57

linkedLayers.....................................................................................................................................................................57

name...................................................................................................................................................................................58

opacity ...............................................................................................................................................................................58

parent.................................................................................................................................................................................58

pixelsLocked....................................................................................................................................................................58

positionLocked...............................................................................................................................................................58

textItem.............................................................................................................................................................................58

transparentPixelsLocked.............................................................................................................................................58

typename .........................................................................................................................................................................58

visible .................................................................................................................................................................................58

Methods ....................................................................................................................................................................................58

adjustBrightnessContrast ...........................................................................................................................................58

adjustColorBalance .......................................................................................................................................................58

adjustCurves....................................................................................................................................................................58

adjustLevels .....................................................................................................................................................................59

applyAddNoise ...............................................................................................................................................................59

applyAverage ..................................................................................................................................................................59

applyBlur...........................................................................................................................................................................59

applyBlurMore ................................................................................................................................................................59

applyClouds.....................................................................................................................................................................59

applyCustomFilter.........................................................................................................................................................59

applyDeInterlace............................................................................................................................................................59

applyDespeckle ..............................................................................................................................................................59

applyDifferenceClouds ................................................................................................................................................59

applyDiffuseGlow ..........................................................................................................................................................59

applyDisplace..................................................................................................................................................................59

applyDustAndScratches..............................................................................................................................................60

applyGaussianBlur.........................................................................................................................................................60

applyGlassEffect.............................................................................................................................................................60

applyHighPass ................................................................................................................................................................60

applyLensBlur .................................................................................................................................................................60

applyLensFlare................................................................................................................................................................60

applyMaximum ..............................................................................................................................................................60

applyMedianNoise ........................................................................................................................................................60

applyMinimum ...............................................................................................................................................................60

applyMotionBlur ............................................................................................................................................................60

applyNTSC........................................................................................................................................................................60

Adobe Photoshop CS2

JavaScript Scripting Reference 7

applyOceanRipple .........................................................................................................................................................60

applyOffset.......................................................................................................................................................................61

applyPinch .......................................................................................................................................................................61

applyPolarCoordinates ................................................................................................................................................61

applyRadialBlur ..............................................................................................................................................................61

applyRipple......................................................................................................................................................................61

applySharpen..................................................................................................................................................................61

applySharpenEdges......................................................................................................................................................61

applySharpenMore .......................................................................................................................................................61

applyShear .......................................................................................................................................................................61

applySmartBlur...............................................................................................................................................................61

applySpherize .................................................................................................................................................................61

applyStyle.........................................................................................................................................................................61

applyTextureFill..............................................................................................................................................................62

applyTwirl.........................................................................................................................................................................62

applyUnSharpMask.......................................................................................................................................................62

applyWave........................................................................................................................................................................62

applyZigZag.....................................................................................................................................................................62

autoContrast....................................................................................................................................................................62

autoLevels ........................................................................................................................................................................62

clear ....................................................................................................................................................................................62

copy ....................................................................................................................................................................................62

cut........................................................................................................................................................................................62

desaturate ........................................................................................................................................................................62

duplicate ...........................................................................................................................................................................63

equalize .............................................................................................................................................................................63

invert ..................................................................................................................................................................................63

link.......................................................................................................................................................................................63

merge.................................................................................................................................................................................63

mixChannels....................................................................................................................................................................63

move...................................................................................................................................................................................64

photoFilter .......................................................................................................................................................................64

posterize ...........................................................................................................................................................................64

rasterize.............................................................................................................................................................................64

remove...............................................................................................................................................................................64

resize ..................................................................................................................................................................................64

rotate..................................................................................................................................................................................64

selectiveColor..................................................................................................................................................................65

shadowHighlight ...........................................................................................................................................................65

threshold...........................................................................................................................................................................65

translate ............................................................................................................................................................................65

unlink .................................................................................................................................................................................65

ArtLayers..........................................................................................................................................................................................68

Properties..................................................................................................................................................................................68

length.................................................................................................................................................................................68

parent.................................................................................................................................................................................68

typename .........................................................................................................................................................................68

Methods ....................................................................................................................................................................................68

index...................................................................................................................................................................................68

add ......................................................................................................................................................................................68

getByName ......................................................................................................................................................................68

Adobe Photoshop CS2

JavaScript Scripting Reference 8

removeAll .........................................................................................................................................................................68

BatchOptions .................................................................................................................................................................................69

Properties..................................................................................................................................................................................69

destination .......................................................................................................................................................................69

destinationFolder ..........................................................................................................................................................69

errorFile .............................................................................................................................................................................69

fileNaming........................................................................................................................................................................69

macintoshCompatible .................................................................................................................................................69

overrideOpen..................................................................................................................................................................69

overrideSave....................................................................................................................................................................70

startingSerial ...................................................................................................................................................................70

suppressOpen.................................................................................................................................................................70

suppressProfile ...............................................................................................................................................................70

typename .........................................................................................................................................................................70

unixCompatible..............................................................................................................................................................70

windowsCompatible ....................................................................................................................................................70

BitmapConversionOptions .......................................................................................................................................................71

Properties..................................................................................................................................................................................71

angle...................................................................................................................................................................................71

frequency..........................................................................................................................................................................71

method..............................................................................................................................................................................71

patternName ...................................................................................................................................................................71

resolution..........................................................................................................................................................................71

shape..................................................................................................................................................................................71

typename .........................................................................................................................................................................71

BMPSaveOptions ..........................................................................................................................................................................72

Properties..................................................................................................................................................................................72

alphaChannels ................................................................................................................................................................72

depth..................................................................................................................................................................................72

flipRowOrder ...................................................................................................................................................................72

osType................................................................................................................................................................................72

rleCompression ..............................................................................................................................................................72

typename .........................................................................................................................................................................72

CameraRawOpenOptions .........................................................................................................................................................73

Properties..................................................................................................................................................................................73

bitsPerChannel ...............................................................................................................................................................73

blueHue.............................................................................................................................................................................73

blueSaturation ................................................................................................................................................................73

brightness.........................................................................................................................................................................73

chromaticAberrationBY...............................................................................................................................................73

chromaticAberrationRC...............................................................................................................................................73

colorNoiseReduction....................................................................................................................................................73

colorSpace........................................................................................................................................................................73

contrast .............................................................................................................................................................................73

exposure ...........................................................................................................................................................................73

greenHue..........................................................................................................................................................................73

greenSaturation .............................................................................................................................................................73

luminanceSmoothing ..................................................................................................................................................73

redHue ...............................................................................................................................................................................73

redSaturation ..................................................................................................................................................................73

resolution..........................................................................................................................................................................73

Adobe Photoshop CS2

JavaScript Scripting Reference 9

saturation .........................................................................................................................................................................73

settings ..............................................................................................................................................................................73

shadows ............................................................................................................................................................................73

shadowTint ......................................................................................................................................................................74

sharpness..........................................................................................................................................................................74

size ......................................................................................................................................................................................74

temperature.....................................................................................................................................................................74

tint.......................................................................................................................................................................................74

typename .........................................................................................................................................................................74

vignettingAmount ........................................................................................................................................................74

vignettingMidpoint ......................................................................................................................................................74

whiteBalance...................................................................................................................................................................74

Channel............................................................................................................................................................................................75

Properties..................................................................................................................................................................................75

color....................................................................................................................................................................................75

histogram .........................................................................................................................................................................75

kind .....................................................................................................................................................................................75

name...................................................................................................................................................................................75

opacity ...............................................................................................................................................................................75

parent.................................................................................................................................................................................75

typename .........................................................................................................................................................................76

visible .................................................................................................................................................................................76

Methods ....................................................................................................................................................................................76

duplicate ...........................................................................................................................................................................76

merge.................................................................................................................................................................................76

delete .................................................................................................................................................................................76

Channels ..........................................................................................................................................................................................77

Properties..................................................................................................................................................................................77

length.................................................................................................................................................................................77

parent.................................................................................................................................................................................77

typename .........................................................................................................................................................................77

Methods ....................................................................................................................................................................................77

index...................................................................................................................................................................................77

add ......................................................................................................................................................................................77

getByName ......................................................................................................................................................................77

removeAll .........................................................................................................................................................................77

CMYKColor......................................................................................................................................................................................82

Properties..................................................................................................................................................................................82

black ...................................................................................................................................................................................82

cyan.....................................................................................................................................................................................82

magenta............................................................................................................................................................................82

typename .........................................................................................................................................................................82

yellow.................................................................................................................................................................................82

ContactSheetOptions .................................................................................................................................................................83

Properties..................................................................................................................................................................................83

acrossFirst.........................................................................................................................................................................83

bestFit ................................................................................................................................................................................83

caption...............................................................................................................................................................................83

columnCount ..................................................................................................................................................................83

flatten.................................................................................................................................................................................83

font......................................................................................................................................................................................83

Adobe Photoshop CS2

JavaScript Scripting Reference 10

fontSize..............................................................................................................................................................................83

height.................................................................................................................................................................................83

horizontal .........................................................................................................................................................................83

mode ..................................................................................................................................................................................83

resolution..........................................................................................................................................................................83

rowCount..........................................................................................................................................................................83

typename .........................................................................................................................................................................83

useAutoSpacing.............................................................................................................................................................83

vertical ...............................................................................................................................................................................84

width ..................................................................................................................................................................................84

DCS1_SaveOptions......................................................................................................................................................................85

Properties..................................................................................................................................................................................85

dCS ......................................................................................................................................................................................85

embedColorProfile........................................................................................................................................................85

encoding...........................................................................................................................................................................85

halftoneScreen ...............................................................................................................................................................85

interpolation....................................................................................................................................................................85

preview..............................................................................................................................................................................85

transferFunction.............................................................................................................................................................85

typename .........................................................................................................................................................................85

vectorData........................................................................................................................................................................85

DCS2_SaveOptions......................................................................................................................................................................86

Properties..................................................................................................................................................................................86

dCS ......................................................................................................................................................................................86

embedColorProfile........................................................................................................................................................86

encoding...........................................................................................................................................................................86

halftoneScreen ...............................................................................................................................................................86

interpolation....................................................................................................................................................................86

multiFileDCS....................................................................................................................................................................86

preview..............................................................................................................................................................................86

spotColors ........................................................................................................................................................................86

transferFunction.............................................................................................................................................................86

typename .........................................................................................................................................................................86

vectorData........................................................................................................................................................................86

Document .......................................................................................................................................................................................87

Properties..................................................................................................................................................................................87

activeChannels ...............................................................................................................................................................87

activeHistoryBrushSource ..........................................................................................................................................87

activeHistoryState .........................................................................................................................................................87

activeLayer .......................................................................................................................................................................87

artLayers............................................................................................................................................................................87

backgroundLayer...........................................................................................................................................................87

bitsPerChannel ...............................................................................................................................................................87

channels............................................................................................................................................................................87

colorProfileName...........................................................................................................................................................87

colorProfileType .............................................................................................................................................................87

componentChannels....................................................................................................................................................88

fullName............................................................................................................................................................................88

height.................................................................................................................................................................................88

histogram .........................................................................................................................................................................88

historyStates....................................................................................................................................................................88

Adobe Photoshop CS2

JavaScript Scripting Reference 11

info ......................................................................................................................................................................................88

layerComps ......................................................................................................................................................................88

layers ..................................................................................................................................................................................88

layerSets............................................................................................................................................................................88

managed...........................................................................................................................................................................88

mode ..................................................................................................................................................................................88

name...................................................................................................................................................................................88

parent.................................................................................................................................................................................88

path.....................................................................................................................................................................................88

pathItems .........................................................................................................................................................................88

pixelAspectRatio ............................................................................................................................................................88

quickMaskMode.............................................................................................................................................................88

resolution..........................................................................................................................................................................88

saved ..................................................................................................................................................................................88

selection............................................................................................................................................................................88

typename .........................................................................................................................................................................88

width ..................................................................................................................................................................................89

xmpMetadata..................................................................................................................................................................89

Methods ....................................................................................................................................................................................90

changeMode ...................................................................................................................................................................90

close....................................................................................................................................................................................90

convertProfile..................................................................................................................................................................90

crop.....................................................................................................................................................................................90

duplicate ...........................................................................................................................................................................90

exportDocument ...........................................................................................................................................................90

flatten.................................................................................................................................................................................90

flipCanvas .........................................................................................................................................................................91

importAnnotations .......................................................................................................................................................91

mergeVisibleLayersl......................................................................................................................................................91

paste...................................................................................................................................................................................91

print ....................................................................................................................................................................................91

rasterizeAllLayers...........................................................................................................................................................91

resizeCanvas ....................................................................................................................................................................91

resizeImage......................................................................................................................................................................91

revealAll.............................................................................................................................................................................91

rotateCanvas ...................................................................................................................................................................92

save .....................................................................................................................................................................................92

saveAs ................................................................................................................................................................................92

splitChannels...................................................................................................................................................................92

trap......................................................................................................................................................................................92

trim......................................................................................................................................................................................92

DocumentInfo ...............................................................................................................................................................................95

Properties..................................................................................................................................................................................95

author ................................................................................................................................................................................95

authorPosition ................................................................................................................................................................95

caption...............................................................................................................................................................................95

captionWriter ..................................................................................................................................................................95

category ............................................................................................................................................................................95

city.......................................................................................................................................................................................95

copyrighted .....................................................................................................................................................................95

copyrightNotice .............................................................................................................................................................95

Adobe Photoshop CS2

JavaScript Scripting Reference 12

country ..............................................................................................................................................................................95

creationDate....................................................................................................................................................................95

credit ..................................................................................................................................................................................95

exif.......................................................................................................................................................................................95

headline ............................................................................................................................................................................95

instructions ......................................................................................................................................................................95

jobName ...........................................................................................................................................................................95

keywords...........................................................................................................................................................................95

ownerUrl ...........................................................................................................................................................................95

parent.................................................................................................................................................................................96

provinceState..................................................................................................................................................................96

source.................................................................................................................................................................................96

supplementalCategories.............................................................................................................................................96

title ......................................................................................................................................................................................96

transmissionReference ................................................................................................................................................96

typename .........................................................................................................................................................................96

urgency .............................................................................................................................................................................96

Documents .....................................................................................................................................................................................99

Properties..................................................................................................................................................................................99

length.................................................................................................................................................................................99

parent.................................................................................................................................................................................99

typename .........................................................................................................................................................................99

Methods ....................................................................................................................................................................................99

index...................................................................................................................................................................................99

add ......................................................................................................................................................................................99

getByName ......................................................................................................................................................................99

EPSOpenOptions ....................................................................................................................................................................... 100

Properties............................................................................................................................................................................... 100

antiAlias.......................................................................................................................................................................... 100

constrainProportions ................................................................................................................................................ 100

height.............................................................................................................................................................................. 100

mode ............................................................................................................................................................................... 100

resolution....................................................................................................................................................................... 100

typename ...................................................................................................................................................................... 100

width ............................................................................................................................................................................... 100

EPSSaveOptions......................................................................................................................................................................... 101

Properties............................................................................................................................................................................... 101

embedColorProfile..................................................................................................................................................... 101

encoding........................................................................................................................................................................ 101

halftoneScreen ............................................................................................................................................................ 101

interpolation................................................................................................................................................................. 101

preview........................................................................................................................................................................... 101

psColorManagement ................................................................................................................................................ 101

transferFunction.......................................................................................................................................................... 101

transparentWhites...................................................................................................................................................... 101

typename ...................................................................................................................................................................... 101

vectorData..................................................................................................................................................................... 101

ExportOptionsIllustrator ......................................................................................................................................................... 102

Properties............................................................................................................................................................................... 102

path.................................................................................................................................................................................. 102

pathName...................................................................................................................................................................... 102

Adobe Photoshop CS2

JavaScript Scripting Reference 13

typename ...................................................................................................................................................................... 102

ExportOptionsSaveForWeb ................................................................................................................................................... 103

Properties............................................................................................................................................................................... 103

blur................................................................................................................................................................................... 103

colorReduction ............................................................................................................................................................ 103

colors............................................................................................................................................................................... 103

dither............................................................................................................................................................................... 103

ditherAmount .............................................................................................................................................................. 103

format ............................................................................................................................................................................. 103

includeProfile ............................................................................................................................................................... 103

interlaced....................................................................................................................................................................... 103

lossy ................................................................................................................................................................................. 103

matteColor .................................................................................................................................................................... 103

optimized ...................................................................................................................................................................... 103

PNG8................................................................................................................................................................................ 104

quality ............................................................................................................................................................................. 104

transparency................................................................................................................................................................. 104

transparencyAmount ................................................................................................................................................ 104

transparencyDither .................................................................................................................................................... 104

typename ...................................................................................................................................................................... 104

webSnap ........................................................................................................................................................................ 104

GalleryBannerOptions ............................................................................................................................................................. 105

Properties............................................................................................................................................................................... 105

contactInfo.................................................................................................................................................................... 105

date.................................................................................................................................................................................. 105

font................................................................................................................................................................................... 105

fontSize........................................................................................................................................................................... 105

photographer............................................................................................................................................................... 105

siteName........................................................................................................................................................................ 105

typename ...................................................................................................................................................................... 105

GalleryCustomColorOptions ................................................................................................................................................. 106

Properties............................................................................................................................................................................... 106

activeLinkColor............................................................................................................................................................ 106

backgroundColor........................................................................................................................................................ 106

bannerColor.................................................................................................................................................................. 106

linkColor......................................................................................................................................................................... 106

textColor ........................................................................................................................................................................ 106

typename ...................................................................................................................................................................... 106

visitedLinkColor........................................................................................................................................................... 106

GalleryImagesOptions ............................................................................................................................................................. 107

Properties............................................................................................................................................................................... 107

border ............................................................................................................................................................................. 107

caption............................................................................................................................................................................ 107

dimension...................................................................................................................................................................... 107

font................................................................................................................................................................................... 107

fontSize........................................................................................................................................................................... 107

imageQuality................................................................................................................................................................ 107

includeCopyright........................................................................................................................................................ 107

includeCredits.............................................................................................................................................................. 107

includeFilename.......................................................................................................................................................... 108

includeTitle ................................................................................................................................................................... 108

Adobe Photoshop CS2

JavaScript Scripting Reference 14

numericLinks ................................................................................................................................................................ 108

resizeConstraint .......................................................................................................................................................... 108

resizeImages................................................................................................................................................................. 108

typename ...................................................................................................................................................................... 108

GalleryOptions............................................................................................................................................................................ 109

Properties............................................................................................................................................................................... 109

addSizeAttributes ....................................................................................................................................................... 109

bannerOptions ............................................................................................................................................................ 109

customColorOptions ................................................................................................................................................. 109

emailAddress................................................................................................................................................................ 109

imagesOptions ............................................................................................................................................................ 109

includeSubFolders ..................................................................................................................................................... 109

layoutStyle .................................................................................................................................................................... 109

preserveAllMetadata ................................................................................................................................................. 109

securityOptions ........................................................................................................................................................... 109

thumbnailOptions...................................................................................................................................................... 109

typename ...................................................................................................................................................................... 109

useShortExtension ..................................................................................................................................................... 109

useUTF8Encoding ...................................................................................................................................................... 109

GallerySecurityOptions ........................................................................................................................................................... 110

Properties............................................................................................................................................................................... 110

content ........................................................................................................................................................................... 110

font................................................................................................................................................................................... 110

fontSize........................................................................................................................................................................... 110

opacity ............................................................................................................................................................................ 110

text ................................................................................................................................................................................... 110

textColor ........................................................................................................................................................................ 110

textPosition................................................................................................................................................................... 110

textRotate...................................................................................................................................................................... 110

typename ...................................................................................................................................................................... 110

GalleryThumbnailOptions...................................................................................................................................................... 111

Properties............................................................................................................................................................................... 111

border ............................................................................................................................................................................. 111

caption............................................................................................................................................................................ 111

columnCount ............................................................................................................................................................... 111

dimension...................................................................................................................................................................... 111

font................................................................................................................................................................................... 111

fontSize........................................................................................................................................................................... 111

includeCopyright........................................................................................................................................................ 111

includeCredits.............................................................................................................................................................. 111

includeFilename.......................................................................................................................................................... 111

includeTitle ................................................................................................................................................................... 111

rowCount....................................................................................................................................................................... 111

size ................................................................................................................................................................................... 111

typename ...................................................................................................................................................................... 111

GIFSaveOptions.......................................................................................................................................................................... 112

Properties............................................................................................................................................................................... 112

colors............................................................................................................................................................................... 112

dither............................................................................................................................................................................... 112

ditherAmount .............................................................................................................................................................. 112

forced .............................................................................................................................................................................. 112

Adobe Photoshop CS2

JavaScript Scripting Reference 15

interlaced....................................................................................................................................................................... 112

matte ............................................................................................................................................................................... 112

palette............................................................................................................................................................................. 112

preserveExactColors .................................................................................................................................................. 112

transparency................................................................................................................................................................. 113

typename ...................................................................................................................................................................... 113

GrayColor...................................................................................................................................................................................... 114

Properties............................................................................................................................................................................... 114

gray .................................................................................................................................................................................. 114

typename ...................................................................................................................................................................... 114

HistoryState ................................................................................................................................................................................. 115

Properties............................................................................................................................................................................... 115

name................................................................................................................................................................................ 115

parent.............................................................................................................................................................................. 115

snapshot ........................................................................................................................................................................ 115

typename ...................................................................................................................................................................... 115

HistoryStates ............................................................................................................................................................................... 116

Properties............................................................................................................................................................................... 116

length.............................................................................................................................................................................. 116

parent.............................................................................................................................................................................. 116

typename ...................................................................................................................................................................... 116

Methods ................................................................................................................................................................................. 116

index................................................................................................................................................................................ 116

getByName ................................................................................................................................................................... 116

HSBColor....................................................................................................................................................................................... 117

Properties............................................................................................................................................................................... 117

brightness...................................................................................................................................................................... 117

hue ................................................................................................................................................................................... 117

saturation ...................................................................................................................................................................... 117

typename ...................................................................................................................................................................... 117

IndexedConversionOptions .................................................................................................................................................. 118

Properties............................................................................................................................................................................... 118

colors............................................................................................................................................................................... 118

dither............................................................................................................................................................................... 118

ditherAmount .............................................................................................................................................................. 118

forced .............................................................................................................................................................................. 118

matte ............................................................................................................................................................................... 118

palette............................................................................................................................................................................. 118

preserveExactColors .................................................................................................................................................. 118

transparency................................................................................................................................................................. 118

typename ...................................................................................................................................................................... 118

JPEGSaveOptions ...................................................................................................................................................................... 119

Properties............................................................................................................................................................................... 119

embedColorProfile..................................................................................................................................................... 119

formatOptions ............................................................................................................................................................. 119

matte ............................................................................................................................................................................... 119

quality ............................................................................................................................................................................. 119

scans................................................................................................................................................................................ 119

typename ...................................................................................................................................................................... 119

LabColor ....................................................................................................................................................................................... 120

Properties............................................................................................................................................................................... 120

Adobe Photoshop CS2

JavaScript Scripting Reference 16

a......................................................................................................................................................................................... 120

b ........................................................................................................................................................................................ 120

l.......................................................................................................................................................................................... 120

typename ...................................................................................................................................................................... 120

LayerComp................................................................................................................................................................................... 121

Properties............................................................................................................................................................................... 121

appearance ................................................................................................................................................................... 121

comment ....................................................................................................................................................................... 121

name................................................................................................................................................................................ 121

parent.............................................................................................................................................................................. 121

position .......................................................................................................................................................................... 121

selected .......................................................................................................................................................................... 121

typename ...................................................................................................................................................................... 121

visibility .......................................................................................................................................................................... 121

Methods ................................................................................................................................................................................. 121

apply................................................................................................................................................................................ 121

recapture ....................................................................................................................................................................... 121

remove............................................................................................................................................................................ 122

resetfromComp ........................................................................................................................................................... 122

LayerComps................................................................................................................................................................................. 123

Properties............................................................................................................................................................................... 123

length.............................................................................................................................................................................. 123

parent.............................................................................................................................................................................. 123

typename ...................................................................................................................................................................... 123

Methods ................................................................................................................................................................................. 123

index................................................................................................................................................................................ 123

add ................................................................................................................................................................................... 123

getByName ................................................................................................................................................................... 123

removeAll ...................................................................................................................................................................... 123

Layers............................................................................................................................................................................................. 124

Properties............................................................................................................................................................................... 124

length.............................................................................................................................................................................. 124

parent.............................................................................................................................................................................. 124

typename ...................................................................................................................................................................... 124

Methods ................................................................................................................................................................................. 124

index................................................................................................................................................................................ 124

getByName ................................................................................................................................................................... 124

removeAll ...................................................................................................................................................................... 124

LayerSet ........................................................................................................................................................................................ 125

Properties............................................................................................................................................................................... 125

allLocked........................................................................................................................................................................ 125

artLayers......................................................................................................................................................................... 125

blendMode.................................................................................................................................................................... 125

bounds............................................................................................................................................................................ 125

enabledChannels........................................................................................................................................................ 125

layers ............................................................................................................................................................................... 125

layerSets......................................................................................................................................................................... 125

linkedLayers.................................................................................................................................................................. 125

name................................................................................................................................................................................ 125

opacity ............................................................................................................................................................................ 125

parent.............................................................................................................................................................................. 125

Adobe Photoshop CS2

JavaScript Scripting Reference 17

typename ...................................................................................................................................................................... 125

visible .............................................................................................................................................................................. 125

Methods ................................................................................................................................................................................. 126

duplicate ........................................................................................................................................................................ 126

link.................................................................................................................................................................................... 126

merge.............................................................................................................................................................................. 126

move................................................................................................................................................................................ 126

remove............................................................................................................................................................................ 126

resize ............................................................................................................................................................................... 126

rotate............................................................................................................................................................................... 126

translate ......................................................................................................................................................................... 126

unlink .............................................................................................................................................................................. 126

LayerSets ...................................................................................................................................................................................... 127

Properties............................................................................................................................................................................... 127

length.............................................................................................................................................................................. 127

parent.............................................................................................................................................................................. 127

typename ...................................................................................................................................................................... 127

Methods ................................................................................................................................................................................. 127

index................................................................................................................................................................................ 127

add ................................................................................................................................................................................... 127

getByName ................................................................................................................................................................... 127

removeAll ...................................................................................................................................................................... 127

LensBlurOptions ........................................................................................................................................................................ 129

Properties............................................................................................................................................................................... 129

amount ........................................................................................................................................................................... 129

bladeCurvature............................................................................................................................................................ 129

brightness...................................................................................................................................................................... 129

distribution ................................................................................................................................................................... 129

focalDistance................................................................................................................................................................ 129

invertDepthMap.......................................................................................................................................................... 129

monochromatic........................................................................................................................................................... 129

radius............................................................................................................................................................................... 129

rotation........................................................................................................................................................................... 129

shape............................................................................................................................................................................... 129

source.............................................................................................................................................................................. 129

threshold........................................................................................................................................................................ 129

typename ...................................................................................................................................................................... 129

NoColor ......................................................................................................................................................................................... 130

Properties............................................................................................................................................................................... 130

typename ...................................................................................................................................................................... 130

Notifier........................................................................................................................................................................................... 131

Properties............................................................................................................................................................................... 131

event................................................................................................................................................................................ 131

eventClass ..................................................................................................................................................................... 131

eventFile ........................................................................................................................................................................ 131

parent.............................................................................................................................................................................. 131

typename ...................................................................................................................................................................... 131

Methods ................................................................................................................................................................................. 131

remove............................................................................................................................................................................ 131

Notifiers......................................................................................................................................................................................... 132

Properties............................................................................................................................................................................... 132

Adobe Photoshop CS2

JavaScript Scripting Reference 18

length.............................................................................................................................................................................. 132

parent.............................................................................................................................................................................. 132

typename ...................................................................................................................................................................... 132

Methods ................................................................................................................................................................................. 132

index................................................................................................................................................................................ 132

add ................................................................................................................................................................................... 133

removeAll ...................................................................................................................................................................... 133

PathItem ....................................................................................................................................................................................... 134

Properties............................................................................................................................................................................... 134

kind .................................................................................................................................................................................. 134

name................................................................................................................................................................................ 134

parent.............................................................................................................................................................................. 134

SubPathItems............................................................................................................................................................... 134

typename ...................................................................................................................................................................... 134

Methods ................................................................................................................................................................................. 134

deselect .......................................................................................................................................................................... 134

duplicate ........................................................................................................................................................................ 134

fillPath ............................................................................................................................................................................. 134

makeClippingPath...................................................................................................................................................... 135

makeSelection ............................................................................................................................................................. 135

remove............................................................................................................................................................................ 135

select ............................................................................................................................................................................... 135

strokePath ..................................................................................................................................................................... 135

PathItems ..................................................................................................................................................................................... 138

Properties............................................................................................................................................................................... 138

length.............................................................................................................................................................................. 138

parent.............................................................................................................................................................................. 138

typename ...................................................................................................................................................................... 138

Methods ................................................................................................................................................................................. 138

index................................................................................................................................................................................ 138

add ................................................................................................................................................................................... 138

getByName ................................................................................................................................................................... 138

removeAll ...................................................................................................................................................................... 138

PathPoint...................................................................................................................................................................................... 139

Properties............................................................................................................................................................................... 139

anchor............................................................................................................................................................................. 139

kind .................................................................................................................................................................................. 139

leftDirection.................................................................................................................................................................. 139

parent.............................................................................................................................................................................. 139

rightDirection............................................................................................................................................................... 139

typename ...................................................................................................................................................................... 139

PathPointInfo .............................................................................................................................................................................. 140

Properties............................................................................................................................................................................... 140

anchor............................................................................................................................................................................. 140

kind .................................................................................................................................................................................. 140

leftDirection.................................................................................................................................................................. 140

rightDirection............................................................................................................................................................... 140

typename ...................................................................................................................................................................... 140

PathPoints.................................................................................................................................................................................... 141

Properties............................................................................................................................................................................... 141

length.............................................................................................................................................................................. 141

Adobe Photoshop CS2

JavaScript Scripting Reference 19

parent.............................................................................................................................................................................. 141

typename ...................................................................................................................................................................... 141

index................................................................................................................................................................................ 141

PDFOpenOptions ...................................................................................................................................................................... 142

Properties............................................................................................................................................................................... 142

antiAlias.......................................................................................................................................................................... 142

bitsPerChannel ............................................................................................................................................................ 142

constrainProportions ................................................................................................................................................ 142

cropPage........................................................................................................................................................................ 142

height.............................................................................................................................................................................. 142

mode ............................................................................................................................................................................... 142

name................................................................................................................................................................................ 142

page................................................................................................................................................................................. 142

resolution....................................................................................................................................................................... 142

suppressWarnings...................................................................................................................................................... 142

typename ...................................................................................................................................................................... 142

usePageNumber ......................................................................................................................................................... 142

width ............................................................................................................................................................................... 142

PDFSaveOptions ........................................................................................................................................................................ 143

Properties............................................................................................................................................................................... 143

alphaChannels ............................................................................................................................................................. 143

annotations................................................................................................................................................................... 143

colorConversion.......................................................................................................................................................... 143

convertToEightBit....................................................................................................................................................... 143

descripton ..................................................................................................................................................................... 143

destinationProfile ....................................................................................................................................................... 143

downgradeColorProfile............................................................................................................................................ 143

downSample ................................................................................................................................................................ 143

downSampleSize ........................................................................................................................................................ 143

downSampleSizeLimit .............................................................................................................................................. 143

embedColorProfile..................................................................................................................................................... 143

embedFonts ................................................................................................................................................................. 143

embedThumbnail....................................................................................................................................................... 143

encoding........................................................................................................................................................................ 143

interpolation................................................................................................................................................................. 143

jpegQuality ................................................................................................................................................................... 144

layers ............................................................................................................................................................................... 144

optimizeForWeb ......................................................................................................................................................... 144

outputCondition ......................................................................................................................................................... 144

outputConditionID..................................................................................................................................................... 144

PDFCompatibility........................................................................................................................................................ 144

PDFStandard ................................................................................................................................................................ 144

preserveEditing ........................................................................................................................................................... 144

presetFile ....................................................................................................................................................................... 144

profileInclusionPolicy................................................................................................................................................ 144

registryName................................................................................................................................................................ 144

spotColors ..................................................................................................................................................................... 144

tileSize............................................................................................................................................................................. 144

transparency................................................................................................................................................................. 144

typename ...................................................................................................................................................................... 144

useOutlines ................................................................................................................................................................... 145

Adobe Photoshop CS2

JavaScript Scripting Reference 20

vectorData..................................................................................................................................................................... 145

view.................................................................................................................................................................................. 145

PhotoCDOpenOptions ............................................................................................................................................................ 146

Properties............................................................................................................................................................................... 146

colorProfileName........................................................................................................................................................ 146

colorSpace..................................................................................................................................................................... 146

orientation..................................................................................................................................................................... 146

pixelSize ......................................................................................................................................................................... 146

resolution....................................................................................................................................................................... 146

typename ...................................................................................................................................................................... 146

PhotoshopSaveOptions .......................................................................................................................................................... 147

Properties............................................................................................................................................................................... 147

alphaChannels ............................................................................................................................................................. 147

annotations................................................................................................................................................................... 147

embedColorProfile..................................................................................................................................................... 147

layers ............................................................................................................................................................................... 147

spotColors ..................................................................................................................................................................... 147

typename ...................................................................................................................................................................... 147

PICTFileSaveOptions ................................................................................................................................................................ 148

Properties............................................................................................................................................................................... 148

alphaChannels ............................................................................................................................................................. 148

compression ................................................................................................................................................................. 148

embedColorProfile..................................................................................................................................................... 148

resolution....................................................................................................................................................................... 148

typename ...................................................................................................................................................................... 148

PICTResourceSaveOptions..................................................................................................................................................... 149

Properties............................................................................................................................................................................... 149

alphaChannels ............................................................................................................................................................. 149

compression ................................................................................................................................................................. 149

embedColorProfile..................................................................................................................................................... 149

name................................................................................................................................................................................ 149

resolution....................................................................................................................................................................... 149

resourceID ..................................................................................................................................................................... 149

typename ...................................................................................................................................................................... 149

PicturePackageOptions........................................................................................................................................................... 150

Properties............................................................................................................................................................................... 150

content ........................................................................................................................................................................... 150

flatten.............................................................................................................................................................................. 150

font................................................................................................................................................................................... 150

fontSize........................................................................................................................................................................... 150

layout .............................................................................................................................................................................. 150

mode ............................................................................................................................................................................... 150

opacity ............................................................................................................................................................................ 150

resolution....................................................................................................................................................................... 150

text ................................................................................................................................................................................... 150

textColor ........................................................................................................................................................................ 150

textPosition................................................................................................................................................................... 150

textRotate...................................................................................................................................................................... 150

typename ...................................................................................................................................................................... 150

PixarSaveOptions ...................................................................................................................................................................... 151

Properties............................................................................................................................................................................... 151

Adobe Photoshop CS2

JavaScript Scripting Reference 21

alphaChannels ............................................................................................................................................................. 151

typename ...................................................................................................................................................................... 151

PNGSaveOptions ....................................................................................................................................................................... 152

Properties............................................................................................................................................................................... 152

interlaced....................................................................................................................................................................... 152

typename ...................................................................................................................................................................... 152

Preferences .................................................................................................................................................................................. 153

Properties............................................................................................................................................................................... 153

additionalPluginFolder............................................................................................................................................. 153

appendExtension........................................................................................................................................................ 153

askBeforeSavingLayeredTIFF.................................................................................................................................. 153

autoUpdateOpenDocuments ................................................................................................................................ 153

beepWhenDone.......................................................................................................................................................... 153

colorChannelsInColor ............................................................................................................................................... 153

colorPicker..................................................................................................................................................................... 153

columnGutter............................................................................................................................................................... 153

columnWidth ............................................................................................................................................................... 153

createFirstSnapshot................................................................................................................................................... 154

dynamicColorSliders.................................................................................................................................................. 154

editLogItems ................................................................................................................................................................ 154

exportClipboard.......................................................................................................................................................... 154

fontPreviewSize........................................................................................................................................................... 154

fullSizePreview............................................................................................................................................................. 154

gamutWarningOpacity............................................................................................................................................. 154

gridSize........................................................................................................................................................................... 154

gridStyle ......................................................................................................................................................................... 154

gridSubDivisions......................................................................................................................................................... 154

guideStyle...................................................................................................................................................................... 154

iconPreview .................................................................................................................................................................. 154

imageCacheForHistograms .................................................................................................................................... 154

imageCacheLevels ..................................................................................................................................................... 154

imagePreviews ............................................................................................................................................................ 154

interpolation................................................................................................................................................................. 154

keyboardZoomResizesWindows........................................................................................................................... 155

macOSThumbnail....................................................................................................................................................... 155

maximizeCompatibility ............................................................................................................................................ 155

maxRAMuse.................................................................................................................................................................. 155

nonLinearHistory ........................................................................................................................................................ 155

numberofHistoryStates ............................................................................................................................................ 155

otherCursors................................................................................................................................................................. 155

paintingCursors........................................................................................................................................................... 155

parent.............................................................................................................................................................................. 155

pixelDoubling .............................................................................................................................................................. 155

pointSize ........................................................................................................................................................................ 155

recentFileListLength.................................................................................................................................................. 155

rulerUnits ....................................................................................................................................................................... 155

saveLogItems ............................................................................................................................................................... 155

saveLogItemsFile ........................................................................................................................................................ 155

savePaletteLocations ................................................................................................................................................ 155

showAsianTextOptions ............................................................................................................................................ 156

showEnglishFontNames .......................................................................................................................................... 156

Adobe Photoshop CS2

JavaScript Scripting Reference 22

showSliceNumber ...................................................................................................................................................... 156

showToolTips ............................................................................................................................................................... 156

smartQuotes................................................................................................................................................................. 156

typename ...................................................................................................................................................................... 156

typeUnits ....................................................................................................................................................................... 156

useAdditionalPluginFolder ..................................................................................................................................... 156

useDiffusionDither ..................................................................................................................................................... 156

useHistoryLog .............................................................................................................................................................. 156

useLowerCaseExtension .......................................................................................................................................... 156

useShiftKeyForToolSwitch....................................................................................................................................... 156

useVideoAlpha ............................................................................................................................................................ 156

windowsThumbnail................................................................................................................................................... 156

PresentationOptions ................................................................................................................................................................ 157

Properties............................................................................................................................................................................... 157

autoAdvance ............................................................................................................................................................... 157

includeFilename.......................................................................................................................................................... 157

interpolation................................................................................................................................................................. 157

loop.................................................................................................................................................................................. 157

magnification ............................................................................................................................................................... 157

pDFFileOptions............................................................................................................................................................ 157

presentation ................................................................................................................................................................ 157

transition........................................................................................................................................................................ 157

typename ...................................................................................................................................................................... 157

RawFormatOpenOptions ....................................................................................................................................................... 158

Properties............................................................................................................................................................................... 158

bitsPerChannel ............................................................................................................................................................ 158

byteOrder ...................................................................................................................................................................... 158

channelNumber .......................................................................................................................................................... 158

headerSize..................................................................................................................................................................... 158

height.............................................................................................................................................................................. 158

interleaveChannels .................................................................................................................................................... 158

retainHeader................................................................................................................................................................. 158

typename ...................................................................................................................................................................... 158

width ............................................................................................................................................................................... 158

RawSaveOptions........................................................................................................................................................................ 159

Properties............................................................................................................................................................................... 159

alphaChannels ............................................................................................................................................................. 159

spotColors ..................................................................................................................................................................... 159

typename ...................................................................................................................................................................... 159

RGBColor....................................................................................................................................................................................... 160

Properties............................................................................................................................................................................... 160

blue .................................................................................................................................................................................. 160

green ............................................................................................................................................................................... 160

hexValue ........................................................................................................................................................................ 160

red .................................................................................................................................................................................... 160

typename ...................................................................................................................................................................... 160

Selection ....................................................................................................................................................................................... 161

Properties............................................................................................................................................................................... 161

bounds............................................................................................................................................................................ 161

parent.............................................................................................................................................................................. 161

typename ...................................................................................................................................................................... 161

Adobe Photoshop CS2

JavaScript Scripting Reference 23

Methods ................................................................................................................................................................................. 161

clear ................................................................................................................................................................................. 161

contract .......................................................................................................................................................................... 161

copy ................................................................................................................................................................................. 161

cut..................................................................................................................................................................................... 161

deselect .......................................................................................................................................................................... 161

expand............................................................................................................................................................................ 161

feather............................................................................................................................................................................. 161

fill ...................................................................................................................................................................................... 162

grow ................................................................................................................................................................................ 162

invert ............................................................................................................................................................................... 162

load .................................................................................................................................................................................. 162

makeWorkPath ............................................................................................................................................................ 162

resize ............................................................................................................................................................................... 162

resizeBoundary............................................................................................................................................................ 162

rotate............................................................................................................................................................................... 162

rotateBoundary ........................................................................................................................................................... 162

select ............................................................................................................................................................................... 162

selectAll .......................................................................................................................................................................... 162

selectBorder.................................................................................................................................................................. 163

similar.............................................................................................................................................................................. 163

smooth ........................................................................................................................................................................... 163

store................................................................................................................................................................................. 163

stroke............................................................................................................................................................................... 163

translate ......................................................................................................................................................................... 163

translateBoundary...................................................................................................................................................... 163

SGIRGBSaveOptions ................................................................................................................................................................. 166

Properties............................................................................................................................................................................... 166

alphaChannels ............................................................................................................................................................. 166

spotColors ..................................................................................................................................................................... 166

typename ...................................................................................................................................................................... 166

SolidColor..................................................................................................................................................................................... 167

Properties............................................................................................................................................................................... 167

cmyk ................................................................................................................................................................................ 167

gray .................................................................................................................................................................................. 167

hsb.................................................................................................................................................................................... 167

lab..................................................................................................................................................................................... 167

model .............................................................................................................................................................................. 167

nearestWebColor........................................................................................................................................................ 167

rgb.................................................................................................................................................................................... 167

typename ...................................................................................................................................................................... 167

Methods ................................................................................................................................................................................. 167

isEqual............................................................................................................................................................................. 167

SubPathInfo................................................................................................................................................................................. 168

Properties............................................................................................................................................................................... 168

closed.............................................................................................................................................................................. 168

entireSubPath .............................................................................................................................................................. 168

operation ....................................................................................................................................................................... 168

typename ...................................................................................................................................................................... 168

SubPathItem................................................................................................................................................................................ 169

Properties............................................................................................................................................................................... 169

Adobe Photoshop CS2

JavaScript Scripting Reference 24

closed.............................................................................................................................................................................. 169

operation ....................................................................................................................................................................... 169

parent.............................................................................................................................................................................. 169

pathPoints ..................................................................................................................................................................... 169

typename ...................................................................................................................................................................... 169

SubPathItems.............................................................................................................................................................................. 170

Properties............................................................................................................................................................................... 170

length.............................................................................................................................................................................. 170

parent.............................................................................................................................................................................. 170

typename ...................................................................................................................................................................... 170

Methods ................................................................................................................................................................................. 170

index................................................................................................................................................................................ 170

TargaSaveOptions..................................................................................................................................................................... 171

Properties............................................................................................................................................................................... 171

alphaChannels ............................................................................................................................................................. 171

resolution....................................................................................................................................................................... 171

rleCompression ........................................................................................................................................................... 171

typename ...................................................................................................................................................................... 171

TextFont........................................................................................................................................................................................ 172

Properties............................................................................................................................................................................... 172

family............................................................................................................................................................................... 172

name................................................................................................................................................................................ 172

parent.............................................................................................................................................................................. 172

postScriptName ......................................................................................................................................................... 172

style.................................................................................................................................................................................. 172

typename ...................................................................................................................................................................... 172

TextFonts...................................................................................................................................................................................... 173

Properties............................................................................................................................................................................... 173

length.............................................................................................................................................................................. 173

parent.............................................................................................................................................................................. 173

typename ...................................................................................................................................................................... 173

Methods ................................................................................................................................................................................. 173

index................................................................................................................................................................................ 173

getByName ................................................................................................................................................................... 173

TextItem........................................................................................................................................................................................ 174

Properties............................................................................................................................................................................... 174

alternateLigatures ...................................................................................................................................................... 174

antiAliasMethod.......................................................................................................................................................... 174

autoKerning.................................................................................................................................................................. 174

autoLeadingAmount................................................................................................................................................. 174

baselineShift ................................................................................................................................................................. 174

capitalization................................................................................................................................................................ 174

color................................................................................................................................................................................. 174

contents ......................................................................................................................................................................... 174

desiredGlyphScaling.................................................................................................................................................. 174

desiredLetterScaling.................................................................................................................................................. 175

desiredWordScaling .................................................................................................................................................. 175

........................................................................................................................................................................................... 175

direction......................................................................................................................................................................... 175

fauxBold ......................................................................................................................................................................... 175

fauxItalic......................................................................................................................................................................... 175

Adobe Photoshop CS2

JavaScript Scripting Reference 25

firstLineIndent.............................................................................................................................................................. 175

font................................................................................................................................................................................... 175

hangingPunctuation ................................................................................................................................................. 176

height.............................................................................................................................................................................. 176

horizontalScale ............................................................................................................................................................ 176

hyphenateAfterFirst................................................................................................................................................... 176

hyphenateBeforeLast................................................................................................................................................ 176

hyphenateCapitalWords .......................................................................................................................................... 176

hyphenateWordsLongerThan................................................................................................................................ 176

hyphenation ................................................................................................................................................................. 176

hyphenationZone....................................................................................................................................................... 176

hyphenLimit ................................................................................................................................................................. 176

justification ................................................................................................................................................................... 176

kind .................................................................................................................................................................................. 176

language ........................................................................................................................................................................ 176

leading............................................................................................................................................................................ 176

leftIndent ....................................................................................................................................................................... 176

ligatures ......................................................................................................................................................................... 176

maximumGlyphScaling ............................................................................................................................................ 177

maximumLetterScaling ............................................................................................................................................ 177

maximumWordScaling............................................................................................................................................. 177

minimumGlyphScaling............................................................................................................................................. 178

minimumLatterScaling............................................................................................................................................. 178

minimumWordScaling.............................................................................................................................................. 178

noBreak .......................................................................................................................................................................... 179

oldStyle........................................................................................................................................................................... 179

parent.............................................................................................................................................................................. 179

position .......................................................................................................................................................................... 179

rightIndent .................................................................................................................................................................... 179

size ................................................................................................................................................................................... 179

spaceAfter ..................................................................................................................................................................... 179

spaceBefore .................................................................................................................................................................. 179

strikeThru....................................................................................................................................................................... 179

textComposer .............................................................................................................................................................. 179

tracking........................................................................................................................................................................... 179

typename ...................................................................................................................................................................... 179

underline........................................................................................................................................................................ 179

useAutoLeading.......................................................................................................................................................... 180

verticalScale.................................................................................................................................................................. 180

warpBend ...................................................................................................................................................................... 180

warpDirection .............................................................................................................................................................. 180

warpHorizontalDistortion........................................................................................................................................ 180

warpStyle....................................................................................................................................................................... 180

warpVerticalDistortion.............................................................................................................................................. 180

width ............................................................................................................................................................................... 180

Methods ................................................................................................................................................................................. 180

convertToShape.......................................................................................................................................................... 180

createPath ..................................................................................................................................................................... 180

TiffSaveOptions.......................................................................................................................................................................... 181

Properties............................................................................................................................................................................... 181

alphaChannels ............................................................................................................................................................. 181

Adobe Photoshop CS2

JavaScript Scripting Reference 26

annotations................................................................................................................................................................... 181

byteOrder ...................................................................................................................................................................... 181

embedColorProfile..................................................................................................................................................... 181

imageCompression.................................................................................................................................................... 181

interleaveChannels .................................................................................................................................................... 181

jpegQuality ................................................................................................................................................................... 181

layerCompression....................................................................................................................................................... 181

layers ............................................................................................................................................................................... 181

saveImagePyramid..................................................................................................................................................... 181

spotColors ..................................................................................................................................................................... 181

transparency................................................................................................................................................................. 181

typename ...................................................................................................................................................................... 181

xmpMetadata ............................................................................................................................................................................. 182

Properties............................................................................................................................................................................... 182

parent.............................................................................................................................................................................. 182

rawData .......................................................................................................................................................................... 182

typename ...................................................................................................................................................................... 182

3 Action Manager .......................................................................................................................183

The ScriptListener Plug-In ...................................................................................................................................................... 183

Installing ScriptListener .................................................................................................................................................... 183

Action Manager Scripting Objects ...................................................................................................................................... 184

Using the Action Manager from JavaScript ..................................................................................................................... 184

4 Using ScriptUI ..........................................................................................................................187

Overview ...................................................................................................................................................................................... 187

ScriptUI Programming Model............................................................................................................................................... 187

Creating a window ............................................................................................................................................................ 187

Container elements............................................................................................................................................................ 188

Window layout .................................................................................................................................................................... 188

Adding elements to containers ..................................................................................................................................... 189

Creation properties ...................................................................................................................................................... 190

Accessing child elements ......................................................................................................................................... 190

Removing elements ........................................................................................................................................................... 190

Types of controls ................................................................................................................................................................ 191

Containers ....................................................................................................................................................................... 191

Panel................................................................................................................................................................................ 191

Group .............................................................................................................................................................................. 191

User interface controls................................................................................................................................................ 191

StaticText ....................................................................................................................................................................... 192

EditText .......................................................................................................................................................................... 192

Button ............................................................................................................................................................................. 192

IconButton .................................................................................................................................................................... 192

Image .............................................................................................................................................................................. 193

Checkbox ....................................................................................................................................................................... 193

RadioButton.................................................................................................................................................................. 193

Progressbar ................................................................................................................................................................... 193

Slider................................................................................................................................................................................ 193

Scrollbar ......................................................................................................................................................................... 194

ListBox............................................................................................................................................................................. 194

DropDownList.............................................................................................................................................................. 194

ListItem........................................................................................................................................................................... 194

Adobe Photoshop CS2

JavaScript Scripting Reference 27

Displaying icons................................................................................................................................................................... 194

Prompts and alerts ............................................................................................................................................................ 195

Modal dialogs ...................................................................................................................................................................... 195

Creating and using modal dialogs ......................................................................................................................... 195

Dismissing a modal dialog ........................................................................................................................................ 196

Default and cancel elements.................................................................................................................................... 196

Resource Specifications ......................................................................................................................................................... 197

Defining Behavior for Controls with Event Callbacks .................................................................................................. 199

Defining event handler functions ................................................................................................................................. 199

Simulating user events...................................................................................................................................................... 199

Automatic Layout ..................................................................................................................................................................... 201

Default layout behavior .................................................................................................................................................... 201

Automatic layout properties........................................................................................................................................... 202

Container orientation.................................................................................................................................................. 202

Aligning children .......................................................................................................................................................... 202

Setting margins ............................................................................................................................................................. 204

Spacing between children ........................................................................................................................................ 205

Determining a preferred size.................................................................................................................................... 205

Creating more complex arrangements ................................................................................................................ 205

Creating dynamic content......................................................................................................................................... 207

Custom layout manager example................................................................................................................................. 208

The AutoLayoutManager algorithm ............................................................................................................................ 210

Automatic layout restrictions ......................................................................................................................................... 211

Example scripts .......................................................................................................................................................................... 212

Alert box builder.................................................................................................................................................................. 212

Resource specification example.............................................................................................................................. 215

Localization in ScriptUI Objects ........................................................................................................................................... 217

Variable values in localized strings ............................................................................................................................... 217

Enabling automatic localization .................................................................................................................................... 217

5 ScriptUI Object Reference .......................................................................................................219

Overview ...................................................................................................................................................................................... 219

Window Class.............................................................................................................................................................................. 220

Window class properties .................................................................................................................................................. 220

coreVersion ................................................................................................................................................................... 220

version ............................................................................................................................................................................ 220

Window class functions .................................................................................................................................................... 220

alert.................................................................................................................................................................................. 220

confirm ........................................................................................................................................................................... 220

find ................................................................................................................................................................................... 220

getResourceText ......................................................................................................................................................... 221

prompt............................................................................................................................................................................ 221

Window Object .......................................................................................................................................................................... 221

Window object constructor ............................................................................................................................................ 221

Window object properties............................................................................................................................................... 221

defaultElement ............................................................................................................................................................ 221

cancelElement ............................................................................................................................................................. 221

frameBounds................................................................................................................................................................ 222

frameLocation.............................................................................................................................................................. 222

frameSize ....................................................................................................................................................................... 222

Container properties.......................................................................................................................................................... 223

Adobe Photoshop CS2

JavaScript Scripting Reference 28

alignChildren................................................................................................................................................................ 223

children .......................................................................................................................................................................... 223

layout .............................................................................................................................................................................. 223

margins........................................................................................................................................................................... 223

orientation..................................................................................................................................................................... 224

spacing ........................................................................................................................................................................... 224

Window object functions................................................................................................................................................. 224

add ................................................................................................................................................................................... 224

center .............................................................................................................................................................................. 224

close................................................................................................................................................................................. 225

hide .................................................................................................................................................................................. 225

notify ............................................................................................................................................................................... 225

remove............................................................................................................................................................................ 225

show ................................................................................................................................................................................ 225

Window event-handling callbacks ............................................................................................................................... 225

onClose........................................................................................................................................................................... 225

onMove .......................................................................................................................................................................... 225

onMoving ...................................................................................................................................................................... 226

onResize ......................................................................................................................................................................... 226

onResizing ..................................................................................................................................................................... 226

onShow .......................................................................................................................................................................... 226

Control Objects ......................................................................................................................................................................... 227

Control object constructors ............................................................................................................................................ 227

add ................................................................................................................................................................................... 227

Control types and creation parameters................................................................................................................ 227

button ............................................................................................................................................................................. 227

checkbox........................................................................................................................................................................ 227

dropdownlist................................................................................................................................................................ 228

edittext ........................................................................................................................................................................... 228

group............................................................................................................................................................................... 229

iconbutton .................................................................................................................................................................... 229

image .............................................................................................................................................................................. 229

item.................................................................................................................................................................................. 229

listbox.............................................................................................................................................................................. 230

panel................................................................................................................................................................................ 230

progressbar................................................................................................................................................................... 231

radiobutton................................................................................................................................................................... 231

scrollbar.......................................................................................................................................................................... 232

slider ................................................................................................................................................................................ 233

statictext ........................................................................................................................................................................ 233

Control object properties................................................................................................................................................. 234

active ............................................................................................................................................................................... 234

alignment ...................................................................................................................................................................... 234

bounds............................................................................................................................................................................ 234

enabled .......................................................................................................................................................................... 234

helpTip............................................................................................................................................................................ 234

icon .................................................................................................................................................................................. 235

index................................................................................................................................................................................ 235

items................................................................................................................................................................................ 235

itemSize.......................................................................................................................................................................... 235

jumpdelta ...................................................................................................................................................................... 235

Adobe Photoshop CS2

JavaScript Scripting Reference 29

justify............................................................................................................................................................................... 235

location........................................................................................................................................................................... 235

maxvalue ....................................................................................................................................................................... 235

minvalue ........................................................................................................................................................................ 236

parent.............................................................................................................................................................................. 236

preferredSize ................................................................................................................................................................ 236

properties ...................................................................................................................................................................... 236

selected .......................................................................................................................................................................... 236

selection......................................................................................................................................................................... 236

size ................................................................................................................................................................................... 236

stepdelta ........................................................................................................................................................................ 236

text ................................................................................................................................................................................... 237

textselection ................................................................................................................................................................. 237

type.................................................................................................................................................................................. 237

value ................................................................................................................................................................................ 237

value ................................................................................................................................................................................ 237

visible .............................................................................................................................................................................. 237

Control object functions................................................................................................................................................... 238

add ................................................................................................................................................................................... 238

find ................................................................................................................................................................................... 238

hide .................................................................................................................................................................................. 238

notify ............................................................................................................................................................................... 238

remove............................................................................................................................................................................ 238

removeAll ...................................................................................................................................................................... 238

show ................................................................................................................................................................................ 238

toString........................................................................................................................................................................... 239

valueOf ........................................................................................................................................................................... 239

Control event-handling callbacks ................................................................................................................................. 239

onClick ............................................................................................................................................................................ 239

onChange ...................................................................................................................................................................... 239

onChanging.................................................................................................................................................................. 239

Size and Location Objects ...................................................................................................................................................... 240

Bounds............................................................................................................................................................................ 240

Dimension ..................................................................................................................................................................... 240

Margins........................................................................................................................................................................... 241

Point ................................................................................................................................................................................ 241

LayoutManager Object ........................................................................................................................................................... 242

AutoLayoutManager object constructor.................................................................................................................... 242

AutoLayoutManager object properties ...................................................................................................................... 242

AutoLayoutManager object functions ........................................................................................................................ 242

layout .............................................................................................................................................................................. 242

6 Using File and Folder Objects .................................................................................................243

Overview ...................................................................................................................................................................................... 243

Specifying Paths......................................................................................................................................................................... 243

Absolute and relative path names................................................................................................................................ 243

Character interpretation in paths.................................................................................................................................. 244

The home directory............................................................................................................................................................ 244

Volume and drive names ................................................................................................................................................. 245

Mac OS volumes............................................................................................................................................................ 245

Windows drives ............................................................................................................................................................. 245

Adobe Photoshop CS2

JavaScript Scripting Reference 30

Aliases...................................................................................................................................................................................... 246

Portability issues.................................................................................................................................................................. 246

Unicode I/O ................................................................................................................................................................................. 246

File Error Handling ................................................................................................................................................................... 247

7 File and Folder Object Reference ...........................................................................................248

Overview ...................................................................................................................................................................................... 248

File Object .................................................................................................................................................................................... 248

File object constructors .................................................................................................................................................... 248

File class properties ............................................................................................................................................................ 249

fs........................................................................................................................................................................................ 249

File class functions.............................................................................................................................................................. 249

decode............................................................................................................................................................................ 249

encode............................................................................................................................................................................ 249

isEncodingAvailable .................................................................................................................................................. 249

openDialog ................................................................................................................................................................... 250

saveDialog..................................................................................................................................................................... 250

File object properties......................................................................................................................................................... 251

absoluteURI................................................................................................................................................................... 251

alias .................................................................................................................................................................................. 251

created............................................................................................................................................................................ 251

creator............................................................................................................................................................................. 251

encoding........................................................................................................................................................................ 251

eof .................................................................................................................................................................................... 251

error ................................................................................................................................................................................. 251

exists................................................................................................................................................................................ 251

fsName............................................................................................................................................................................ 251

hidden............................................................................................................................................................................. 251

length.............................................................................................................................................................................. 251

lineFeed.......................................................................................................................................................................... 251

modified......................................................................................................................................................................... 251

name................................................................................................................................................................................ 251

parent.............................................................................................................................................................................. 251

path.................................................................................................................................................................................. 252

readonly ......................................................................................................................................................................... 252

relativeURI ..................................................................................................................................................................... 252

type.................................................................................................................................................................................. 252

File object functions........................................................................................................................................................... 252

close................................................................................................................................................................................. 252

copy ................................................................................................................................................................................. 252

createAlias ..................................................................................................................................................................... 252

execute ........................................................................................................................................................................... 252

getRelativeURI ............................................................................................................................................................. 252

open ................................................................................................................................................................................ 253

openDlg ......................................................................................................................................................................... 254

read.................................................................................................................................................................................. 254

readch ............................................................................................................................................................................. 254

readln .............................................................................................................................................................................. 254

remove............................................................................................................................................................................ 254

rename............................................................................................................................................................................ 255

resolve............................................................................................................................................................................. 255

Adobe Photoshop CS2

JavaScript Scripting Reference 31

saveDlg........................................................................................................................................................................... 255

seek.................................................................................................................................................................................. 255

tell..................................................................................................................................................................................... 255

write................................................................................................................................................................................. 256

writeln............................................................................................................................................................................. 256

Folder Object ............................................................................................................................................................................. 257

Folder object constructors............................................................................................................................................... 257

Folder class properties ...................................................................................................................................................... 257

appData.......................................................................................................................................................................... 257

commonFiles................................................................................................................................................................ 257

current ............................................................................................................................................................................ 257

fs........................................................................................................................................................................................ 257

myDocuments ............................................................................................................................................................. 257

startup............................................................................................................................................................................. 257

system............................................................................................................................................................................. 258

temp ................................................................................................................................................................................ 258

trash................................................................................................................................................................................. 258

userData......................................................................................................................................................................... 258

Folder class functions ........................................................................................................................................................ 258

decode............................................................................................................................................................................ 258

encode............................................................................................................................................................................ 258

isEncodingAvailable .................................................................................................................................................. 258

selectDialog .................................................................................................................................................................. 259

Folder object properties................................................................................................................................................... 259

absoluteURI................................................................................................................................................................... 259

alias .................................................................................................................................................................................. 259

created............................................................................................................................................................................ 259

error ................................................................................................................................................................................. 259

exists................................................................................................................................................................................ 259

fsName............................................................................................................................................................................ 259

modified......................................................................................................................................................................... 259

name................................................................................................................................................................................ 259

parent.............................................................................................................................................................................. 259

path.................................................................................................................................................................................. 259

relativeURI ..................................................................................................................................................................... 259

Folder object functions..................................................................................................................................................... 260

create .............................................................................................................................................................................. 260

execute ........................................................................................................................................................................... 260

getFiles ........................................................................................................................................................................... 260

getRelativeURI ............................................................................................................................................................. 260

remove............................................................................................................................................................................ 260

rename............................................................................................................................................................................ 260

resolve............................................................................................................................................................................. 260

selectDlg ........................................................................................................................................................................ 261

File and Folder Error Messages ............................................................................................................................................ 262

File and Folder Supported Encoding Names .................................................................................................................. 263

Additional encodings ........................................................................................................................................................ 263

8 Scripting Constants .................................................................................................................265

AdjustmentReference ............................................................................................................................................... 265

AnchorPosition............................................................................................................................................................ 265

Adobe Photoshop CS2

JavaScript Scripting Reference 32

AntiAlias ......................................................................................................................................................................... 265

AutoKernType.............................................................................................................................................................. 265

BatchDestinationType .............................................................................................................................................. 265

BitmapConversionType............................................................................................................................................ 265

BitmapHalfToneType ................................................................................................................................................ 265

BitsPerChannelType................................................................................................................................................... 265

BlendMode.................................................................................................................................................................... 266

BMPDepthType ........................................................................................................................................................... 266

ByteOrder ...................................................................................................................................................................... 266

CameraRAWSettingsType........................................................................................................................................ 266

CameraRAWSize.......................................................................................................................................................... 266

ChangeMode................................................................................................................................................................ 266

ChannelType ................................................................................................................................................................ 267

ColorBlendMode......................................................................................................................................................... 267

ColorModel ................................................................................................................................................................... 267

ColorPicker .................................................................................................................................................................... 267

ColorProfile ................................................................................................................................................................... 267

ColorReductionType.................................................................................................................................................. 267

ColorSpaceType .......................................................................................................................................................... 268

CopyrightedType........................................................................................................................................................ 268

CreateFields .................................................................................................................................................................. 268

CropToType .................................................................................................................................................................. 268

DCSType......................................................................................................................................................................... 268

DepthMapSource ....................................................................................................................................................... 268

DescValueType ............................................................................................................................................................ 268

DialogModes ................................................................................................................................................................ 268

Direction ........................................................................................................................................................................ 268

DisplacementMapType ............................................................................................................................................ 268

Dither .............................................................................................................................................................................. 268

DocumentFill................................................................................................................................................................ 269

DocumentMode.......................................................................................................................................................... 269

EditLogItemsType....................................................................................................................................................... 269

ElementPlacement..................................................................................................................................................... 269

EliminateFields ............................................................................................................................................................ 269

ExportType.................................................................................................................................................................... 269

Extension ....................................................................................................................................................................... 269

FileNamingType .......................................................................................................................................................... 269

FontPreviewType........................................................................................................................................................ 270

ForcedColors ................................................................................................................................................................ 270

FormatOptions ............................................................................................................................................................ 270

GalleryConstrainType................................................................................................................................................ 270

GalleryFontType.......................................................................................................................................................... 270

GallerySecurityTextColorType ............................................................................................................................... 270

GallerySecurityTextPositionType.......................................................................................................................... 270

GallerySecurityTextRotateType ............................................................................................................................. 270

GallerySecurityType................................................................................................................................................... 270

GalleryThumbSizeType............................................................................................................................................. 270

Geometry....................................................................................................................................................................... 271

GridLineStyle ................................................................................................................................................................ 271

GridSize .......................................................................................................................................................................... 271

GuideLineStyle............................................................................................................................................................. 271

Adobe Photoshop CS2

JavaScript Scripting Reference 33

IllustratorPathType..................................................................................................................................................... 271

Intent............................................................................................................................................................................... 271

JavaScriptExecutionMode ....................................................................................................................................... 271

Justification................................................................................................................................................................... 271

Language....................................................................................................................................................................... 271

LayerCompression...................................................................................................................................................... 271

LayerKind....................................................................................................................................................................... 272

LensType........................................................................................................................................................................ 272

MagnificationType ..................................................................................................................................................... 272

MatteType ..................................................................................................................................................................... 272

NewDocumentMode................................................................................................................................................. 272

NoiseDistribution........................................................................................................................................................ 272

OffsetUndefinedAreas .............................................................................................................................................. 272

OpenDocumentMode............................................................................................................................................... 272

OpenDocumentType................................................................................................................................................. 273

OperatingSystem........................................................................................................................................................ 273

Orientation.................................................................................................................................................................... 273

OtherPaintingCursors ............................................................................................................................................... 273

PaintingCursors ........................................................................................................................................................... 273

Palette............................................................................................................................................................................. 274

PathKind......................................................................................................................................................................... 274

PDFCompatibility........................................................................................................................................................ 274

PDFEncoding................................................................................................................................................................ 274

PDFResample ............................................................................................................................................................... 274

PDFStandard ................................................................................................................................................................ 274

PhotoCDColorSpace.................................................................................................................................................. 274

PhotoCDSize................................................................................................................................................................. 274

PICTBitsPerPixels......................................................................................................................................................... 275

PICTCompression........................................................................................................................................................ 275

PicturePackageTextType.......................................................................................................................................... 275

PointKind ....................................................................................................................................................................... 275

PointType ...................................................................................................................................................................... 275

PolarConversionType ................................................................................................................................................ 275

Preview........................................................................................................................................................................... 275

PrintEncoding .............................................................................................................................................................. 275

PurgeTarget .................................................................................................................................................................. 275

QueryStateType........................................................................................................................................................... 275

RadialBlurMethod....................................................................................................................................................... 275

RadialBlurQuality ........................................................................................................................................................ 275

RasterizeType ............................................................................................................................................................... 276

ReferenceFormType .................................................................................................................................................. 276

ResampleMethod ....................................................................................................................................................... 276

ResetTarget ................................................................................................................................................................... 276

RippleSize ...................................................................................................................................................................... 276

SaveBehavior................................................................................................................................................................ 276

SaveDocumentType .................................................................................................................................................. 276

SaveEncoding .............................................................................................................................................................. 277

SaveLogItemsType..................................................................................................................................................... 277

SaveOptions ................................................................................................................................................................. 277

SelectionType............................................................................................................................................................... 277

ShapeOperation.......................................................................................................................................................... 277

Adobe Photoshop CS2

JavaScript Scripting Reference 34

SmartBlurMode ........................................................................................................................................................... 277

SmartBlurQuality......................................................................................................................................................... 277

SourceSpaceType ....................................................................................................................................................... 277

SpherizeMode.............................................................................................................................................................. 277

StrikeThruType ............................................................................................................................................................ 277

StrokeLocation............................................................................................................................................................. 277

TargaBitsPerPixels ...................................................................................................................................................... 277

TextCase......................................................................................................................................................................... 277

TextComposer.............................................................................................................................................................. 278

TextType ........................................................................................................................................................................ 278

TextureType.................................................................................................................................................................. 278

TIFFEncoding................................................................................................................................................................ 278

ToolType ........................................................................................................................................................................ 278

TransitionType ............................................................................................................................................................. 278

TrimType ........................................................................................................................................................................ 278

TypeUnits....................................................................................................................................................................... 279

UndefinedAreas .......................................................................................................................................................... 279

UnderlineType ............................................................................................................................................................. 279

Units................................................................................................................................................................................. 279

Urgency .......................................................................................................................................................................... 279

WarpStyle ...................................................................................................................................................................... 279

WaveType...................................................................................................................................................................... 279

WhiteBalanceType...................................................................................................................................................... 280

ZigZagType................................................................................................................................................................... 280

9 ExtendScript Tools and Features............................................................................................281

The ExtendScript Toolkit......................................................................................................................................................... 281

Configuring the Toolkit window ................................................................................................................................... 282

Selecting a debugging target ........................................................................................................................................ 283

Selecting scripts................................................................................................................................................................... 284

Tracking data ........................................................................................................................................................................ 284

The JavaScript console ..................................................................................................................................................... 285

The call stack ........................................................................................................................................................................ 286

The Script Editor .................................................................................................................................................................. 287

Mouse navigation and selection ............................................................................................................................. 287

Keyboard navigation and selection ....................................................................................................................... 287

Syntax checking ............................................................................................................................................................ 288

Debugging in the Toolkit ................................................................................................................................................. 288

Evaluation in help tips................................................................................................................................................. 288

Controlling code execution ...................................................................................................................................... 288

Visual indication of execution states ..................................................................................................................... 289

Setting breakpoints .................................................................................................................................................... 290

Profiling .................................................................................................................................................................................. 291

Dollar ($) Object ........................................................................................................................................................................ 293

Dollar ($) object properties ............................................................................................................................................. 293

build................................................................................................................................................................................. 293

buildDate ....................................................................................................................................................................... 293

error ................................................................................................................................................................................. 293

flags ................................................................................................................................................................................. 293

global .............................................................................................................................................................................. 293

level.................................................................................................................................................................................. 293

Adobe Photoshop CS2

JavaScript Scripting Reference 35

locale ............................................................................................................................................................................... 293

localize............................................................................................................................................................................ 294

memCache .................................................................................................................................................................... 294

objects ............................................................................................................................................................................ 294

os ...................................................................................................................................................................................... 294

screens............................................................................................................................................................................ 294

strict ................................................................................................................................................................................. 294

version ............................................................................................................................................................................ 294

Dollar ($) object functions ............................................................................................................................................... 294

about ............................................................................................................................................................................... 294

bp ..................................................................................................................................................................................... 294

clearbp............................................................................................................................................................................ 294

gc ...................................................................................................................................................................................... 294

getenv............................................................................................................................................................................. 294

list ..................................................................................................................................................................................... 294

setbp................................................................................................................................................................................ 295

sleep ................................................................................................................................................................................ 295

summary ........................................................................................................................................................................ 295

write................................................................................................................................................................................. 295

writeln............................................................................................................................................................................. 295

Object statistics ............................................................................................................................................................. 295

ExtendScript Reflection Interface ........................................................................................................................................ 297

Reflection Object................................................................................................................................................................. 297

Reflection object properties ..................................................................................................................................... 297

description .................................................................................................................................................................... 297

help.................................................................................................................................................................................. 297

methods......................................................................................................................................................................... 297

name................................................................................................................................................................................ 297

properties ...................................................................................................................................................................... 297

Reflection object functions ....................................................................................................................................... 297

find ................................................................................................................................................................................... 297

ReflectionInfo Object......................................................................................................................................................... 298

ReflectionInfo object properties ............................................................................................................................. 298

arguments ..................................................................................................................................................................... 298

dataType ........................................................................................................................................................................ 298

defaultValue ................................................................................................................................................................. 298

description .................................................................................................................................................................... 298

help.................................................................................................................................................................................. 299

isCollection.................................................................................................................................................................... 299

max .................................................................................................................................................................................. 299

min ................................................................................................................................................................................... 299

name................................................................................................................................................................................ 299

type.................................................................................................................................................................................. 299

Localizing ExtendScript Strings............................................................................................................................................ 300

Variable values in localized strings ............................................................................................................................... 300

Enabling automatic localization .................................................................................................................................... 300

Locale names ........................................................................................................................................................................ 301

Testing localization ............................................................................................................................................................ 302

Global localize function .................................................................................................................................................... 303

localize............................................................................................................................................................................ 303

User Notification Helper Functions..................................................................................................................................... 304

Adobe Photoshop CS2

JavaScript Scripting Reference 36

Global alert function .......................................................................................................................................................... 304

alert.................................................................................................................................................................................. 304

Global confirm function.................................................................................................................................................... 305

confirm ........................................................................................................................................................................... 305

Global prompt function.................................................................................................................................................... 305

prompt............................................................................................................................................................................ 305

Specifying Measurement Values ........................................................................................................................................ 307

UnitValue Object ................................................................................................................................................................. 307

UnitValue object constructor ................................................................................................................................... 307

UnitValue object properties...................................................................................................................................... 308

baseUnit ......................................................................................................................................................................... 308

type.................................................................................................................................................................................. 308

value ................................................................................................................................................................................ 308

UnitValue object functions........................................................................................................................................ 308

as....................................................................................................................................................................................... 308

convert............................................................................................................................................................................ 308

Converting pixel and percentage values ................................................................................................................... 308

Computing with unit values ........................................................................................................................................... 309

Modular Programming Support .......................................................................................................................................... 311

Preprocessor directives..................................................................................................................................................... 311

#engine name .............................................................................................................................................................. 311

#include file................................................................................................................................................................... 311

#includepath path ...................................................................................................................................................... 312

#script name ................................................................................................................................................................. 312

#strict on ........................................................................................................................................................................ 312

#target name ................................................................................................................................................................ 312

Importing and exporting between scripts................................................................................................................. 312

Operator Overloading ............................................................................................................................................................ 314

Application and Namespace Specifiers............................................................................................................................. 315

Application specifiers ........................................................................................................................................................ 315

Namespace specifiers ........................................................................................................................................................ 316

Script Locations and Checking Application Installation ............................................................................................. 316

Appendix A: Event ID Codes ...................................................................................................318

Index .........................................................................................................................................326

1

Introduction

This reference describes the objects and commands in the Adobe® Photoshop® CS2 JavaScript type library.

A companion document, Photoshop CS2 Scripting Guide, describes basic scripting concepts and the

Photoshop object model. This document provides reference details of the Photoshop object model, and additional information on JavaScript-specific features.

Adobe Photoshop CS2 uses ExtendScript, Adobe’s extended implementation of JavaScript. See Script

Support in Adobe Photoshop CS2 for additional information.

This book contains the following sections:

● This introduction, which describes scripting support in Adobe Photoshop CS2, and lists changes to the

JavaScript interface since the previous release.

JavaScript Object Reference

, which provides a complete reference for all Photoshop DOM objects and commands.

Using ScriptUI , which describes how to use ScriptUI, an ExtendScript component that provides a

user-interface model to scripters.

ScriptUI Object Reference , which provides the reference details of the ScriptUI object model.

Using File and Folder Objects

, which describes ExtendScript’s platform-independent representation of files and folders.

File and Folder Object Reference , which provides a complete reference for the ExtendScript

File

and

Folder classes.

Scripting Constants

, which lists all enumerations used in the Photoshop type library.

ExtendScript Tools and Features

, which describes ExtendScript’s debugging tools and programming utilities.

Script Support in Adobe Photoshop CS2

The Scripts menu supports JavaScript scripts for Windows®.

For a file to be recognized by Photoshop as a valid script file it must have the correct file name extension:

Script Type

AppleScript

JavaScript

ExtendScript

VBScript

Visual Basic

File Type compiled script

OSAS file text text executable

Extension

.scpt

(none)

.js

.jsx

.vbs

.exe

Platform

Mac OS®

Mac OS & Windows

Windows

Windows

37

Adobe Photoshop CS2

JavaScript Scripting Reference Introduction 38

JavaScript support

All of the Adobe Creative Suite 2 applications, including Adobe Photoshop CS2, use ExtendScript, Adobe’s extended implementation of JavaScript. ExtendScript files are distinguished by the

.jsx

extension.

ExtendScript offers all standard JavaScript features, plus additional features and utilities, such as:

A debugging environment (the ExtendScript Toolkit)

A localization utility

Tools that allow you to combine scripts and direct them to particular applications

Platform-independent file and folder representation

For details of these and additional features, see Using File and Folder Objects

and ExtendScript Tools and

Features .

Executing scripts

Adobe Photoshop CS2’s interface includes a Scripts menu (File > Scripts) which provides quick and easy access to your JavaScripts. Scripts can be listed directly as menu items that run when you select them, or you can navigate to and run any JavaScript in your file system.

If Adobe Photoshop CS2 encounters an error during script execution, it displays the error message.

Installing scripts

To install a JavaScript in the Scripts menu, place it in the Scripts folder (Photoshop CS2 > Presets >

Scripts). The names of the scripts in the Scripts folder, without the file name extension, will be displayed in the Scripts menu. Any number of scripts may be installed in the Scripts menu.

Scripts added to the Scripts folder while Adobe Photoshop CS2 is running will not appear in the Scripts menu until the next time you launch the application.

You may use sub-folders in the Scripts folder to help organize the scripts in the Scripts menu. Each subfolder will be displayed as a separate submenu containing the scripts in that subfolder.

Executing other scripts

The Browse item at the end of the Scripts menu (File > Scripts > Browse) allows you to execute scripts which are not installed in the Scripts folder. You can also use Browse to select scripts installed in the Scripts folder after the application was last launched.

Selecting Browse displays a file browser dialog which allows you to select a script file for execution. Only

.js

or

.jsx

files are displayed in the browse dialog. When you select a script file, it is executed the same way as an installed script.

Startup scripts

On startup, Adobe Photoshop CS2 executes all

.jsx

files that it finds in the startup folders.

On Windows, the startup folder for user-defined scripts is:

%APPDATA%\Adobe\StartupScripts

On Mac OS, the startup folder for user-defined scripts is:

Adobe Photoshop CS2

JavaScript Scripting Reference Introduction 39

~/Library/Application Support/Adobe/StartupScripts/

If your script is in this main startup folder, it is also executed by all other Adobe Creative Suite 2 applications at startup. If such a script is meant to be executed only by Adobe Photoshop CS2, it must include code such as the following: if( BridgeTalk.appName == "photoshop" ) {

//continue executing script

}

For additional details, see

Script Locations and Checking Application Installation .

Changes Since Earlier Versions

The following changes have been made to the JavaScript object model and language support in Adobe

Photoshop CS2:

The following classes have been added to the JavaScript interface:

CameraRawOpenOptions

, which you use to specify options when opening a document in Camera

Raw format.

ExportOptionsSaveForWeb

, which you use to optimize documents for the Web.

ContactSheetOptions , which you use to create and format contact sheets.

BatchOptions

, which you use to specify options for the Batch command.

LensBlurOptions

, which you use to specify options when applying the Lens Blur filter to a layer.

Notifier

and

Notifiers

, which you use to associate a script with an event so that the script executes when the event occurs. For example, you can create a notifier

object to associate a script with the Photoshop CS2 application opening; whenever the application opens, the script runs.

Support for interapplication communication among Creative Suite 2 applications through exported

ExtendScript functions and interapplication messaging. For details, see the Creative Suite 2 Bridge

JavaScript Reference.

Support for the ExtendScript Toolkit and other ExtendScript features and utilities. See ExtendScript

Tools and Features

.

Changes in ScriptUI

The ScriptUI component of JavaScript has been updated and extended in this release, and some features are incompatible with the CS version.

● In Photoshop CS, panel coordinates were measured from outside the frame (including the title bar), but in Photoshop CS2, panel coordinates are measured from the inside the frame (the content area). This means that if you use the same values to set the vertical positions of child controls in a panel, the positions are slightly different in the two versions. When you add a panel to a window, you can choose to set a creation property ( su1PanelCoordinates ), which causes that panel to automatically adjust the positions of its children. When automatic adjustment is enabled, you provide position values that were correct for Photoshop CS, and the result is the same in Photoshop CS2. You can also set automatic adjustment for a window; in this case, it applies to all child panels of that window unless it is explicitly disabled in the child panel.

In CS you could define an onClick

event handler function for a

StaticText element, and the function would be invoked when you click on the text. This is not supported in CS2.

Adobe Photoshop CS2

JavaScript Scripting Reference Introduction 40

In Photoshop CS, if a ScriptUI dialog contained one or more edittext control elements, keyboard focus was automatically assigned to the first-created edittext field. For example, when

Photoshop CS runs the following script, focus is assigned to w.name

, and the content of that control

(the string 'Jane Doe') is highlighted. var w = new Window ('dialog', 'Sample dialog', [0, 0, 180, 110]); w.add ('statictext', [15, 15, 65, 35], 'Name:'); w.name = w.add ('edittext', [70, 15, 165, 35], 'Jane Doe'); w.add ('statictext', [15, 45, 65, 65], 'Address:'); w.addr = w.add ('edittext', [70, 45, 165, 65], 'Notes'); w.ok = w.add ('button', [40, 75, 140, 95], 'OK', { name:'ok' }); w.center(); var ok = w.show() == 1;

In Photoshop CS2, the keyboard focus is not automatically assigned to any control element. The script must specify which control, if any, should have the focus, by setting its active property to true . For example, you must change the previous script as follows to explicitly assign focus to the w.name

field: var w = new Window ('dialog', 'Sample dialog', [0, 0, 180, 110]); w.add ('statictext', [15, 15, 65, 35], 'Name:'); w.name = w.add ('edittext', [70, 15, 165, 35], 'Jane Doe'); w.name.active = true; w.add ('statictext', [15, 45, 65, 65], 'Address:'); w.addr = w.add ('edittext', [70, 45, 165, 65], 'Notes'); w.ok = w.add ('button', [40, 75, 140, 95], 'OK', { name:'ok' }); w.center(); var ok = w.show() == 1;

2

JavaScript Object Reference

The objects of the JavaScript type library for Adobe® Photoshop® CS2 are presented alphabetically and in tabular format in this chapter.

Object properties and methods are described in separate tables for each object. See Working with the

Properties Tables

and

Working with the Methods Tables for information on how to use these tables.

Sample code for several object model classes is given to help illustrate the syntax as well as usage of the object class.

Working with the Properties Tables

The Properties table for an object lists the following:

The properties you can use with the object

The value type for each property

When the value type is a constant or another object, the value is a hypertext link to the constant’s or object’s listing, as in the following Properties table sample.

The property’s input status: read-only or read-write.

A description that explains what the property is

Descriptions are omitted for self-explanatory properties.

Property Value Type What it is displayDialogs

DialogModes

Read-write. Controls whether or not Adobe Photoshop CS2 displays dialog boxes.

Working with the Methods Tables

The Methods table for an object lists the following:

The method name

Parameter(s)

When a parameter type or return value is a constant or another object, the value is a hypertext link to the constant’s or object’s listing. In the following Methods table sample, the parameter type

ActionDescriptor

is an object; the parameter type

DialogModes

is a constant; the return value

ActionDescriptor is also an object.

Appeasements can be required or optional. Optional parameters are indicated in the table by square

brackets ([]). See ‘Working with Method Parameters’ on page 42 for information on using parameters.

Return value type(s)

A description, if applicable

41

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 42

Method Parameter Type executeAction

(eventID

[, descriptor]

[, displayDialogs]) number (long)

ActionDescriptor

DialogModes

Returns

ActionDescriptor

What it does

Plays an ActionManager event.

Working with Method Parameters

Optional parameters are surrounded by square brackets ( [ ] ). In the following Methods table sample, the parameters descriptor

and displayDialogs

are optional and the parameter eventID

is not. See

Therefore, if you use the executeAction()

method for the object associated with the sample Methods table above, you must include an eventID value in the parentheses following the method name. The eventID

value must be a number, as indicated by the number (long)

in the table’s Parameter Type column.

If you use an optional parameter, you must separate the parameters with a comma, as indicated by the comma that precedes each optional parameter in the table.

Also, if you use an optional parameter, you must enter the values in the order they are listed in the table so that the JavaScript compiler knows which value you are entering. To skip an optional parameter, insert an extra comma to act as a placeholder.

The following sample provides values for an eventID and a displayDialog , but skips the descriptor parameter (represented by the empty value between two commas). The statement executes action #4233 and allows only error type dialog boxes to be displayed. app.executeAction(4233,,error)

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 43

ActionDescriptor

A record of key-value pairs for actions, such as those included on the Adobe Photoshop CS2 Actions menu.

Note: The

ActionDescriptor

class is part of the Action Manager functionality. See ‘Action Manager’ on page 183

.

Properties

Property count typename

Value Type number (long) string

What it is

Read-only. The number of keys contained in the descriptor.

Read-only. The class name of the referenced actionDescriptor object.

Methods

Method clear

() erase

(key) fromStream

(value)

Parameter Type number (long) string getBoolean

(key) getClass

(key) getData

(key) getDouble

(key) number (long) number (long) number (long) number (long) getEnumerationType

(key) getInteger

(key) number (long) getEnumerationValue

(key) number (long) number (long) getKey

(index) getList

(key) number (long) number (long)

Returns

ActionList

What it does

Clears the descriptor.

Erases a key from the descriptor.

boolean number (long) string number (double) number (long) number (long) number (long) number (long)

Creates a descriptor from a stream of bytes; for reading from disk.

Gets the value of a key of type boolean.

Gets the value of a key of type class.

Gets raw byte data as a string value.

Gets the value of a key of type double.

Gets the enumeration type of a key.

Gets the enumeration value of a key.

Gets the value of a key of type integer.

Gets the ID of the Nth key.

Gets the value of a key of type list.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 44

Method getObjectType

(key) getObjectValue

(key) getPath

(key) getReference

(key) getString

(key) getType

(key) getUnitDoubleType

(key) getUnitDoubleValue

(key) hasKey

(key) isEqual

(otherDesc) putBoolean

(key,

value) putClass

(key,

value) putData

(key,

value) putDouble

(key,

value) putEnumerated

(key,

enumType,

value) putInteger

(key,

value)

Parameter Type number (long) number (long) number (long) number (long) number (long)

Returns number (long)

What it does (Continued)

Gets the class ID of an object in a key of type object.

ActionDescriptor

Gets the value of a key of type object.

file

ActionReference

string

DescValueType

Gets the value of a key of type

Alias.

Gets the value of a key of type

ActionReference

.

Gets the value of a key of type string.

Gets the type of a key.

number (long) number (long) number (long) number (long) number (long) boolean number (long) number (double) boolean

ActionDescriptor

boolean

Gets the unit type of a key of type

UnitDouble.

Gets the value of a key of type

UnitDouble.

Checks whether the descriptor contains the provided key.

Determines whether the descriptor is the same as another descriptor.

Sets the value for a key whose type is boolean. number (long) number (long)

Sets the value for a key whose type is class. number (long) string string Puts raw byte data as a string value. number (long) number (double)

Sets the value for a key whose type is double. number (long) number (long) number (long) number (long) number (long)

Sets the enumeration type and

value for a key. See Chapter 8,

“Scripting Constants” , for

information on enumerated types.

Sets the value for a key whose type is integer.

JavaScript Scripting Reference

Method putList

(key,

value) putObject

(key,

classID,

value) putPath

(key,

value) putReference

(key,

value) putString

(key,

value) putUnitDouble

(key,

unitID,

value) toStream

Adobe Photoshop CS2

Parameter Type Returns number (long)

ActionList

number (long) number (long)

ActionDescriptor

number (long) file number (long)

ActionReference

number (long) string number (long) number (long) number (double) string

JavaScript Object Reference 45

What it does (Continued)

Sets the value for a key whose type is an

ActionList

object.

Sets the value for a key whose type is an Action Descriptor.

Sets the value for a key whose type is path.

Sets the value for a key whose type is an object reference.

Sets the value for a key whose type is string.

Sets the value for a key whose type is a unit value formatted as a double.

Gets the entire descriptor as a stream of bytes; for writing from disk.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 46

ActionList

The list of commands that comprise an Action (such as an Action created using the Actions palette in the

Adobe Photoshop CS2 application).

Note: The

ActionList

object is part of the Action Manager functionality. For details on using the Action

Manager, see ‘Action Manager’ on page 183

.

Properties

Property count typename

Value Type number (long) string

What it is

Read-only. The number of commands that comprise the action.

Read-only. The class name of the referenced

ActionList object.

Methods

With the exception of the clear()

method, you use the methods of this object to either get the value of a specific type of data in the list or set (put) the value type.

Method clear

() getBoolean

(index) getClass

(index) getData

(index) getDouble

(index) getEnumerationType

(index) getEnumerationValue

(index) getInteger

(index) getList

(index) getObjectType

(index)

Parameter Type Returns number (long) number (long) number (long) number (long) number (long) number (long) number (long) number (long) number (long) boolean number (long) string number (double) number (long) number (long) number (long)

ActionList

number (long)

What it does

Clears the list.

Gets the value of a list item of type boolean.

Gets the value of a list item of type class.

Gets raw byte data as a string value.

Gets the value of a list item of type double.

Gets the enumeration type of a list item.

Gets the enumeration value of a list item.

Gets the value of a list item of type integer.

Gets the value of a list item of type list.

Gets the class ID of a list item of type object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 47

Method getObjectValue

(index) getPath

(index) getReference

(index) getString

(index) getType

(index) getUnitDoubleType

(index) getUnitDoubleValue

(index) putBoolean

(value) putClass

(value) putData

(value) putDouble

(value) putEnumerated

(enumType,

value) putInteger

(value) putList

(value) putObject

(classID,

value) putPath

(value)

Parameter Type Returns

ActionDescriptor

number (long) number (long) number (long) number (long) file

ActionReference

string

DescValueType

What it does (Continued)

Gets the value of a list item of type object.

Gets the value of a list item of type

Alias.

Gets the value of a list item of type

ActionReference

.

Gets the value of a list item of type string.

Gets the type of a list item.

number (long) number (long) number (long) boolean number (long) number (double)

Gets the unit value type of a list item of type Double.

Gets the unit value of a list item of type double.

Sets the value to either true or false.

Sets the class or data type. number (long) string

Puts raw byte data as a string value.

Sets the value type as a double.

number (double) number (long) number (long) number (long)

ActionList

number (long)

ActionDescriptor

Sets the value type as an enumerated, or constant, value.

Both the type of constant and the actual value are required in the following format: constantType.VALUE

See

Chapter 8, “Scripting

Constants”

, for information on constant value types and values.

Sets the value of a list item of type integer.

Sets the value of a list item of type list or array.

Sets the value of a list item of type object. file

Sets the value of a list item of type path.

JavaScript Scripting Reference

Method putReference

(value) putString

(value) putUnitDouble

(classID,

value)

Adobe Photoshop CS2

Parameter Type Returns

ActionReference

string number (long) number (double)

JavaScript Object Reference 48

What it does (Continued)

Sets the value of a list item whose type a reference to an object created in the script.

Sets the value of a list item of type string.

Sets the value of a list item of type unit value represented as a double.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 49

ActionReference

Contains data describing a referenced Action.

Note: The

ActionReference

object is part of the Action Manager functionality. For details on using the

Action Manager, see ‘Action Manager’ on page 183 .

Properties

Property typename

Value type string

What it does

Read-only. The class name of the referenced Action object.

Methods

Method getContainer

() getDesiredClass

() getEnumeratedType

() getEnumeratedValue

() getForm

() getIdentifier

() getIndex

() getName

() getOffset

() getProperty

() putClass

(desiredClass) number (long)

Parameter Type Returns

ActionReference

number (long) number (long) number (long)

What it does

Gets the container object in the containment hierarchy for the object.

Gets a number representing the class of the object.

Gets the enumeration type. See

Chapter 8, “Scripting Constants” ,

for information on enumeration types and values.

Gets the enumeration value.

ReferenceFormType

Gets the form of an

ActionReference

.

number (long) Gets the identifier value for a reference whose form is identifier.

number (long) string

Gets the index value for a reference in a list or array.

Gets the name of a reference.

number (long) number (long)

Gets the offset of the object’s index value.

Gets the property ID value.

Sets the class type of the object.

The class name is required.

Adobe Photoshop CS2

JavaScript Scripting Reference

Method putEnumerated

(desiredClass,

enumType,

value)

Parameter Type number (long) number (long) number (long)

Returns putIdentifier

(desiredClass,

value) putIndex

(desiredClass,

value) putName

(desiredClass,

value) putOffset

(desiredClass,

value) putProperty

(desiredClass,

value) number (long) number (long) number (long) number (long) number (long) string number (long) number (long) number (long) number (long)

JavaScript Object Reference 50

What it does (Continued)

Sets the object’s type to

‘Enumerated’. The class type, enumeration type and actual enumeration value are required in the following format: classtype.enumerationType

.VALUE

Sets the value of the identifier.

Sets the object’s index value in a list.

Sets the object’s name.

Sets the object’s offset from the current object.

Sets the value of the object’s property.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 51

Application

The Adobe Adobe Photoshop CS2 application object, which contains all other Adobe Photoshop CS2 objects.

Note: Because you open JavaScripts through the application itself, you do not need to use the

Application

object as part of the containment hierarchy that describes an object.

However, if you choose to include the

Application

object in your code, you must use the pre-defined global object name app

, rather than the class name

Application

, in a script, as in the following sample: var docRef = app.documents.add(800, 600, 72, “docRef”, NewDocumentMode.RGB)

The following sample uses the

Application

object incorrectly: var docRef = Application.documents.add(800, 600, 72, “docRef”,

NewDocumentMode.RGB)

However, the most common way to add an element in your code is to omit references to the

Application

object altogether, as in the following sample: var docRef = documents.add(800, 600, 72, “docRef”, NewDocumentMode.RGB)

Properties

Property activeDocument backgroundColor colorSettings displayDialogs documents fonts foregroundColor freeMemory locale macintoshFileTypes name

Value Type

Document

SolidColor

String

DialogModes

What it is

Read-write. The frontmost document. (Setting this property is equivalent to clicking an open document in the Adobe Photoshop CS2 application to bring it to the front of the screen.)

Read-write. The color mode for the document’s background color.

Read-write. The name of selected color setting’s set.

Read-write. The dialog mode for the document, which indicates whether or not Adobe

Photoshop CS2 displays dialogs when the script runs.

Documents

TextFonts

SolidColor

number (double) string

Read-only. The collection of open documents.

Read-only. The fonts installed on this system.

Read-write. The default foreground color (used to paint, fill, and stroke selections).

Read-only. The amount of unused memory available to Adobe Photoshop CS2.

Read-only. The language location of the application.

array of strings Read-only. A list of file image types Adobe

Photoshop CS2 can open. string Read-only. The application's name.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 52

Property notifiers preferences preferencesFolder scriptingVersion

Value Type

Notifiers

Preferences

alias string

What it is (Continued)

Read-only. The collection of notifiers currently configured (in the Scripts Events Manager menu in the Adobe Photoshop CS2 application). notifiersEnabled path boolean file

Read-write. Indication of whether all notifiers are enabled or disabled.

Read-only. The full path to the location of the

Adobe Photoshop CS2 application.

playbackDisplayDialogs

DialogModes

playbackParameters

Read-write. The dialog mode for playback mode, which indicates whether or not Adobe

Photoshop CS2 displays dialogs in playback mode.

ActionDescriptor

Read-write. The playback options, which indicate the speed at which Adobe Photoshop CS2 plays actions.

Read-only. The application preference settings

(equivalent to selecting Edit > Preferences in the

Adobe Photoshop CS2 application in Windows or

Photoshop > Preferences in Mac OS).

Read-only. The full path to the Preferences folder.

Read-only. The version of the Scripting interface.

typename version windowsFileTypes string string

Read-only. The class name of the referenced app object.

Read-only. The version of Adobe Photoshop application you are running.

array of strings Read-only. A list of file image extensions Adobe

Photoshop CS2 can open.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 53

Methods

Method batch

(inputFiles,

action,

from

[, options])

Parameter Type array of files string string

BatchOptions

Returns string

What it does

Runs the batch automation routine (similar to the Batch command, or File >

Automate > Batch in the

Adobe Photoshop CS2 application).

Note: The inputFiles parameter specifies the source for the files to be manipulated by the

Batch command.

Causes a “beep” sound. beep

() bringToFront charIDToTypeID

(charID) string doAction

(action,

from) string string executeAction

(eventID

[, descriptor]

[, displayDialogs]) number (long)

ActionDescriptor

DialogModes

executeActionGet

(reference)

ActionReference

load

(document) file makeContactSheet

(inputFiles

[, options]) array of files

ContactSheetOptions

makePDFPresentation

(inputFiles

outputFiles

[, options]) array of files file

PresentationOptions

makePhotoGallery

(inputFolder

outputFolder

[, options]) file file

GalleryOptions

number (long)

ActionDescriptor

ActionDescriptor

string string string

Makes Adobe Photoshop CS2 the active (front-most) application.

Converts from a four character code (character ID) to a runtime ID.

Plays an action from the

Actions palette.

Plays an ActionManager event.

Obtains an

ActionDescriptor

.

Loads the support document from the specified location.

Creates a contact sheet from the specified files.

Creates an Adobe PDF presentation file from the specified input files.

Creates a web photo gallery from the files in the specified input folder.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 54

Method makePhotomerge

(inputFiles) makePicturePackage

(inputFiles

[, options]) open

(document

[, as])

Parameter Type array of files

Returns string array of files

PicturePackageOptions

string file object object (open options)

Document

Note: See individual file type open options, such as

CameraRawOpenO ptions or

EPSOpenOptions

, etc.

purge

(target) stringIDToTypeID

(stringID) typeIDToCharID

(typeID)

PurgeTarget

string number (number

(long)) number (long) string typeIDToStringID

(typeID) number (number

(long)) string

What it does (Continued)

Merges multiple files into one; user interaction required.

Creates a picture package from the specified input files.

Opens the specified document as the optionally specified file type.

Purges one or more caches.

Converts from a string ID to a runtime ID.

Converts from a runtime ID to a character ID.

Converts from a runtime ID to a string ID.

First Sample Script

The following script invokes an alert box to display Properties important to an application such as version number, the path to the application, the amount of memory available, and the number of documents open.

When a user presses the OK button on the alert box, a second dialog opens, which asks users whether they would like the foreground and background colors set for the document presently open. If no document is open, the script opens a new document for the user.

The script (with no document open) produces a progression of three dialogs.

Application.jsx

//Create a Welcome message

// Use the name and version properties of the application object to

// Append the application’s name and version to the Welcome message

// use "\r" to insert a carriage return

// use the combination operator += to append info to the message var message = "Welcome to " + app.name; message += " version " + app.version + "\r\r";

// find out where Adobe Photoshop CS2 is installed

// and add the path to the message

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 55

// add the optional parameter fsName to the path property

// to display the file system name in the most common format message += "I’m installed in " + app.path.fsName + "\r\r"

// see how much memory Adobe Photoshop CS2 has to play with message += "You have this much memory available for Adobe Photoshop CS2

:

" + app.freeMemory + ""\r\r"

// use the length property of the documents object to

// see how many documents are open var documentsOpen = app.documents.length

message += "You currently have " + documentsOpen + " document(s) open.\r\r"

// display the message to the user alert(message)

// answer will be true for a "Yes" answer and false for a "No" answer var answer = confirm("Do you want me to set the foreground and background to my favorite colors?")

// set the colors if (answer) {

// I don’t have a favorite color. Why did I ask you may wonder?

app.foregroundColor.rgb.red = Math.random() * 255 app.foregroundColor.rgb.green = Math.random() * 255 app.foregroundColor.rgb.blue = Math.random() * 255

} app.backgroundColor.rgb.red = Math.random() * 255 app.backgroundColor.rgb.green = Math.random() * 255 app.backgroundColor.rgb.blue = Math.random() * 255

// Open a document if (app.documentsOpen == 0) {

// use the application’s path and the offset to the samples folder var sampleDocToOpen = File(app.path + "/Samples/Eagle.psd")

// compose a message with the name of the file message = "Would you like me to open a sample for you? (" message += sampleDocToOpen.fsName

message += ")"

// ask the user another question answer = confirm(message)

}

// open the document accordingly if (answer) { open(sampleDocToOpen)

}

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 56

Second Sample Script

The following script presents a progression of images as an Adobe PDF slide show.

PDFPresentation.jsx

// use all the files in the Samples folder var inputFolder = new Folder(app.path + "/Samples/")

// see if we have something interesting if (inputFolder != null) {

// get all the files found in this folder that are Adobe Photoshop CS2 (.psd format) var inputFiles = inputFolder.getFiles("*.psd")

// output to the desktop var outputFile = File("~/Desktop/JavaScriptPresentation.pdf")

// there are defaults but I like to set the options myself var options = new PresentationOptions options.presentation = true options.view = true options.autoAdvance = true options.interval = 5 options.loop = true options.transition = TransitionType.RANDOM

// create the presentation makePDFPresentation(inputFiles, outputFile, options)

}

Note: To run this code on non-English platforms, substitute the following path for the outputFile variable: var outputFile = File("~/JavaScriptPresentation.pdf")

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 57

ArtLayer

An object within a document that contains the visual elements of the image (equivalent to a layer in the

Adobe Photoshop CS2 application).

Note: Most likely, you will use variables to refer to

ArtLayer

objects in your script. However, if you choose not to use a variable, be aware that, because the

ArtLayer

class is also a property of the Document

object, you use the object name, artLayer , rather than the class name, ArtLayer , in your code.

The following example uses correct syntax to refer to an

ArtLayer

object by name and then assign its allLocked property value: documents(0).artLayer(“my layer”).allLocked = true

The following example, which uses an upper case A in the object name, is incorrect: documents(0).ArtLayer(“my layer”).allLocked = true

Properties

Property allLocked blendMode bounds fillOpacity grouped isBackgroundLayer kind linkedLayers

Value Type boolean

What it is

Read-write. Indicates whether to completely lock the layer’s contents and settings.

BlendMode

Read-write. The layer’s blending mode.

Array(UnitValue) Read-only. An array of coordinates that describes the bounding rectangle of the layer.

number (double) boolean boolean

Read-write. The interior opacity of the layer (between

0.0 and 100.0).

Read-write. Indication of whether to group this layer with the layer beneath it.

Read-write. Indicates whether the layer is a background layer or normal layer.

LayerKind

Note: A document can have only one background layer.

Read-write. Sets the layer’s kind (such as 'text layer') for an empty layer.

Note: Valid only when the layer is empty and when isBackgroundLayer

is false

. See

isBackgroundLayer .

array of layers

Note: You can use the kind

property to make a background layer a normal layer; however, to make a layer a background layer, you must set isBackgroundLayer

to true

.

Read-only. The layers linked to this layer.

Note: See

link

.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 58

Property name opacity parent pixelsLocked positionLocked textItem

Value Type string number (double) object

(

Document

) boolean

What it is (Continued)

Read-write. The layer’s name.

Read-write. The master opacity of the layer (0.0 -

100.0).

Read-only. The object's container.

boolean

TextItem

transparentPixelsLocked boolean typename visible string boolean

Read-write. Indicates whether the pixels in the layer’s image can be edited using the paintbrush tool.

Read-write. Indicates whether the pixels in the layer’s image can be moved within the layer.

Read-only. The text item that is associated with the layer.

Note: Valid only when kind = LayerKind.TEXT

.

See

kind

.

Read-write. Indicates whether editing is confined to the opaque portions of the layer.

Read-only. The class name of the referenced artLayer

object.

Read-write. Indicates whether the layer is visible.

Methods

Method Parameter Type adjustBrightnessContrast

(brightness,

contrast) number (number (long)) number (number (long))

Returns What it does

Adjusts the brightness (-100 -

100) and contrast (-100 - 100).

adjustColorBalance

([shadows]

[, midtones]

[, highlights]

[, preserveLuminosity] array of integers array of integers array of integers boolean

Adjusts the color balance of the layer’s component channels. For shadows

, midtones

, and highlights

, the array must include three values (-100 - 100), which represent cyan or red, magenta or green, and yellow or blue, when the document mode is CMYK or RGB. adjustCurves

(curveShape) array of points

(Array (Array(x, y)))

Note: See mode in the

Properties table of the

Document

object.

Adjusts the tonal range of the selected channel using up to fourteen points.

Adobe Photoshop CS2

JavaScript Scripting Reference

Method adjustLevels

(inputRangeStart,

inputRangeEnd,

inputRangeGamma,

outputRangeStart,

outputRangeEnd) applyAddNoise

(amount,

distribution,

monochromatic) applyAverage

() applyBlur

() applyBlurMore

() applyClouds

() applyCustomFilter

(characteristics,

scale,

offset)

Parameter Type number (long) number (long) number (double) number (long) number (long) number (double)

NoiseDistribution

boolean array of twenty-five

numbers (long) number (long) number (long) applyDeInterlace

(eliminateFields,

createFields) applyDespeckle

() applyDifferenceClouds

() applyDiffuseGlow

(graininess,

glowAmount,

clearAmount) applyDisplace

(horizontalScale,

verticalScale,

displacement,

undefinedareas,

displacementMapFiles)

EliminateFields

CreateFields

number (long) number (long) number (long) number (long) number (long)

DisplacementMapType

UndefinedAreas

file

JavaScript Object Reference 59

Returns What it does (Continued)

Adjusts the levels of the selected channels

( inputRangeStart

: 0 - 253; inputRangeEnd

:

( inputRangeStart

+ 2) - 255; inputRangeGamma : 0.10 - 9.99; outputRangeStart

: 0 - 253; outputRangeEnd

:

( outputRangeStart

+ 2) - 255.

Applies the Add Noise filter

( amount

: 0.1% - 400%).

Applies the Average filter.

Applies the Blur filter.

Applies the Blur More filter.

Applies the Clouds filter.

Applies a custom filter.

Note: Required parameter values define the filter.

Refer to Adobe

Photoshop CS2 Help for specific instructions.

Applies the De-Interlace filter.

Applies the Despeckle filter.

Applies the Difference Clouds filter.

Applies the Diffuse Glow filter

( graininess

: 0 - 10; glowAmount

: 0 - 20; clearAmount

: 0 - 20).

Applies the Displace filter using the specified horizontal and vertical scale (-999 - 999), mapping type, treatment of undistorted areas, and path to the distortion image map.

Adobe Photoshop CS2

JavaScript Scripting Reference

Method applyDustAndScratches

(radius,

threshold) applyGaussianBlur

(radius)

Parameter Type number (long) number (long) number (double) applyGlassEffect

(distortion,

smoothness,

scaling

[, invert]

[, texture]

[, textureFile]) applyHighPass

(radius) applyLensBlur

([options]) applyLensFlare

(brightness,

flareCenter,

lensType) number (long) number (long) number (long) boolean

TextureType

file number (double)

LensBlurOptions

number (long)

Array(UnitValue)

LensType

applyMaximum

(radius) applyMedianNoise

(radius) applyMinimum

(radius) applyMotionBlur

(angle,

radius) applyNTSC

() applyOceanRipple

(size,

magnitude) number (double) number (double) number (double) number (long) number (double) number (long) number (long)

JavaScript Object Reference 60

Returns What it does (Continued)

Applies the Dust & Scratches filter ( radius

: 1 - 100; threshold

: 0 - 255).

Applies the Gaussian Blur filter within the specified radius (in pixels) (0.1 - 250.0).

Applies the Glass filter

( distortion

: 0 - 20; smoothness

: 1 - 15; scaling

(in percent): 50 - 200).

Applies the High Pass filter within the specified radius (in pixels) (0.1 - 250.0).

Applies the Lens Blur filter.

Applies the Lens Flare filter with the specified brightness (0 -

300%), the x and y coordinates

(unit value) of the flare center, and the lens type.

Applies the Maximum filter within the specified radius (in pixels) (1 - 100).

Applies the Median Noise filter within the specified radius (in pixels) (1 - 100).

Applies the Minimum filter within the specified radius (in pixels) (1 - 100).

Applies the Motion Blur filter

( angle

: -360 - 360; radius

: 1 -

999).

Applies the NTSC colors filter.

Applies the Ocean Ripple filter in the specified size (1 - 15) and magnitude (0 - 20).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 61

Method applyOffset

(horizontal,

vertical,

undefinedAreas) applyPinch

(amount) applyPolarCoordinates

(conversion) applyRadialBlur

(amount,

blurMethod,

blurQuality) applyRipple

(amount,

size)

Parameter Type

UnitValue

UnitValue

OffsetUndefinedAreas

number (long)

PolarConversionType

number (long)

RadialBlurMethod

RadialBlurQuality

number (long)

RippleSize

Returns What it does (Continued)

Moves the layer the specified amount horizontally and vertically (min/max amounts depend on layer size), leaving an undefined area at the layer’s original location.

Applies the Pinch filter in the specified amount (as a percentage) (-100 - 100).

Applies the Polar Coordinates filter.

Applies the Radial Blur filter in the specified amount (1 - 100) using either a spin or zoom effect and the specified quality.

Applies the Ripple filter in the specified amount (-999 to 999) throughout the image and in the specified size.

Applies the Sharpen filter.

applySharpen

() applySharpenEdges

() applySharpenMore

() applyShear

(curve,

undefinedAreas) applySmartBlur

(radius,

threshold,

blurQuality,

mode) applySpherize

(amount,

mode) applyStyle

(styleName) array of points

(Array (Array(x, y)))

UndefinedAreas

number (double) number (double)

SmartBlurQuality

SmartBlurMode

number (long)

SpherizeMode

string

(

Applies the Sharpen Edges filter.

Applies the Sharpen More filter.

Applies the Shear filter (

- 255 points).

radius

: 0.1 - 100.0;

0.1 - 100.0).

curve

Applies the smart blur filter

: 2 threshold

:

Applies the Spherize filter in the specified amount (as percentage) (-100 - 100).

Applies the specified style to the layer.

Note: You must use a style from the Styles list in the Layer

Style dialog.

JavaScript Scripting Reference

Method applyTextureFill

(textureFile) applyTwirl

(angle) applyUnSharpMask

(amount,

radius,

threshold) applyWave

(generatorNumber,

minimumWavelength,

maximumWavelength,

minimumAmplitude,

maximumAmplitude,

horizontalScale,

verticalScale,

waveType,

undefinedAreas,

randomSeed) applyZigZag

(amount,

ridges,

style) autoContrast

() autoLevels

() clear

() copy

([merge]) cut

() desaturate

()

Adobe Photoshop CS2

Parameter Type file number (long) number (double) number (double) number (long) number (long) number (long) number (long) number (long) number (long) number (long) number (long)

WaveType

UndefinedAreas

number (long) number (long) number (long)

ZigZagType

boolean

JavaScript Object Reference 62

Returns What it does (Continued)

Applies the Texture Fill filter.

Applies the Twirl filter at the specified angle (-999 - 999).

Applies the Unsharp Mask filter

( amount : 1 - 500 as percent; radius

: 0.1 - 250.00; threshold

:

0 - 255).

Applies the Wave filter

( generatorNumber

: 1 - 999; minimumWavelength

: 1 - 998; maximumWavelength

:

2 - minimumWavelength

+ 1; minimumAmplitude maximumAmplitude

: 1 - 998;

:

2 - minimumAmplitude

+ 1; horizontalScale

: 1% - 100%; verticalScale : 1% - 100%).

Applies the Zigzag filter

( amount

: -100 - 100; ridges

: 0 -

20).

Adjusts the contrast of the selected channels automatically.

Adjusts the levels of the selected channels using the auto levels option.

Cuts the layer without moving it to the clipboard.

Copies the layer to the clipboard. When the optional argument is set to true , a merged copy is performed (that is, all visible layers are copied to the clipboard).

Cuts the layer to the clipboard.

Converts a color image to a grayscale image in the current color mode by assigning equal values of each component color to each pixel.

Adobe Photoshop CS2

JavaScript Scripting Reference

Method duplicate

([relativeObject]

[, insertionLocation]) equalize

()

Parameter Type object (Layer)

ElementPlacement

invert

() link

(with) merge

() mixChannels

(outputChannels

[, monochrome]) object (Layer) array of array of

numbers (double) boolean

JavaScript Object Reference 63

Returns What it does (Continued) object

(Layer)

Creates a duplicate of the object on the screen.

Redistributes the brightness values of pixels in an image to more evenly represent the entire range of brightness levels within the image.

Inverts the colors in the layer by converting the brightness value of each pixel in the channels to the inverse value on the

256-step color-values scale.

Links the layer with the specified layer.

ArtLayer

Merges the layer down, removing the layer from the document; returns a reference to the art layer that this layer is merged into.

Modifies a targeted (output) color channel using a mix of the existing color channels in the image. ( outputChannels

= An array of channel specifications.

For each component channel, specify a list of adjustment values (-200 - 200) followed by a

'constant' value (-200 - 200).)

Note: When monochrome = true , the maximum number of channel value specifications is 1.

Note: Valid only when document.mode =

DocumentMode.RGB

or document.mode =

DocumentMode.CMYK

.

Note: RGB arrays must include four doubles. CMYK arrays must include five doubles.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 64

Method move

(relativeObject,

insertionLocation) rasterize

(target)

Parameter Type object (artLayer or

layerSet)

ElementPlacement

photoFilter

([fillColor]

[, density]

[, preserveLuminosity])

SolidColor

number (long) boolean posterize

(levels) number (long)

RasterizeType

Returns What it does (Continued)

Moves the layer relative to the object specified in parameters.

Note: For art layers, only the constant values

ElementPlacement.

PLACEBEFORE and

ElementPlacement.

PLACEATEND

are valid.

For layer sets, only the constant values

ElementPlacement.

PLACEBEFORE and

ElementPlacement.INS

IDE

are valid.

Adjust the layer’s color balance and temperature as if a color filter had been applied

( density

: 1% - 100%).

Specifies the number of tonal levels (2 - 255) for each channel and then maps pixels to the closest matching level.

Converts the targeted contents in the layer into a flat, raster image.

Deletes the object.

remove

() resize

([horizontal]

[, vertical]

[, anchor]) rotate

(angle

[, anchor]) number (double) number (double)

AnchorPosition

number (double)

AnchorPosition

Resizes the layer to the specified dimensions (as a percentage of its current size) and places it in the specified position.

Rotates rotates the layer around the specified anchor point

(default:

AnchorPosition.MIDDLECENTE

R

).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 65

Method selectiveColor

(selectionMethod

[, reds]

[, yellows]

[, greens]

[, cyans]

[, blues]

[, magentas]

[, whites]

[, neutrals]

[, blacks]) shadowHighlight

([shadowAmount]

[, shadowWidth]

[, shadowRadius]

[, highlightAmount]

[, highlightWidth]

[, highlightRadius]

[, colorCorrection]

[, midtoneContrast]

[, blackClip]

[, whiteClip]) threshold

(level)

Parameter Type

AdjustmentReference

array of numbers (long) array of numbers (long) array of numbers (long) array of numbers (long) array of numbers (long) array of numbers (long) array of numbers (long) array of numbers (long) array of numbers (long)

Returns What it does (Continued)

Modifies the amount of a process color in a specified primary color without affecting the other primary colors.

Note: Each color array must have four components.

number (long) number (long) number (long) number (long) number (long) number (long) number (long) number (long) number (double) number (double) number (long)

UnitValue

UnitValue

Adjusts the range of tones in the image’s shadows and highlights

( shadowAmount

: 0 - 100 as percent; shadowWidth : 0 - 100 as percent; shadowRadius

: 0 -

2500 in pixels; highlightAmount

: 0 - 100 as percent; highlightWidth : 0 -

100 as percent; highlightRadius

: 0 - 2500 in pixels; colorCorrection

: -100 -

100; midtoneContrast : -100 -

100; blackClip

: 0.000 - 50.000; whiteClip

: 0.000 - 50.000).

Converts grayscale or color images to high-contrast, B/W images by converting pixels lighter than the specified threshold to white and pixels darker than the threshold to black (level: 1 - 255).

Moves the layer the specified amount (in pixels) relative to its current position.

Unlinks the layer.

translate

([deltaX]

[, deltaY]) unlink

()

Sample Script

The following script creates art layers to display a duck and a sand dune in an overlying checkerboard pattern. An alert box prompts the user to press OK. A multi-layered collage then displays.

ArtLayer.jsx

// Save the current preferences var startRulerUnits = app.preferences.rulerUnits

var startTypeUnits = app.preferences.typeUnits

var startDisplayDialogs = app.displayDialogs

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 66

// Set Adobe Photoshop CS2 to use pixels and display no dialogs app.preferences.rulerUnits = Units.PIXELS

app.preferences.typeUnits = TypeUnits.PIXELS

app.displayDialogs = DialogModes.NO

//Close all the open documents

while (app.documents.length) { app.activeDocument.close()

}

// Create a new document to merge all the samples into var mergedDoc = app.documents.add(1000, 1000, 72, "Merged Samples",

NewDocumentMode.RGB, DocumentFill.TRANSPARENT, 1)

// Use the path to the application and append the samples folder var samplesFolder = Folder(app.path + "/Samples/")

//Get all the files in the folder var fileList = samplesFolder.getFiles()

// open each file for (var i = 0; i < fileList.length; i++) {

// The fileList is folders and files so open only files if (fileList[i] instanceof File) { open(fileList[i])

// use the document name for the layer name in the merged document var docName = app.activeDocument.name

// flatten the document so we get everything and then copy app.activeDocument.flatten() app.activeDocument.selection.selectAll() app.activeDocument.selection.copy()

// don’t save anything we did app.activeDocument.close(SaveOptions.DONOTSAVECHANGES)

// make a random selection on the document to paste into

// by dividing the document up in 4 quadrants and pasting

// into one of them by selecting that area var topLeftH = Math.floor(Math.random() * 2) var topLeftV = Math.floor(Math.random() * 2) var docH = app.activeDocument.width.value / 2 var docV = app.activeDocument.height.value / 2 var selRegion = Array(Array(topLeftH * docH, topLeftV * docV),

Array(topLeftH * docH + docH, topLeftV * docV),

Array(topLeftH * docH + docH, topLeftV * docV + docV),

Array(topLeftH * docH, topLeftV * docV + docV),

Array(topLeftH * docH, topLeftV * docV)) app.activeDocument.selection.select(selRegion) app.activeDocument.paste()

// change the layer name and opacity app.activeDocument.activeLayer.name = docName app.activeDocument.activeLayer.fillOpacity = 50

}

}

// sort the layers by name

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 67 for (var x = 0; x < app.activeDocument.layers.length; x++) { for (var y = 0; y < app.activeDocument.layers.length - 1 - x; y++) {

// Compare in a non-case sensitive way var doc1 = app.activeDocument.layers[y].name

var doc2 = app.activeDocument.layers[y + 1].name

if (doc1.toUpperCase() > doc2.toUpperCase()) { app.activeDocument.layers[y].move(app.activeDocument.layers[y+1],

ElementPlacement.PLACEAFTER)

}

}

}

// Reset the application preferences app.preferences.rulerUnits = startRulerUnits app.preferences.typeUnits = startTypeUnits app.displayDialogs = startDisplayDialogs

Adobe Photoshop CS2

JavaScript Scripting Reference

ArtLayers

The collection of artLayer

objects in the document.

Note: Because the

ArtLayers

class is a property of the Document

object, you use the object name, artLayers

, rather than the class name,

ArtLayers

, in your code. For example: var layerRef = docRef.artLayers.add()

The following sample uses the

ArtLayers

object incorrectly: var layerRef = docRef.ArtLayers.add()

Properties

Property length

Value Type number (long) parent typename object

(document) string

What it is

Read-only. The number of elements in the artLayers collection.

Read-only. The object's container.

Read-only. The class name of the referenced artLayers

object.

Methods

Method index

(itemKey) add

() getByName

(name) removeAll

()

Parameter Type Returns

ArtLayer

number

ArtLayer

string

ArtLayer

Nothing

JavaScript Object Reference 68

What it does

Gets an element from the artLayers collection.

Creates a new artLayer

in the document.

Get the first element in the artLayers collection with the provided name.

Removes all elements from the artLayers collection.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 69

BatchOptions

Options to specify when running a Batch command.

Note: You specify the batch source folder as the inputFiles

parameter of the batch()

method, which is a method of the

Application

class. See

‘batch’ on page 53

. JavaScript supports only folders as sources for batch commands.

Properties

Property destination destinationFolder errorFile fileNaming macintoshCompatible overrideOpen

Value type file

What it is

BatchDestinationType

Read-write. The type of destination for the processed files (default:

BatchDestinationType.NODESTINATION

).

Read-write. The folder location for the processed files. file

Array

(

FileNamingType

options)

Note: Valid only when destination =

BatchDestinationType.FOLDER

.

See

destination

.

Read-write. The file in which to log errors encountered.

Note: To display errors on the screen (and stop batch processing when errors occur) leave blank.

Read-write. A list of file naming options

(maximum: 6).

boolean boolean

Note: Valid only when destination =

BatchDestinationType.FOLDER

.

See

destination

.

Read-write. Indication of whether to make the final file names Macintosh compatible (default: true

).

Note: Valid only when destination =

BatchDestinationType.FOLDER

.

See

destination

.

Read-write. Indication of whether to override action open commands (default: false

).

JavaScript Scripting Reference

Property overrideSave startingSerial suppressOpen suppressProfile typename unixCompatible windowsCompatible

Adobe Photoshop CS2

Value type boolean number (long) boolean boolean string boolean boolean

JavaScript Object Reference 70

What it is (Continued)

Read-write. Indication of whether to override save as action steps with the specified destination

(default: false

).

Note: Valid only when destination =

BatchDestinationType.FOLDER or destination =

BatchDestinationType.SAVEANDCLOSE

.

See

destination

.

Read-write. The starting serial number to use in naming files (default: 1 ).

Note: Valid only when destination =

BatchDestinationType.FOLDER

.

See

destination

.

Read-write. Indication of whether to suppress the file open options dialogs (default: false

).

Read-write. Indication of whether to suppress the color profile warnings (default: false

).

Read-only. The class name of the referenced batchOptions

object.

Read-write. Indication of whether to make the final file name Unix compatible (default: true

).

Note: Valid only when destination =

BatchDestinationType.FOLDER

.

See

destination

.

Read-write. Indication of whether to make the final file names Windows compatible (default: true

).

Note: Valid only when destination =

BatchDestinationType.FOLDER

.

See

destination

.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 71

BitmapConversionOptions

Options to be specified when converting an image to Bitmap mode.

Note: Convert color images to grayscale before converting the image to bitmap mode. See

‘desaturate’ on page 62

(in the Methods table of the

ArtLayer

object).

Properties

Property angle frequency method patternName resolution shape typename

Value Type number (double) number (double)

What it is

Read-write. The angle (in degrees) at which to

orient individual dots (-180 - 180). See shape .

Note: Valid only when method =

BitmapConversionType.HALFTONESCREEN

.

See method .

Read-write. The number of printer dots (per inch) to use (1.0 - 999.99). string

Note: Valid only when method =

BitmapConversionType.HALFTONESCREEN

.

See method .

BitmapConversionType

Read-write. The conversion method to use (default:

BitmapConversionType.DIFFUSIONDITHER

).

Read-write. The name of the pattern to use.

number (double)

BitmapHalfToneType

Note: Valid only when method =

BitmapConversionType.CUSTOMPATTERN

.

See method .

Read-write. The output resolution in pixels per inch

(default:

72.0

).

Read-write. The dot shape to use.

string

Note: Valid only when method =

BitmapConversionType.HALFTONESCREEN

.

See method .

Read-only. The class name of the referenced bitmapConversionOptions

object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 72

BMPSaveOptions

Options that can be specified when saving a document in BMP format.

Properties

Property alphaChannels

Value Type boolean depth flipRowOrder osType rleCompression typename

BMPDepthType

boolean

OperatingSystem

boolean string

What it is

Read-write. Indication of whether to save the alpha channels.

Read-write. The number of bits per channel.

Read-write. Indication of whether to write the image from top to bottom (default: false

).

Note: Available only when osType =

OperatingSystem.WINDOWS

.

See osType

.

Read-write. The target OS.

(default:

OperatingSystem.WINDOWS

).

Read-write. Indication of whether to use RLE compression.

Note: Available only when osType =

OperatingSystem.WINDOWS

.

See osType

.

Read-only. The class name of the referenced

BMPSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 73

CameraRawOpenOptions

Options that can be specified when opening a document in Camera Raw format.

Properties

Property bitsPerChannel blueHue blueSaturation brightness chromaticAberrationBY number (long) chromaticAberrationRC number (long) colorNoiseReduction colorSpace contrast exposure greenHue greenSaturation luminanceSmoothing redHue redSaturation resolution saturation settings shadows

Value type

BitsPerChannelType

number (long) number (long) number (long) number (long)

ColorSpaceType

number (long) number (double) number (long) number (long) number (long)

What it is

Read-write. The number of bits per channel.

Read-write. The blue hue of the shot (-100 -

100).

Read-write. The blue saturation of the shot

(-100 - 100).

Read-write. The brightness of the shot (0 - 150).

Read-write. The chromatic aberration B/Y of the shot (-100 - 100).

Read-write. The chromatic aberration R/C of the shot (-100 - 100).

Read-write. The color noise reduction of the shot (0 - 100).

Read-write. The colorspace for the image.

Read-write. The contrast of the shot (-50 - 100).

Read-write. The exposure of the shot (4.0 - 4.0).

Read-write. The green hue of the shot (-100 -

100).

Read-write. The green saturation of the shot

(-100 - 100).

Read-write. The luminance smoothing of the shot (0 - 100).

number (long) number (long) number (double) number (long)

Read-write. The red hue of the shot (-100 - 100).

Read-write. The red saturation of the shot (-100

- 100).

Read-write. The resolution of the document in pixels per inch (1 - 999).

Read-write. The saturation of the shot (-100 -

100).

CameraRAWSettingsType

Read-write. The global settings for all Camera

RAW options.

number (long) Read-write. The shadows of the shot (0 - 100).

Adobe Photoshop CS2

JavaScript Scripting Reference

Property shadowTint sharpness size temperature tint typename vignettingAmount vignettingMidpoint whiteBalance

Value type number (long) number (long)

CameraRAWSize

number (long) number (long) string number (long) number (long)

WhiteBalanceType

JavaScript Object Reference 74

What it is (Continued)

Read-write. The shadow tint of the shot (-100 -

100).

Read-write. The sharpness of the shot (0 - 100).

Read-write. The size of the new document.

Read-write. The temperature of the shot (2000 -

50000).

Read-write. The tint of the shot (-150 - 150).

Read-only. The class name of the referenced cameraRawOpenOptions object.

Read-write. The vignetting amount of the shot

(-100 - 100).

Read-write. The vignetting mid point of the shot

(-100 - 100).

Read-write. The white balance options for the image.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 75

Channel

Object that stores information about a color element in the image, analogous to a plate in the printing process that applies a single color. The document’s color mode determines the number of default channels; for example, an RGB document has four default channels:

A composite channel: RGB

● Three component channels: red, green, blue

A channel can also be an alpha channel, which stores selections as masks, or a spot channel, which stores spot colors.

Note: Most likely, you will use variables to refer to

Channel

objects in your script. However, if you choose not to use a variable, be aware that, because the Channel class is also a property of the

Document

object, you use the object name, channel

, rather than the class name,

Channel

, in your code.

The following example uses correct syntax to refer to a Channel object by name and then assign its opacity

property value: documents(0).channel(“my channelr”).opacity = 22

The following example, which uses an upper case C in the object name, is incorrect: documents(0).Channel(“my channelr”).opacity = 22

Properties

Property color histogram kind name opacity parent

Value Type

SolidColor

array of 256 numbers (long)

ChannelType

string number (double) object (document)

What it is

Read-write. The color of the channel.

Note: Not valid when type = ChannelType.COMPONENT

.

Read-only. A histogram of the color of the channel.

Note: Not valid when type = ChannelType.COMPONENT

. For component channel histogram values, use the histogram

property of the document

object

instead. See histogram .

Read-write. The channel type.

Read-write. The channel's name.

Read-write. The opacity to use for alpha channels or the solidity to use for spot channels (0 - 100).

Note: Valid only when type = ChannelType.MASKEDAREA

or type = ChannelType.SELECTEDAREA

.

Read-only. The object's container.

JavaScript Scripting Reference

Property typename

Value Type string visible boolean

Methods

Method Parameter Type duplicate

([targetDocument])

Document

merge

() delete

()

Adobe Photoshop CS2

JavaScript Object Reference 76

What it is (Continued)

Read-only. The class name of the referenced channel object.

Read-write. Indicates whether the channel is visible.

Returns

Channel

What it does

Duplicates the channel.

Merges a spot channel into the component channels.

Deletes the channel.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 77

Channels

The collection of channel

objects in the document. See

Channel

.

Note: Because the

Channels

class is also a property of the

Document object, you use the object name,

channels

, rather than the class name,

Channels

, in your code. For example: var channelRef = docRef.channels.add()

The following sample uses the

ArtLayer

object incorrectly: var channelRef = docRef.Channels.add()

Properties

Property length parent typename

Value Type string

What it is number (long) Read-only. The number of elements in the channels collection.

object (document) Read-only. The channels object’s container.

Read-only. The class name of the referenced channels object.

Methods

Method index

(itemKey) add

() getByName

(name) removeAll

()

Parameter Type number string

Returns

Channel

Channel

Channel

What it does

Gets an element from the channels collection.

Creates a new channel object.

Get the first element in the channels collection with the provided name.

Removes all channel objects from the channels collection

.

Sample Script

The following script produces a strobe effect, as a progression of dialogs display.

Note: This script contains a switch construction that uses a break

statement. The break

statement requires an ending semicolon (:), as in the following sample: break;

Histogram.jsx

// Save the current preferences var startRulerUnits = app.preferences.rulerUnits

var startTypeUnits = app.preferences.typeUnits

var startDisplayDialogs = app.displayDialogs

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 78

// Set Adobe Photoshop CS2 to use pixels and display no dialogs app.preferences.rulerUnits = Units.PIXELS

app.preferences.typeUnits = TypeUnits.PIXELS

app.displayDialogs = DialogModes.NO

// if there are no documents open then try to open a sample file if (app.documents.length == 0) { open(File(app.path + "/Samples/Eagle.psd"))

}

// get a reference to the working document var docRef = app.activeDocument

// create the output file

// first figure out which kind of line feeds we need if ($.os.search(/windows/i) != -1) { fileLineFeed = "windows"

} else { fileLineFeed = "macintosh"

}

// create the output file accordingly fileOut = new File("~/Desktop/Histogram.log") fileOut.lineFeed = fileLineFeed fileOut.open("w", "TEXT", "????")

// write out a header fileOut.write("Histogram report for " + docRef.name)

// find out how many pixels I have var totalCount = docRef.width.value * docRef.height.value

// more info to the out file fileOut.write(" with a total pixel count of " + totalCount + "\n")

// channel indexer var channelIndex = 0

// remember which channels are currently active var activeChannels = app.activeDocument.activeChannels

// document histogram only works in these modes if (docRef.mode == DocumentMode.RGB ||

docRef.mode == DocumentMode.INDEXEDCOLOR ||

docRef.mode == DocumentMode.CMYK) {

// activate the main channels so we can get the documents histogram

TurnOnDocumentHistogramChannels(docRef)

}

// Output the documents histogram

OutputHistogram(docRef.histogram, "Luminosity", fileOut)

// local reference to work from var myChannels = docRef.channels

// loop through each channel and output the histogram for (var channelIndex = 0; channelIndex < myChannels.length; channelIndex++) {

// the channel has to be visible to get a histogram

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 79 myChannels[channelIndex].visible= true

// turn off all the other channels for (var secondaryIndex = 0; secondaryIndex < myChannels.length; secondaryIndex++) { if (channelIndex != secondaryIndex) { myChannels[secondaryIndex].visible= false

}

}

}

// Use the function to dump the histogram

OutputHistogram(myChannels[channelIndex].histogram, myChannels[channelIndex].name, fileOut)

// close down the output file fileOut.close()

// reset the active channels docRef.activeChannels = activeChannels

// Reset the application preferences app.preferences.rulerUnits = startRulerUnits app.preferences.typeUnits = startTypeUnits app.displayDialogs = startDisplayDialogs

// Utility function that takes a histogram and name

// and dumps to the output file function OutputHistogram(inHistogram, inHistogramName, inOutFile) {

// find ouch which count has the largest number

// I scale everything to this number for the output var largestCount = 0

// a simple indexer I can reuse var histogramIndex = 0

// see how many samples we have total var histogramCount = 0

// search through all and find the largest single item for (histogramIndex = 0; histogramIndex < inHistogram.length; histogramIndex++) { histogramCount += inHistogram[histogramIndex] if (inHistogram[histogramIndex] > largestCount) largestCount = inHistogram[histogramIndex]

}

// These should match if (histogramCount != totalCount) { alert("Something bad is happening!")

}

// see how much each "X" is going to count as var pixelsPerX = largestCount / 100

// output this data to the file inOutFile.write("One X = " + pixelsPerX + " pixels.\n")

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 80

// output the name of this histogram inOutFile.write(inHistogramName + "\n")

// loop through all the items and output in the following format

// 001

// 002 for (histogramIndex = 0; histogramIndex < inHistogram.length; histogramIndex++) {

// I need an extra "0" for this line item to keep everything in line if (histogramIndex < 10) inOutFile.write("0")

// I need an extra "0" for this line item to keep everything in line if (histogramIndex < 100) inOutFile.write("0")

// output the index to file inOutFile.write(histogramIndex)

// some spacing to make it look nice inOutFile.write(" ")

// figure out how many X’s I need var outputX = inHistogram[histogramIndex] / largestCount * 100

// output the X’s for (var a = 0; a < outputX; a++) inOutFile.write("X") inOutFile.write("\n")

}

} inOutFile.write("\n")

// Function to active all the channels according to the documents mode

// Takes a document reference for input function TurnOnDocumentHistogramChannels(inDocument) {

// see how many channels we need to activate var visibleChannelCount = 0

// based on the mode of the document switch (inDocument.mode) { case DocumentMode.BITMAP: case DocumentMode.GRAYSCALE: case DocumentMode.INDEXEDCOLOR: visibleChannelCount = 1 break; case DocumentMode.DUOTONE: visibleChannelCount = 2 break; case DocumentMode.RGB: case DocumentMode.LAB: visibleChannelCount = 3 break;

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 81

} case DocumentMode.CMYK: visibleChannelCount = 4 break; case DocumentMode.DUOTONE: visibleChannelCount = 4 break; case DocumentMode.MULTICHANNEL: default: visibleChannelCount = inDocument.channels.length + 1 break;

}

// now get the channels to activate into a local array var aChannelArray = new Array()

// index for the active channels array var aChannelIndex = 0 for(var channelIndex = 0; channelIndex < inDocument.channels.length; channelIndex++) { if (channelIndex < visibleChannelCount) { aChannelArray[aChannelIndex++] = inDocument.channels[channelIndex]

}

}

// now activate them inDocument.activeChannels = aChannelArray

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 82

CMYKColor

The definition of a CMYK color.

Properties

Property black cyan magenta typename yellow

Value Type What it is number (double) Read-write. The black color value (as percent) (0.0 - 100.0).

number (double) Read-write. The cyan color value (as percent) (0.0 - 100.0).

number (double) Read-write. The magenta color value (as percent)

(0.0 - 100.0).

string Read-only. The class name of the referenced

CMYKColor

object.

number (double) Read-write. The yellow color value (as percent) (0.0 - 100.0).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 83

ContactSheetOptions

Options that can be specified for a contact sheet.

Properties

Property acrossFirst

Value Type boolean bestFit caption columnCount flatten font fontSize height horizontal mode resolution rowCount typename useAutoSpacing boolean boolean number (long) boolean

GalleryFontType

number (long) number (long) number (long)

NewDocumentMode

number (double) number (long) string boolean

What it is

Read-write. Indication of whether to place the images horizontally (left to right, then top to bottom) first (default: true ).

Read-write. Indication of whether to rotate images for the best fit (default: false

).

Read-write. Indication of whether to use the filename as a caption for the image (default: true ).

Read-write. The number of columns to include

(1 - 100; default:

5

).

Read-write. Indication of whether to flatten all layers in the final document (default: true ).

Read-write. The font used for the caption (default:

GalleryFontType.ARIAL

).

Read-write. The font size to use for the caption

(default: 12 ).

Read-write. The height (in pixels) of the resulting document (100 - 2900; default:

720

).

Read-write. The horizontal spacing (in pixels) between images (0 - 29000; default: 1 ).

Read-write. The document color mode (default:

NewDocumentMode.RGB

).

Read-write. The resolution of the document in pixels per inch (35 - 1200; default: 72.0

).

Read-write. The number of rows to use (1 - 100; default:

6

).

Read-only. The class name of the referenced contactSheetOptions object.

Read-write. Indication of whether to auto space the images (default: true

).

JavaScript Scripting Reference

Property vertical width

Adobe Photoshop CS2

Value Type number (long) number (long)

JavaScript Object Reference 84

What it is (Continued)

Read-write. The vertical spacing (in pixels) between images (0 - 29000; default:

1

).

Note: Valid only when useAutoSpacing = false

.

Read-write. The width (in pixels) of the resulting document (100 - 2900; default:

576

).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 85

DCS1_SaveOptions

Options that can be specified when saving a CMYK document in DCS1 format.

Properties

Property dCS embedColorProfile encoding halftoneScreen interpolation preview transferFunction typename vectorData

Value Type

DCSType

boolean

SaveEncoding

boolean boolean

Preview

boolean string boolean

What it is

Read-write. (default:

DCSType.COLORCOMPOSITE

).

Read-write. Indication of whether to embed the color profile in the document

Read-write. The type of encoding to use for document

(default:

SaveEncoding.BINARY

).

Read-write. Indication of whether to include halftone screen (default: false ).

Read-write. Indication of use image interpolation (default: false

)

Read-write. The type of preview (default:

Preview.MACOSEIGHTBIT

).

Read-write. Indication of whether to include the Transfer functions to compensate for dot gain between the image and film (default: false

).

Read-only. The class name of the referenced

DCS1_SaveOptions object.

Read-write. Indication of whether to include vector data.

Note: Valid only if the document includes vector data

(un-rasterized text).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 86

DCS2_SaveOptions

Options that can be specified when saving a CMYK document in DCS2 format.

Properties

Property dCS

Value Type

DCSType

embedColorProfile encoding halftoneScreen interpolation multiFileDCS preview spotColors transferFunction typename vectorData boolean

SaveEncoding

boolean boolean boolean

Preview

boolean boolean string boolean

What it is

Read-write. The type of composite file to create

(default:

DCSType.NOCOMPOSITE

).

Read-write. Indication of whether to embed the color profile in the document.

Read-write. The type of encoding to use (default:

SaveEncoding.BINARY

).

Read-write. Indication of whether to include the halftone screen (default: false

).

Read-write. Indication of whether to use image interpolation (default: false

).

Read-write. Indication of whether to save color channels as multiple files or a single file (default: false

).

Read-write. The preview type (default:

Preview.MACOSEIGHTBIT

).

Read-write. Indication of whether to save spot colors.

Read-write. Indication of whether to include the

Transfer functions to compensate for dot gain between the image and film (default: false ).

Read-only. The class name of the referenced

DCS2_SaveOptions

object.

Read-write. Indication of whether to include vector data.

Note: Valid only if the document includes vector data (un-rasterized text).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 87

Document

The active containment object for layers and all other objects in the script; the basic canvas for the file.

Note: In Adobe Photoshop CS2, a document can also be referred to as an image or a canvas.

● The term image refers to the entire document and its contents. You can trim or crop an image.

You resize an image using the resizeImage()

method.

● The term canvas refers to the space in which the document sits on the screen. You can rotate or flip the canvas. You resize the canvas using the resizeCanvas()

method.

Note: Most likely, you will use variables to refer to

Document

objects in your script. However, if you choose not to use a variable, be aware that, because the

Document

class is also a property of the

Application

object, you use the object name, document , rather than the class name, Document , in your code.

The following example uses correct syntax to refer to a

Document

object by name and then assign its colorProfileType property value: document(“my document”).colorProfileType = ColorProfile.CUSTOM

The following example, which uses an upper case D in the object name, is incorrect:

Document(“my document”).colorProfileType = ColorProfile.CUSTOM

Properties

Property Value Type What it is

Read-write. The selected channels.

activeChannels

Array ( Channel

objects) activeHistoryBrushSource

HistoryState

activeHistoryState activeLayer artLayers backgroundLayer bitsPerChannel channels colorProfileName colorProfileType

HistoryState

object (layer)

ArtLayers

ArtLayer

BitsPerChannelType

Channels

string

ColorProfile

Read-write. The history state to use with the history brush.

Read-write. The selected

HistoryState object.

Read-write. The selected layer.

Read-only. The artLayers

collection.

Read-only. Indicates whether the layer is a background layer.

Read-write. The number of bits per channel.

Read-write. The channels

collection.

Read-write. The name of the color profile.

Note: Valid only when colorProfileType =

ColorProfile.CUSTOM

or colorProfileType =

ColorProfile.WORKING

. See

colorProfileType

.

Read-write. The type of color model that defines the document’s working space.

JavaScript Scripting Reference

Property componentChannels fullName height histogram historyStates info layerComps layers layerSets managed mode name parent path pathItems pixelAspectRatio quickMaskMode resolution saved selection typename

Value Type

Array ( Channel

objects) file

UnitValue array of 256

numbers (long)

HistoryStates

DocumentInfo

LayerComp

Layers

LayerSets

boolean

DocumentMode

string

Application

file

PathItems

number (double) boolean number (double) boolean

Selection

string

Adobe Photoshop CS2

JavaScript Object Reference 88

What it is (Continued)

Read-only. A list of the component color channels.

Read-only. The full path name of the document.

Read-only. The height of the document (unit value).

Read-only. A histogram showing the number of pixels at each color intensity level for the composite channel.

Note: Valid only when mode = DocumentMode.RGB

; mode = DocumentMode.CMYK

; or mode = DocumentMode.INDEXEDCOLOR

.

See mode .

Read-only. The

HistoryStates

collection.

Read-only. Metadata about the document.

Read-only. The

LayerComps

collection.

Read-only. The Layers collection.

Read-only. The

LayerSets

collection.

Read-only. Indicates whether the document a is workgroup document.

Read-only. The color profile.

Read-only. The document's name.

Read-only. The

Document

object's container.

Read-only. The path to the document.

Read-only. The PathItems collection.

Read-write. The (custom) pixel aspect ratio to use (0.100 - 10.000).

Read-write. Indicates whether the document is in Quick Mask mode.

Read-only. The document’s resolution (in pixels per inch).

Read-only. Indicates whether the document has been saved since the last change.

Read-only. The selected area of the document.

Read-only. The class name of the

Document object.

JavaScript Scripting Reference

Property width xmpMetadata

Adobe Photoshop CS2

Value Type

UnitValue

xmpMetadata

JavaScript Object Reference 89

What it is (Continued)

Read-only. The width of the document (unit value).

Read-only. Camera raw settings for the image.

Note: Valid only for documents opened in

Camera Raw format.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 90

Methods

Method changeMode

(destinationMode

[, options]) close

([saving])

Parameter Type

ChangeMode

object

(

BitmapConversionOptions

or

IndexedConversionOptions

)

Returns What it does

Changes the color profile.

SaveOptions

Closes the document. If any changes have been made, the script presents an alert with three options: save, do not save, prompt to save.

The optional parameter specifies a selection in the alert box (default:

SaveOptions.

PROMPTTOSAVECHANGES

).

Changes the color profile.

convertProfile

(destinationProfile,

intent

[, blackPointCompensation]

[, dither]) string

Intent

boolean boolean crop

(bounds

[, angle]

[, width]

[, height])

Array(UnitValue) number (double)

UnitValue

UnitValue

Note: The destinationProfil e parameter must be either a string that names the color mode or

Working

RGB

,

Working CMYK

,

Working Gray

,

Lab

Color ( meaning one of the working color spaces or Lab color).

Crops the document. The first parameter is an array of four coordinates that mark the portion remaining after cropping, in the following order: left, top, right, bottom. duplicate

() exportDocument

(exportIn

[, exportAs]

[, options]) file

ExportType

ExportOptionsIllustrator

Document

Creates a duplicate of the document

object.

Exports the document.

flatten

()

Flattens all layers.

JavaScript Scripting Reference

Method flipCanvas

(direction) importAnnotations

(file) mergeVisibleLayersl

() paste

([intoSelection]) boolean

Adobe Photoshop CS2

Parameter Type

Direction

file print

([postScriptEncoding]

[, sourceSpace]

[, printSpace]

[, intent]

[blackPointCompensation])

PrintEncoding

SourceSpaceType

string

Intent

boolean rasterizeAllLayers

() resizeCanvas

([width]

[, height]

[, anchor]) resizeImage

([width]

[, height]

[, resolution]

[, resampleMethod]) revealAll

()

UnitValue

UnitValue

AnchorPosition

UnitValue

UnitValue number (double)

ResampleMethod

JavaScript Object Reference 91

Returns What it does (Continued)

Flips the image within the canvas in the specified direction.

Imports annotations into the document.

Flattens all visible layers in the document.

ArtLayer Pastes the contents of the clipboard into the document. If the optional argument is set to true

and a selection is active, the contents are pasted into the selection.

Prints the document.

Note: printSpace

specifies the color space for the printer. Valid values are nothing

(that is, the same as the source); or

Working RGB ,

Working CMYK

,

Working Gray

,

Lab

Color

( meaning one of the working color spaces or Lab color); or a string specifying a specific colorspace

(default: nothing ).

Rasterizes all layers.

Changes the size of the canvas to display more or less of the image but does not change the image size.

See

resizeImage .

Changes the size of the image.

Expands the document to show clipped sections.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 92

Method rotateCanvas

(angle)

Parameter Type number (double)

Returns What it does (Continued)

Rotates the canvas

(including the image) in clockwise direction.

Saves the document.

save

() saveAs

(saveIn

[, options]

[, asCopy]

[, extensionType]) file object (corresponding

SaveOptions object*) boolean

Extension

* Examples:

BMPSaveOptions

DCS2_SaveOptions

JPEGSaveOptions

TiffSaveOptions

etc.

Saves the document with specified save options.

splitChannels

() trap

(width) trim

([type]

[, top]

[, left]

[, bottom]

[, right]) number (long)

TrimType

boolean boolean boolean boolean

Array (

Document

objects)

Splits the document channels into separate images.

Applies trapping to a CMYK document.

Note: Valid only when

document.

mode =

DocumentMode.CMYK

.

See mode .

Trims the transparent area around the image on the specified sides of the canvas.

Note: Default is true

for all boolean values.

Sample Script

The following script creates a document that contains two images (an eagle and a duck) obtained from the

Adobe Photoshop CS2 Samples folder and employs the following steps:

Determines which image is larger.

Resizes the smaller image to match the larger image.

Creates a merged document twice as high as either image in order to hold both images.

Selects part of the document to and pastes the eagle into the selection. T

Inverts the selection and pastes the duckinto the lower part of the document.

Positions the eagle over the duck.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 93

Document.jsx

// Save the current preferences var startRulerUnits = app.preferences.rulerUnits

var startTypeUnits = app.preferences.typeUnits

var startDisplayDialogs = app.displayDialogs

// Set Adobe Photoshop CS2 to use pixels and display no dialogs app.preferences.rulerUnits = Units.PIXELS

app.preferences.typeUnits = TypeUnits.PIXELS

app.displayDialogs = DialogModes.NO

// first close all the open documents while (app.documents.length) { app.activeDocument.close()

}

// Open the eagle and duck files from the samples folder var eagleDoc = open(File(app.path + "/Samples/Eagle.psd")) var duckDoc = open(File(app.path + "/Samples/Ducky.tif"))

// Find out which document is larger

// Resize the smaller document the to the larger document’s size

// The resize requires the document be the active/front document if ((eagleDoc.width.value * eagleDoc.height.value) > (duckDoc.width.value * duckDoc.height.value)) { app.activeDocument = duckDoc duckDoc.resize(eagleDoc.width, eagleDoc.height)

} else { app.activeDocument = eagleDoc eagleDoc.resizeImage(duckDoc.width, duckDoc.height)

}

// Create a new document twice as high as two files var mergedDoc = app.documents.add(duckDoc.width, duckDoc.height * 2, duckDoc.resolution, "EagleOverDuck")

// Copy the eagle to the top; make it the active document so we can manipulate it app.activeDocument = eagleDoc eagleDoc.activeLayer.copy()

//Pastethe eagle to the merged document, making the merged document active app.activeDocument = mergedDoc

// Select a square area at the top of the new document var selRegion = Array(Array(0, 0),

Array(mergedDoc.width.value, 0),

Array(mergedDoc.width.value, mergedDoc.height.value / 2),

Array(0, mergedDoc.height.value / 2),

Array(0, 0))

// Create the selection mergedDoc.selection.select(selRegion)

//Paste in the eagle mergedDoc.paste()

// do the same thing for the duck app.activeDocument = duckDoc duckDoc.activeLayer.copy()

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 94 app.activeDocument = mergedDoc mergedDoc.selection.select(selRegion)

// Inverting the selection so the bottom of the document is now selected mergedDoc.selection.invert()

// Paste the duck mergedDoc.paste()

// get rid of our originals without modifying them duckDoc.close(SaveOptions.DONOTSAVECHANGES) eagleDoc.close(SaveOptions.DONOTSAVECHANGES)

// Reset the application preferences app.preferences.rulerUnits = startRulerUnits app.preferences.typeUnits = startTypeUnits app.displayDialogs = startDisplayDialogs

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 95

DocumentInfo

Metadata about a document

object. These values can be set by selecting File > File Info in the Adobe

Photoshop CS2 application.

Note: You use the object name info

, rather than the class name

DocumentInfo

, in a script, as in the following sample, which sets the author

, caption

, and copyrighted

properties: var docRef = open(fileList[i])

// set the file info docRef.info.author = "Mr. Adobe programmer" docRef.info.caption = "Adobe Photo shoot" docRef.info.copyrighted = CopyrightedType.COPYRIGHTEDWORK

The following sample uses the

DocumentInfo

object incorrectly: docRef.DocumentInfo.author = "Mr. Adobe programmer" docRef.DocumentInfo.caption = "Adobe Photo shoot" docRef.DocumentInfo.copyrighted = CopyrightedType.COPYRIGHTEDWORK

Properties

Property author authorPosition caption captionWriter category city copyrighted copyrightNotice country creationDate credit exif headline instructions jobName keywords ownerUrl

Value Type string string string string string string

CopyrightedType

string string string string

Array of arrays:

Array(Array (tag, tag

data)), ...) string string string

Array (strings) string

What it is

Read-write.

Read-write.

Read-write.

Read-write.

Read-write.

Read-write.

Read-write. The copyrighted status.

Read-write.

Read-write.

Read-write.

Read-write.

Read-only. Camera data that includes camera settings used when the image was taken. Sample array values are: tag =

“camera”; tag value = “Cannon”.

Read-write.

Read-write.

Read-write.

Read-write. A list of keywords that can identify the document or its contents.

Read-write.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 96

Property parent provinceState source supplementalCategories title transmissionReference typename

Value Type object (

Document )

string string

Array (strings) string string string urgency

Urgency

What it is (Continued)

Read-only. The info

object's container.

Read-write.

Read-write.

Read-write.

Read-write.

Read-write.

Read-only. The class name of the referenced info

object.

Read-write.

Sample Script

The following script sets document info (metadata) for all of the files in a specified folder and then saves the modified files as low-quality JPEG images in a new folder without changing the originals.

Ask the user to specify the folder that contains the original files and the output folder for the JPEG images, and then check that the folders exist.

Open each file and use the documentInfo

object properties to tag it with the following metadata:

● author: Mr. Adobe programmer

● caption: Adobe Photo shoot captionWriter: Mr. Adobe programmer city: San Jose copyrightNotice: Copyright (c) Adobe programmer Photography

● copyrighted status: Copyrighted Work country: USA

● state: CA

Save the new documents in JPEG format with a low quality setting.

DocumentInfo.jsx

// Save the current preferences var startDisplayDialogs = app.displayDialogs

// Set Adobe Photoshop CS2 to use pixels and display no dialogs app.displayDialogs = DialogModes.NO

// ask the user for the input folder var inputFolder = Folder.selectDialog("Select a folder to tag")

// ask the user for the output folder var outputFolder = Folder.selectDialog("Select a folder for the output files")

// see if we got something interesting from the dialog if (inputFolder != null && outputFolder != null) {

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 97

// get all the files found in this folder var fileList = inputFolder.getFiles()

// save the outputs in JPEG var jpegOptions = new JPEGSaveOptions()

// set the jpeg quality really low so the files are small jpegOptions.quality = 1

// open each one in turn for (var i = 0; i < fileList.length; i++) {

// The fileList includes both folders and files so open only files if (fileList[i] instanceof File && fileList[i].hidden == false) {

// get a reference to the new document var docRef = open(fileList[i])

// tag all of the documents with photo shoot information docRef.info.author = "Mr. Adobe programmer" docRef.info.caption = "Adobe Photo shoot" docRef.info.captionWriter = "Mr. Adobe programmer" docRef.info.city = "San Jose" docRef.info.copyrightNotice = "Copyright (c) Adobe programmer

Photography" docRef.info.copyrighted = CopyrightedType.COPYRIGHTEDWORK

docRef.info.country = "USA" docRef.info.provinceState = "CA"

// change the date to a Adobe Photoshop CS2 date format

// "YYYYMMDD" var theDate = new Date()

// the year is from 1900 ????

var theYear = (theDate.getYear() + 1900).toString()

// convert the month from 0..12 to 00..12

var theMonth = theDate.getMonth().toString() if (theDate.getMonth() < 10) { theMonth = "0" + theMonth

}

// convert the day from 0..31 to 00.31

var theDay = theDate.getDate().toString() if (theDate.getDate() < 10) { theDay = "0" + theDay

}

// stick them all together docRef.info.creationDate = theYear + theMonth + theDay

// flatten because we are saving to JPEG docRef.flatten()

// go to 8 bit because we are saving to JPEG docRef.bitsPerChannel = BitsPerChannelType.EIGHT

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 98

// save and close docRef.saveAs(new File(outputFolder + "/Output" + i + ".jpg"), jpegOptions)

// don’t modify the original docRef.close(SaveOptions.DONOTSAVECHANGES)

}

}

}

// Reset the application preferences app.displayDialogs = startDisplayDialogs

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 99

Documents

The collection of open document

objects. See

Document

for information on the document

object.

Note: Because the

Documents

class is a property of the Application

object, you use the object name, documents

, rather than the class name,

Documents

, in your code, as in the following example: documents.add(800, 500, 72, “myDocument”, NewDocumentMode.RGB)

The following example, which uses an upper case D in the object name, is incorrect:

Documents.add(800, 500, 72, “myDocument”, NewDocumentMode.RGB)

Properties

Property length

Value Type number (long) parent typename object

( Application

) string

What it is

Read-only. The number of elements in the documents collection.

Read-only. The documents objects’ container.

Read-only. The class name of the referenced documents object.

Methods

Method index

(itemKey) add

([width]

[, height]

[, resolution]

[, name]

[, mode]

[, initialFill]

[pixelAspectRatio]) getByName

(name)

Parameter Type number

UnitValue

UnitValue number (double) string

NewDocumentMode

DocumentFill

number (double) string

Returns

Document

Document

Document

What it does

Gets an element from the documents collection.

Adds a document

object

( pixelAspectRatio

: 0.100 0 10.00).

Gets the first element in the documents collection with the provided name

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 100

EPSOpenOptions

Options that can be specified when opening an EPS format document.

Properties

Property antiAlias constrainProportions height mode resolution typename width

Value Type boolean boolean

UnitValue

OpenDocumentMode

number (double) string

UnitValue

What it is

Read-write. Indication of whether to use antialias.

Read-write. Indication of whether to constrain the proportions of the image.

Read-write. The height of the image (unit value).

Read-write. The color profile to use as the document mode.

Read-write. The resolution of the document in pixels per inch.

Read-only. The class name of the referenced

EPSOpenOptions

object.

Read-write. The width of the image (unit value).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 101

EPSSaveOptions

Options that can be specified when saving a document in EPS format.

Properties

Property embedColorProfile

Value Type boolean encoding halftoneScreen interpolation preview psColorManagement transferFunction transparentWhites typename vectorData

SaveEncoding

boolean boolean

Preview

boolean boolean boolean string boolean

What it is

Read-write. Indication of whether to embed the color profile in this document.

Read-write. The type of encoding to use (default:

SaveEncoding.BINARY

).

Read-write. Indication of whether to include the halftone screen (default: false

).

Read-write. Indication of whether to use image interpolation (default: false

).

Read-write. The preview type.

Read-write. Indication of whether to use Postscript color management (default: false ).

Read-write. Indication of whether to include the

Transfer functions to compensate for dot gain between the image and film (default: false

).

Read-write. Indication of whether to display white areas as transparent.

Note: Valid only when document.

mode -

DocumentMode.BITMAP

. See ‘mode’ on page 88 (in the Properties table of the

document

object) or ‘changeMode’ on page 90

(in the Methods table of the document

object).

Read-only. The class name of the referenced

EPSSaveOptions object.

Read-write. Indication of whether to include vector data.

Note: Valid only if the document includes vector data (text).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 102

ExportOptionsIllustrator

Options that can be specified when exporting a

PathItem object to an Adobe Illustrator® file.

Properties

Property path pathName typename

Value Type

IllustratorPathType

string string

What it is

Read-write. The type of path to export

(default:

IllustratorPathType.DOCUMENTBOUNDS

).

Read-write. The name of the path to export.

Note: Valid only when path =

IllustratorPathType.NAMEDPATH

.

See path .

Read-only. The class name of the referenced exportOptionsIllustrator object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 103

ExportOptionsSaveForWeb

Options that can be specified when optimizing a document for the web.

Properties

Property blur colorReduction colors dither ditherAmount format includeProfile interlaced lossy matteColor optimized

Value type number (double)

What it is

Read-write. Applies blur to the image to reduce artifacts (default:

0.0

).

ColorReductionType

Read-write. The color reduction algorithm (default:

ColorReductionType.SELECTIVE

).

number (long)

Dither

number (long)

SaveDocumentType

Read-write. The number of colors in the palette

(default:

256

).

Read-write. The type of dither (default:

Dither.DIFFUSION

).

Read-write. The amount of dither (default: 100).

Note: Valid only when dither = Dither.DIFFUSION

. See

dither

.

Read-write. The file format to use (default:

SaveDocumentType.COMPUSERVEGIF

).

boolean boolean number (long)

RGBColor

boolean

Note: For this property, only

COMPUSERVEGIF

,

JPEG , PNG-8 , PNG-24 , and BMP are supported.

Read-write. Indication of whether to include the document’s embedded color profile (default: false ).

Read-write. Indication of whether to download in multiple passes; progressive (default: false

).

Read-write. The amount of lossiness allowed

(default: 0 ).

Read-write. The colors to blend transparent pixels against.

Read-write. Indication of whether to create smaller but less compatible files (default: true ).

Note: Valid only when format = SaveDocumentType.JPEG

.

See

format

.

JavaScript Scripting Reference

Property

PNG8 quality transparency transparencyAmount transparencyDither typename webSnap

Adobe Photoshop CS2

Value type boolean number (long) boolean number (long)

Dither

string number (long)

JavaScript Object Reference 104

What it is (Continued)

Read-write. Indicates the number of bits; true

= 8, false

= 24 (default: true

).

Note: Valid only when format = SaveDocumentType.PNG

.

See

format

.

Read-write. The quality of the produced image (0 -

100 as percentage; default:

60

).

Read-write. Indication of transparent areas of the image should be included in the saved image(default: true ).

Read-write. The amont of transparency dither

(default: 100).

Note: Valid only if transparency = true

. See

transparency .

Read-write. The transparency dither algorithm

(default:

transparencyDither = Dither.NONE

).

Read-only. The class name of the referenced

ExportOptionsSaveForWeb object.

Read-write. The tolerance amount within which to snap close colors to web palette colors (default:

0

).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 105

GalleryBannerOptions

Options that define the bannerOptions

property of the galleryOptions

object. See

‘GalleryOptions’ on page 109

.

Tip: You can preserve default values for many galleryBannerOptions properties by setting the galleryOptions

property preserveAllMetadata

to true

or by choosing File > Automate > Web

Photo Gallery, and then choosing Preserve all metadata on the Options area of the Web Photo

Gallery dialog.

Properties

Property contactInfo date font fontSize photographer siteName typename

Value Type string string

GalleryFontType

number (long) string string string

What it is

Read-write. The web photo gallery contact info.

Read-write. The web photo gallery date

(default: current date).

Read-write. The font setting for the banner text (default:

GalleryFontType.ARIAL

).

Read-write. The font size for the banner text (1 - 7; default:

3

).

Read-write. The web photo gallery photographer.

Read-write. The web photo gallery site name (default:

Adobe Web Photo Gallery ).

Read-only. The class name of the referenced galleryBannerOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 106

GalleryCustomColorOptions

Options that define the customColorOptions

property of the galleryOptions

object. See

‘GalleryOptions’ on page 109 .

Tip: You can preserve default values for many galleryCustomColorOptions properties by setting the galleryOptions

property preserveAllMetadata

to true

or by choosing File > Automate > Web

Photo Gallery, and then choosing Preserve all metadata on the Options area of the Web Photo

Gallery dialog.

Properties

Property activeLinkColor backgroundColor bannerColor linkColor textColor typename visitedLinkColor

Value Type

RGBColor

RGBColor

RGBColor

RGBColor

RGBColor

string

RGBColor

What it is

Read-write. The color to use to indicate an active link.

Read-write. The background color.

Read-write. The banner color.

Read-write. The color to use to indicate a link.

Read-write. The text color.

Read-only. The class name of the referenced galleryCustomColorOptions object.

Read-write. The color to use to indicate a visited link.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 107

GalleryImagesOptions

Options that define the imagesOptions

property of the galleryOptions

object. See

‘GalleryOptions’ on page 109

.

Tip: You can preserve default values for many galleryImagesOptions properties by setting the galleryOptions

property preserveAllMetadata

to true

or by choosing File > Automate > Web

Photo Gallery, and then choosing Preserve all metadata on the Options area of the Web Photo

Gallery dialog.

Properties

Property border

Value Type number (long) caption dimension font fontSize imageQuality includeCopyright includeCredits boolean number (long)

GalleryFontType

number (long) number (long) boolean boolean

What it is

Read-write. The size (in pixels) of the border that separates images (0 - 99; default: 0 ).

Read-write. Indication of whether to generate image captions (default: false

).

Read-write. The resized image dimensions in pixels (default: 350 ).

Note: Valid only when resizeImages = true

. See resizeImages

.

Read-write. The font to use for image captions (default: GalleryFontType.ARIAL

).

Read-write. The font size for image captions

(1 - 7; default:

3

).

Note: Valid only when caption = true

. See

caption

.

Read-write. The quality setting for a JPEG image (0 - 12; default:

5)

.

Read-write. Indication of whether to include copyright information in captions (default: false

).

Note: Valid only when caption = true

. See

caption

.

Read-write. Indication of whether to include the credits in image captions (default: false

).

Note: Valid only when caption = true

. See

caption

.

JavaScript Scripting Reference

Property includeFilename includeTitle numericLinks resizeConstraint resizeImages typename

Adobe Photoshop CS2

JavaScript Object Reference 108

Value Type boolean boolean boolean

GalleryConstrainType

boolean string

What it is (Continued)

Read-write. Indication of whether to include the file name in image captions (default: true

).

Note: Valid only when caption = true

. See

caption

.

Read-write. Indication of whether to include the title in image captions (default: false

).

Note: Valid only when caption = true

. See

caption

.

Read-write. Indication of whether to add numeric links (default: true

).

Read-write. The image dimensions to constrain in the gallery image (default:

GalleryConstrainType.CONSTRAINBOTH

).

Note: Valid only when resizeImages = true

. See resizeImages

.

Read-write. Indication of whether to automatically resize images for placement on the gallery pages (default: true

).

Read-only. The class name of the referenced galleryImagesOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 109

GalleryOptions

Options that can be specified for a Web photo gallery.

Tip: You can preserve default values for many galleryOptions properties by choosing File > Automate

> Web Photo Gallery, and then choosing Preserve all metadata on the Options area of the Web

Photo Gallery dialog.

Properties

Property addSizeAttributes bannerOptions customColorOptions emailAddress imagesOptions includeSubFolders layoutStyle preserveAllMetadata securityOptions thumbnailOptions typename useShortExtension useUTF8Encoding

Value Type boolean

GalleryBannerOptions

boolean string

What it is

Read-write. Indicates whether width and height attributes for images will be added (default: true

).

Read-write. The options related to banner settings.

GalleryCustomColorOptions

Read-write. The options related to custom color settings.

string

GalleryImagesOptions

Read-write. The email address to show on the web page.

Read-write. The options related to images settings.

Read-write. Indication of whether to include all files found in sub folders of the input folder (default: true

).

Read-write. The style to use for laying out the web page (default: Centered

Frame 1 - Basic

).

boolean

GallerySecurityOptions

GalleryThumbnailOptions

Read-write. Indicates whether to save metadata (default: false

).

Read-write. The options related to security settings.

Read-write. The options related to thumbnail image settings.

string boolean boolean

Read-only. The class name of the referenced galleryOptions object.

Read-write. Indicates whether the short web page extension

.htm

or number (long) web page extension

.html

will be used (default: true

).

Read-write. Indicates whether the web page should use UTF-8 encoding

(default: false ).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 110

GallerySecurityOptions

Options that define the securityOptions

property of the galleryOptions

object. See ‘GalleryOptions’ on page 109 .

Tip: You can preserve default values for many gallerySecurityOptions properties by setting the galleryOptions

property preserveAllMetadata

to true

or by choosing File > Automate > Web

Photo Gallery, and then choosing Preserve all metadata on the Options area of the Web Photo

Gallery dialog.

Properties

Property content font fontSize opacity text textColor textPosition textRotate typename

Value Type

GallerySecurityType

GalleryFontType

number (long) number (long) string

RGBColor

GallerySecurityTextPositionType

GallerySecurityTextRotateType

string

What it is

Read-write. The web photo gallery security content (default:

GallerySecurityType.NONE

).

Read-write. The web photo gallery security font (default:

GalleryFontType.ARIAL

).

Read-write. The web photo gallery security font size (1 - 72; default:

3

).

Read-write. The web page security opacity as a percent (default: 100 ).

Read-write. The web photo gallery security custom text.

Read-write. The web page security text color.

Read-write. The web photo gallery security text position (default:

GallerySecurityTextPositionType.

CENTERED ).

Read-write. The web photo gallery security text orientation to use (default:

GallerySecurityTextRotateType.ZE

RO ).

Read-only. The class name of the referenced gallerySecurityOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 111

GalleryThumbnailOptions

Options that define the thumbnailOptions

property of the galleryOptions

object. See

‘GalleryOptions’ on page 109 .

Tip: You can preserve default values for many galleryThumbnailOptions properties by setting the galleryOptions

property preserveAllMetadata

to true

or by choosing File > Automate > Web

Photo Gallery, and then choosing Preserve all metadata on the Options area of the Web Photo

Gallery dialog.

Properties

Property border caption columnCount dimension font fontSize includeCopyright includeCredits includeFilename includeTitle rowCount size typename

Value Type number (long) boolean number (long) number (long)

GalleryFontType

number (long) boolean boolean boolean boolean number (long)

GalleryThumbSizeType

string

What it is

Read-write. The amount of border pixels you want around your thumbnail images (0 - 99; default:

0

).

Read-write. Indicates whether there is a caption (default: false

).

Read-write. The number of columns on the page (default:

5

).

Read-write. The web photo gallery thumbnail dimension in pixels

(default: 75) .

Read-write. The web photo gallery font

(default:

GalleryFontType.ARIAL

).

Read-write. The font size for thumbnail images text (1 - 7; default: 3 ).

Read-write. Indication of whether to include copyright information for thumbnails

(default: false

).

Read-write. Indication of whether to include credits for thumbnails (default: false

).

Read-write. Indication of whether to include file names for thumbnails (default: false

).

Read-write. Indication of whether to include titles for thumbnails (default: false

).

Read-write. The number of rows on the page

(default:

3

).

Read-write. The thumbnail image size

(default:

GalleryThumbSizeType.MEDIUM

).

Read-only. The class name of the referenced

GalleryThumbnailOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 112

GIFSaveOptions

Options that can be specified when saving a document in GIF format.

Properties

Property colors dither ditherAmount forced interlaced matte palette preserveExactColors

Value Type number (long)

Dither

number (long)

ForcedColors

boolean

MatteType

Palette

boolean

What it is

Read-write. The number of palette colors.

Note: Valid only when palette = Palette.LOCALADAPTIVE

; palette = Palette.LOCALPERCEPTUAL

; palette = Palette.LOCALSELECTIVE

; palette = Palette.MACOSPALETTE

; palette = Palette.UNIFORM

; palette = Palette.WEBPALETTE

; or palette = Palette.WINDOWSPALETTE

.

See palette .

Read-write. The dither type.

Read-write. The amount of dither. (1 - 100; default:

75

).

Note: Valid only for when dither =

Dither.DIFFUSION

. See dither .

Read-write. The type of colors to force into the color palette.

Read-write. Indicates whether rows should be interlaced (default: false ).

Read-write. The color to use to fill anti-aliased edges adjacent to transparent areas of the image

(default:

MatteType.WHITE

).

Note: When transparency = false , the matte color is applied to transparent areas. See

transparency .

Read-write. The type of palette to use (default:

Palette.LOCALSELECTIVE

).

Read-write. Indication of whether to protect colors in the image that contain entries in the color table from being dithered.

Note: Valid only when dither = Dither.DIFFUSION

. See dither .

JavaScript Scripting Reference

Property transparency typename

Adobe Photoshop CS2

Value Type boolean string

JavaScript Object Reference 113

What it is (Continued)

Read-write. Indication of whether to preserve transparent areas of the image during conversion to GIF format.

Read-only. The class name of the referenced

GIFSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference

GrayColor

Options for defining a gray color.

Properties

Property gray typename

Value Type number (double) string

JavaScript Object Reference 114

What it is

Read-write. The gray value (0.0 - 100.0; default: 0.0).

Read-only. The class name of the referenced grayColor object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 115

HistoryState

A version of the document stored automatically (and added to the

HistoryStates

collection), which

preserves the document’s state, each time the document is changed. See HistoryStates for information

about the

HistoryStates

collection.

Note: Because the

HistoryState

class is also a property of the Document object, you use the object

name, historyState , rather than the class name, HistoryState , in your code.

The following example uses correct syntax to refer to a

HistoryState object named

AddLayerMask and then assign its snapshot property value: documents(0).historyState(“AddLayerMask”).snapshot = true

The following example, which uses an upper case A in the object name, is incorrect: documents(0).HistoryState(“AddLayerMask”).snapshot = true

Properties

Property name parent snapshot typename

Value Type string

What it is

Read-only. The

HistoryState

object's name.

object (

Document

) Read-only. The

HistoryState

object's container.

boolean string

Read-only. Indicates whether the history state is a snapshot.

Read-only. The class name of the referenced HistoryState object.

Adobe Photoshop CS2

JavaScript Scripting Reference

HistoryStates

The collection of

HistoryState

objects in the document. See

HistoryState

for more information on

HistoryState

objects.

Note: Because the

HistoryStates

class is also a property of the Document

object, you use the object name, historyStates

, rather than the class name,

HistoryStates

, in your code.

The following example uses correct syntax to fill a Selection object (referred to by the variable selRef ) with an object in the

HistoryStates collection: selRef.fill(activeDocument.historyStates[7])

The following example, which uses an upper case H in the object name, is incorrect: selRef.fill(activeDocument.HistoryStates[7])

Properties

Property length parent typename

Value Type number (long)

object ( Document )

string

What it is

Read-only. The number of elements in the HistoryStates collection.

Read-only. The

HistoryStates

object's container.

Read-only. The class name of the referenced

HistoryStates object.

Methods

Method index

(itemKey) getByName

(name)

Parameter Type number string

JavaScript Object Reference 116

Returns

HistoryState

HistoryState

What it does

Gets an element from the

HistoryStates

collection.

Get the first element in the

HistoryStates

collection with the provided name.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 117

HSBColor

Options that can be specified for a color object using the HSB color model.

Properties

Property brightness hue saturation typename

Value Type What it is number (double) Read-write. The brightness value (between 0.0 and 100.0).

number (double) Read-write. The hue value (between 0.0 and 360.0).

number (double) Read-write. The saturation value (between 0.0 and 100.0).

string Read-only. The class name of the referenced

HSBColor object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 118

IndexedConversionOptions

Options that can be specified when converting an RGB image to an indexed color model.

Properties

Property colors

Value Type number (long) dither ditherAmount forced matte palette preserveExactColors transparency typename

Dither

number (long)

ForcedColors

MatteType

Palette

boolean boolean string

What it is

Read-write. The number of palette colors.

Note: Valid only when palette = Palette.LOCALADAPTIVE; palette = Palette.LOCALPERCEPTUAL; palette = Palette.LOCALSELECTIVE; palette = Palette.MACOSPALETTE; palette = Palette.UNIFORM; palette = Palette.WEBPALETTE; or palette = Palette.WINDOWSPALETTE .

See palette

.

Read-write. The dither type.

Read-write. The amount of dither. (1 - 100).

Note: Valid only when dither =

Dither.diffusion

.

Read-write. The type of colors to force into the color palette.

Read-write. Read-write. The color to use to fill anti-aliased edges adjacent to transparent areas of the image (default: MatteType.WHITE

).

Note: When transparency = false

, the matte color is applied to transparent areas. See

transparency

.

Read-write. The palette type (default:

Palette.EXACT

).

Read-write.Indication of whether to protect colors in the image that contain entries in the color table from being dithered.

Note: Valid only when dither =

Dither.DIFFUSION

. See dither .

Read-write. Indication of whether to preserve transparent areas of the image during conversion to GIF format.

Read-only. The class name of the referenced

IndexedConversionOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 119

JPEGSaveOptions

Options that can be specified when saving a document in JPEG format.

Properties

Property embedColorProfile

Value Type boolean formatOptions matte quality scans typename

FormatOptions

MatteType

number (long) number (long) string

What it is

Read-write. Indication of whether to embed the color profile in the document.

Read-write.The download format to use (default:

FormatOptions.STANDARDBASELINE

).

Read-write. The color to use to fill anti-aliased edges adjacent to transparent areas of the image (default:

MatteType.WHITE

).

Note: When transparency = false

, the matte color is applied to transparent areas. See

transparency

.

Read-write. The image quality setting to use (affects file size and compression) (0 - 12; default:

3

).

Read-write. The number of scans to make to incrementally display the image on the page

(3 - 5; default: 3 ).

Note: Valid only for when formatOptions =

FormatOptions.PROGRESSIVE

.

Read-only. The class name of the referenced

JPEGSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 120

LabColor

Options that can be specified when defining a color object using the LAB color model.

Properties

Property a b l typename

Value Type What it is number (double) Read-write. The a-value (-128.0 - 127.0).

number (double) Read-write. The b-value (-128.0 - 127.0).

number (double) string

Read-write. The L-value (0.0 - 100.0).

Read-only. The class name of the referenced

LabColor object.

Adobe Photoshop CS2

JavaScript Scripting Reference

LayerComp

A snapshot of a state of the layers in a document (can be used to view different page layouts or compostions).

Note: Because the

LayerComp

class is also a property of the

Document object, you use the object name,

layerComp

, rather than the class name,

LayerComp

, in your code.

The following example uses correct syntax to set the comment property value for a

LayerComp object named myLayerComp

: activeDocument.layerComp(“myLayerComp”).comment = “View from shoreline”

The following example, which uses an upper case L in the object name, is incorrect: activeDocument.LayerComp(“myLayerComp”).comment = “View from shoreline”

Properties

Property appearance comment name parent position selected typename visibility

Value Type boolean string string object (

Document

) boolean boolean string boolean

What it is

Read-write. Indication of whether to use layer appearance (layer styles) settings.

Read-write. A description of the layer comp.

Read-write. The name of the layer comp.

Read-write. The layerComp

object's container.

Read-write. Indication of whether to use layer position.

Read-only. Indication of whether the layer comp is currently selected.

Read-only. The class name of the referenced layerComp object.

Read-write. Indication of whether to use layer visibility settings .

Methods

Method apply

() recapture

()

Parameter Type Returns

JavaScript Object Reference 121

What it does

Applies the layer comp to the document.

Recaptures the current layer state(s) for this layer comp.

Adobe Photoshop CS2

JavaScript Scripting Reference

Method remove

() resetfromComp

()

Parameter Type Returns

JavaScript Object Reference 122

What it does (Continued)

Deletes the layerComp

object.

Resets the layer comp state to the document state.

Adobe Photoshop CS2

JavaScript Scripting Reference

Parameter Type number

Returns

LayerComp

JavaScript Object Reference 123

LayerComps

The collection of layerComp

objects in the document. See

LayerComp for information on

layerComp objects.

Note: Because the

LayerComps

class is also a property of the

Document object, you use the object name,

layerComps

, rather than the class name,

LayerComps

, in your code.

The following example uses correct syntax to add a

LayerComps

: activeDocument.layerComps.add(“myLayerComp”, “View from Shoreline”, true, true, true)

The following example, which uses an upper case L in the object name, is incorrect: activeDocument.LayerComps.add(“myLayerComp”, “View from Shoreline”, true, true, true)

Properties

Property length parent typename

Value Type number (long) object (

Document )

string

What it is

Read-only. The number of elements in the layerComps collection.

Read-only. The layerComps

object's container.

Read-only. The class name of the referenced layerComps

object.

Methods

Method index

(itemKey) add

(name,

comment,

appearance,

position,

visibility) getByName

(name) removeAll

() string string boolean boolean boolean string

LayerComp

LayerComp

What it does

Gets an element from the layerComps

collection.

Adds a layer comp.

Gets the first element in the collection with the provided name.

Removes all layerComp

objects from the layerComps collection.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 124

Layers

The collection of layer objects, including artLayer

and layerSet

objects, in the document. See

ArtLayer

for information on artLayer

objects. See

LayerSet

for information on layerSet

objects.

Note: Because the

Layers

object is a property of the

Document object (as well as several other objects),

you use the object name, layers

, rather than the class name,

Layers

, in your code. The following example uses the length property to count the number of layer objects in the active document, then displays the number on the screen: var layerNum = app.activeDocument.layers.length

alert(layerNum)

The following example uses an upper case L, which is incorrect: var layerNum = app.activeDocument.Layers.length

alert(layerNum)

Properties

Property length parent typename

Methods

Method index

(itemKey) getByName

(name) removeAll

()

Value Type number (long)

What it is

Read-only. The number of elements in the layers collection.

object (document or layerSet)

Read-only. The layers

object's container.

string Read-only. The class name of the referenced layers

object.

Parameter Type Returns What it does object(Layer) Gets an element from the collection.

number string

Layer Gets the first element in the layers collection with the provided name.

Removes all layers from the collection.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 125

LayerSet

A group of layer objects, which can include artLayer

objects and other (nested) layerSet

objects. A single command or set of commands manipulates all layers in a layerSet

object.

Note: Most likely, you will use variables to refer to layerSet

objects in your script. However, if you choose not to use a variable, be aware that, because the

LayerSet

class is also a property of the Document

object, you use the object name, layerSet , rather than the class name, LayerSet , in your code.

The following example uses correct syntax to refer to a layerSet

object by name and then assign its allLocked property value: documents(0).layerSet(“myLayerSet”).allLocked = true

The following example, which uses an upper case L in the object name, is incorrect: documents(0).LayerSet(“myLayerSet”).allLocked = true

Properties

Property allLocked artLayers blendMode bounds enabledChannels layers layerSets linkedLayers name opacity parent typename visible

Value Type boolean

ArtLayer

BlendMode

Array(UnitValue)

Array (

Channel

objects)

What it is

Read-write. Indicates whether the contents in the layers contained in the layerSet

object are editable.

Read-only. The artLayer

objects in this layer set.

Read-write. The blend mode to use for the layer set.

Read-only. The bounding rectangle of the layer set.

Read-write. The channels enabled for the layer set; must be a list of component channels.

LayerSets

LayerSets

Note: See kind in the Properties table for the Channel object (

Channel

).

Read-only. The layers in this layerSet

object.

Read-only. Layer Sets contained within a Layer Set.

Array (layers) string number (double)

Read-only. The layers linked to this layerSet object.

Read-write. The name of the layerSet

object.

Read-write. The master opacity of the layerSet

object

(0.0 - 100.0).

object (document or layerSet)

Read-only. The layerSet object's container.

string boolean

Read-only. The class name of the referenced layerSet object.

Read-write. Indicates whether the layerSet

object is visible.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 126

Methods

Method Parameter Type Returns What it does duplicate

([relativeObject]

[, insertionLocation]) object (

ArtLayer

or LayerSet

)

ElementPlacement

object (Layer) Creates a duplicate of the layerSet object.

link

(with) merge

() move

(relativeObject,

insertionLocation) object (Layer) object (layer or

layerSet)

ElementPlacement

ArtLayer

Links the layer set with another layer.

Merges the layerset; returns a reference to the art layer created by this method.

Moves the layerSet object.

remove

()

Deletes the layerSet object.

resize

([horizontal]

[, vertical]

[, anchor]) rotate

(angle

[, anchor]) translate

([deltaX]

[, deltaY]) number (double) number (double)

AnchorPosition

number (double)

AnchorPosition

UnitValue

UnitValue

Resizes all layers in the layer set to to the specified dimensions (as a percentage of its current size) and places the layer set in the specified position.

Rotates all layers in the layer set around the specified anchor point

(default:

.

AnchorPosition.MIDDLECENTER

)

Moves the position relative to its current position.

unlink

()

Unlinks the layer set.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 127

LayerSets

The collection of layerSet

objects in the document. See LayerSet for information on

layerSet

objects.

Note: Because the

LayerSets

class is a property of the Document

object, you use the object name, layerSets

, rather than the class name,

LayerSets

, in your code. For example: var laysetRef = docRef.layerSets.add()

The following sample uses the layerSets

object incorrectly: var laysetRef = docRef.LayerSets.add()

Properties

Property length parent typename

Value Type string

What it is number (long) Read-only. The number of elements in the layerSets collection.

object (document or layerSet)

Read-only. The layerSets

object's container.

Read-only. The class name of the referenced layerSets object.

Methods

Method index

(itemKey) add

() getByName

(name) removeAll

()

Parameter Type Returns

LayerSet number

LayerSet string

LayerSet

What it does

Gets an element from the layerSets collection.

Creates a new layerSet

object.

Gets the first element in the layerSets collection with the provided name.

Removes the layer set, and any layers or layer sets it contains, from the document.

Sample Script

The following script creates three layer sets, then nests a second layer set in each layer set, and then creates a text layer in each nested set that that displays the text “Layer in n Set Inside n Set”, where n represents the ordinal number of the set (first, second, or third).

Note: The script uses the

$

object, which is defined in ‘Dollar ($) Object’ on page 293 .

LayerSets.jsx

$.level = 1

//close all open documents while (app.documents.length) { app.activeDocument.close()

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 128

}

// create a working document var docRef = app.documents.add()

// create an array to hold the layer sets var myLayerSets = new Array()

// Create an array to hold the text var textArray = Array("First", "Second", "Third")

//Create an indexer variable var i = 0

// Create three layer sets at the top level for (i = 0; i < 3; i++) { myLayerSets[i] = new Array() myLayerSets[i][0] = docRef.layerSets.add()

}

// Rearrange the layer sets with the first one on top, second next, etc.

myLayerSets[1][0].moveAfter(myLayerSets[0][0]) myLayerSets[2][0].moveAfter(myLayerSets[1][0])

// Create a layer set inside each layer set for (i = 0; i < 3; i++) { myLayerSets[i][0].name = textArray[i] + " Set" myLayerSets[i][1] = myLayerSets[i][0].layerSets.add() myLayerSets[i][1].name = "Inside " + textArray[i] + " Set"

}

// Create an array to hold the layers var myLayers = new Array()

// Create a text layer with a description inside each layer set for (i = 0; i < 3; i++) { myLayers[i] = myLayerSets[i][1].artLayers.add() myLayers[i].kind = LayerKind.TEXT

myLayers[i].textItem.contents = "Layer in " + textArray[i] + " Set Inside "

+ textArray[i] + " Set" myLayers[i].textItem.position = Array(app.activeDocument.width * i * 0.33, app.activeDocument.height * (i + 1) * 0.25) myLayers[i].textItem.size = 12

}

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 129

LensBlurOptions

Defines the optional parameter of the artLayer

object’s applyLensBlur()

method.

Note: See

‘applyLensBlur’ on page 60 (in the Methods table of the

artLayer

object).

Properties

Property amount bladeCurvature brightness distribution focalDistance invertDepthMap monochromatic radius rotation shape source threshold typename

Value type number (long) number (long) number (long)

NoiseDistribution

number (long) boolean boolean number (long) number (long)

Geometry

DepthMapSource

number (long) string

What it is

Read-write. The amount of noise (default:

0

).

Read-write. The blade curvature of the iris (default: 0 ).

Read-write. The brightness for the specular highlights

(default:

0

).

Read-write. The distribution value for the noise

(default: NoiseDistribution.UNIFORM

).

Read-write. The blur focal distance for the depth map

(default:

0

).

Read-write. Indicates whether the depth map is inverted (default: false ).

Read-write. Indicates whether the noise is monochromatic (default: false

).

Read-write. The radius of the iris (default:

15

).

Read-write. The rotation of the iris (default: 0 ).

The shape of the iris (default:

Geometry.HEXAGON

).

Read-write. The source for the depth map (default:

DepthMapSource.NONE

).

Read-write. The threshold for the specular highlights

(default:

0

).

Read-only. The class name of the referenced lensBlurOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference

NoColor

An object that represents a missing color.

Properties

Property typename

Value type string

JavaScript Object Reference 130

What it is

Read-only. The class name of the referenced noColor object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 131

Notifier

An event-handler object that tells the script to execute specified code when a specified event occurs.

Note: Because the

Notifier

class is also a property of the

Document object, you use the object name,

notifier

, rather than the class name,

Notifier

, in your code.

Properties

Property event

Value type string eventClass eventFile parent typename string file object

( Application

) string

What it is

Read-only. The event ID in four characters or a unique string that the notifier is associated with.

Read-only. The class ID of the event associated with the

Notifier object, four characters or a unique string.

Note:

For a list of four-character codes, see Appendix A:

Event ID Codes

.

Read-only. The path to the file to execute when the event occurs/activates the notifier.

Read-only. The notifier object’s container.

Read-only. The class name of the referenced notifier object.

Methods

Method remove

()

Parameter type Returns What it does

Deletes the notifier

object.

Note: Y ou can remove a notifier object from the Script Events Manager drop-down list by deleting the file named

Script Events

Manager.xml

from in the

Photoshop preferences folder. See

Adobe Photoshop CS2 help for more information.

Adobe Photoshop CS2

JavaScript Scripting Reference

Methods

Method index

(itemKey)

Parameter type Returns

Notifier

number

JavaScript Object Reference 132

Notifiers

The collection of notifier

objects in the document; the notifiers

property of the app

object. See

‘Notifier’ on page 131 for information on

notifier

objects. See notifiers

(in the Properties table of the app object).

Note: Because the

Notifiers

class is a property of the Document

object, you use the object name, notifiers

, rather than the class name,

Notifiers

, in your code. For example: var notRef = activeDocument.notifiers.add(“OnClickGoButton”, app.path +

“/Presets/Scripts/Event Only Scripts/4322.jsx””)

The following sample uses the

Notifiers

object incorrectly: var notRef = activeDocument.Notifiers.add(“OnClickGoButton”, app.path +

“/Presets/Scripts/Event Only Scripts/4322.jsx””)

Properties

Property length parent typename

Value type number (long)

What it is

Read-only. The number of elements in the notifiers collection.

Read-only. The notifiers object’s container object

( Application

) string Read-only. Read-only. The class name of the referenced notifiers object.

What it does

Gets an element from the notifiers collection.

Adobe Photoshop CS2

JavaScript Scripting Reference

Method add

(event,

eventFile

[, eventClass])

Parameter type Returns

Notifier

string string file removeAll

()

JavaScript Object Reference 133

What it does (Continued)

Creates a notifier

object.

Note: eventClass defines the class ID of the event: four characters or a unique string. For a list of four-character

codes, see Appendix A: Event ID Codes .

Tip: Remember to omit the single quotes when including a four-character ID in your code.

Note: An eventClass

value corresponds to the value you would type in the

Descriptive Lable box when adding an event in the Script Events Manager in the Adobe Photoshop CS2 application.

For more information on using the

Script Events Manager, please refer to

Adobe Photoshop CS2 help.

Removes all notifier

objects from the notifiers collection.

Note: You can remove a notifier

object from the Script Events Manager drop-down list by deleting the file named Script Events Manager.xml from in the Photoshop preferences folder. See Adobe Photoshop CS2 help for more information.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 134

PathItem

A path or drawing object, such as the outline of a shape or a straight or curved line, which contains sub paths that comprise its geometry.

Note: Because the

PathItem

class is also a property of the Document

object, you use the object name, pathItem

, rather than the class name,

PathItem

, in your code.

The following example uses correct syntax to select a pathItem

object : activeDocuments.pathItem(“myPath”).select()

The following example, which uses an upper case P in the object name, is incorrect: activeDocuments.PathItem(“myPath”).select()

Properties

Property kind name parent

SubPathItems typename

Value Type

PathKind

string object

(document)

SubPathItems

string

What it is

Read-write. The pathItem

object’s type.

Read-write. The pathItem object’s name.

Read-only. The pathItem

object's container.

Read-only. The sub path objects for this pathItem object.

Read-only. The class name of the referenced pathItem object.

Methods

Method deselect

() duplicate

(name)

Parameter Type string fillPath

([fillColor]

[, mode]

[, opacity]

[, preserveTransparency]

[, feather]

[, wholePath]

[, antiAlias])

Object ( SolidColor

,

ArtLayer

,

HistoryState

)

ColorBlendMode

number (double) boolean number (double) boolean boolean

Returns What it does

Deselects this pathItem object.

Duplicates this pathItem object with the new name specified in the argument.

Fills the area enclosed by the path ( opacity : 0 - 100 as percent; feather

: 0.0 - 250.0 in pixels).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 135

Method makeClippingPath

([flatness]) makeSelection

([feather]

[, antiAlias]

[, operation])

Parameter Type number (double) number (double) boolean

SelectionType

Returns What it does (Continued)

Makes this pathItem

object the clipping path for this document; the optional parameter tells the PostScript printer how to approximate curves in the path (0.2 - 100).

Makes a selection

object, whose border is the path, from this pathItem

object ( feather

:

0.0 - 250.0 in pixels).

Note:

See Selection .

Deletes this pathItem

object.

remove

() select

() strokePath

([tool]

[, simulatePressure])

ToolType

boolean

Makes this pathItem

object the active or selected pathItem object.

Strokes the path with the specified information.

Sample Script

The following creates a path in three segments: two diagonal lines that form a V, and a curved line above the V that makes it look like a 2D ice cream cone.

Paths.jsx

// Save the current preferences var startRulerUnits = app.preferences.rulerUnits

var startTypeUnits = app.preferences.typeUnits

var startDisplayDialogs = app.displayDialogs

// Set Adobe Photoshop CS2 to use pixels and display no dialogs app.preferences.rulerUnits = Units.PIXELS

app.preferences.typeUnits = TypeUnits.PIXELS

app.displayDialogs = DialogModes.NO

// first close all the open documents while (app.documents.length) { app.activeDocument.close()

}

// create a document to work with var docRef = app.documents.add(5000, 7000, 72, “Simple Line“)

//line #1--it’s a straight line so the coordinates for anchor, left, and //right

//for each point have the same coordinates var lineArray = new Array() lineArray[0] = new PathPointInfo lineArray[0].kind = PointKind.CORNERPOINT

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 136 lineArray[0].anchor = Array(100, 100) lineArray[0].leftDirection = lineArray[0].anchor

lineArray[0].rightDirection = lineArray[0].anchor

lineArray[1] = new PathPointInfo lineArray[1].kind = PointKind.CORNERPOINT

lineArray[1].anchor = Array(150, 200) lineArray[1].leftDirection = lineArray[1].anchor

lineArray[1].rightDirection = lineArray[1].anchor

var lineSubPathArray = new Array() lineSubPathArray[0] = new SubPathInfo() lineSubPathArray[0].operation = ShapeOperation.SHAPEXOR

lineSubPathArray[0].closed = false lineSubPathArray[0].entireSubPath = lineArray

//line#2 var lineArray2[0] = new Array() lineArray2[0].kind = PointKind.CORNERPOINT

lineArray2[0].anchor = Array(150, 200) lineArray2[0].leftDirection = lineArray2[0].anchor

lineArray2[0].rightDirection = lineArray2[0].anchor

lineArray2[1] = new PathPointInfo lineArray2[1].kind = PointKind.CORNERPOINT

lineArray2[1].anchor = Array(200, 100) lineArray2[1].leftDirection = lineArray2[1].anchor

lineArray2[1].rightDirection = lineArray2[1].anchor

lineSubPathArray[1] = new SubPathInfo() lineSubPathArray[1].operation = ShapeOperation.SHAPEXOR

lineSubPathArray[1].closed = false lineSubPathArray[1].entireSubPath = lineArray2

//ice cream curve

//it’s a curved line, so there are 3 points, not 2

//coordinates for the middle point (lineArray3[1]) are different.

//The left direction is positioned “above” the anchor on the screen.

//The right direction is positioned “below” the anchor

//You can change the coordinates for these points to see

//how the curve works...

var lineArray3[0] = new Array() lineArray3[0].kind = PointKind.CORNERPOINT

lineArray3[0].anchor = Array(200, 100) lineArray3[0].leftDirection = lineArray3[0].anchor

lineArray3[0].rightDirection = lineArray3[0].anchor

lineArray3[1] = new PathPointInfo lineArray3[1].kind = PointKind.CORNERPOINT

lineArray3[1].anchor = Array(150, 50) lineArray31].leftDirection = Array(100, 50) lineArray3[1].rightDirection = Array(200, 50) lineArray3[2] = new PathPointInfo lineArray3[2].kind = PointKind.CORNERPOINT

lineArray3[2].anchor = Array(100, 100) lineArray3[2].leftDirection = lineArray3[2].anchor

lineArray3[2].rightDirection = lineArray3[2].anchor

lineSubPathArray[1] = new SubPathInfo()

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 137 lineSubPathArray[1].operation = ShapeOperation.SHAPEXOR

lineSubPathArray[1].closed = false lineSubPathArray[1].entireSubPath = lineArray3

//create the path item var myPathItem = docRef.pathItems.add(“A Line”, lineSubPathArray);

// stroke it so we can see something myPathItem.strokePath(ToolType.BRUSH)

// Reset the application preferences preferences.rulerUnits = startRulerUnits; preferences.typeUnits = startTypeUnits; displayDialogs = startDisplayDialogs

Adobe Photoshop CS2

JavaScript Scripting Reference

Methods

Method index

(itemKey) add

(name,

entirePath) getByName

(name) removeAll

()

JavaScript Object Reference 138

PathItems

The collection of pathItem

objects in the document. See PathItem

for information on pathItem

objects.

Note: Because the

PathItems

class is a property of the Document

object, you use the object name, pathItems

, rather than the class name,

PathItems

, in your code. For example: var myPathItem = docRef.pathItems.add(“A Line”, lineSubPathArray)

The following sample uses the

PathItems

object incorrectly: var myPathItem = docRef.PathItems.add(“A Line”, lineSubPathArray)

Properties

Property length parent typename

Value Type number (long) object

(document) string

What it is

Read-only. The number of pathItem

objects in the pathItems

collection.

Read-only. The pathItems object's container.

Read-only. The class name of the referenced pathItems object.

Parameter Type number string

Array (

SubPathItem

objects)

Returns What it does

PathItem

Gets a pathItem

object from the pathItems collection.

PathItem

Creates a new pathItem object.

string

PathItem

Get the first element in the pathItems collection with the provided name.

Removes all pathItem

objects from the pathItems

collection.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 139

PathPoint

Information about an array of

PathPointInfo

objects.

Note: You do not use the

PathPoint

object to create points that make up a path. Rather, you use the

PathPoint

object to retrieve information about the points that describe path segments. To create path points, use the

PathPointInfo

objects. See PathPointInfo .

Properties

Property anchor kind leftDirection parent rightDirection typename

Value Type

Array(UnitValue)

PointKind

Array(UnitValue) object (

SubPathItem )

Array(UnitValue) string

What it is

Read-write. The point on the curve

( leftDirection

/ rightDirection

are points representing the control handle end points).

Read-write. The

PathPoint

object’s type.

Read-write. The x and y coordinates that define the left handle.

Read-only. The

PathPoint object's container.

Read-write. The x and y coordinates that define the right handle.

Read-only. The class name of the referenced

PathPoint

object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 140

PathPointInfo

A point on a path, expressed as an array of three coordinate arrays: the anchor point, left direction point, and right direction point. For paths that are straight segments (not curved), the coordinates of all three points are the same. For curved segements, the the coordinates are different. The difference between the anchor point and the left or right direction points determines the arc of the curve. You use the left direction point to bend the curve “outward” or make it convex; you use the right direction point to bend the curve “inward” or make it concave.

Properties

Property anchor

Value Type

Array kind leftDirection rightDirection typename

PointKind

Array

(UnitValue)

Array

(UnitValue) string

What it is

Read-write. The x and y coordinates of one end point of the path segment.

Read-write. The

PathPointInfo object’s kind.

Read-write. The location of the left direction point (’in’ position).

Read-write. The location of the right handle (’out’ position).

Read-only. The class name of the referenced PathPointInfo object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 141

PathPoints

A collection of

PathPoint

objects that comprises the

PathPoints

property of the

SubPathItem

object.

See SubPathItem for more information.

Properties

Property length parent typename

Value Type number (long) object (

SubPathItem )

string

What it is

Read-only. The number of elements in the

PathPoint s collection.

Read-only. The

PathPoints

object's container.

Read-only. The class name of the referenced

PathPoints object.

Method index

(itemKey)

Parameter type number

Returns

PathPoint

What it does

Gets an element from the

PathPoints collection.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 142

PDFOpenOptions

Options that can be specified when opening a document in generic Adobe PDF format.

Properties

Property antiAlias bitsPerChannel constrainProportions cropPage height mode name page resolution suppressWarnings typename usePageNumber width

Value Type boolean

UnitValue

OpenDocumentMode

What it is

Read-write. Indication of whether to use antialias.

BitsPerChannelType

Read-write. The number of bits per channel.

boolean

CropToType

Deprecated for Adobe Photoshop CS2.

Read-write. The method of cropping to use.

Deprecated for Adobe Photoshop CS2.

Read-write. The color model to use.

string number (long) number (double) boolean string boolean

UnitValue

Read-write. The name of the document.

Read-write. The page to which to open the document.

Read-write. The resolution of the document (in pixels per inch).

Read-write. Indication of whether to suppress warnings when opening the document.

Read-only. The class name of the referenced

PDFOpenOptions object.

Read-write. Indication of whether the value specified in the page

property will refer to an image number when usePageNumber = false

.

See page

.

Deprecated for Adobe Photoshop CS2.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 143

PDFSaveOptions

Options that can be specified when saving a document in Adobe PDF format.

Properties

Property alphaChannels annotations colorConversion convertToEightBit descripton destinationProfile downgradeColorProfile downSample downSampleSize downSampleSizeLimit embedColorProfile embedFonts embedThumbnail encoding interpolation

Value Type boolean boolean boolean boolean string string boolean

PDFResample

number (double) number (double) boolean boolean boolean

PDFStandard

boolean

What it is

Read-write. Indication of whether to save the alpha channels with the file.

Read-write. Indication of whether to save comments with the file.

Read-write. Indication of whether to convert the color profile to a destination profile.

Read-write. Indication of whether to convert a 16-bit image to 8-bit for better compatibility with other applications.

Read-write. Description of the save options to use.

Read-write. Description of the final RGB or

CMYK output device, such as a monitor or a press standard.

Deprecated for Adobe Photoshop CS2.

Read-write. The down sample method to use.

Read-write. The size to downsample images if they exceed the limit in pixels per inch.

Read-write. Limits downsampling or subsampling to images that exceed this value in pixels per inch.

Read-write. Indication of whether to embed the color profile in the document.

Deprecated for Adobe Photoshop CS2.

Read-write. Indication of whether to include a small preview image in Adobe PDF files.

Read-write. The encoding method to use

(default:

PDFEncoding.PDFZIP

).

Deprecated for Adobe Photoshop CS2.

JavaScript Scripting Reference

Property jpegQuality layers optimizeForWeb outputCondition outputConditionID

PDFCompatibility

PDFStandard preserveEditing presetFile profileInclusionPolicy registryName spotColors tileSize transparency typename

Adobe Photoshop CS2

Value Type number (long) boolean boolean string string

PDFCompatibility

PDFStandard

boolean string boolean string boolean nunber (long) boolean string

JavaScript Object Reference 144

What it is (Continued)

Read-write. The quality of the produced image (0 - 12), which is inversely proportionate to the compression amount.

Note: Valid only when encoding = PDFEncoding.JPEG

.

Read-write. Indication of whether to save the document’s layers.

Read-write. Indication of whether to improve performance of PDF files on Web servers.

Read-write. An optional comment field for inserting descriptions of the output condition. The text is stored in the PDF/X file.

Read-write. Indentifier for the output condition.

Read-write. The PDF version to make the document compatible with.

Read-write. The PDF standard to make the document compatible with.

Read-write. Indication of whether to reopen the PDF in Adobe Photoshop CS2 with native Photoshop data intact.

Read-write. The preset file to use for settings.

Note: This option overrides other settings.

Read-write. Indication of whether to show which profiles to include.

Read-write. URL where the output condition is registered.

Read-write. Indication of whether to save spot colors.

Read-write. Compression option.

Note: Valid only when encoding =

PDFEncoding.JPEG2000

.

Deprecated for Adobe Photoshop CS2.

Read-only. The class name of the referenced

PDFSaveOptions object.

JavaScript Scripting Reference

Property useOutlines vectorData view

Adobe Photoshop CS2

Value Type boolean boolean boolean

JavaScript Object Reference 145

What it is (Continued)

Deprecated for Adobe Photoshop CS2.

Deprecated for Adobe Photoshop CS2.

Read-write. Indication of whether to open the saved PDF in Adobe Acrobat.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 146

PhotoCDOpenOptions

Options to be specified when opening a Kodak Photo CD (PCD) files, including high-resolution files from

Pro Photo CD discs.

Properties

Property colorProfileName colorSpace orientation pixelSize resolution typename

Value Type string

PhotoCDColorSpace

Orientation

PhotoCDSize

number (double) string

What it is

Read-write. The profile to use when reading the image.

Read-write. The colorspace for the image.

Read-write. The image orientation.

Read-write. The image dimensions.

Read-write. The image resolution (in pixels per inch).

Read-only. The class name of the referenced photoCDOpenOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 147

PhotoshopSaveOptions

Options that can be specified when saving a document in PSD format.

Properties

Property alphaChannels annotations embedColorProfile layers spotColors typename

Value Type boolean boolean boolean boolean boolean string

What it is

Read-write. Indication of whether to save the alpha channels.

Read-write. Indication of whether to save the annotations.

Read-write. Indication of whether to embed the color profile in the document.

Read-write. Indication of whether to preserve the layers.

Read-write. Indication of whether to save the spot colors.

Read-only. The class name of the referenced photoshopSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 148

PICTFileSaveOptions

Options that can be specified when saving a document in PICT format.

Properties

Property alphaChannels compression embedColorProfile resolution typename

Value Type boolean

PICTCompression

boolean

PICTBitsPerPixels

string

What it is

Read-write. Indication of whether to save the alpha channels.

Read-write. (default: PICTCompression.NONE

)

Read-write. Indication of whether to embed the color profile in the document.

Read-write. The number of bits per pixel.

Read-only. The class name of the referenced

PICTFileSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 149

PICTResourceSaveOptions

Options that can be specified when saving a document as a PICT Resource file.

Properties

Property alphaChannels compression embedColorProfile name resolution resourceID typename

Value Type boolean

PICTCompression

What it is

Read-write. Indication of whether to save the alpha channels.

Read-write. The type of compression to use (default:

PICTCompression.NONE

).

boolean number (long)

Read-write. Indication of whether to embed the color profile in the document.

string

PICTBitsPerPixels

Read-write. The name of the PICT resource.

Read-write. The number of bits per pixel.

Read-write. The ID of the PICT resource (default:

128

).

string Read-only. The class name of the referenced

PICTResourceSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 150

PicturePackageOptions

Options that can be specified for a Picture Package.

Properties

Property content flatten font fontSize layout mode opacity resolution text

Value type

PicturePackageTextType

boolean

GalleryFontType

number (long) string

NewDocumentMode

number (long) number (double) string

What it is

Read-write. The content information (default:

PicturePackageTextType.NONE

).

Read-write. Indicates whether all layers in the final document are flattened (default: true

).

Read-write. The font used for security text

(default:

GalleryFontType.ARIAL

).

Read-write. The font size used for security text (default:

12

).

Read-write. The layout to use to generate the picture package (default:

“(2)5x7”

).

Read-write. Read-write. The color profile to use as the document mode

(default:

NewDocumentMode.RGB

).

Read-write. The web page security opacity as a percent (default: 100 ).

Read-write. The resolution of the document in pixels per inch (default:

72.0

).

Read-write. The picture package custom text.

textColor

RGBColor

textPosition

GallerySecurityTextPositionType

textRotate typename

GallerySecurityTextRotateType

string

Note: Valid only when content =

PicturePackageType.USER

. See

content .

Read-write. The color to use for security text.

Read-write. The security text position

(default:

GallerySecurityTextPositionType.

CENTERED

).

Read-write. The orientation to use for security text (default:

GallerySecurityTextRotateType.ZERO

).

Read-only. The class name of the referenced

PicturePackageOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 151

PixarSaveOptions

Options that can be specified when saving a document in Pixar format.

Properties

Property alphaChannels typename

Value Type boolean string

What it is

Read-write. Indication of whether to save the alpha channels.

Read-only. The class name of the referenced

PixarSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 152

PNGSaveOptions

Options that can be specified when saving a document in PNG format.

Properties

Property interlaced typename

Value Type boolean string

What it is

Read-write. Indicates whether the should rows be interlaced (default: false

).

Read-only. The class name of the referenced

PNGSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 153

Preferences

Options to define for the preferences

property of the app

object. See preferencesFolder (in the

Properties table for the app

object).

Note: Because the

Preferences

class is a property of the Document

object, you use the object name, preferences

, rather than the class name,

Preferences

, in your code. For example: app.preferences.rulerUnits = Units.PIXELS

app.preferences.typeUnits = TypeUnits.PIXELS

The following code incorrectly uses an upper case P: app.Preferences.rulerUnits = Units.PIXELS

app.Preferences.typeUnits = TypeUnits.PIXELS

Note: Defining the preferences

properties is basically equivalent to selecting Edit > Preferences

(Windows) or Photoshop > Preferences in the Adobe Photoshop CS2 application. For explanations of individual settings, please refer to Adobe Photoshop CS2 Help.

Properties

Property additionalPluginFolder

Value Type file appendExtension askBeforeSavingLayeredTIFF autoUpdateOpenDocuments beepWhenDone colorChannelsInColor colorPicker columnGutter columnWidth

SaveBehavior

boolean boolean boolean boolean

ColorPicker

number (double) number (double)

What it is

Read-write. The path to an additional plug-in folder.

Note: Valid only when useAdditionalPluginFolder = true

. See

useAdditionalPluginFolder .

Read-write. Save files with extensions on

Windows.

Read-write. Indication of whether to ask the user to verify layer preservation options when saving a file in TIFF format.

Read-write. Indication of whether to automatically update open documents.

Read-write. Indication of whether to beep when a process finishes.

Read-write. Indication of whether to display component channels in the

Channels palette in color.

Read-write.

Read-write. The width of the column gutters (in points). (0.1 - 600.0).

Read-write. Column width (in points) (0.1

- 600.0).

JavaScript Scripting Reference

Property createFirstSnapshot dynamicColorSliders editLogItems exportClipboard fontPreviewSize fullSizePreview gamutWarningOpacity gridSize gridStyle gridSubDivisions guideStyle iconPreview imageCacheForHistograms imageCacheLevels imagePreviews interpolation

Adobe Photoshop CS2

JavaScript Object Reference 154

Value Type boolean boolean

EditLogItemsType

boolean

FontPreviewType

boolean number (double)

GridSize

GridLineStyle

number (long)

GuideLineStyle

boolean boolean number (long)

SaveBehavior

ResampleMethod

What it is (Continued)

Read-write. Indication of whether to automatically make the first snapshot when a new document is created.

Read-write. Indication of whether dynamic color sliders appear in the Color palette.

Read-write. The options for editing history log items.

Note: Valid only when useHistoryLog

= true

. See useHistoryLog .

Read-write. Indication of whether to retain Adobe Photoshop CS2 contents on the clipboard after you exit the application.

Read-write. Indication of whether to show font previews in the type tool font menus.

Read-write. (Mac only.) Indication of whether to show image preview as a full size image or thumbnail.

Read-write. (0 - 100 as percent).

Read-write. The size to use for squares in the grid.

Read-write. The formatting style for non-printing grid lines.

Read-write. (1 - 100)

Read-write. The formatting style for non-printing guide lines.

Read-write. (Mac only.)

Read-write. Indication of whether to use the sampled data cache for histograms in the Level dialog (faster but not as accurate).

Read-write. The number of images to hold in the cache (1 - 8).

Read-write. The behavior mode to use when saving files.

Read-write. The method to use to assign color values to any new pixels created when an image is resampled or resized.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 155

Property keyboardZoomResizesWindows macOSThumbnail maximizeCompatibility maxRAMuse nonLinearHistory numberofHistoryStates otherCursors paintingCursors parent pixelDoubling pointSize recentFileListLength rulerUnits saveLogItems saveLogItemsFile savePaletteLocations

Value Type boolean boolean

QueryStateType

number (long) boolean

What it is (Continued)

Read-write. Indication of whether to automatically resize the window when zooming in or out using keyboard shortcuts.

Read-write. (Mac only.) Indication of whether to create a thumbnail when saving the image.

Read-write. The behavior to use to check whether to maximize compatibility when opening Adobe Photoshop CS2 (PSD) files .

Read-write. The maximum percentage of available RAM used by Adobe

Photoshop CS2 (5 - 100).

Read-write. Indication of whether to allow non-linear history.

number (long) Read-write. The number of history states to preserve (1 - 100).

OtherPaintingCursors

Read-write. The type of pointer to use.

PaintingCursors

Read-write. The type of pointer to use.

object ( Application

) Read-write. The preferences

object's container.

boolean

PointType

Read-write. Indication of whether to halve the resolution or (double the size of pixels) to make previews display more quickly.

Read-write. The point/pica size.

number (long)

Units

Read-write. The number of items in the recent file list (0 - 30).

Read-write. The unit the scripting system will use when receiving and returning values.

SaveLogItemsType

file boolean

Read-write. The options for saving the history items.

Read-write. The path to the history log file.

Read-write. Indication of whether to make new palette locations the default location.

Adobe Photoshop CS2

JavaScript Scripting Reference

Property showAsianTextOptions

Value Type boolean showEnglishFontNames showSliceNumber showToolTips smartQuotes typename typeUnits boolean boolean boolean boolean string

TypeUnits

useAdditionalPluginFolder boolean useDiffusionDither useHistoryLog useLowerCaseExtension useShiftKeyForToolSwitch boolean boolean boolean useVideoAlpha boolean windowsThumbnail boolean boolean

JavaScript Object Reference 156

What it is (Continued)

Read-write. Indication of whether to display Asian text options in the

Paragraph palette.

Read-write. Indication of whether to list

Asian font names in English.

Read-write. Indication of whether to display slice numbers in the document window when using the Slice tool.

Read-write. Indication of whether to show pop up definitions on mouse over.

Read-write. Indication of whether to use curly or straight quote marks.

Read-only. The class name of the referenced preferences object.

Read-write. The unit type-size that the numeric inputs are assumed to represent.

Read-write. Indication of whether to use an additional folder for compatible plug-ins stored with a different application.

Read-write. Indication of whether to use diffusion dithering to minimize distinctive patterning caused by pattern dithering.

Read-write. Indication of whether to create a log file for history states.

Read-write. Indicates whether the file extension should be lowercase.

Read-write. Indication of whether to enable cycling through a set of hidden tools.

Read-write. Indication of whether to enable Adobe Photoshop CS2 to send transparency information to your computer’s video board. (Requires hardware support.)

Read-write. (Requires hardware support.)

Indication of whether to create a thumbnail when saving the image on

Windows.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 157

PresentationOptions

Options that can be specified for Adobe PDF presentations.

Properties

Property autoAdvance includeFilename interpolation loop magnification pDFFileOptions presentation transition typename

Value Type boolean boolean boolean boolean

What it is

Read-write. Indication of whether to auto advance images when when viewing the presentation

(default: true ).

Note: Valid only when presentation = true

.

See

presentation .

Read-write. Indication of whether to include the file name for the image (default: false ).

Read-write. Indication of whether to use image interpolation (default: false

).

Read-write. Indication of whether to begin the presentation again after the last page (default: false

).

Note: Valid only when autoAdvance = true

. See

autoAdvance

.

MagnificationType

Read-write. The magnification type to use when viewing the image.

PDFSaveOptions

boolean

TransitionType

Read-write. Options to use when creating the PDF file.

Read-write. Indication of whether the output will be a presentation (default: false

); when false

, the output is a Multi-Page document.

Read-write. The transition from one image to the next (default: TransitionType.NONE

). string

Note: Valid only when autoAdvance = true

. See

autoAdvance

.

Read-only. The class name of the referenced

PresentationOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 158

RawFormatOpenOptions

Options that can be specified when opening a document in RAW format.

Properties

Property bitsPerChannel

Value Type number (long) byteOrder channelNumber headerSize height interleaveChannels retainHeader typename width

ByteOrder

number (long) number (long) number (long) boolean boolean string number (long)

What it is

Read-write. The number of bits for each channel.

Note: The only valid values are bitsPerChannel =

BitsPerChannelType.EIGHT

or bitsPerChannel =

BitsPerChannelType.SIXTEEN

.

Read-write. The order in which bytes will be read.

Note: Valid only when bitsPerChannel =

BitsPerChannelType.SIXTEEN

. See

bitsPerChannel

.

Read-write. The number of channels in the image

(1 - 56).

Note: The value of channelNumber

cannot exceed the number of channels in the image. When bitsPerChannel =

BitsPerChannelType.SIXTEEN

, only the following values are valid: 1, 3, or 4. See

bitsPerChannel

.

Read-write. The number of bytes of information that will appear in the file before actual image information begins; that is, the number of zeroes inserted at the beginning of the file as placeholders (0 - 1919999).

Read-write. The height of the image (in pixels).

Read-write. Indication of whether to store color values sequentially.

Read-write. Indication of whether to retain the header when saving.

Note: Valid only when

headerSize is 1 or greater.

Read-only. The class name of the referenced

RawFormatOpenOptions object.

Read-write. The image width in pixels.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 159

RawSaveOptions

Options that can be specified when saving a document in RAW format.

Properties

Property alphaChannels spotColors typename

Value Type boolean boolean string

What it is

Read-write. Indicates whether alpha channels should be saved.

Read-write. Indicates whether the spot colors should be saved.

Read-only. The class name of the referenced

RawSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference

RGBColor

The definition of a color in RGB color mode.

Properties

Property blue

Value Type number (double) green hexValue red typename number (double) string number (double) string

JavaScript Object Reference 160

What it is

Read-write. The blue color value (

0.0 - 255.0; default: 255.0).

Read-write. The green color value

(0.0 - 255.0; default: 255.0).

Read-write. The hex representation of the color.

Read-write. The red color value

(0.0 - 255.0; default: 255.0).

Read-only. The class name of the referenced

RGBColor

object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 161

Selection

The selected area of a document or layer.

Note: Because the

Selection

class is a property of the Document

object, you use the object name, selection

, rather than the class name,

Selection

, in your code, as in the following example: checkersDoc.selection.fill(app.foregroundColor)

Properties

Property bounds parent typename

Value Type array of UnitValues object (

Document

) string

What it is

Read-only. The bounding rectangle of the entire selection.

Read-only. The object's container.

Read-only. The class name of the referenced selection object.

Methods

Method clear

() contract

(by) copy

([merge]) cut

() deselect

() expand

(by) feather

(by)

Parameter Type

UnitValue boolean

UnitValue

UnitValue

Returns What it does

Clears the selection and does not copy it to the clipboard.

Contracts the selection by the specified amount.

Copies the selection to the clipboard. When the optional argument is used and set to true

, a merged copy is performed (all visible layers in the selection are copied).

Clears the current selection and copies it to the clipboard.

Deselects the current selection.

Expands the selection by the specified amount.

Feathers the edges of the selection by the specified amount.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 162

Method Parameter Type fill

(filltype

[, mode]

[, opacity]

[, preserveTransparency])

Object (

SolidColor ,

ArtLayer ,

HistoryState );

or String

ColorBlendMode

number (long) boolean

Returns What it does (Continued)

Fills the selection ( opacity

: 1 -

100 as percent).

grow

(tolerance,

antiAlias) invert

() number (long) boolean

Grows the selection to include all adjacent pixels falling within the specified tolerance range.

Inverts the selection

(deselects the selection and selects the rest of the layer or document).

load

(from

[, combination]

[, inverting]) makeWorkPath

([tolerance]) resize

([horizontal]

[, vertical]

[, anchor]) resizeBoundary

([horizontal]

[, vertical]

[, anchor])

Channel

SelectionType

boolean number (double) number (double) number (double)

AnchorPosition

number (double) number (double)

AnchorPosition

Note: To flip the selection

shape, see rotate .

Loads the selection from the specified channel.

Makes this selection item the work path for this document.

Resizes the selected area to the specified dimensions and anchor position.

rotate

(angle

[, anchor]) rotateBoundary

(angle

[, anchor]) select

(region

[, type]

[, feather]

[, antiAlias]) number (double)

AnchorPosition

number (double)

AnchorPosition

Array (points:

Array (Array (x,y),...)

SelectionType

number (double) boolean

Changes the size of the selection to the specified dimensions around the specified anchor.

Rotates the selection by the specified amount around the specified anchor point.

Rotates the boundary of the selection around the specified anchor.

Selects the specified region. selectAll

()

Selects the entire layer.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 163

Method selectBorder

(width) similar

(tolerance,

antiAlias) smooth

(radius)

Parameter Type

UnitValue number (long) boolean number (long)

Returns What it does (Continued)

Selects the selection border only (in the specified width); subsequent actions do not affect the selected area within the borders.

Grows the selection to include pixels throughout the image falling within the tolerance range.

Cleans up stray pixels left inside or outside a color-based selection (within the radius specified in pixels).

Saves the selection as a channel.

Strokes the selection border

( opacity

: 1 - 100 as percent).

store

(into

[, combination])

Channel

SelectionType

stroke

(strokeColor,

width

[, location]

[, mode]

[, opacity]

[, preserveTransparency])

Object (color) number (long)

StrokeLocation

ColorBlendMode

number (long) boolean translate

([deltaX]

[, deltaY]) translateBoundary

([deltaX]

[, deltaY])

UnitValue

UnitValue

UnitValue

UnitValue

Moves the entire selection relative to its current position.

Moves the selection relative to its current position.

Sample Script

The following script creates a checkerboard using the following steps:

Create an 800 x 800 pixel document.

Divide the entire document into 100 x 100 pixel squares.

Select every other square in the first row, then shift the selection criteria to select the alternate squares in the following row. Repeat until every other square in the document is selected.

Fill the selected squares with the foreground color from the palette.

Invert the selection and fill the newly selected squares with the background color from the palette.

Deselect the squares to remove the selection outlines (the “marching ants").

Selection.jsx

// Save the current preferences var startRulerUnits = app.preferences.rulerUnits

var startTypeUnits = app.preferences.typeUnits

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 164 var startDisplayDialogs = app.displayDialogs

// Set Adobe Photoshop CS2 to use pixels and display no dialogs app.preferences.rulerUnits = Units.PIXELS

app.preferences.typeUnits = TypeUnits.PIXELS

app.displayDialogs = DialogModes.NO

//Close all the open documents while (app.documents.length) { app.activeDocument.close()

}

//Create variables for the 800 pixel board divided in even 100 x 100 squares var docSize = 800 var cells = 8 var cellSize = docSize / cells

// create a new document var checkersDoc = app.documents.add(docSize, docSize, 72, "Checkers")

// Create a variable to use for selecting the checker board

// That allows me to shift the selection one square to the right

//on every other row, and then shift back for the rows in between.

var shiftIt = true

// loop through vertically to create the first row for (var v = 0; v < docSize; v += cellSize) {

// Switch the shift for a new row shiftIt = !shiftIt

// loop through horizontally for (var h = 0; h < docSize; h += (cellSize * 2)) {

// push over the cellSize to start with only if (shiftIt && h == 0) { h += cellSize

}

// Select a square selRegion = Array(Array(h, v),

Array(h + cellSize, v),

Array(h + cellSize, v + cellSize),

Array(h, v + cellSize),

Array(h, v))

// In the first ineration of the loop, start the selection

//In subsequent iterations, use the EXTEND constant value

//of the select() method to add to the selection (in the loop’s else clause) if (h == 0 && v == 0) { checkersDoc.selection.select(selRegion)

} else { checkersDoc.selection.select(selRegion, SelectionType.EXTEND)

}

// turn this off for faster execution

// turn this on for debugging

WaitForRedraw()

}

}

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 165

// Fill the current selection with the foreground color checkersDoc.selection.fill(app.foregroundColor)

//Invert the selection checkersDoc.selection.invert()

// Fill the new selection with the background color checkersDoc.selection.fill(app.backgroundColor)

// Clear the selection to get rid of the non-printing borders checkersDoc.selection.deselect()

// Reset the application preferences app.preferences.rulerUnits = startRulerUnits app.preferences.typeUnits = startTypeUnits app.displayDialogs = startDisplayDialogs

// A helper function for debugging

// It also helps the user see what is going on

// if you turn it off for this example you

// get a flashing cursor for a number (long) time function WaitForRedraw()

{ var eventWait = charIDToTypeID(‘Wait’) var enumRedrawComplete = charIDToTypeID(‘RdCm’) var typeState = charIDToTypeID(‘Stte’) var keyState = charIDToTypeID(‘Stte’) var desc = new ActionDescriptor()

desc.putEnumerated(keyState, typeState, enumRedrawComplete)

} executeAction(eventWait, desc, DialogModes.NO)

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 166

SGIRGBSaveOptions

Options that can be specified when saving a document in SGIRGB format.

Note: The SGIRGB format is not installed automatically with Adobe Photoshop CS2.

Properties

Property alphaChannels spotColors typename

Value Type boolean boolean string

What it is

Read-write. Indication of whether to save the alpha channels.

Read-write. Indication of whether to save the spot colors.

Read-only. The class name of the referenced SGIRGBSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference

Methods

Method isEqual

(color)

Parameter Type Returns boolean

SolidColor

JavaScript Object Reference 167

SolidColor

A color definition used in the document.

Properties

Property cmyk gray hsb lab model nearestWebColor rgb typename

Value Type

CMYKColor

GrayColor

HSBColor

LabColor

ColorModel

RGBColor

RGBColor

string

What it is

Read-write. The CMYK color mode.

Read-write. The Grayscale color mode.

Read-write. The HSB color mode.

Read-write. The LAB color mode.

Read-write. The color model.

Read-only. The nearest web color to the current color.

Read-write. The RGB color mode.

Read-only. The class name of the referenced

SolidColor object.

What it does

Indication of whether the SolidColor object is visually equal to the specified color.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 168

SubPathInfo

An array of

PathPointInfo

objects that describes a straight or curved segment of a path.

Properties

Property closed entireSubPath operation typename

Value Type boolean

What it is

Read-write. Indication of whether the path describes an enclosed area.

Array ( PathPoint

objects)

Read-write.

ShapeOperation

string

Read-write. The sub path’s operation on other sub paths.

Read-only. The class name of the referenced

SubPathInfo object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 169

SubPathItem

Information about a path.

Note: You do not use the

SubPathItem

object to create a path. Rather, you use the

SubPathInfo

object to retrieve information about a path. (Note that all of the

SubPathItem

object’s properties are

Read-only.) To create path segments, see

SubPathInfo .

Properties

Property closed operation parent pathPoints typename

Value Type boolean

ShapeOperation

object

( PathItem )

PathPoints

What it is

Read-only. Indicates whether the path is closed.

Read-only. The sub path operation on other sub paths.

Read-only. The object's container.

string

Read-only. The

PathPoints

collection.

Read-only. The class name of the referenced SubPathItem object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 170

SubPathItems

A collection of

SubPathItem

objects. See SubPathItem

.

Properties

Property length parent typename

Value Type number (long) object

(

PathItem

) string

What it is

Read-only. The number of elements in the

SubPathItems collection.

Read-only. The SubPathItems object's container.

Read-only. The class name of the referenced SubPathItems object.

Methods

Method index

(itemKey)

Parameter type Returns number

SubPathItem

What it does

Gets an element from the

SubPathItems collection.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 171

TargaSaveOptions

Options that can be set when saving a document in TGA (Targa) format.

Properties

Property alphaChannels resolution rleCompression typename

Value Type boolean

What it is

Read-write. Indication of whether to save the alpha channels.

TargaBitsPerPixels

Read-write. The number of bits per pixel (default:

TargaBitsPerPixels.TWENTYFOUR

).

boolean Read-write. Indicates whether RLE compression should be used (default: true

).

string Read-only. The class name of the referenced

TargaSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 172

TextFont

Details about a font in the

TextFonts

collection. See TextFonts for more information on the

TextFonts collection.

Properties

Property family name parent postScriptName style typename

Value Type string

What it is

Read-only. The font family.

string Read-only. The name of the font.

object

( Application

)

Read-only. The object's container.

string Read-only. The PostScript name of the font.

string string

Read-only. The font style.

Read-only. The class name of the referenced textFont object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 173

TextFonts

The collection of fonts available on your computer.

Note: The

TextFonts

class corresponds to the fonts

property of the

TextFonts

object. In a script, you use the object name fonts

, rather than the class name

TextFonts

, to refer to a

TextFonts

object.

The following example uses the length property to determine, and then display, the number of

TextFonts installed on the machine.

● Correct:

● alert(app.fonts.length)

Incorrect: alert(app.TextFonts.length)

See

Application

, specifically the fonts

property, for more information.

Properties

Property length parent typename

Value Type number (long) object

( Application )

string

What it is

Read-only. The number of elements in the

TextFonts collection.

Read-only. The object's container.

Read-only. The class name of the referenced TextFonts object.

Methods

Method index

(itemKey) getByName

(name)

Parameter Type Returns

TextFont

number

TextFont

string

What it does

Gets an element from the

TextFonts collection.

Gets the first element in the TextFonts collection with the provided name.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 174

TextItem

The text in an artLayer

object whose kind

property is

LayerKind.TEXT

. See

ArtLayer , specifically the

kind

property, for more information.

Note: Because the

TextItem

class is a property of the

ArtLayer

class, you use the object name, textItem

, rather than the class name,

TextItem

, in your code. For example: myLayers[i].textItem.contents = "Layer in " + textArray[i] + " Set Inside "

Properties

Property alternateLigatures antiAliasMethod autoKerning autoLeadingAmount baselineShift capitalization color contents desiredGlyphScaling

Value Type boolean

What it is

Read-write. Indication of whether to use alternate ligatures.

AntiAlias

AutoKernType

Note: Alternate ligatures are the same as

Discretionary Ligatures. Please refer to Adobe

Photoshop CS2 Help for more information.

Read-write. The method of anti aliasing to use.

Read-write. The auto kerning option to use.

number (double) Read-write. The percentage to use for auto (default) leading (0.01 - 5000.00 in points).

UnitValue

Note: Valid only when useAutoLeading = true

.

See

useAutoLeading .

Read-write. The unit value to use in the baseline offset of text.

TextCase

SolidColor

Read-write. The text case.

Read-write. The text color.

string Read-write. The actual text in the layer.

number (double) Read-write. The desired amount (percentage) to scale the horizontal size of the text letters (50 - 200; at 100, the width of characters is not scaled).

Note: Valid only when justification =

Justification.CENTERJUSTIFIED

; justification =

Justification.FULLYJUSTIFIED

; justification =

Justification.LEFTJUSTIFIED

; or justification =

Justification.RIGHTJUSTIFIED

. See

justification . The following values are also

required: minimumGlyphScaling and

maximumGlyphScaling .

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 175

Property direction fauxBold

Value Type

Direction

boolean

What it is (Continued) desiredLetterScaling

Note: ‘Letter Scaling’ is basically equivalent to

‘Letter Spacing’ in the

Adobe Photoshop CS2 application Justification dialog (Select

Justification on the

Paragraphs palette menu).

number (double) Read-write. The amount of space between letters

(100 - 500; at 0, no space is added between letters).

Note: Valid only when justification =

Justification.CENTERJUSTIFIED

; justification =

Justification.FULLYJUSTIFIED

; justification =

Justification.LEFTJUSTIFIED

; or justification =

Justification.RIGHTJUSTIFIED

. See

justification . The following values are also

required: minimumLatterScaling

and

maximumLetterScaling

. desiredWordScaling

Note: ‘Word Scaling’ is basically equivalent to

‘Word Spacing’ in the

Adobe Photoshop CS2 application Justification dialog (Select

Justification on the

Paragraphs palette menu).

number (double) Read-write. The amount (percentage) of space between words (0 -1000; at 100, no additional space is added between words).

Note: Valid only when justification =

Justification.CENTERJUSTIFIED

; justification =

Justification.FULLYJUSTIFIED

; justification =

Justification.LEFTJUSTIFIED

; or justification =

Justification.RIGHTJUSTIFIED

. See

justification . The following values are also

required: minimumWordScaling and

maximumWordScaling .

Read-write. The text orientation.

Read-write. Indication of whether to use faux bold

(default: false

).

fauxItalic firstLineIndent font boolean

UnitValue string

Note: Using fauxBold.true

is equivalent to selecting text and clicking the Faux Bold button in the Character palette.

Read-write. Indication of whether to use faux italic

(default: false

).

Note: Using fauxItalic.true

is equivalent to selecting text and clicking the Faux Italic button in the Character palette.

Read-write. The amount (unit value) to indent the first line of paragraphs (-1296 - 1296).

Read-write. The text face of the character.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 176

Property hangingPunctuation height horizontalScale hyphenateAfterFirst hyphenateBeforeLast hyphenateCapitalWords hyphenation hyphenationZone hyphenLimit justification kind language leading leftIndent ligatures

Value Type boolean

UnitValue number (long) number (long) number (long) boolean hyphenateWordsLongerThan number (long) boolean

UnitValue number (long)

Justification

TextType

Language

UnitValue

UnitValue boolean

What it is (Continued)

Read-write. Indication of whether to use roman

Hanging Punctuation.

Read-write. The height of the bounding box (unit value) for paragraph text.

Note: Valid only when kind = TextType.PARAGRAPHTEXT

. See

kind .

Read-write. Character scaling (horizontal) in proportion to vertical scale (0 - 1000 in percent). See

verticalScale

.

Read-write. The number of letters after which hyphenation in word wrap is allowed (1 - 15).

Read-write. The number of letters before which hyphenation in word wrap is allowed (1 - 15).

Read-write. Indication of whether to allow hyphenation in word wrap of capitalized words.

Read-write. The minimum number of letters a word must have in order for hyphenation in word wrap to be allowed (2 - 25).

Read-write. Indication of whether to use hyphenation in word wrap.

Read-write. The distance at the end of a line that will cause a word to break in unjustified type (0 - 720 pica).

Read-write. The maximum number of consecutive lines that can end with a hyphenated word.

Read-write. The paragraph justification.

Read-write. The text-wrap type.

Read-write. The language to use.

Read-write. The leading amount (unit value).

Read-write. The amount (unit value) of space to indent text from the left (-1296 - 1296).

Read-write. Indication of whether to use ligatures.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 177

Property maximumGlyphScaling

Value Type What it is (Continued) number (double) Read-write. The maximum amount (percentage) to scale the horizontal size of the text letters (50 - 200; at

100, the width of characters is not scaled).

Note: Valid only when justification =

Justification.CENTERJUSTIFIED

; justification =

Justification.FULLYJUSTIFIED

; justification =

Justification.LEFTJUSTIFIED

; or justification =

Justification.RIGHTJUSTIFIED

. See

justification . The following values are also

required: minimumGlyphScaling and

desiredGlyphScaling .

maximumLetterScaling

Note: ‘Letter Scaling’ is basically equivalent to

‘Letter Spacing’ in the

Adobe Photoshop CS2 application Justification dialog (Select

Justification on the

Paragraphs palette menu).

number (double) Read-write. The maximum amount of space to allow between letters (100 - 500; at 0, no space is added between letters).

Note: Valid only when justification =

Justification.CENTERJUSTIFIED

; justification =

Justification.FULLYJUSTIFIED

; justification =

Justification.LEFTJUSTIFIED

; or justification =

Justification.RIGHTJUSTIFIED

. See

justification . The following values are also

required: minimumLatterScaling

and

desiredLetterScaling

.

maximumWordScaling

Note: ‘Word Scaling’ is basically equivalent to

‘Word Spacing’ in the

Adobe Photoshop CS2 application Justification dialog (Select

Justification on the

Paragraphs palette menu).

number (double) Read-write. The maximum amount (percentage) of space to allow between words (0 -1000; at 100, no additional space is added between words).

Note: Valid only when justification =

Justification.CENTERJUSTIFIED

; justification =

Justification.FULLYJUSTIFIED

; justification =

Justification.LEFTJUSTIFIED

; or justification =

Justification.RIGHTJUSTIFIED

. See

justification . The following values are also

required: minimumWordScaling and

desiredWordScaling .

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 178

Property minimumGlyphScaling

Value Type What it is (Continued) number (double) Read-write. The minimum amount (percentage) to scale the horizontal size of the text letters (50 - 200; at

100, the width of characters is not scaled).

Note: Valid only when justification =

Justification.CENTERJUSTIFIED

; justification =

Justification.FULLYJUSTIFIED

; justification =

Justification.LEFTJUSTIFIED

; or justification =

Justification.RIGHTJUSTIFIED

. See

justification . The following values are also

required: minimumGlyphScaling and

desiredGlyphScaling .

minimumLatterScaling

Note: ‘Letter Scaling’ is basically equivalent to

‘Letter Spacing’ in the

Adobe Photoshop CS2 application Justification dialog (Select

Justification on the

Paragraphs palette menu).

number (double) Read-write. The minimum amount (percentage) of space between letters (100 - 500; at 0, no space is removed between letters).

Note: Valid only when justification =

Justification.CENTERJUSTIFIED

; justification =

Justification.FULLYJUSTIFIED

; justification =

Justification.LEFTJUSTIFIED

; or justification =

Justification.RIGHTJUSTIFIED

. See

justification . The following values are also

required: maximumLetterScaling

and

desiredLetterScaling

.

minimumWordScaling

Note: ‘Word Scaling’ is basically equivalent to

‘Word Spacing’ in the

Adobe Photoshop CS2 application Justification dialog (Select

Justification on the

Paragraphs palette menu).

number (double) Read-write. The minimum amount (percentage) of space between words (0 -1000; at 100, no space is removed between words).

Note: Valid only when justification =

Justification.CENTERJUSTIFIED

; justification =

Justification.FULLYJUSTIFIED

; justification =

Justification.LEFTJUSTIFIED

; or justification =

Justification.RIGHTJUSTIFIED

. See

justification . The following values are also

required: maximumWordScaling

and

desiredWordScaling .

JavaScript Scripting Reference

Property noBreak oldStyle parent position rightIndent size spaceAfter spaceBefore strikeThru textComposer tracking typename underline

Adobe Photoshop CS2

JavaScript Object Reference 179

Value Type boolean

What it is (Continued)

Read-write. Indication of whether to allow words to break at the end of a line. boolean

Tip: When enacted on large amounts of consecutive characters, noBreak = true

can prevent word wrap and thus may prevent some text from appearing on the screen.

Read-write. Indication of whether to use old style type.

Read-write. The textItem

object's container.

object

(

ArtLayer

)

Array

(UnitValue) string

UnderlineType

Read-write. The position of origin for the text. The array must contain two values (unit value).

UnitValue

Tip: Setting the position

property is basically equivalent to clicking the text tool at a point in the document to create the point of origin for text.

Read-write. The amount of space (unit value) to indent text from the right (-1296 - 1296).

number (double) Read-write. The font size in points.

UnitValue

UnitValue

Read-write. The amount of space (unit value) to use after each paragraph (-1296 - 1296).

Read-write. The amount of space (unit value) to use before each paragraph (-1296 - 1296).

StrikeThruType

TextComposer

Read-write. The text strike through option to use.

Read-write. The composition method to use to evaluate line breaks and optimize the specified hyphenation and justification options.

Note: Valid only when kind = TextType.PARAGRAPHTEXT

. See

kind .

number (double) Read-write. The amount of uniform spacing between multiple characters (-1000 - 10000).

Note: Tracking units are 1/1000 of an em space. The width of an em space is relative to the current type size. In a 1-point font, 1 em equals 1 point; in a 10-point font, 1 em equals 10 points. So, for example, 100 units in a 10-point font are equivalent to 1 point.

Read-only. The class name of the referenced textItem

object.

Read-write. The text underlining options.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 180

Property useAutoLeading

Value Type boolean

What it is (Continued)

Read-write. Indication of whether to use a font's built-in leading information.

verticalScale warpBend warpDirection number (long) Read-write. Character scaling (vertical) in proportion to horizontal scale (0 - 1000 in percent). See

horizontalScale

.

number (double) Read-write. The warp bend percentage (-100 - 100).

Direction

Read-write. The warp direction. warpHorizontalDistortion number (double) Read-write. The horizontal distortion (as percentage) of the warp (-100 - 100).

warpStyle warpVerticalDistortion width

WarpStyle

Read-write. The style of warp to use. number (double) Read-write. The vertical distortion (as percentage) of the warp (-100 - 100).

UnitValue Read-write. The width of the bounding box (unit value) for paragraph text.

Note: Valid only when kind = TextType.PARAGRAPHTEXT

.

See

kind

.

Methods

Method convertToShape

() createPath

()

Parameter Type Returns What it does

Converts the text item and its containing layer to a fill layer with the text changed to a clipping path.

Creates a clipping path from the outlines of the actual text items (such as letters or words).

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 181

TiffSaveOptions

Options that can be specified when saving a document in TIFF format.

Properties

Property alphaChannels annotations byteOrder embedColorProfile imageCompression interleaveChannels jpegQuality layerCompression layers saveImagePyramid spotColors transparency typename

Value Type boolean boolean

ByteOrder

boolean

TIFFEncoding

boolean number (long)

LayerCompression

boolean boolean boolean boolean string

What it is

Read-write. Indication of whether to save the alpha channels.

Read-write. Indication of whether to save the annotations.

Read-write. The order in which the document’s bytes will be read. (The default is

ByteOrder.MACOS

when running on MacOS and

ByteOrder.IBM

when running on a PC.)

Read-write. Indication of whether to embed the color profile in the document.

Read-write. The compression type (default:

TIFFEncoding.NONE

).

Read-write. Indication of whether the channels in the image will be interleaved.

Read-write. The quality of the produced image

(0 - 12), which is inversely proportionate to the amount of JPEG compression.

Note: Valid only when imageCompression =

TIFFEncoding.JPEG

.

Read-write. The method of compression to use when saving layers (as opposed to saving composite data).

Note: Valid only when layers = true . See

layers

Read-write. Indication of whether to save the layers.

Read-write. Indication of whether to preserve multi-resolution information (default: false

).

Read-write. Indication of whether to save the spot colors.

Read-write. Indication of whether to save the transparency as an additional alpha channel when the file is opened in another application.

Read-only. The class name of the referenced tiffSaveOptions object.

Adobe Photoshop CS2

JavaScript Scripting Reference JavaScript Object Reference 182

xmpMetadata

Camera raw image file settings stored in an XMP file in the same folder as the raw file with the same base name and an XMP extension.

Properties

Property parent rawData typename

Value Type object

( Document )

string string

What it is

Read-only. The object's container.

Read-only. The raw XML form of file information.

Read-only. The class name of the referenced xmpMetadata object.

3

Action Manager

Adobe Photoshop CS2 actions allow you to save time by automating repetitive tasks. You create and run actions in the application interface using the Actions palette.

You can also manage actions in scripts using a utility called the Action Manager. The Action Manager allows you to write scripts that target Adobe Photoshop CS2 functionality that is not otherwise accessible in the scripting interface, such as third party plug-ins and filters. The only requirement for using the Action

Manager is that the task that you want to access from the Action Manager is recordable.

This chapter describes how to use the Action Manager and the scripting interface objects it includes.

The ScriptListener Plug-In

Before you use the Action Manager, you must install the ScriptListener plug-in. ScriptListener records a file with scripting code corresponding to the actions you perform in the UI.

Tip: Because ScriptListener records most of your actions, install ScriptListener only when you are creating

Action Manager. Leaving ScriptListener installed continuously will not only create large files that occupy memory on your hard drive, it can slow Adobe Photoshop CS2 performance.

When you perform a task or series of tasks in Adobe Photoshop CS2, ScriptListener creates a file,

ScriptingListenerJS.log

, which contains JavaScript code that represents your actions.

On Windows, ScriptListener places file the file on your C:\ drive.

● On Mac OS, ScriptListener creates the file on the desktop.

Note: There is no AppleScript interface to the Action Manager. However, you can access the Action

Manager from an AppleScript by executing a JavaScript via the AppleScript.

Installing ScriptListener

The ScriptListener plug-in is located in the

..\Adobe Photoshop CS2\Scripting Guide\Utilities folder.

To install the ScriptListener:

1. Select the file

ScriptListener.8li

and then choose Edit > Copy.

2. Paste the file copy to the following location:

..\Adobe Photoshop CS\Plug-Ins\Adobe Photoshop Only\Automate

3. Open Adobe Photoshop CS2.

Note: If Adobe Photoshop CS2 is already open, close it and then start it again.

To uninstall the ScriptListener:

1. Close Adobe Photoshop CS2.

183

Adobe Photoshop CS2

JavaScript Scripting Reference Action Manager 184

2. Verify that a copy of the file

ScriptListener.8li

still exists in the

..\Adobe Photoshop

CS2\Scripting Guide\Utilities

folder.

3. Delete the file ScriptListener.8li

from the following location:

..\Adobe Photoshop CS\Plug-Ins\Adobe Photoshop Only\Automate

4. Delete the log file

ScriptingListenerJS.log

from your C:\ drive (Windows) or desktop (Mac OS).

Note: In Windows, even though you remove the ScriptListener from the Automate folder, it may continue to record actions. To prevent the

ScriptingListenerJS.log file from becoming too large, delete it each time you finish playing a Adobe Photoshop CS2 action.

Action Manager Scripting Objects

The objects ActionDescriptor ,

ActionList and

ActionReference

are part of the Action Manager functionality.

Using the Action Manager from JavaScript

The section demonstrates how to create the

ScriptingListenerJS.log log file and use its contents to create your script.

The procedures in this section uses the Action Manager to make the Emboss filter available to the scripting interface. (By default, the Emboss filter is available only via the Adobe Photoshop CS2 interface.)

Note: ScriptListener must be installed in the

Automate

folder before you begin the following procedure.

See

Installing ScriptListener

.

To make the Emboss filter scriptable:

1. Open Adobe Photoshop CS2, then open a document.

2. Choose Window > Actions, then choose New Action from the Actions palette menu.

3. Name the action, then click Record.

4. Choose Filter > Stylize > Emboss.

5. Using the following settings:

Angle: 135

Height: 3

● Amount: 100

6. Do one of the following:

● In Windows, open C:\ScriptingListenerJS.log

.

Adobe Photoshop CS2

JavaScript Scripting Reference Action Manager 185

On Mac OS, open

ScriptingListenerJS.log

on the desktop.

At the end of the file you will see code similar to the following (although your numbers may be different): var id19 = charIDToTypeID( "Embs" ); var desc4 = new ActionDescriptor(); var id20 = charIDToTypeID( "Angl" ); desc4.putInteger( id20, 135 ); var id21 = charIDToTypeID( "Hght" ); desc4.putInteger( id21, 3 ); var id22 = charIDToTypeID( "Amnt" ); desc4.putInteger( id22, 100 ); executeAction( id19, desc4 );

Note: ScriptListener separates logged commands with horizontal lines composed of hyphens (-----...). If this is not the first action recorded in the log, you can easily locate the most recent action; it follows the final hyphen-line.

7. In the script, identify the values that you used with the filter (135, 3 and 100), then copy the JavaScript code from

ScriptListenerJS.log

to another file and substitute the filter specification values with variable names.

In the following example,

135

has been replaced with angle

;

3

has been replaced with height

;

100

has been replaced with amount .

var id19 = charIDToTypeID( "Embs" ); var desc4 = new ActionDescriptor(); var id20 = charIDToTypeID( "Angl" ); desc4.putInteger( id20, angle ); var id21 = charIDToTypeID( "Hght" ); desc4.putInteger( id21, height ); var id22 = charIDToTypeID( "Amnt" ); desc7.putInteger( id22, amount ); executeAction( id19, desc4 );

8. Wrap the code in a JavaScript function. In the following example, the function name is emboss

.

function emboss( angle, height, amount )

{ var id19 = charIDToTypeID( "Embs" ); var desc4 = new ActionDescriptor(); var id20 = charIDToTypeID( "Angl" ); desc4.putInteger( id20, angle ); var id21 = charIDToTypeID( "Hght" ); desc4.putInteger( id21, height ); var id22 = charIDToTypeID( "Amnt" ); desc7.putInteger( id22, amount ); executeAction( id19, desc4 );

}

9. To use a JavaScript to apply the Emboss filter to a document, include the emboss function in the

JavaScript and call the function with the desired parameters. For example, the following example applies the Emboss filter with angle 75, height 2, and amount 89.

// Open the document in the script

//Call emboss with desired parameters emboss( 75, 2, 89 );

//finish the script

//include the function in the script file

Adobe Photoshop CS2

JavaScript Scripting Reference function emboss(angle, height, amount )

{ var id32 = charIDToTypeID( "Embs" ); var desc7 = new ActionDescriptor(); var id33 = charIDToTypeID( "Angl" ); desc7.putInteger( id33, angle ); var id34 = charIDToTypeID( "Hght" ); desc7.putInteger( id34, height ); var id35 = charIDToTypeID( "Amnt" ); desc7.putInteger( id35, amount ); executeAction( id32, desc7 );

}

Action Manager 186

4

Using ScriptUI

Overview

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 UI control elements within an Adobe Creative Suite 2 application. ScriptUI objects are available to JavaScript scripts for the following applications:

Adobe Photoshop CS2

Adobe Bridge CS2

Note: Adobe GoLive CS SDK includes another version of these objects, which have diverged somewhat in usage and functionality. See the Adobe GoLive CS SDK Programmer’s Guide and Adobe GoLive CS SDK

Programmer’s Reference for details.

This chapter describe how to work with these objects, and Chapter 5, “ScriptUI Object Reference ," provides

the details of the objects with their properties, methods, and creation parameters.

ScriptUI Programming Model

ScriptUI defines

Window

objects that represent platform-specific windows, and various control elements such as

Button

and

StaticText

, that represent user-interface controls. These objects share a common set of properties and methods that allow you to query the type, move the element around, set the title, caption or content, and so on. Many element types also have properties unique to that class of elements.

Creating a window

ScriptUI defines the following types of windows:

Modal dialog boxes: not resizable, holds focus when shown.

Main windows: resizable, suitable for use as an application's main window. (Main windows are not normally created by script developers for Adobe Creative Suite 2 applications. )

To create a new window, use the Window constructor function. The constructor takes the desired type of the window. The type is

"dialog"

for a modal dialog. You can supply optional arguments to specify an initial window title and bounds.

The following example creates an empty dialog with the variable name dlg

, which is used in subsequent examples:

// Create an empty dialog window near the upper left of the screen var dlg = new Window('dialog', 'Alert Box Builder', [100,100,480,490]);

Newly created windows are initially hidden; the show

method makes them visible and responsive to user interaction. For example: dlg.show();

187

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 188

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.

A

Group

is the simplest container used to visually organize related controls. You would typically define a group and populate it with related elements, for instance an edittext

box and its descriptive statictext label.

A

Panel

is a frame object, also typically used to visually organize related controls. It has a text property to specify a title, and can have a border to visually separate the collection of elements from other elements of a dialog.

You might create a

Panel

and populate it with several

Groups

, each with their own elements. You can create nested containers, with different layout properties for different containers, in order to define a relatively complex layout without any explicit placement.

You can add elements to any container using the add

method (see Adding elements to containers ). An

element added to a container is considered a child of that container. Certain operations on a container apply to its children; for example, when you hide a container, its children are also hidden.

Window layout

When a script creates a

Window

and adds various UI elements to it, the locations and sizes of elements and spacing between elements is known as the layout of the window. Each UI element has properties which define its location and dimensions: location , size , and bounds . These properties are initially undefined, and a script that employs

Automatic Layout should leave them undefined for the main window as well as

its contained elements, allowing the automatic layout mechanism to set their values.

Your script can access these values , and (if not using auto-layout) set them as follows:

The location

of a window is defined by a Point

object containing a pair of coordinates ( x

and y

) for the top left corner (the origin), specified in the screen coordinate system. The location

of an element within a window or other container is defined as the origin point specified in the container’s coordinate system. That is, the x

and y

values are relative to the origin of the container.

The following examples show equivalent ways of placing the content region of an existing window at screen coordinates [10, 50]:

● win.location = [10, 50]; win.location = {x:10, y:50}; win.location = "x:10, y:50";

The size of an element’s region is defined by a

Dimension object containing a

width and height in pixels.

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.height = 100;

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 189

The bounds

of an element are defined by a

Bounds

object containing both the origin point ( x

, y

) and size ( width

, height

) To define the size and location of windows and controls in one step, use the bounds property.

The value of the bounds

property can be a string with appropriate contents, an inline JavaScript

Bounds object, or a four-element array. The following examples show equivalent ways of placing a 380 by 390 pixel window near the upper left corner of the screen: var dlg = new Window('dialog', 'Alert Box Builder', [100,100,480,490]); dlg.bounds = [100,100,480,490]; dlg.bounds = {x:100, y:100, width:380, height:390}; dlg.bounds = {left:100, top:100, right:480, bottom:490}; dlg.bounds = "left:100, top:100, right:480, bottom:490";

The window

dimensions define the size of the content region of the window, or that portion of the window that a script can directly control. The actual window size is typically larger, because the host platform’s window system typically adds title bars and borders. The bounds property for a Window refers only to its content region. To determine the bounds of the frame surrounding the content region of a window, use the

Window Object

’s frameBounds

property.

Adding elements to containers

To add elements to a window

, panel

, or group

, use the container’s

add

method. This method accepts the type

of the element to be created and some optional parameters, depending on the element type. It creates and returns an object of the specified type.

In additions to windows, ScriptUI defines the following user-interface elements and controls:

● Panels (frames) and groups, to collect and organize other control types

Push buttons with text or icons, radio buttons, checkbox buttons

Static text or images, edit text

Progressbars, scrollbars, sliders

Lists, which include list boxes and drop-down (also called popup) lists. Each item in a list is a control of type item , and the parent list’s items property contains an array of child items. You can add list items

with the parent list’s add method.

You can specify the initial size and position of any new element relative to the working area of the parent container, in an optional bounds

parameter. Different types of elements have different additional

parameters. For elements which display text, for example, you can specify the initial text. See the ScriptUI

Object Reference for details.

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.add('button', undefined, 'Test');

Tip: This example creates a dynamic property, btnPnl , on the parent window object, which contains the returned reference to the child control object. This is not required, but provides a useful way to access your controls.

A new element is initially set to be visible, but it not shown unless its parent object is shown.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 190

Creation properties

Some element types have attributes that can only be specified when the element is created. These are not normal properties of the element, in that they cannot be changed during the element’s lifetime, and they are only needed once. For these element types, you can supply an optional creation-properties argument to the add

method. This argument is an object with one or more properties that control aspects of the element’s appearance, or special functions such as whether an edit text element is editable or read-only.

See Control object constructors for details.

All UI elements have an optional creation property called name , which assigns a name for identifying that element. For example, the following creates a new

Button

element with the name 'ok': dlg.btnPnl.buildBtn = dlg.btnPnl.add('button', undefined, 'Build', {name:'ok'});

Note: In Photoshop CS, panel coordinates were measured from outside the frame (including the title bar), but in Photoshop CS2, panel coordinates are measured from the inside the frame (the content area).

This means that if you use the same values to set the vertical positions of child controls in a panel, the positions are slightly different in the two versions. When you add a panel to a window, you can choose to set a creation property ( su1PanelCoordinates ), which causes that panel to

automatically adjust the positions of its children; see the add

method for panel

. When automatic adjustment is enabled, you provide position values that were correct for Photoshop CS, and the result is the same in Photoshop CS2. You can also set automatic adjustment for a window; in this case, it applies to all child panels of that window unless it is explicitly disabled in the child panel. See

Window object constructor

.

Accessing child elements

A reference to each element added to a container is appended to the container’s children property. You can access the child elements through this array, using a 0-based index. For controls that are not containers, the children

collection is empty.

In this example, the msgPnl

panel was the first element created in dlg

, so the script can access the panel object at index 0 of the parent’s children property to set the the text for the title: var dlg = new Window('dialog', 'Alert Box Builder'); dlg.msgPnl = dlg.add('panel'); dlg.children[0].text = 'Messages';

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.text = "Build";

For list controls (type list

and dropdown

), you can access the child list-item objects through the items array.

Removing elements

To add elements to a window

, panel

, or group

, use the container’s

remove

method. This method accepts an object representing the element to be removed, or the name of the element, or the index of the element in the container's children collection (see

Accessing child elements ).

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 191

The specified element is removed from view if it was currently visible, and it is no longer accessible from the container or window. The results of any further references by a script to the object representing the element are undefined.

To remove list items from a list, use the parent list control’s

remove

method in the same way. It removes the item from the parent’s items

list, hides it from view, and deletes the item object.

Types of controls

The following sections introduce the types of controls you can add to a

Window

or other container element

( panel

or group

). For details of the properties and functions, and of how to create each type of element, see

ScriptUI Object Reference

.

Containers

These are types of

Control Objects

which are contained in windows, and which contain and group other controls.

Panel

Group

Typically used to visually organize related controls.

Set the text

property to define a title which appears at the top of the

Panel

.

● An optional borderStyle creation property controls the appearance of the border drawn around the panel.

You can use Panels as separators: those with width = 0 appear as vertical lines and those with height = 0

appear as horizontal lines. var dlg = new Window('dialog', 'Alert Box Builder',[100,100,480,245]); dlg.msgPnl = dlg.add('panel', [25,15,355,130], 'Messages');

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 .

User interface controls

These are types of

Control Objects

which are contained in windows, panels, and groups, and which provide specific kinds of display and user interaction.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 192

StaticText

EditText

Button

IconButton

Typically used to display text strings that are not intended for direct manipulation by a user, such as informative messages or labels.

This example creates a

Panel

and adds several

StaticText

elements: var dlg = new Window('dialog', 'Alert Box Builder',[100,100,480,245]); dlg.msgPnl = dlg.add('panel', [25,15,355,130], 'Messages'); dlg.msgPnl.titleSt = dlg.msgPnl.add('statictext', [15,15,105,35],

'Alert box title:'); dlg.msgPnl.msgSt = dlg.msgPnl.add('statictext', [15,65,105,85],

'Alert message:'); dlg.show();

Allows users to enter text, which is returned to the script when the dialog is dismissed. Text in EditText elements can be selected, copied, and pasted.

● Set the text

property to assign the initial displayed text in the element, and read it to obtain the current text value, as entered or modified by the user.

● Set the textselection

property to replace the current selection with new text, or to insert text at the cursor (insertion point). Read this property to obtain the current selection, if any.

This example adds some EditText elements, with initial values that a user can accept or replace: var dlg = new Window('dialog', 'Alert Box Builder',[100,100,480,245]); dlg.msgPnl = dlg.add('panel', [25,15,355,130], 'Messages'); dlg.msgPnl.titleSt = dlg.msgPnl.add('statictext', [15,15,105,35],

'Alert box title:'); dlg.msgPnl.titleEt = dlg.msgPnl.add('edittext', [115,15,315,35],

'Sample Alert'); dlg.msgPnl.msgSt = dlg.msgPnl.add('statictext', [15,65,105,85],

'Alert message:'); dlg.msgPnl.msgEt = dlg.msgPnl.add('edittext', [115,45,315,105],

'<your message here>', {multiline:true}); dlg.show();

Note the creation property on the second

EditText

field, where multiline:true indicates a field in which a long text string can be entered. The text wraps to appear as multiple lines.

Typically used to initiate some action from a window when a user clicks the button; for example, accepting a dialog's current settings, canceling a dialog, bringing up a new dialog, and so on.

Set the text

property to assign a label to identify a

Button

's function.

The onClick

callback method provides behavior.

var dlg = new Window('dialog', 'Alert Box Builder',[100,100,480,245]); dlg.btnPnl = dlg.add('panel', [15,50,365,95], 'Build it'); dlg.btnPnl.testBtn = dlg.btnPnl.add('button', [15,15,115,35], 'Test'); dlg.btnPnl.buildBtn = dlg.btnPnl.add('button', [125,15,225,35],

'Build', {name:'ok'}); dlg.btnPnl.cancelBtn = dlg.btnPnl.add('button', [235,15,335,35],

'Cancel', {name:'cancel'}); dlg.show();

A button that displays an icon instead of text. Like a text button, typically initiates an action in response to a click.

The icon

property identifies the icon image; see Displaying icons

.

The onClick

callback method provides behavior.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 193

Image

Checkbox

RadioButton

Progressbar

Slider

Displays an iconic image.

The icon

property identifies the icon image; see Displaying icons

.

Allows the user to set a boolean state.

Set the text

property to assign an identifying text string that appears next to the clickable box.

The user can click to select or deselect the box, which shows a checkmark when selected. The value=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.

// Add a checkbox to control the buttons that dismiss an alert box dlg.hasBtnsCb = dlg.add('checkbox', [125,145,255,165],

'Should there be alert buttons?'); dlg.hasBtnsCb.value = true;

Allows the user to select one choice among several.

Set the text

property to assign an identifying text string that appears next to the clickable button.

The value=true

when the button is selected. The button shows the state in a platform-specific manner, with a filled or empty dot, for example.

You group a related set of radio buttons by creating all the related elements one after another. When any button's value becomes true

, the value of all other buttons in the group becomes false . When you create a group of radio buttons, you should set the state of one of them true

: var dlg = new Window('dialog', 'Alert Box Builder',[100,100,480,245]); dlg.alertBtnsPnl = dlg.add('panel', [45,50,335,95], 'Button alignment'); dlg.alertBtnsPnl.alignLeftRb = dlg.alertBtnsPnl.add('radiobutton',

[15,15,95,35], 'Left'); dlg.alertBtnsPnl.alignCenterRb = dlg.alertBtnsPnl.add('radiobutton',

[105,15,185,35], 'Center'); dlg.alertBtnsPnl.alignRightRb = dlg.alertBtnsPnl.add('radiobutton',

[195,15,275,35], 'Right'); dlg.alertBtnsPnl.alignCenterRb.value = true ; dlg.show();

Typically used to display the progress of a time-consuming operation. A colored bar covers a percentage of the area of the control, representing the percentage completion of the operation. The value property reflects and controls how much of the visible area is colored, relative to the maximum value ( maxvalue

). By default the range is 0 to 100, so the value=50

when the operation is half done.

Typically used to select within a range of values. The slider is a horizontal bar with a draggable indicator, and you can click a point on the slider bar to jump the indicator to that location. The value

property reflects and controls the position of the indicator, within the range determined by minvalue

and maxvalue

. By default the range is 0 to

100, so setting value=50

moves the indicator to the middle of the bar.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 194

Scrollbar

ListBox

DropDownList

ListItem

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.

You can create scrollbars with horizontal or vertical orientation; if width is greater than height

, it is horizontal, otherwise it is vertical.

Scrollbars are often created with an associated EditText field to display the current value of the scrollbar, and to allow setting the scrollbar's position to a specific value.

This example creates a scrollbar with associated

StaticText

and

EditText

elements within a panel: dlg.sizePnl = dlg.add('panel', [60,240,320,315], 'Dimensions'); dlg.sizePnl.widthSt = dlg.sizePnl.add('statictext', [15,15,65,35],

'Width:'); dlg.sizePnl.widthScrl = dlg.sizePnl.add('scrollbar', [75,15,195,35],

300, 300, 800); dlg.sizePnl.widthEt = dlg.sizePnl.add('edittext', [205,15,245,35]);

The last three arguments to the add method that creates the scrollbar define the values for the value

, minvalue

and maxvalue

properties.

These controls display lists of items, which are represented by

ListItem

objects in the items

property. You can access the items in this array using a 0-based index.

A

ListBox

control displays a list of choices. When you create the object, you specify whether it allows the user to select only one or multiple items. If a list contains more items than can be displayed in the available area, a scrollbar may appear that allows the user to scroll through all the list items.

● A DropDownList control displays a single visible item. When you click the control, a list drops down and allows you to select one of the other items in the list.

Drop-down lists can have nonselectable separator items for visually separating groups of related items, as in a menu.

You can specify the choice items on creation of the list object, or afterward using the list object’s

add method. You can remove items programmatically with the list object’s remove and removeAll method.

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:

● item

: the typical item in any type of list. It displays text or an icon, and can be selected. To display an icon, set the item object’s icon

property; see Displaying icons .

separator

: a separator is a nonselectable visual element in adrop-down list.

Although it has a text property, the value is ignored, and the item is displayed as a horizontal line.

Displaying icons

You can display icon images in Image or IconButton controls, or in place of strings as the selectable items in a Listbox or DropdownList control. In each case, the image is defined by setting the element's icon

property, either to a named icon resource, a File Object , or the pathname of a file containing the iconic

image (see

Specifying Paths ).

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 195

The image data for an icon must be in Portable Network Graphics (PNG) format. See http://www.libpng.org

for detailed information on the PNG format.

You can set or reset the icon property at any time to change the image displayed in the element.

The scripting environment can define icon resources, which are available to scripts by name. To specify an icon resource, set a control’s icon

property to the resource’s JavaScript name, or refer to the resource by name when creating the control. For example, to create a button with an application-defined icon resource: myWin.upBtn = myWin.add ("iconbutton", undefined, "SourceFolderIcon");

Photoshop CS2 defines these icon resources:

Step1Icon

Step2Icon

Step3Icon

Step4Icon

SourceFolderIcon

DestinationFolderIcon

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. An image is never scaled to fit the available space.

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. You can often use these standard dialogs for simple interactions with your users, rather than designing special-purpose dialogs of your own.

Use the static functions alert , confirm , and

prompt on the

Window

class to invoke these dialogs with your own messages. You do not need to create a window object to call these functions.

Modal dialogs

A modal dialog is initially invisible. Your script invokes it using the

show method, which does not return

until the dialog has been dismissed. The user can dismiss it by using a platform-specific window gesture, or by using one of the dialog controls that you supply, typically an OK or Cancel button. The

onClick

method of such a button must call the close or hide

method to close the dialog. The close

method allows you to pass a value to be returned by the show

method.

For an example of how to define such buttons and their behavior, see

Defining Behavior for Controls with

Event Callbacks

.

Creating and using modal dialogs

A dialog typically contains some controls that the user must interact with, to make selections or enter values that your script will use. In some cases, the result of the user action is stored in the object, and you can retrieve it after the dialog has been dismissed. For example, if the user changes the state of a

Checkbox or

RadioButton

, the new state is found in the control’s value

property.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 196

However, if you need to respond to a user action while the dialog is still active, you must assign the control a callback function for the interaction event, either

onClick

or

onChange

. The callback function is the value of the onClick or onChange property of the control.

For example, if you need to validate a value that the user enters in a edittext

control, you can do so in an onChange

callback handler function for that control. The callback can perform the validation, and perhaps display an alert to inform the user of errors.

Sometimes, a modal dialog presents choices to the user that must be correct before your script allows the dialog to be dismissed. If your script needs to validate the state of a dialog after the user clicks OK, you can define an

onClose

event handler for the dialog. This callback function is invoked whenever a window is 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. It can then return true

to allow the dialog to be dismissed, or false

to allow the user to correct any errors.

Dismissing a modal dialog

Every modal dialog should have at least one button that the user can click to dismiss the dialog. Typically modal dialogs have an OK and a Cancel button to close the dialog with or without accepting changes that were made in it.

You can define onClick

callbacks for the buttons that close the parent dialog by calling its close method.

You have the option of sending a value to the close

method, which is in turn passed on to and returned from the

show method that invoked the dialog. This return value allows your script to distinguish different

closing events; for example, clicking OK can return 1, clicking Cancel can return 2. However, for this typical behavior, you do not need to define these callbacks explicitly; see

Default and cancel elements below.

For some dialogs, such as a simple alert with only an OK button, you do not need to return any value. For more complex dialogs with several possible user actions, you might need to distinguish more outcomes. If you need to distinguish more than two closing states, you must define your own closing callbacks rather than relying on the default behavior.

If, by mistake, you create a modal dialog with no buttons to dismiss it, or if your dialog does have buttons, but their onClick handlers do not function properly, a user can still dismiss the dialog by typing E SC . In this case, the system will execute a call to the dialog’s close

method, passing a value of 2. This is not, of course, a recommended way to design your dialogs, but is provided as an escape hatch to prevent the application from hanging in case of an error in the operations of your dialog.

Default and cancel elements

The user can typically dismiss a modal dialog by clicking an OK or Cancel button, or by typing certain keyboard shortcuts. By convention, typing E NTER is the same as clicking OK or the default button, and typing E SC is the same as clicking Cancel. The keyboard shortcut has the same effect as calling

notify

for the associated button

control.

To determine which control is notified by which keyboard shortcut, set the dialog

object’s

defaultElement

and

cancelElement

properties. The value is the control object that should be notified when the user types the associated keyboard shortcut.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 197

For buttons assigned as the defaultElement

, if there is no onClick

handler associated with the button, clicking the button or typing E NTER

calls the parent dialog’s close

method, passing a value of 1 to be returned by the

show

call that opened the dialog.

For buttons assigned as the cancelElement

, if there is no onClick

handler associated with the button, clicking the button or typing E SC calls the parent dialog’s

close

method, passing a value of 2 to be

returned by the show call that opened the dialog.

If you do not set the defaultElement

and cancelElement

properties explicitly, ScriptUI tries to choose reasonable defaults when the dialog is about to be shown for the first time. For the default element, it looks for a button whose name or text value is " ok " (disregarding case). For the cancel element, it looks for 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.

To make this feature most useful, it is recommended that you always provide the name creation property for buttons meant to be used in this way.

Resource Specifications

You can create one or more UI elements at a time using a resource specification. This specially formatted string provides a simple and compact means of creating an element, including any container element and its component elements. The resource-specification string is passed as the type

parameter to the

Window()

or add()

constructor function.

The general structure of a resource specification is an element type specification (such as dialog ), followed by a set of braces enclosing one or more property definitions. var myResource = "dialog{ control_specs }"; var myDialog = new Window ( myResource );

Controls are defined as properties within windows and other containers. For each control, give the class name of the control, followed by the properties of the control enclosed in braces. For example, the following specifies a

Button

: testBtn: Button { text: 'Test' }

The following resource string specifies a panel that contains several

StaticText

and

EditText

controls:

"msgPnl: Panel { text: 'Messages', bounds:[25,15,355,130], \ titleSt: StaticText { text:'Alert box title:', \ bounds:[15,15,105,35] }, \ titleEt: EditText { text:'Sample Alert', bounds:[115,15,315,35] }, \ msgSt: StaticText { text:'Alert message:', \ bounds:[15,65,105,85] }, \ msgEt: EditText { text:'<your message here>', \ bounds:[115,45,315,105], properties:{multiline:true} } \

}"

The property with name properties

specifies creation properties; see Creation properties

.

A property value can be specified as null

, true

, false

, a string, a number, an inline array, or an object.

● An inline array contains one or more values in the form:

[value, value,...]

An object can be an inline object, or a named object, in the form :

{classname inlineObject}

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 198

An inline object contains one or more properties, in the form:

{ propertyName :propertyValue, propertyName :propertyValue,... }

The

Resource specification example

shows how to build a complete window and all its contents with a resource specificaiton. The resource specification format can also be used to create a single element or container and its child elements. For example, if the alertBuilderResource

in

Resource specification example did not contain the panel

btnPnlResource

, you could define that resource separately, then add it to the dialog as follows: var btnPnlResource =

"panel { text: 'Build it', bounds:[15,330,365,375], \ testBtn: Button { text:'Test', bounds:[15,15,115,35] }, \ buildBtn: Button { text:'Build', bounds:[125,15,225,35], \ properties:{name:'ok'} }, \ cancelBtn: Button { text:'Cancel', bounds:[235,15,335,35], \ properties:{name:'cancel'} } \

}"; dlg = new Window(alertBuilderResource); dlg.btnPnl = dlg.add(btnPnlResource); dlg.show();

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 199

Defining Behavior for Controls with Event Callbacks

You must define the behavior of your controls in order for them to respond to user interaction. You do this by defining event-handling callback functions as part of the definition of the control or window. To respond to a specific event, define a handler function for it, and assign a reference to that function in the corresponding property of the window or control object. Different types of windows and controls respond to different actions, or events:

Windows generate events when the user moves or resizes the window. To handle these events, define callback functions for

onMove ,

onMoving , onResize

, and

onResizing

. To respond to the user opening or

closing the window, define callback functions for onShow

and onClose

.

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

.

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. To handle these events,

define callback functions for onChange and onChanging .

Defining event handler functions

Your script can define an event handler as a named function referenced by the callback property, or as an unnamed function defined inline in the callback property.

If you define a named function, assign its name as the value of the corresponding callback property. For example:

● function hasBtnsCbOnClick { /* do something interesting */ } hasBtnsCb.onClick = hasBtnsCbOnClick;

For a simple, unnamed function, set the property value directly to the function definition:

UI_element.callback_name = function () { handler_definition};

Event-handler functions take no arguments.

For example, the following sets the onClick

property of the checkbox hasBtnsCb

, to a function that enables another control in the same dialog: hasBtnsCb.onClick = function ()

{ this.parent.alertBtnsPnl.enabled = this.value; };

The following statements set the onClick

event handlers for buttons that close the containing dialog, returning different values to the show

method that invoked the dialog, so that the calling script can tell which button was clicked: buildBtn.onClick = function () { this.parent.parent.close(1); }; cancelBtn.onClick = function () { this.parent.parent.close(2); };

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.

The notify method takes an optional argument that specifies which event it should simulate. If a control can generate only one kind of event, notification generates that event by default.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 200

The following controls generate the onClick

event: button checkbox iconbutton radiobutton

The following controls generate the onChange

event: dropdownlist edittext listbox scrollbar slider

The following controls generate the onChanging

event: edittext scrollbar slider

In radiobutton

and checkbox

controls, the boolean value

property automatically changes when the user clicks the control. If you use notify() to simulate a click, the value changes just as if the user had clicked. For example, if the value

of a checkbox hasBtnsCb

is true

, this code changes the value to false

: if (dlg.hasBtnsCb.value == true) dlg.hasBtnsCb.notify();

// dlg.hasBtnsCb.value is now false

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 201

Automatic Layout

When a script creates a window and its associated UI elements, it can explicitly control the size and location of each element and of the container elements, or it can take advantage of the automatic layout capability provided by ScriptUI. The automatic layout mechanism uses certain available information about

UI elements, along with a set of layout rules, to establish a visually pleasing layout of the controls in a dialog, automatically determining the proper sizes for elements and containers.

Automatic layout is easier to program than explicit layout. It makes a script easier to modify and maintain, and it also makes the script easier to localize for different languages.

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.layout = new AutoLayoutManager(myWin);

Default layout behavior

By default, the autoLayoutManager

object implements the default layout behavior. A script can modify the properties of the default layout manager object, or create a new, custom layout manager if it needs more specialized layout behavior. See

Custom layout manager example .

Child elements of a container can be organized in a single row or column, or in a stack, where the elements overlap one other in the same region of the container, and only the top element is fully visible. This is controlled by the container’s orientation

property, which can have the value row

, column

, or stack

.

You can nest

Panel

and

Group

containers to create more complex organizations. For example, to display two columns of controls, you can create a panel with a row orientation that in turn contains two groups, each with a column orientation.

Containers have properties to control inter-element spacing and margins within their edges. The layout manager provides defaults if these are not set.

The alignment of child elements within a container is controlled by the alignChildren property of the container, and the alignment property of the individual controls. The alignChildren

property determines an overall strategy for the container, which can be overridden by a particular child element’s alignment

value.

A layout manager can determine the best size for a child element through the element’s preferredSize property. The value defaults to dimensions determined by the UI framework based on characteristics of the control type and variable characteristics such as a displayed text string.

For details of how you can set these property values to affect the automatic layout, see Automatic layout properties

.

Note: ScriptUI does not offer direct control of fonts, and fonts are chosen differently on different platforms, so windows that are created the same way can appear different on different platforms.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 202

Automatic layout properties

Your script establishes rules for the layout manager by setting the values of certain properties, both in the container object and in the child elements. The following examples show the effects of various combinations of values for these properties. The examples are based on a simple window containing a

StaticText

,

Button

and

EditText

element, created (using

Resource Specifications

) as follows: var w = new Window(

"window { \ orientation: 'row', \ st: StaticText { }, \ pb: Button { text: 'OK' }, \ et: EditText { size:[20, 30] } \

}"); 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. It can have these values:

● row

: Child elements are arranged next to each other, in a single row from left to right across the container. The height of the container is based on the height of the tallest child element in the row, and the width of the container is based on the combined widths of all the child elements.

● column : Child elements are arranged above and below each other, in a single column from top to bottom across the container. The height of the container is based on the combined heights of all the child elements, and the width of the container is based on the widest child element in the column.

stack

: Child elements are arranged overlapping one another, as in a stack of papers. The elements overlie one another in the same region of the container. Only the top element is fully visible. The height of the container is based on the height of the tallest child element in the stack, and the width of the container is based on the widest child element in the stack.

The following figure shows the results of laying out the sample window with each of these orientations:

Aligning children

The alignment of child elements within a container is controlled by two properties: alignChildren

in the parent container, and alignment

in each child. The alignChildren

value in the parent container controls the alignment of all children within that container, unless it is overridden by the alignment value set on an individual child element.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 203

These properties use the same values, which specify alignment along one axis, depending on the orientation of the container. The property values are not case-sensitive; for example, the strings

FILL

,

Fill , and fill are all valid.

Elements in a row can be aligned along the vertical axis, in these ways:

● top : The element's top edge is located at the top margin of its container.

bottom

: The element's bottom edge is located at the bottom margin of its container.

center

: The element is centered within the top and bottom margins of its container.

fill

: The element’s height is adjusted to fill the height of the container between the top and bottom margins.

Elements in a column can be aligned along the horizontal axis, in these ways:

● left

: The element's left edge is located at the left margin of its container.

● right

: The element's right edge is located at the right margin of its container.

● center : The element is centered within the right and left margins of its container.

fill

: The element’s width is adjusted to fill the width of the container between the right and left margins.

Elements in a stack can be aligned along either the vertical or the horizontal axis, in these ways:

● top : The element's top edge is located at the top margin of its container, and the element is centered within the right and left margins of its container.

● bottom : The element's bottom edge is located at the bottom margin of its container, and the element is centered within the right and left margins of its container.

left : The element's left edge is located at the left margin of its container, and the element is centered within the top and bottom margins of its container.

● right : The element's right edge is located at the right margin of its container, and the element is centered within the top and bottom margins of its container.

center : The element is centered within the top, bottom, right and left margins of its container.

fill

: The element’s height is adjusted to fill the height of the container between the top and bottom margins., and the element’s width is adjusted to fill the width of the container between the right and left margins.

The following figure shows the results of creating the sample window with row orientation and the bottom

and top

alignment settings in the parent’s alignChildren

property:

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 204

The following figure shows the results of creating the sample window with column orientation and the right

, left

, and fill

alignment settings in the parent’s alignChildren

property. Notice how in the fill case, each element is made as wide as the widest element in the container:

You can override the container's child alignment, as specified by alignChildren , by setting the alignment

property of a particular child element. The following diagram shows the result of setting alignment

to right

for the

EditText

element, when the parent’s alignChildren

value is left:

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.

The following figure shows the results of creating the sample window with row orientation and margins of

5 and 15 pixels:

This figure shows the results of creating the sample window with column orientation, a top margin of 0 pixels, a bottom margin of 20 pixels, and left and right margins of 15 pixels:

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 205

Spacing between children

The spacing

property of a container specifies the number of pixels separating one child element from its adjacent sibling element.

This figure shows the results of creating the sample window with row orientation, and spacing of 15 and 5 pixels, respectively:

This figure shows the results of creating the sample window with column orientation, and spacing of 20 pixels:

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.

If an element's size

property is not defined, the layout manager uses the value of preferredSize

to determine the dimensions of each element during the layout process. Generally, you should avoid setting the preferredSize

property explicitly, and let ScriptUI determine the best value based on the state of an element at layout time. This allows you to set the text

properties of your UI elements using localizable strings (see

Localization in ScriptUI Objects

). The width and height of each element are calculated at layout time based on the chosen language-specific text string, rather than relying on the script to specify a fixed size for each element.

However, a script can explicitly set the preferredSize

property to give hints to the layout manager about the intended sizes of elements for which a reasonable default size is not easily determined, such as an

EditText element that has no initial text content to measure.

Creating more complex arrangements

You can easily create more complex arrangements by nesting

Group

containers within

Panel

containers and other Group containers.

Many dialogs consist of rows of information to be filled in, where each row has columns of related types of controls. For instance, an edit field is typically in a row next to a static text label that identifies it, and a series of such rows are arranged in a column. This example (created using

Resource Specifications ) shows a

simple dialog in which a user can enter information into two EditText fields, each arranged in a row with

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 206 its

StaticText

label. To create the layout, a

Panel

with a column orientation contains two

Group

elements with row orientation. These groups contain the control rows. A third

Group

, outside the panel, contains the row of buttons. res =

"dialog { \ info: Panel { orientation: 'column', \ text: 'Personal Info', \ name: Group { orientation: 'row', \ s: StaticText { text:'Name:' }, \ e: EditText { preferredSize: [200, 20] } \

}, \ addr: Group { orientation: 'row', \ s: StaticText { text:'Street / City:' }, \ e: EditText { preferredSize: [200, 20] } \

}, \

} \ buttons: Group { orientation: 'row', \ okBtn: Button { text:'OK', properties:{name:'ok'} }, \ cancelBtn: Button { text:'Cancel', properties:{name:'cancel'} } \

} \

}"; win = new Window (res); win.center(); win.show();

In this simplest example, the columns are not vertically aligned. When you are using fixed-width controls in your rows, a simple way to get an attractive alignment of the StaticText labels for your EditText fields is to align the child rows in the

Panel

to the right of the panel. In the example, add the following to the

Panel

specification: info: Panel { orientation: 'column', alignChildren:'right', \

This creates the following result:

Suppose now that you need two panels, and want each panel to have the same width in the dialog. You can specify this at the level of the dialog window object, the parent of both panels. Specify alignChildren='fill' , which makes each child of the dialog match its width to the widest child.

res =

"dialog { alignChildren: 'fill', \ info: Panel { orientation: 'column', alignChildren:'right', \ text: 'Personal Info', \ name: Group { orientation: 'row', \

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 207 s: StaticText { text:'Name:' }, \ e: EditText { preferredSize: [200, 20] } \

} \

}, \ workInfo: Panel { orientation: 'column', \ text: 'Work Info', \ name: Group { orientation: 'row', \ s: StaticText { text:'Company name:' }, \ e: EditText { preferredSize: [200, 20] } \

}, \

} \ 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.show();

To make the buttons to appear at the right of the dialog, the buttons

group overrides the fill

alignment of its parent (the dialog), and specifies alignment= ' right ' .

Creating dynamic content

Many dialogs need to present different sets of information based on the user selecting some option within the dialog. You can use the stack orientation to present different views in the same region of a dialog.

A stack

orientation of a container places child elements so they are centered in a space which is wide enough to hold the widest child element, and tall enough to contain the tallest child element. If you arrange groups or panels in such a stack, you can show and hide them in different combinations to display a different set of controls in the same space, depending on other choices in the dialog.

For example, this dialog changes dynamically according to the user’s choice in the

DropDownList

.

The following script creates this dialog. It compresses the "Personal Info" and "Work Info" panels from the previous example into a single

Panel

that has two

Groups

arranged in a stack. A

DropDownList

allows the

user to choose which set of information to view. When the user makes a choice in the list, its onChange

function shows one group, and hides the other.

res =

"dialog { \ whichInfo: DropDownList { alignment:'left' }, \

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 208 allGroups: Panel { orientation:'stack', \ info: Group { orientation: 'column', \ name: Group { orientation: 'row', \ s: StaticText { text:'Name:' }, \ e: EditText { preferredSize: [200, 20] } \

}, \

} \ workInfo: Group { orientation: 'column', \ name: Group { orientation: 'row', \

} \

}, \ s: StaticText { text:'Company name:' }, \ e: EditText { preferredSize: [200, 20] } \

}, \ 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.whichInfo.onChange = function () { if (this.selection != null) { for (var g = 0; g < this.items.length; g++) this.items[g].group.visible = false; //hide all other groups this.selection.group.visible = true;//show this group

}

} var item = win.whichInfo.add ('item', 'Personal Info'); item.group = win.allGroups.info; item = win.whichInfo.add ('item', 'Work Info'); item.group = win.allGroups.workInfo; win.whichInfo.selection = win.whichInfo.items[0]; win.center(); win.show();

Custom layout manager example

This script creates a dialog almost identical to the one in the previous example, except that it defines a layout-manager subclass, and assigns an instance of this class as the layout

property for the last

Group

in the dialog. (The example also demonstrates the technique for defining a reusable class in JavaScript.)

This script-defined layout manager positions elements in its container in a stair-step fashion, so that the buttons are staggered rather than in a straight line.

/* Define a custom layout manager that arranges the children

** of 'container' in a stair-step fashion.*/ function StairStepButtonLayout (container) { this.initSelf(container); }

Adobe Photoshop CS2

JavaScript Scripting Reference

// 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.children[i]; if (typeof child.layout != "undefined")

// If child is a container, call its layout method child.layout.layout(); child.size = child.preferredSize; child.location = [left, top]; width = left + child.size.width; top += child.size.height + vspacing; left += hspacing;

} this.container.preferredSize = [width, top - vspacing];

}

// Attach methods to Object's prototype

StairStepButtonLayout.prototype.initSelf = SSBL_initSelf;

StairStepButtonLayout.prototype.layout = SSBL_layout;

// Define a string containing the resource specification for the controls res =

"dialog { \ whichInfo: DropDownList { alignment:'left' }, \ allGroups: Panel { orientation:'stack', \ info: Group { orientation: 'column', \ name: Group { orientation: 'row', \ s: StaticText { text:'Name:' }, \

} \ e: EditText { preferredSize: [200, 20] } \

}, \ workInfo: Group { orientation: 'column', \ name: Group { orientation: 'row', \ s: StaticText { text:'Company name:' }, \

} \ e: EditText { preferredSize: [200, 20] } \

}, \ buttons: Group { orientation: 'row', alignment: 'right', \ okBtn: Button { text:'OK', properties:{name:'ok'} }, \

} \ cancelBtn: Button { text:'Cancel', properties:{name:'cancel'} } \

}";

// 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;

Using ScriptUI 209

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 210 item = win.whichInfo.add ('item', 'Work Info'); item.group = win.allGroups.workInfo; win.whichInfo.selection = win.whichInfo.items[0];

// Override the default layout manager for the 'buttons' group

// with custom layout manager win.buttons.layout = new StairStepButtonLayout(win.buttons); win.center(); win.show();

The AutoLayoutManager algorithm

When a script creates a window object and its elements and shows it the first time, the visible UI-platform window and controls are created. At this point, if no explicit placement of controls was specified by the script, all the controls are located at [0, 0] within their containers, and have default dimensions. Before the window is made visible, the layout manager’s layout

method is called to assign locations and sizes for all the elements and their containers.

The default

AutoLayoutManager

’s layout

method performs these steps when invoked during the initial call to a window

object’s show

method.

For example:

1. Read the bounds

property for the managed container; if undefined, proceed with auto layout. If defined, assume that the script has explicitly placed the elements in this container, and cancel the layout operation (if both the location

and size

property have been set, this is equivalent to setting the bounds property, and layout does not proceed).

2. Determine the container’s margins and inter-element spacing from its margins

and spacing properties, and the orientation and alignment of its child elements from the container’s orientation and alignChildren

properties. If any of these properties are undefined, use default settings obtained from platform and UI framework-specific default values.

3. Enumerate the child elements, and for each child:

● If the child is a container, call its layout manager (that is, execute this entire algorithm again for the container).

Read its alignment property; if defined, override the default alignment established by the parent container with its alignChildren

property.

Read its size property: if defined, use it to determine the child’s dimensions. If undefined, read its preferredSize

property to get the child’s dimensions. Ignore the child's location

property.

All the per-child information is collected for later use.

4. Based on the orientation, calculate the trial location of each child in the row or column, using inter-element spacing and the container’s margins.

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. For stack orientation, center each child horizontally and vertically in its container.

7. Set the bounds

property for each child element.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 211

8. Set the container’s preferredSize

property, based on the margins and dimensions of the row or column of child elements.

Automatic layout restrictions

The following restrictions apply to the automatic layout mechanism:

The default layout manager does not attempt to lay out a container that has a defined bounds property. The script programmer can override this behavior by defining a custom layout manager for the container.

The layout mechanism does not track changes to element sizes after the initial layout has occurred. The script can initiate another layout by calling the layout manager’s layout

method, and can force the manager to recalculate the sizes of all child containers by passing the optional argument as true .

The layout mechanism does not support re-layout if a dialog window is resized.

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 212

Example scripts

These examples demonstrate two ways of building and populating a ScriptUI dialog. The first creates each control with a separate add

method, while the second defines a resource string that creates the control hierarchy.

The two examples create the same dialog, which collects values from the user. When the Alert Box Builder dialog is dismissed, the script builds a resource string from the collected values, and saves it to a file. That resource string can later be used to create and display the user-configured alert box.

Alert box builder

This variation builds the dialog using the window and panel add

methods to create each control.

//------------- Functions -------------//

/* This function creates the builder dialog using the add method

** An alternative that uses a resource specification is shown

** in the following section */ function createBuilderDialog() {

// Create an empty dialog window near the upper left of the screen var dlg = new Window('dialog', 'Alert Box Builder'); dlg.frameLocation = [100, 100];

// Add a panel to hold title and 'message text' strings dlg.msgPnl = dlg.add('panel', undefined, 'Messages'); dlg.msgPnl.alignChildren = "right"; dlg.msgPnl.title = dlg.msgPnl.add('group'); dlg.msgPnl.msg = dlg.msgPnl.add('group'); dlg.msgPnl.msgWidth = dlg.msgPnl.add('group'); dlg.msgPnl.msgHeight = dlg.msgPnl.add('group'); with (dlg.msgPnl) { title.st = title.add('statictext', undefined, 'Alert box title:'); title.et = title.add('edittext', undefined, 'Sample Alert'); title.et.preferredSize = [200,20]; msg.st = msg.add('statictext', undefined, 'Alert message:'); msg.et = msg.add('edittext', undefined, '<your message here>',

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 213

{multiline:true}); msg.et.preferredSize = [200,60]; msgWidth.st = msgWidth.add('statictext', undefined, 'Message width:'); msgWidth.sl = msgWidth.add('slider', undefined, 150, 100, 300); msgWidth.sl.preferredSize = [150, 20]; msgWidth.et = msgWidth.add('edittext'); msgWidth.et.preferredSize = [40, 20]; msgHeight.st = msgHeight.add('statictext', undefined, 'Message height:'); msgHeight.sl = msgHeight.add('slider', undefined, 20, 20, 300); msgHeight.sl.preferredSize = [150, 20]; msgHeight.et = msgHeight.add('edittext'); msgHeight.et.preferredSize = [40, 20];

}

// Add a checkbox to control the presence of buttons to dismiss the alert box dlg.hasBtnsCb = dlg.add('checkbox', undefined, 'Has alert buttons?');

// Add panel to determine alignment of buttons on the alert box dlg.alertBtnsPnl = dlg.add('panel', undefined, 'Button alignment'); dlg.alertBtnsPnl.orientation = "row"; dlg.alertBtnsPnl.alignLeftRb = dlg.alertBtnsPnl.add('radiobutton', undefined, 'Left'); dlg.alertBtnsPnl.alignCenterRb = dlg.alertBtnsPnl.add('radiobutton', undefined, 'Center'); dlg.alertBtnsPnl.alignRightRb = dlg.alertBtnsPnl.add('radiobutton', undefined, 'Right');

// Add a panel with buttons to test parameters and

// create the alert box specification dlg.btnPnl = dlg.add('panel', undefined, 'Build it'); dlg.btnPnl.orientation = "row"; dlg.btnPnl.testBtn = dlg.btnPnl.add('button', undefined, 'Test'); dlg.btnPnl.buildBtn = dlg.btnPnl.add('button', undefined, 'Build',

{name:'ok'}); dlg.btnPnl.cancelBtn = dlg.btnPnl.add('button', undefined, 'Cancel', {name:'cancel'}); return dlg;

} // createBuilderDialog

/* This function initializes the values in the controls

** of the builder dialog */ function initializeBuilder(builder) {

// Set up initial control states with (builder) { hasBtnsCb.value = true; alertBtnsPnl.alignCenterRb.value = true; with (msgPnl) { msgWidth.et.text = msgWidth.sl.value; msgHeight.et.text = msgHeight.sl.value;

}

}

// Attach event callback functions to controls

/* The 'has buttons' checkbox enables or disables the panel that

determines the justification of the 'alert' button group */ builder.hasBtnsCb.onClick = function () { this.parent.alertBtnsPnl.enabled = this.value; };

/* The edittext fields and scrollbars in msgPnl are connected */ with (builder.msgPnl) { msgWidth.et.onChange = function () { this.parent.parent.msgWidth.sl.value = this.text; }; msgWidth.sl.onChanging =

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 214 function () { this.parent.parent.msgWidth.et.text = this.value; }; msgHeight.et.onChange = function () { this.parent.parent.msgHeight.sl.value = this.text; }; msgHeight.sl.onChanging = function () { this.parent.parent.msgHeight.et.text = this.value; };

} with (builder.btnPnl) {

// The Test button creates a trial Alert box from

// the current specifications testBtn.onClick = function () {

Window.alert('Type Enter or Esc to dismiss the test Alert box'); createTestDialog(createResource(this.parent.parent));

};

// The Build and Cancel buttons close this dialog buildBtn.onClick = function () { this.parent.parent.close(1); }; cancelBtn.onClick = function () { this.parent.parent.close(2); };

};

} // initializeBuilder

/* This function invokes the dialog an returns its result */ function runBuilder(builder) { return builder.show();

}

/* This function creates and returns a string containing a dialog

** resource specification that will create an Alert dialog using

** the parameters the user entered in the builder dialog. */ function createResource(builder) {

// Define the initial part of the resource spec with dialog parameters var res = "dialog { " + stringProperty("text", builder.msgPnl.title.et.text) +

"\n";

// Define the alert message statictext element, sizing it as user specified var textWidth = Number(builder.msgPnl.msgWidth.et.text); var textHeight = Number(builder.msgPnl.msgHeight.et.text); res += " msg: StaticText { " + stringProperty("text", builder.msgPnl.msg.et.text) +

" preferredSize: [" + textWidth + ", " + textHeight + "],\n" +

" justify:'center', properties:{multiline:true} }";

// Define buttons if desired var hasButtons = builder.hasBtnsCb.value; if (hasButtons) { var groupAlign = "center";

// Align buttons as specified if (builder.alertBtnsPnl.alignLeftRb.value) groupAlign = "left"; else if (builder.alertBtnsPnl.alignRightRb.value) groupAlign = "right"; res += ",\n" +

" btnGroup: Group {\n" + stringProperty(" alignment", groupAlign) +

"\n" +

" okBtn: Button { " + stringProperty("text", "OK") +"},\n"; res += " cancelBtn: Button { " + stringProperty("text", "Cancel") +"}" +

" }";

}

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 215

// done res += "\n}"; return res;

} function stringProperty(pname, pval) { return pname + ":'" + pval + "', ";

} function createTestDialog(resource) { var target = new Window (resource); target.center(); return target.show();

}

//------------- Main script -------------// var builder = createBuilderDialog(); //for an alternative, see below initializeBuilder(builder); if (runBuilder(builder) == 1) {

// Create the Alert dialog resource specification string var resSpec = createResource(builder);

// Write the resource spec string to a file w/platform file-open dialog var fname = File.openDialog('Save resource specification'); var f = File(fname); if (f.open('w')) { var ok = f.write(resSpec); if (ok) ok = f.close(); if (! ok)

Window.alert("Error creating " + fname + ": " + f.error);

}

}

Resource specification example

This example provides an alternative method of building the same initial

Alert box builder

dialog, using a resource specification instead of explicit calls to the add

method of a container element. To use this alternate version, add this code to the beginning of the previous example in place of the createBuilderDialog

function. In the main script, replace the line: var builder = createBuilderDialog(); with this line: var builder = createBuilderDialogFromResource();

The new code follows: var alertBuilderResource =

"dialog { \ text: 'Alert Box Builder', frameLocation:[100,100], \ msgPnl: Panel { orientation:'column', alignChildren:'right', \ text: 'Messages', \ title: Group { \ st: StaticText { text:'Alert box title:' }, \ et: EditText { text:'Sample Alert', \ preferredSize:[200, 20] } \

}, \ msg: Group { \ st: StaticText { text:'Alert message:' }, \ et: EditText { text:'<your message here>', \ preferredSize:[200, 60], properties:{multiline:true} } \

}, \

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 216 msgWidth: Group { alignChildren:'center', \ st: StaticText { text:'Message width:' }, \ sl: Slider { minvalue:100, maxvalue:300, value:150, \ preferredSize:[150, 20] }, \ et: EditText { preferredSize:[40, 20] } \

}, \ msgHeight: Group { alignChildren:'center', \ st: StaticText { text:'Message height:' }, \ sl: Slider { minvalue:20, maxvalue:300, \ preferredSize:[150, 20] }, \ et: EditText { preferredSize:[40, 20] } \

} \

}, \ hasBtnsCb: Checkbox { text:'Has alert buttons?', \ alignment:'center' }, \ alertBtnsPnl: Panel { orientation:'row', \ text: 'Button alignment', \ alignLeftRb: RadioButton { text:'Left' }, \ alignCenterRb: RadioButton { text:'Center' }, \ alignRightRb: RadioButton { text:'Right' } \

}, \ btnPnl: Panel { orientation:'row', \ text: 'Build it', \

}"; testBtn: Button { text:'Test' }, \ buildBtn: Button { text:'Build', properties:{name:'ok'} }, \

} \ cancelBtn: Button { text:'Cancel', properties:{name:'cancel'} } \

// This function creates the builder dialog from the resource string function createBuilderDialogFromResource() { var builder = new Window(alertBuilderResource); return builder;

} // createBuilderDialogFromResource

Adobe Photoshop CS2

JavaScript Scripting Reference Using ScriptUI 217

Localization in ScriptUI Objects

For portions of your user interface that are displayed on the screen, you may want to localize the displayed text. You can localize the display strings in any ScriptUI object (including

These tables list unique identifiers for the top-level menus in Adobe Bridge

s) simply and efficiently, using the Global localize function . This function takes as its argument a localization object containing the localized versions of a

string.

For complete details of this ExtendScript feature, see Localizing ExtendScript Strings

.

A localization object is a JavaScript object literal whose property names are locale names, and whose property values are the localized text strings. The locale name is an identifier as specified in the ISO 3166 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. It matches the current locale and platform to one of the object's properties and returns the associated string. On a German system, for example, the property de

provides the string

"Ja"

.

When your script uses localization to provide language-appropriate strings for UI elements, it should also

take advantage of the Automatic Layout

feature. The layout manager can determine the best size for each

UI element based on its localized text

value, automatically adjusting the layout of your script-defined dialogs to allow for the varying widths of strings for different languages.

Variable values in localized strings

The localize

function allows you to include variables in the string values. Each variable is replaced with the result of evaluating an additional argument. For example: today = { en: "Today is %1/%2.", de: "Heute ist der %2.%1."

}; d = new Date();

Window.alert (localize (today, d.getMonth()+1, d.getDate()));

Enabling automatic localization

If you do not need variable replacement, you can use automatic localization. To turn on automatic localization, set the global value:

$.localization=true

When it is enabled, you can specify a localization object directly as the value of any property that takes a localizable string, without using the localize

function. For example: btnText = { en: "Yes", de: "Ja", fr: "Oui" }; b1 = w.add ("button", undefined, btnText);

The localize

function always performs its translation, regardless of the setting of the

$.localize

variable. For example:

//Only works if the $.localize=true b1 = w.add ("button", undefined, btnText);

Adobe Photoshop CS2

JavaScript Scripting Reference

//Always works, regardless of $.localize value b1 = w.add ("button", undefined, localize (btnText));

If you need to include variables in the localized strings, use the localize

function.

Using ScriptUI 218

5

ScriptUI Object Reference

Overview

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 UI control elements within an Adobe Creative Suite 2 application.

For an overview of the ScriptUI object model and a description of usage, see

Chapter 4, “Using ScriptUI

."

This chapter provides the details of the ScriptUI classes and objects with their properties, methods, and creation parameters.

Window Class

Window Object

Control Objects

Size and Location Objects

LayoutManager Object

219

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 220

Window Class

The

Window

class defines these static properties and functions which are available globally through reference to the class. Window instances created with new Window()

do not have these properties and functions.

Window class properties coreVersion version

String The internal core version number of the ScriptUI components. Read only.

String The main version number of the ScriptUI components. Read only.

Window class functions alert

Window.alert

(message[, title, errorIcon]) confirm

Window.confirm

(message[,noAsDflt ,title ]) find

Window.find (resourceName)

Window.find (type, title)

Displays the localizable message

string in a user alert box that

provides an OK button. For details, see the ExtendScript alert

function.

The alert dialog is not intended for lengthy messages. When the string argument is too long, the alert dialog truncates it.

Displays the localizable message string in a self-sizing modal dialog box with Yes and No buttons. Returns true

if the user clicks Yes, false

if the user clicks No.

For details, see the ExtendScript

confirm function.

The confirmation dialog can show longer messages than the alert and prompt dialogs, but if this string is too long, the dialog truncates it.

Finds and returns an existing window object, which can be a window already created by a script, or a windows created by the application (if the application supports this case).

resourceName : A named resource that identifies a window that the application exposes to JavaScript. (Not supported in all

ScriptUI implementations.) type

: The window creation type, dialog

. Used to distinguish between windows with the same title. If the type is unimportant, pass null

or an empty string. title

: The title of the window to find.

If it finds an existing window, the method returns the corresponding JavaScript window

object. If not, it returns null

.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 221 getResourceText

Window.getResourceText

(textResource) prompt

Window.prompt

(message, preset[, title ])

Finds and returns a text string representation of the textResource from the host application's resource data. If no string resource matches the textResource name, the name is treated as literal text.

Displays a modal dialog that returns the user’s text input.

● When the user clicks OK to dismiss the dialog, the method returns the text the user entered.

● When the user clicks the Cancel button, the method returns null

.

For details, see the ExtendScript

prompt

function.

Window Object

Window object constructor

To create a new

Window

object: new Window (type [, title, bounds, {creation_properties}]); type The window type. The value is: dialog

: Creates a modal dialog.

title bounds creation_properties

Optional. The window title. A localizable string.

Optional. The window’s position and size.

Optional. An object that can contain any of these properties: resizeable

: When true

, the window can be resized by the user.

Default is false

.

su1PanelCoordinates

: When true

, the child panels of this window automatically adjust the positions of their children for compatibility with Photoshop CS (in which the vertical coordinate was measured from outside the frame). Default is false

. Individual panels can override the parent window’s setting.

Creates and returns a new window

object, or null

if window creation failed.

Window object properties

Window elements contain the following properties, in addition to those common to all ScriptUI elements: defaultElement Object cancelElement Object

For a window of type dialog

, the control to notify when a user types the E NTER key. By default, looks for a button

whose name or text is " ok

" (case disregarded).

For a window of type dialog , the control to notify when a user types the E

SC

key in Windows®, or the C

MD . combination in Mac

OS®. By default, looks for a button

whose name or text is " cancel

"

(case disregarded).

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 222 frameBounds frameLocation frameSize

Bounds

Point

A Bounds object for the boundaries of the Window's frame in

screen coordinates. The frame consists of the title bar and borders that enclose the content region of a window, depending on the windowing system. Read only.

A Point object for the location of the top left corner of the

Window's frame. The same as

[frameBounds.x, frameBounds.y]

.

Set this value to move the window frame to the specified location on the screen. The frameBounds

value changes accordingly.

Dimension A object for the size and location of the Window's frame

in screen coordinates. Read only.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 223

Container properties

The following table shows properties that are available on window objects and container objects (controls of type panel

and group

).

alignChildren children layout

String

Array of Object

LayoutManager

Tells the layout manager how unlike-sized children of a container should be aligned within a column or row. Order of creation determines which children are at the top of a column or the left of a row; the earlier a child is created, the closer it is to the top or left of its column or row.

If defined, alignment

for a child element overrides the alignChildren setting for the parent container.

Allowed values depend on the orientation

value. For orientation=row : top bottom center (default) fill

For orientation=column

: left right center (default) fill

For orientation=stack

: top bottom left right center (default) fill

Values are not case sensitive.

The collection of UI elements that have been added to this container ( window

, panel

, group

). An array indexed by number or by a string containing an element's name . The length

property of this array is the number of child elements for container elements, and is zero for controls.

Read only.

A LayoutManager Object for a container (

window , panel , group

). The first time a container object is made visible,

ScriptUI invokes this layout manager by calling its layout function. Default is an instance of the

LayoutManager

class that is automatically created when the container element is created. margins 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 UI guidelines.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 224 orientation String spacing Number

How elements are organized within this container.

Interpreted by the layout manager for the container. The

default LayoutManager Object accepts the

(case-insensitive) values: row column stack

The default orientation depends on the type of container.

For

Window

and

Panel

, the default is column

, and for

Group the default is row

.

The allowed values for the container’s alignChildren

and its children’s alignment

properties depend on the orientation.

The number of pixels separating one child element from its adjacent sibling element. Because each container holds only a single row or column of children, only a single spacing value is needed for a container. The default value is based on the type of container, and is chosen to match standard Adobe UI guidelines.

Window object functions

These functions are defined for window

objects.

add

(type [, bounds, text,

{ creation_props> } ]); type

Creates and returns a new control or container object and adds it to the children of this window. Returns null

if unable to create the object.

The control type. See

Control types and creation parameters

.

bounds text creation_props

Optional. A bounds specification that describes the size and position of the

new control or container, relative to its parent. See Bounds

object for specification formats.

If supplied, this value creates a new

Bounds

object which is assigned to the new object’s bounds

property.

Optional. String. Initial text to be displayed in the control as the title, label, or contents, depending on the control type. If supplied, this value is assigned to the new object’s text property.

Optional. Object. The properties of this object specify creation parameters,

which are specific to each object type. See

Control types and creation parameters

.

center

windowObj.center ([window]) window

Centers this window on the screen, or with respect to another specified window.

Optional. A

Window Object

.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 225 close

windowObj.close ([result]) result

Closes this window. If an

onClose callback is defined for the

window, calls that function before closing the window.

Optional. A number to be returned from the show

method that invoked this window as a modal dialog.

hide

windowObj.hide() event

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.

For a modal dialog, closes the dialog and sets its result to 0. notify

windowObj.notify([event])

Sends a notification message, simulating the specified user interaction event. For example, to simulate a dialog being moved by a user: myDlg.notify("onMove")

Optional. The name of the window event handler to call. One of: onClose onMove onMoving onResize onResizing onShow remove

windowObj.remove(index)

windowObj.remove(text)

windowObj.remove(child) index text child

Removes the specified child control from this window’s array. No error results if the child does not exist. Returns children

The child control to remove, specified by 0-based index, text

value, or as a control object.

undefined .

show

windowObj.show()

Shows this window, container, or control. If an

onShow callback is defined for a

window, calls that function before showing the window.

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.

For a modal dialog, opens the dialog and does not return until the dialog is

dismissed. If it is dismissed via the close method, this method returns any

result

value passed to that method. Otherwise, returns 0.

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

object.

Callback onClose onMove

Description

Called when a request is made to close the window, either by an explicit call to the close

function or by a user action (clicking the OS-specific close icon in the title bar).

The function is called before the window actually closes; it can return false

to cancel the close operation.

Called when the window has been moved.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 226

Callback onMoving onResize onResizing onShow

Description

Called while a window in being moved, each time the position changes. A handler can monitor the move operation.

Called when the window has been resized.

Called while a window is being resized, each time the height or width changes. A handler can monitor the resize operation.

Called when a request is made to open the window using the

show

method, before the window is made visible, but after automatic layout is complete. A handler can modify the results of the automatic layout.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 227

Control Objects

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

(type [, bounds, text,

{ creation_props> } ]); type

Creates and returns a new control or container object and adds it to the children of this window or container. Returns null

if unable to create the object.

The control type. See

Control types and creation parameters

.

bounds text creation_props

Optional. A bounds specification that describes the size and position of the new control or container, relative to its parent. See

Bounds

object for specification formats.

If supplied, this value creates a new

Bounds

object which is assigned to the new object’s bounds

property.

Optional. String. Initial text to be displayed in the control as the title, label, or contents, depending on the control type. If supplied, this value is assigned to the new object’s text property.

Optional. Object. The properties of this object specify creation parameters, which are specific to each object type. See

Control types and creation parameters

.

Control types and creation parameters

The following type names 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 used in resource specifications to define controls within a window or panel.

Type name button checkbox

Class name

Button

Checkbox

Description

A pushbutton containing a text string. Calls the onClick callback if

the control is clicked or if its

notify method is called.

To add to a window w

: w.add (“button” [, bounds, text ]); bounds

: Optional. The control’s position and size. text

: Optional. The text displayed in the control.

A dual-state control showing a box with a checkmark when value=true

, empty when value=false

. Calls the onClick callback if

the control is clicked or if its

notify method is called.

To add to a window w

: w.add (“checkbox” [, bounds, text ]); bounds : Optional. The control’s position and size. text

: Optional. The text displayed in the control.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 228

Type name Class name dropdownlist DropDownList

Description

A drop-down list with zero or more items. Calls the onChange

callback if the item selection is changed or if its notify method is

called.

To add to a window w : w.add ("dropdown list", bounds [, items]

[, {creation_properties}]); bounds

: The control’s position and size. items : Optional. Supply this argument or the creation_properties

argument, not both. An array of strings for the text of each list item. An item

object is created for each item. An item with the text string

"-"

creates a separator item.

creation_properties : Optional. Supply this argument or the items

argument, not both. This form is most useful for

elements defined using Resource Specifications . An object

that contains the following property:

items : An array of strings for the text of each list item. An item object is created for each item. An item with the text string

"-"

creates a separator item.

edittext EditText An edit text field that the user can change. Calls the

onChange

callback if the text is changed and the user types E NTER or the control

loses focus, or if its notify

method is called. Calls the onChanging

callback when any change is made to the text. The textselection property contains currently selected text.

To add to a window w

: w.add (“edittext” [, 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:

multiline

: When false

(the default), the control accepts a single line of text. When true , the control accepts multiple lines, in which case the text wraps within the width of the control.

readonly

: When false

(the default), the control accepts text input. When true

, the control does not accept input but only displays the contents of the text property.

noecho

: When false

(the default), the control displays input text.

When true

, the control does not display input text (used for password input fields).

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 E NTER ).

When true , the control only signals an onChange event when the editable text is changed and the user types E

NTER

; other changes to the keyboard focus do not signal the event.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 229

Type name group iconbutton image item

Class name

Group

IconButton

Image

ListItem

Description

A container for other controls. Containers have additional properties that control the children; see

Container properties . 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]); bounds : Optional. The element’s position and size.

A pushbutton containing an icon. Calls the onClick callback if the

control is clicked or if its notify method is called.

To add to a window w

: w.add (“iconbutton” [, 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 button control, or a pathname or

File Object

for an image file. Images must be in PNG format.

creation_properties : Optional. An object that contains the following property:

style

: A string for the visual style, one of: button

: Has a visible border with a raised or 3D appearance.

toolbutton

: Has a flat appearance, appropriate for inclusion in a toolbar

Displays an icon or image.

To add to a window w

: w.add (“image” [, bounds, icon]); 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.

A choice item in a list box or drop-down list. The objects are created when items are specified on creation of the parent list object, or afterward using the list control’s

add method.

Items in a drop-down list can be of type separator

, in which case they cannot be selected, and are shown as a horizontal line.

Item objects have these properties which are not found in other controls:

index

selected

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 230

Type name listbox panel

Class name

ListBox

Panel

Description

A list box with zero or more items. Calls the

onChange

callback if the item selection is changed or if its

notify

method is called.

To add to a window w

: w.add ("listbox", bounds [, items,

{creation_properties}]); bounds : Optional. The control’s position and size. items

: Optional. An array of strings for the text of each list item.

An item

object is created for each item. Supply this argument, or the items

property in creation_properties

, not both.

creation_properties : Optional. An object that contains any of the following properties:

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. An item object is created for each item. An item with the text string

"-"

creates a separator item. Supply this property, or the items

argument, not both. This form is most useful for

elements defined using Resource Specifications .

A container for other types of controls, with an optional frame.

Containers have additional properties that control the children; see

Container properties . Hiding a panel hides all its children. Making it

visible makes visible those children that are not individually hidden.

To add to a window w

: w.add (“panel” [, bounds, text, {creation_properties} ]); bounds

: Optional. The element’s position and size. A panel whose width is 0 appears as a vertical line. A panel whose height is 0 appears as a horizontal line. text

: Optional. The text displayed in the border of the panel. creation_properties : Optional. An object that contains the following property:

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. Default is false

, meaning that the panel does not adjust the positions of its children, even if the parent window has automatic adjustment enabled.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 231

Type name Class name progressbar Progressbar radiobutton RadioButton

Description

A horizontal rectangle that shows progress of an operation. All progressbar

controls have a horizontal orientation. The value property contains the current position of the progress indicator; the default is 0. There is a minvalue

property, but it is always 0; attempts to set it to a different value are silently ignored.

To add to a window w

: w.add (“progressbar” [, bounds, value, maxvalue]); bounds

: Optional. The control’s position and size.

value

: Optional. The initial position of the progress indicator.

Default is 0.

maxvalue : Optional. The maximum value that the value property can be set to. Default is 100.

A dual-state control, grouped with other radiobuttons, of which only one can be in the selected state. Shows the selected state when value=true , empty when value=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. Only one radiobutton in a group can be set at a time; setting a different radiobutton

unsets the original one.

To add to a window w

: w.add (“radiobutton” [, bounds, text ]); bounds

: Optional. The control’s position and size. text

: Optional. The text displayed in the control.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 232

Type name scrollbar

Class name

Scrollbar

Description

A scrollbar with a draggable scroll indicator and stepper buttons to move the indicator. The scrollbar

control has a horizontal orientation if the width

is greater than the height

at creation time, or vertical if its height

is greater than its width

.

Calls the

onChange callback after the position of the indicator is

changed or if its notify

method is called. Calls the

onChanging

callback repeatedly while the user is moving the indicator.

The value

property contains the current position of the scrollbar’s indicator within the scrolling area, within the range of minvalue

and maxvalue .

The stepdelta

property determines the scrolling unit for the up or down arrow; default is 1.

The jumpdelta

property determines the scrolling unit for a jump (as when the bar is clicked outside the indicator or arrows); default is

20% of the range between minvalue

and maxvalue

.

To add to a window w : w.add (“scrollbar” [, bounds, value, minvalue, maxvalue]); 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. The maximum value that the value

property can be set to. Default is 100. Together with minvalue

, defines the scrolling range.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 233

Type name slider statictext

Class name

Slider

StaticText

Description

A slider with a moveable position indicator. All slider

controls have

a horizontal orientation. Calls the onChange callback after the

position of the indicator is changed or if its notify

method is called.

Calls the

onChanging

callback repeatedly while the user is moving the indicator.

The value

property contains the current position of the indicator within the range of minvalue

and maxvalue

.

To add to a window w

: w.add (“slider” [, bounds, value, minvalue, maxvalue]); bounds

: Optional. The control’s position and size.

value

: Optional. The initial position of the 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 range.

maxvalue : Optional. The maximum value that the value

property can be set to. Default is 100. Together with minvalue

, defines the range.

A text field that the user cannot change.

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:

multiline

: When false

(the default), the control displays a single line of text. When true

, the control displays multiple lines, in which case the text wraps within the width of the control.

scrolling

: When false

(the default), the displayed text cannot be scrolled. When true

, the displayed text can be vertically scrolled using the U P A RROW and D OWN A RROW ; this case implies multiline=true .

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 234

Control object properties

The following table shows the properties of all ScriptUI elements. Some values apply only to controls of particular types, as indicated.

active alignment

Boolean When false

otherwise. Set to true

to make a given control or dialog active.

● A modal dialog that is visible is by definition the active dialog.

● An active control is the one with focus—that is, the one that accepts keystrokes, or in the case of a

Button

, be selected when the user types a Return.

String Applies to child elements of a container. If defined, this value overrides the alignChildren setting for the parent container.

Allowed values depend on the orientation

value of the parent container. For orientation=row

: top bottom center (default) fill

For orientation=column

: left right center (default) fill

For orientation=stack : top bottom left right center (default) fill

Values are not case sensitive. bounds screen coordinates for window

elements, and parent-relative coordinates for child elements. For windows, the bounds refer only to the window's content region.

Setting an element's size

or location

changes its bounds property, and vice-versa. enabled helpTip String

When false

, control elements do not accept input, and all types of elements have a grayed-out appearance.

A brief help message (also called a tool tip) that is displayed in a small floating window when the mouse cursor hovers over a UI control element. Set to an empty string or null

to remove help text.

JavaScript Scripting Reference icon index items itemSize jumpdelta justify location maxvalue

Adobe Photoshop CS2

ScriptUI Object Reference 235

String or File

The name of an icon resource or the pathname or File Object for

a file that contains a platform-specific icon image in PNG format.

For an

IconButton

, the icon appears as the content of the button.

For a

ListItem

, the icon is displayed to the left of the text.

For an

Image

, the icon is the entire content of the image element.

Number For items collection of its parent list control. Read-only.

Array of Object For a list object ( listbox

or dropdown

list), a collection of

ListItem

objects for the items in the list. Access by 0-based index. To obtain the number of items in the list, use items.length

. Read-only.

Dimension For a list object ( listbox

or dropdown

list), a

Dimension

object describing the width and height in pixels of each item in the list.

Used by auto-layout to determine the preferredSize

of the list, if not otherwise specified.

If not set explicitly, the size of each item is set to match the largest height and width among all items in the list

Number

String

The amount to increment or decrement a scrollbar

indicator's position when the user clicks ahead or behind the moveable element. Default is 20% of the range between the maxvalue

and minvalue property values.

The justification of text in static text and edit text controls. One of: left (default) center right

Note: Justification only works if the value is set before the window containing the control is displayed for the first time.

Number 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.

By default, location is undefined .

The maximum value that the value

property can have.

If maxvalue is reset less than value , value is reset to maxvalue . If maxvalue

is reset less than minvalue

, minvalue

is reset to maxvalue

.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 236 minvalue parent preferredSize properties selected selection size stepdelta

Number

Object

The minimum value that the value

property can have.

If minvalue

is reset greater than value

, value

is reset to minvalue

.

If minvalue

is reset greater than maxvalue

, maxvalue

is reset to minvalue

.

The parent object of a UI object, a window , panel or group , or null for window

objects. Read only.

Dimension A

Dimension

object used by layout managers to determine the best size for each element. If not explicitly set by a script, value is established by the UI framework in which ScriptUI is employed, and is based on such attributes of the element as its text, font, font size, icon size, and other UI framework-specific attributes.

A script can explicitly set preferredSize

before the layout manager is invoked in order to establish an element size other than the default.

Object An object that contains one or more creation properties of the element (properties used only when the element is created).

Boolean For true

, the item is part of the selection

for its parent list. When false

, the item is not selected.

Set to true to select this item in a single-selection list, or to add it to the to the selection array for a multi-selection list.

ListItem, Array of

ListItem

For a list object ( listbox

or dropdown

list), the currently selected

ListItem

object for a single-selection list, or an array of

ListItem objects for 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.

You can set the value using the index of an item or an array of indices, rather than object references. If set to an index value that is out of range, the operation is ignored. When set with index values, the property still returns object references.

If you set the value to an array for a single-selection list, only the first item in the array is selected.

If you set the value to a single item for a multi-selection list, that item is added to the current selection.

If no items are selected, the value is null

. Set to null

to deselect all items.

Dimension A

object that defines the actual dimensions of an element. Initially undefined

, and unless explicitly set by a script, it is defined by a

LayoutManager

. A script can explicitly set size before the layout manager is invoked to establish an element size other than the preferredSize

or the default size.

Defined as [bounds.width, bounds.height] . Setting an element's size

changes its bounds

property, and vice-versa.

Number The amount by which to increment or decrement a

Scrollbar element's position when the user clicks a stepper button.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 237 text textselection type value value visible

String

String

String

Boolean

The title, label, or displayed text. Ignored for certain window types. For controls, the meaning depends on the control type.

Buttons use the text as a label, for example, while edit fields use the text

to access the content.

This is a localizable string: see Localization in ScriptUI Objects

The currently selected text in a control that displays text, or the empty string if there is no text selected.

Setting the value replaces the current text selection and modifies the value of the text

property. If there is no current selection, inserts the new value into the text

string at the current insertion point. The textselection value is reset to an empty string after it modifies the text

value.

Note: Setting the textselection property before the edittext control’s parent

Window

exists is an undefined operation.

Contains the type name of the element, as specified on creation.

For window

objects, one of the type names window

or dialog

.

● For controls, the type of the control, as specified in the add method that created it.

Read only.

For a checkbox or radiobutton, true

if the control is in the selected or set state, false

if it is not.

Number For a scrollbar or slider, the current position of the indicator. If set to a value outside the range specified by minvalue and maxvalue , it is automatically reset to the closest boundary.

Boolean 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.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 238

Control object functions

The following table shows the methods defined for each element type, and for specific control types as indicated. add

listObj.add

(type, text[, index]) type text

For list objects ( listbox

or dropdown

list) only. Adds an item to the items

array at the given index. Returns the item

control object for type=item

, or null

for type=separator

.

The type of item to add. One of: item

: A basic, selectable item with a text label.

separator

: A separator. For dropdownlist

controls only. In this case, the text value is ignored, and the method returns null .

The localizable text label for the item. index Optional. The index into the current item list after which this item is inserted. If not supplied, or greater than the current list length, the new item is added at the end.

find

listObj.find(text)

For list objects ( listbox or dropdown list) only. Looks in this object’s items

array for an item

object with the given text

value. Returns the item

object if found; otherwise, returns null

.

text hide

controlObj.hide()

The text of the item to find.

Hides 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.

notify

controlObj.notify([event]) event

Sends a notification message, simulating the specified user interaction event.

Optional. The name of the control event handler to call. One of: onClick onChange onChanging

By default, simulates the onChange event for an edittext control, an onClick event for controls that support that event.

remove

containerObj.remove(index)

containerObj.remove(text)

containerObj.remove(child) index text child

For containers ( panel

, group

), removes the specified child control from the container’s children

array.

For list objects ( listbox

or dropdown

list) only, removes the specified item from this object’s items

array. No error results if the item does not exist.

The item or child to remove, specified by 0-based index, text

value, or as a control object.

removeAll

listObj.removeAll() show

controlObj.show()

For list objects ( listbox

or dropdown

list) only. Removes all items from the object’s items array.

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.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 239 toString

listItemObj.toString() valueOf

listItemObj.valueOf()

For item

controls only. Returns the value of this item’s text

property as a string.

For item

controls only. Returns the index number of this item in the parent list’s items

array.

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.

onClick onChange onChanging

Called when the user clicks one of the following control types: button checkbox iconbutton radiobutton

Called when the user finishes making a change in one of the following control types:

● dropdownlist edittext listbox scrollbar slider

For an edittext control, called only when the change is complete—that is, when focus moves to another control, or the user types E

NTER

. The exact behavior depends on the creation parameter enterKeySignalsOnChange

; see the edittext description.

For a slider

or scrollbar

, called when the user has finished dragging the position marker or has clicked the control.

Called for each incremental change in one of the following control types:

● edittext scrollbar slider

For an edittext

control, called for each keypress while the control has focus.

For a slider

or scrollbar

, called for any motion of the position marker.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 240

Size and Location Objects

ScriptUI defines objects to represent the complex values of properties that place and size windows and UI elements. These objects cannot be created directly, but are created when you set the corresponding property. That property then returns that object. For example, the bounds

property returns a

Bounds

object.

You can set these properties as objects, strings, or arrays.

● e.prop = Object

: The object must contain the set of properties defined for this type, as shown in the table below. The properties have integer values.

● e.prop = String

: The string must be an executable JavaScript inline object declaration, conforming to the same object description. e.prop = Array

: The array must have integer coordinate values in the order defined for this type, as shown in the table below. For example:

The following examples show equivalent ways of placing a 380 by 390 pixel window near the upper left corner of the screen: var dlg = new Window('dialog', 'Alert Box Builder'); dlg.bounds = {x:100, y:100, width:380, height:390}; //object dlg.bounds = {left:100, top:100, right:480, bottom:490}; //object dlg.bounds = "x:100, y:100, width:380, height:390"; //string dlg.bounds = "left:100, top:100, right:480, bottom:490"; //string dlg.bounds = [100,100,480,490]; //array

You can access the resulting object as an array with values in the order defined for the type, or as an object with the properties supported for the type.

The following table shows the property-value object types, the element properties that create and contain them, and their array and object-property formats.

Bounds

Dimension

Defines the boundaries of a window within the screen’s coordinate space, or of a UI 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.

An object must contain properties named left , top , right , bottom , or x , y , width

, height

.

An array must have values in the order [left, top, right, bottom] .

Defines the size of a window

or UI element. Contains an array,

[width, height]

, that defines the element’s size in pixels.

A

Dimension

object is created when you set an element’s size

or preferredSize property.

An object must contain properties named width

and height

.

● An array must have values in the order [width, height] .

JavaScript Scripting Reference

Margins

Point

Adobe Photoshop CS2

ScriptUI Object Reference 241

Defines the number of pixels between the edges of a container and its outermost child elements. Contains an array

[left, top, right, bottom]

whose elements define the margins between the left edge of a container and its leftmost child element, and so on.

A Margins object is created when you set an element’s margins property.

An object must contain properties named left

, top

, right

, and bottom

.

An array must have values in the order

[left, top, right, bottom]

.

You can also set the margins

property to a number; all of the array values are then set to this number.

Defines the location of a window

or UI element. Contains an array,

[x, y]

, whose values represent the origin point of the element as horizontal and vertical pixel offsets from the origin of the element's coordinate space.

A Point object is created when you set an element’s location property.

● An object must contain properties named x

and y

.

An array must have values in the order

[x, y]

.

Adobe Photoshop CS2

JavaScript Scripting Reference ScriptUI Object Reference 242

LayoutManager Object

Controls the automatic layout behavior for a window or container. The subclass AutoLayoutManager implements the default automatic layout behavor.

AutoLayoutManager object constructor

Create an instance of the AutoLayoutManager class with the new operator: myWin.layout = new AutoLayoutManager(myWin);

An instance is automatically created when you create a window

or container ( group

or panel

) object, and

referenced by the container’s layout

property. This instance implements the default layout behavior unless you override it.

AutoLayoutManager object properties

The default object has no predefined properties, but a script can assign arbitrary properties to an object it creates, to store data needed by the script-defined layout algorithm.

AutoLayoutManager object functions layout

win.layout.layout

(recalculate) recalculate

Invokes the automatic layout behavior for the managed container. Adjusts sizes and positions of the child elements of this window or container according to the placement and alignment property values in the parent and children.

Invoked automatically the first time the window is displayed. Thereafter, the script must invoke it explicitly to change the layout in case of changes in the size or position of the parent or children.

Optional. When true

, forces the layout manager to recalculate the container size for this and any child containers. Default is false

.

These tables list unique identifiers for the top-level menus in Adobe Bridge

6

Using File and Folder Objects

Overview

Because path name syntax is very different in Windows, Mac OS and UNIX ® , Adobe ExendScript defines the

File

and

Folder

objects to provide platform-independent access to the underlying file system. A

File

Object

represents a disk file, a Folder Object represents a directory or folder.

The

Folder

object supports file system functionality such as traversing the hierarchy; creating, renaming or removing files; or resolving file aliases.

The

File

object supports input/output functions to read or write files.

There are several ways to distinguish between a

File

and a

Folder

object. For example: if (f instanceof File) ...

if (typeof f.open == "undefined") ...// Folders do not open

File

and

Folder

objects can be used anywhere that a path name is required, such as in properties and arguments for files and folders. For details about the objects and their properties and methods, see

Chapter 7, “File and Folder Object Reference

."

Note: When you create two

File

objects that refer to the same disk file, they are treated as distinct objects. If you open one of them for I/O, the operating system may inhibit access from the other object, because the disk file already is open.

Specifying Paths

When creating a

File

or

Folder

object, you can specify a platform-specific path name, or an absolute or relative path in a platform-independent format known as universal resource identifier (URI) notation. The path stored in the object is always an absolute, full path name that points to a fixed location on the disk.

Use the toString

method to obtain the name of the file or folder as string containing an absolute path name in URI notation.

Use the

fsName

property to obtain the platform-specific file name.

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.jsx

A relative path name in URI notation is appended to the path of the current directory, as stored in the

globally-available current property of the

Folder

class. It starts with a folder or file name, or with one of the special names dot (

.

) for the current directory, or dot dot (

..

) for the parent of the current directory. A

243

Adobe Photoshop CS2

JavaScript Scripting Reference Using File and Folder Objects 244 slash (

/

) separates path elements. For example, the following paths describe various relative locations for the file myFile.jsx

: myFile.jsx

./myFile.jsx

In the current directory.

../myFile.jsx

../../myFile.jsx

In the parent of the current directory.

In the grandparent of the current directory.

../dir1/myFile.jsx

In dir1

, which is parallel to the current directory.

Relative path names are independent of different volume names on different machines and operating systems, and therefore make your code considerably more portable. You can, for example, use an absolute path for a single operation, to set the current directory in the

Folder.current

property, and use relative paths for all other operations. You would then need only a single code change to update to a new platform or file location.

Character interpretation in paths

There are some platform differences in how pathnames are interpreted:

● In Windows and Mac OS, path names are not case sensitive. In UNIX, paths are case sensitive.

In Windows, both the slash (

/

) and the backslash (

\

) are valid path element separators.

In Mac OS, both the slash (

/

) and the colon (

:

) are valid path element separators.

If a path name starts with two slashes (or backslashes in Windows), the first element refers to a remote server. For example,

//myhost/mydir/myfile

refers to the path

/mydir/myfile

on the server myhost

.

URI notation allows special characters in pathnames, but they must specified with an escape character ( % ) followed by a hexadecimal character code. Special characters are those which are not alphanumeric and not one of the characters:

/ - — . ! ~ * ' ( )

A space, for example, is encoded as

%20

, so the file name

"my file"

is specified as

"my%20file"

. Similarly, the character ä is encoded as %E4 , so the file name "Bräun" is specified as "Br%E4un" .

This encoding scheme is compatible with the global JavaScript functions encodeURI

and decodeURI

.

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. In Mac OS, the default home directory is

/Users/ username . In UNIX, it is typically

/home/ username or

/users/ username .

Extend Script assigns the home directory value directly from the platform value.

In Windows, the

HOME

environment variable is optional. If it is assigned, its value must be a Windows path name or a path name referring to a remote server (such as

\\myhost\mydir

). If the

HOME

environment variable is undefined, the Extend Script default is the user's home directory, usually the

C:\Documents and Settings\ username folder.

Adobe Photoshop CS2

JavaScript Scripting Reference Using File and Folder Objects 245

Note: A script can access many of the folders that are specified with platform-specific variables through static, globally-available

Folder class properties ; for instance, appData contains the folder that

stores application data for all users.

Volume and drive names

A volume or drive name can be the first part of an absolute path in URI notation. The values are interpreted according to the platform.

Mac OS volumes

When Mac OS X starts, the startup volume is the root directory of the file system. All other volumes, including remote volumes, are part of the /Volumes directory. The File and Folder objects use these rules to interpret the first element of a path name:

If the name is the name of the startup volume, discard it.

If the name is a volume name, prepend

/Volumes

.

Otherwise, leave the path as is.

Mac OS 9 is not supported as an operating system, but the use of the colon as a path separator is still supported and corresponds to URI and to Mac OS X paths as shown in the following table. These examples assume that the startup volume is

MacOSX

, and that there is a mounted volume

Remote

.

URI path name

/MacOSX/dir/file

/Remote/dir/file

/root/dir/file

~/dir/file

Mac OS 9 path name Mac OS X path name

MacOSX:dir:file

Remote:dir:file

/dir/file

/Volumes/Remote/dir/file

Root:dir:file /root/dir/file

/Users/jdoe/dir/file

Windows drives

In Windows, volume names correspond to drive letters. The URI path

/c/temp/file

normally translates to the Windows path C:\temp\file .

If a drive exists with a name matching the first part of the path, that part is always interpreted as that drive.

It is possible for there to be a folder in the root that has the same name as the drive; imagine, for example, a folder

C:\C

in 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. That is, if there is a folder

D:\C

, and if the current drive is

D:

, the URI path

/c/temp/file

translates to the Windows path

D:\c\temp\file

. In this case, to access drive C, you would have to use the Windows path name conventions.

To access a remote volume, use a uniform naming convention (UNC) path name of the form

// servername / sharename . These path names are portable, because both Max OS X and UNIX ignore multiple slash characters. Note that in Windows, UNC names do not work for local volumes.

These examples assume that the current drive is D:

Adobe Photoshop CS2

JavaScript Scripting Reference Using File and Folder Objects 246

URI path name

/c/dir/file

/remote/dir/file

/root/dir/file

~/dir/file

Windows path name c:\dir\file

D:\remote\dir\file

D:\root\dir\file

C:\Documents and Settings\jdoe\dir\file

Aliases

When you access an alias, the operation is transparently forwarded to the real file. The only operations that affect the alias are calls to rename

and remove

, and setting properties readonly

and hidden

. When a

File object represents an alias, the alias

property of the object returns true

, and the resolve

method returns the File or Folder object for the target of the alias.

In Windows, all file system aliases (called shortcuts) are actual files whose names end with the extension

.lnk

. Never use this extension directly; the

File

and

Folder

objects work without it.

For example, suppose there is a shortcut to the file

/folder1/some.txt

in the folder

/folder2

. The full

Windows file name of the shortcut file is \folder2\some.txt.lnk

.

To access the shortcut from a

File

object, specify the path

/folder2/some.txt

. Calling that

File

object’s open

method opens the linked file (in

/folder1

). Calling the

File

object’s rename

method renames the shortcut file itself (leaving the

.lnk

extension intact).

However, Windows permits a file and its shortcut to reside in the same folder. In this case, the File object always accesses the original file. You cannot create a

File

object to access the shortcut when it is in the same folder as its linked file.

A script can create a file alias by creating a

File

object for a file that does not yet exist on disk, and using its

createAlias method to specify the target of the alias.

Portability issues

If your application will run on multiple platforms, use relative path names, or try to originate path names from the home directory. If that is not possible, work with Mac OS X and UNIX aliases, and store your files on a machine that is remote to your Windows machine so that you can use UNC names.

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. By default, this conversion process assumes that the system encoding is used (code page 1252 in Windows or Mac Roman in Mac OS). The encoding

property of a

File

object returns the current encoding. You can set the encoding

property to the name of the desired encoding. The

File

object looks for the corresponding encoder in the operating system to use for subsequent I/O. The name is one of the standard Internet names that are used to describe the encoding of HTML files, such as ASCII , X-SJIS , or ISO-8859-1 . For a complete list, see

File and Folder Supported Encoding Names

.

Adobe Photoshop CS2

JavaScript Scripting Reference Using File and Folder Objects 247

A special encoder,

BINARY

, is provided for binary I/O. This encoder simply extends every 8-bit character it finds to a Unicode character between 0 and 255. When using this encoder to write binary files, the encoder writes the lower 8 bits of the Unicode character. For example, to write the Unicode character 1000 , which is

0x3E8, the encoder actually writes the character 232 (0xE8).

The data of some of the common file formats (UCS-2, UCS-4, UTF-8, UTF-16) starts with a special byte order mark (BOM) character (

\uFEFF

). The

File.open

method reads a few bytes of a file looking for this character. If it is found, the corresponding encoding is set automatically and the character is skipped. If there is no BOM character at the beginning of the file, open()

reads the first 2 KB of the file and checks whether the data might be valid UTF-8 encoded data, and if so, sets the encoding to UTF-8.

To write 16-bit Unicode files in UTF-16 format, use the encoding UCS-2. This encoding uses whatever byte-order format the host platform supports.

When using UTF-8 encoding or 16-bit Unicode, always write the BOM character "

\uFEFF

" as the first character of the file.

File Error Handling

Each object has an error

property. If accessing a property or calling a method causes an error, this property contains a message describing the type of the error. On success, the property contains the empty string. You can set the property, but setting it only causes the error message to be cleared. If a file is open, assigning an arbitrary value to the property also resets its error flag.

For a complete list of supported error messages, see File and Folder Error Messages

.

7

File and Folder Object Reference

Overview

Because path name syntax is very different in Windows, Mac OS and UNIX, the File and Folder objects are defined to provide platform-independent access to the underlying file system. A File object is associated with a disk file, a Folder object with a directory or folder.

The Folder object supports file-system functionality such as traversing the hierarchy, creating, renaming or removing files, or resolving file aliases.

The File object supports I/O functions to read or write files.

File and Folder objects can be used anywhere a path name is required, such as in properties and arguments for files and folders.

For a description of the pathname syntax and object usage, see

Chapter 6, “Using File and Folder Objects

."

This chapter provides detail about the classes and objects, their properties and methods, and the supported encoding names:

File Object

Folder Object

File and Folder Error Messages

File and Folder Supported Encoding Names

File Object

Represents a file in the local file system in an platform-independent manner. All properties and methods resolve file system aliases automatically and act on the original file unless otherwise noted.

File object constructors

To create a File object, use the File function or the new operator. The constructor accepts full or partial path names, and returns the new object. The CRLF sequence for the file is preset to the system default, and the encoding is preset to the default system encoding.

File ([path]); //can return a Folder object new File ([path]); //always returns a File object path Optional. The absolute or relative path to the file associated with this object, specified in platform-specific or URI format; see

Specifying Paths

. The value stored in the object is the absolute path.

The path need not refer to an existing file. If not supplied, a temporary name is generated.

If the path refers to an existing folder:

The

File

function returns a

Folder

object instead of a

File

object.

The new

operator returns a

File

object for a nonexisting file with the same name.

248

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 249

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 (what) what encode

File.encode (what) what

Decodes the specified string as required by RFC 2396 and returns the decoded string.

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

".

Special characters are those with a numeric value greater than 127, except the following:

/ - _ . ! ~ * ' ( )

Encodes the specified string as required by RFC 2396 and returns the encoded string.

All special characters are encoded in UTF-8 and stored as escaped characters starting with the percent sign followed by two hexadecimal digits. For example, the string " my file " is encoded as " my%20file

".

Special characters are those with a numeric value greater than

127, except the following:

/ - _ . ! ~ * ' ( )

String. The string to encode. isEncodingAvailable

File.isEncodingAvailable (name) name

Returns true

if your system supports the specified encoding, false

otherwise.

String. The encoding name.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 250 openDialog

File.openDialog

([prompt][,select]) prompt select

Opens the built-in platform-specific file-browsing dialog in which a user can select an existing file to open.

If the user clicks OK, returns a

File

object for the selected file.

If the user cancels, returns null

.

Optional. A string containing the prompt text, if the dialog allows a prompt.

Optional. A file or files to be preselected when the dialog opens:

● In Windows, a string containing a comma-separated list of file types with descriptive text, to be displayed in the bottom of the dialog as a drop-down list from which the user can select which types of files to display.

Each element starts with the descriptive text, followed by a colon and the file search masks for this text, separated by semicolons. For example, to display two choices, one labeled Text Files that allows selection of text files with extensions .TXT

and .DOC

, and the other labeled All files that allows selection of all files:

Text Files:*.TXT;*.DOC,All files:*

In Mac OS, a string containing the name of a function defined in the current

JavaScript scope that takes a

File

object argument. The function is called for each file about to be displayed in the dialog, and the file is displayed only when the function returns true

. saveDialog

File.saveDialog

([prompt][,select]) prompt

Opens the built-in platform-specific file-browsing dialog in which a user can select an existing file location to which to save this file.

If the user clicks OK, returns a

File

object for the selected file, and overwrites the existing file. If the user cancels, returns null

.

Optional. A string containing the prompt text, if the dialog allows a prompt.

select Optional. A file or files to be preselected when the dialog opens:

In Windows, a string containing a comma-separated list of file types with descriptive text, to be displayed in the bottom of the dialog as a drop-down list from which the user can select which types of files to display.

Each element starts with the descriptive text, followed by a colon and the file search masks for this text, separated by semicolons. For example, to display two choices, one labeled Text Files that allows selection of text files with extensions

.TXT

and

.DOC

, and the other labeled All files that allows selection of all files:

Text Files:*.TXT;*.DOC,All files:*

In Mac OS, a string containing the name of a function defined in the current

JavaScript scope that takes a

File

object argument. The function is called for each file about to be displayed in the dialog, and the file is displayed only when the function returns true

.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 251

File object properties

These properties are available for File objects.

absoluteURI alias created creator encoding eof error exists fsName hidden length lineFeed modified name parent

String

Boolean

Date

String

String

Boolean

String

Boolean

String

Boolean

Number

String

Date

String

Folder

The full path name for the referenced file in URI notation. Read-only.

When true , the object refers to a file system alias or shortcut.

Read-only.

The creation date of the referenced file, or null

if the object does not refer to a file on disk. Read-only.

The Mac OS file creator as a four-character string. In Windows or UNIX, value is

"????"

. Read-only.

Gets or sets the encoding for subsequent read/write operations. One of the encoding constants listed in

File and Folder Supported

Encoding Names

. 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.

When writing, the lower byte of each Unicode character is treated as a single byte to write.

When true , a read attempt caused the current position to be beyond the end of the file, or the file is not open. Read only.

A message describing the last file system error; see File and Folder

Error Messages . Setting this value clears any error message and resets

the error bit for opened files.

When true

, the path name of this object refers to an existing file. Read only.

The platform-specific name of the referenced file as a full path name.

Read-only.

When true

, the file is not shown in the platform-specific file browser.

Read/write. If the object references a file-system alias or shortcut, the flag is altered on the alias, not on the original file.

The size of the file in bytes. Can be set only for a file that is not open, in which case it truncates or pads the file with 0-bytes to the new length.

How line feed characters are written. One of: windows

: Windows style mac

: Mac OS style unix

: UNIX style

The date of the referenced file’s last modification, or null if the object does not refer to a file on disk. Read-only.

The name of the referenced file without the path specification.

Read-only.

The Folder object for the folder that contains this file. Read-only.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 252 path readonly relativeURI String type

String

Boolean

String

The path portion of the absolute URI, or the empty string If the name does not have a path. Read-only.

When true

, prevents the file from being altered or deleted. If the referenced file is a file-system alias or shortcut, the flag is altered on the alias, not on the original file.

The path name for the referenced file in URI notation, relative to the current folder. Read-only.

The Mac OS file type as a four-character string. In Windows and UNIX, the value is

"????"

. Read-only.

File object functions

These functions are available for File objects.

close

fileObj.close () copy

fileObj.copy (target)

Closes this open file. Returns true on success, false if there are I/O errors.

Copies this object’s referenced file to the specified target location.

Resolves any aliases to find the source file. If a file exists at the target location, it is overwritten. Returns true if the copy was successful, false

otherwise. target A string with the URI path to the target location, or a

File

object that references the target location.

createAlias

fileObj.createAlias

(toFile, [isFinderAlias])

Makes this file into a file-system alias or shortcut to the specified file.

The referenced file for this object must exist on disk. Returns true

if the operation was successful, false

otherwise. toFile The

File

object for the target of the new alias.

isFinderAlias execute

fileObj.execute ()

Optional, Mac OS only. When true

, the alias is created as a legacy Finder alias. When false (the default), the alias is created as a Unix symlink.

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

Returns a string containing the URI for this file or folder relative to the specified base path, in URI notation. If no base path is supplied, returns the URI relative to the path of the current folder.

Optional. A string containing the base path for the relative URI. Default is the current folder.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 253 open

fileObj.open

(mode[,type][,creator]) mode

Open the file for subsequent read/write operations. The method resolves any aliases to find the file. Returns true

if the file has been opened successfully, false otherwise.

The method attempts to detect the encoding of the open file. It reads a few bytes at the current location and tries to detect the Byte Order

Mark character

0xFFFE

. If found, the current position is advanced behind the detected character and the encoding property is set to one of the strings

UCS-2BE

,

UCS-2LE

,

UCS4-BE

,

UCS-4LE

, or

UTF-8

. If the marker character is not found, it checks for zero bytes at the current location and makes an assumption about one of the above formats

(except UTF-8). If everything fails, the encoding

property is set to the system encoding.

Note: Be careful about opening a file more than once. The operating system usually permits you to do so, but if you start writing to the file using two different File objects, you can destroy your data.

A string indicating the read/write mode. One of: r

: (read) Opens for reading. If the file does not exist or cannot be found, the call fails.

w

: (write) Opens a file for writing. If the file exists, its contents are destroyed. If the file does not exist, creates a new, empty file.

e

: (edit) Opens an existing file for reading and writing.

type creator

Optional. In Mac OS, the type of a newly created file, a 4-character string. Ignored in

Windows and UNIX.

Optional. In Mac OS, the creator of a newly created file, a 4-character string. Ignored in Windows and UNIX.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 254 openDlg

fileObj.OpenDlg

([prompt][,select]) prompt

Opens the built-in platform-specific file-browsing dialog, in which the user can select an existing file to open. If the user clicks OK, returns a

File or Folder object for the selected file or folder. If the user cancels, returns null

.

Differs from the class method openDialog() in that it presets the current folder to this

File

object’s parent folder and the current file to this object’s associated file.

Optional. A string containing the prompt text, if the dialog allows a prompt.

select Optional. A file or files to be preselected when the dialog opens:

In Windows, a string containing a comma-separated list of file types with descriptive text, to be displayed in the bottom of the dialog as a drop-down list from which the user can select which types of files to display.

Each element starts with the descriptive text, followed by a colon and the file search masks for this text, separated by semicolons. For example, to display two choices, one labeled Text Files that allows selection of text files with extensions

.TXT

and

.DOC

, and the other labeled All files that allows selection of all files:

Text Files:*.TXT;*.DOC,All files:*

In Mac OS, a string containing the name of a function defined in the current

JavaScript scope that takes a

File

object argument. The function is called for each file about to be displayed in the dialog, and the file is displayed only when the function returns true

. read

fileObj.read ([chars]) chars

Reads the contents of the file starting at the current position, and returns a string that contains up to the specified number of characters.

Optional. An integer specifying the number of characters to read. By default, reads from the current position to the end of the file. If the file is encoded, multiple bytes might be read to create single Unicode characters.

readch

fileObj.readch () readln

fileObj.readln () remove

fileObj.remove ()

Reads a single text character from the file at the current position, and returns it in a string. Line feeds are recognized as

CR

,

LF

,

CRLF

, or

LFCR pairs. If the file is encoded, multiple bytes might be read to create single Unicode characters.

Reads a single line of text from the file at the current position, and returns it in a string. Line feeds are recognized as

CR

,

LF

,

CRLF

, or

LFCR pairs. If the file is encoded, multiple bytes might be read to create single Unicode characters.

Deletes the file associated with this object from disk, immediately, without moving it to the system trash. Returns true

if the file is deleted successfully.

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.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 255 rename

fileObj.rename (newName) newName

Renames the associated file. Returns true

on success.

Does not resolve aliases, but renames the referenced alias or shortcut file itself.

The new file or folder name, with no path.

resolve

fileObj.resolve ()

If this object references an alias or shortcut, this method resolves that alias and returns a new

File

object that references the file-system element to which the alias resolves.

Returns null

if this object does not reference an alias, or if the alias cannot be resolved.

saveDlg

fileObj.saveDlg

([prompt][,preset]) prompt

Opens the built-in platform-specific file-browsing dialog, in which the user can select an existing file location at which to save this file. If the user clicks OK, returns a

File

or

Folder

object for the selected file or folder. If the user cancels, returns null

.

Differs from the class method saveDialog()

in that it presets the current folder to this

File

object’s parent folder and the file to this object’s associated file, and prompts the user to confirm before overwriting an existing file.

Optional. A string containing the prompt text, if the dialog allows a prompt.

preset Optional. A file or files to be preselected when the dialog opens:

In Windows, a string containing a comma-separated list of file types with descriptive text, to be displayed in the bottom of the dialog as a drop-down list from which the user can select which types of files to display.

Each element starts with the descriptive text, followed by a colon and the file search masks for this text, separated by semicolons. For example, to display two choices, one labeled Text Files that allows selection of text files with extensions

.TXT

and

.DOC

, and the other labeled All files that allows selection of all files:

Text Files:*.TXT;*.DOC,All files:*

In Mac OS, a string containing the name of a function defined in the current

JavaScript scope that takes a

File

object argument. The function is called for each file about to be displayed in the dialog, and the file is displayed only when the function returns true

. seek

fileObj.seek (pos, mode) pos

Seeks to the specified position in the file, and returns true

if the position was changed. The new position cannot be less than 0 or greater than the current file size.

The new current position in the file as an offset in bytes from the start, current position, or end, depending on the mode

. mode tell

fileObj.tell ()

The seek mode, one of:

0: Seek to absolute position, where pos=0

is the first byte of the file.

1: Seek relative to the current position.

2. Seek backward from the end of the file.

Returns the current position as a byte offset from the start of the file.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 256 write

fileObj.write

(text[, text...]...) text

Writes the specified text to the file at the current position. Returns true

on success.

For encoded files, writing a single Unicode character may write multiple bytes.

Note: Be careful not to write to a file that is open in another application or object, as this can overwrite existing data. text One or more strings to write, which are concatenated to form a single string.

writeln

fileObj.writeln

(text[, text...]...)

Writes the specified text to the file at the current position, and appends a Line Feed sequence in the style specified by the linefeed property. Returns true

on success.

For encoded files, writing a single Unicode character may write multiple bytes.

Note: Be careful not to write to a file that is open in another application or object, as this can overwrite existing data.

One or more strings to write, which are concatenated to form a single string.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 257

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.

Folder ([path]); //can return a File object new Folder ([path]); //always returns a Folder object path Optional. The absolute or relative path to the folder associated with this object, specified in

URI format; see

Specifying Paths . The value stored in the object is the absolute path.

The path need not refer to an existing folder. If not supplied, a temporary name is generated.

If the path refers to an existing file:

The

Folder

function returns a

File

object instead of a

Folder

object.

The new

operator returns a

Folder

object for a nonexisting folder with the same name.

Folder class properties

These properties are available as static properties of the Folder class. It is not necessary to create an instance to access them.

appData commonFiles current fs myDocuments startup

Folder

Folder

Folder

String

Folder

A Folder object for the folder that contains application data for all users.

Read-only.

In Windows, the value of %APPDATA% (by default, C:\Documents and

Settings\All Users\Application Data

)

In Mac OS, /Library/Application Support

A

Folder

object for the folder that contains files common to all programs. Read-only.

In Windows, the value of

%CommonProgramFiles%

(by default,

C:\Program Files\Common Files

)

In Mac OS,

/Library/Application Support

A

Folder

object for the current folder. Assign either a

Folder

object or a string containing the new path name to set the current folder.

The name of the file system. Read-only. One of Windows , Macintosh , or

Unix

.

Folder

object for the default document folder. Read-only.

In Windows,

C:\Documents and Settings\username\My Documents

● In Mac OS, ~/Documents

A

Folder

object for the folder containing the executable image of the running application. Read-only.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 258 system temp trash userData

Folder

Folder

Folder

Folder

A

Folder

object for the folder containing the operating system files.

Read-only.

In Windows, the value of

%windir%

(by default,

C:\Windows

)

In Mac OS,

/System

A

Folder

object for the default folder for temporary files. Read-only.

A

Folder

object for the folder containing deleted items. Read-only.

A Folder object for the folder that contains application data for the current user. Read-only.

In Windows, the value of %APPDATA% (by default, C:\Documents and

Settings\username\Application Data

)

In Mac OS, ~/Library/Application Support

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 (what) what

Decodes the specified string as required by RFC 2396 and returns the decoded string.

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

".

Special characters are those with a numeric value greater than 127, except the following:

/ - _ . ! ~ * ' ( ) encode

Folder.encode (what) what

Encodes the specified string as required by RFC 2396 and returns the encoded string.

All special characters are encoded in UTF-8 and stored as escaped characters starting with the percent sign followed by two hexadecimal digits. For example, the string " my file " is encoded as " my%20file

".

Special characters are those with a numeric value greater than

127, except the following:

/ - _ . ! ~ * ' ( )

String. The string to encode. isEncodingAvailable

File.isEncodingAvailable (name) name

Returns true

if your system supports the specified encoding, false

otherwise.

String. The encoding name.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 259 selectDialog

Folder.selectDialog

([prompt][,preset]) prompt

Opens the built-in platform-specific file-browsing dialog. If the user clicks OK, returns a

Folder

object for the selected folder. If the user cancels, returns null .

Differs from the object method selectDlg()

in that it does not preselect a folder.

Optional. A string containing the prompt text, if the dialog allows a prompt.

preset Optional. A

Folder

object for a folder to be preselected when the dialog opens.

Folder object properties

These properties are available for Folder objects.

absoluteURI alias created error exists fsName modified name parent path relativeURI

String

Boolean

Date

String

Boolean

String

Date

String

Folder

String

String

The full path name for the referenced folder in URI notation. Read-only.

When true

, the object refers to a file system alias or shortcut.

Read-only.

The creation date of the referenced folder, or null

if the object does not refer to a folder on disk. Read-only.

A message describing the last file system error; see File and Folder

Error Messages . Setting this value clears any error message and resets

the error bit for opened folders.

When true , the path name of this object refers to an existing folder.

Read only.

The platform-specific name of the referenced folder as a full path name. Read-only.

The date of the referenced folder's last modification, or null if the object does not refer to a folder on disk. Read-only.

The name of the referenced folder without the path specification.

Read-only.

The Folder object for the folder that contains this folder, or null if this object refers to the root folder of a volume. Read-only.

The path portion of the absolute URI, or the empty string If the name does not have a path. Read-only.

The path name for the referenced folder in URI notation, relative to the current folder. Read-only.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 260

Folder object functions

These functions are available for Folder objects.

create

folderObj.create () execute

folderObj.execute () getFiles

folderObj.getFiles ([mask])

Creates a folder at the location to which the path name points.

Returns true

if the folder was created successfully.

Opens this folder in the file browser (as if it had been double-clicked in a file browser). Returns true

immediately if the folder was opened successfully.

Returns an array of File and Folder objects for the contents of this folder, filtered by the supplied mask

, or null

if this object’s referenced folder does not exist.

mask Optional. A search mask for file names. A string that can contain question mark (

?

) and asterisk ( * ) wild cards. Default is "*" , which matches all file names.

Can also be the name of a function that takes a

File

or

Folder

object as its argument. It is called for each file or folder found in the search; if it returns true , the object is added to the return array.

Note: In Windows, all aliases end with the extension .lnk

, which is stripped from the file name when found to preserve compatibility with other operating systems. You can search for all aliases by supplying the search mask

"*.lnk"

, but note that such code is not portable.

getRelativeURI

folderObj.getRelativeURI

([basePath])

Returns a string containing the URI for this folder relative to the specified base path, in URI notation. If no base path is supplied, returns the URI relative to the path of the current folder.

basePath Optional. A string containing the base path for the relative URI. Default is the current folder.

remove

folderObj.remove ()

Deletes the empty folder associated with this object from disk, immediately, without moving it to the system trash. Returns true

if the folder is deleted successfully.

Folders must be empty before they can be deleted.

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.

rename

folderObj.rename (newName)

Renames the associated folder. Returns true

on success.

Does not resolve aliases; instead, renames the referenced alias or shortcut file itself.

newName The new folder name, with no path.

resolve

folderObj.resolve ()

If this object references an alias or shortcut, this method resolves that alias and returns a new

Folder

object that references the file-system element to which the alias resolves.

Returns null

if this object does not reference an alias, or if the alias cannot be resolved.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 261 selectDlg

folderObj.selectDlg

([prompt][,preset]) prompt

Opens the built-in platform-specific file-browsing dialog. If the user clicks OK, returns a

File

or

Folder

object for the selected file or folder. If the user cancels, returns null .

Differs from the class method selectDialog()

in that it preselects this folder.

Optional. A string containing the prompt text, if the dialog allows a prompt.

preset Optional. A

Folder

object for a folder to be preselected when the dialog opens.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 262

File and Folder Error Messages

The following messages can be returned in the error

property.

File or folder does not exist

File or folder already exists

I/O device is not open

Read past EOF

Conversion error

Partial multibyte character found

Permission denied

Cannot change directory

Cannot create

Cannot rename

Cannot delete

I/O error

Cannot set size

Cannot open

Cannot close

Read error

Write error

Cannot seek

Cannot execute

The file or folder does not exist, but the parent folder exists.

The file or folder already exists.

An I/O operation was attempted on a file that was closed.

Attempt to read beyond the end of a file.

The content of the file cannot be converted to Unicode.

The character encoding of the file data has errors.

The OS did not allow the attempted operation.

Cannot change the current folder.

Cannot create a folder.

Cannot rename a file or folder.

Cannot delete a file or folder.

Unspecified I/O error.

Setting the file size failed.

Opening of a file failed.

Closing a file failed.

Reading from a file failed.

Writing to a file failed.

Seek failure.

Unable to execute the specified file.

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 263

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. Underlines are replaced with dashes before matching an encoding name.

The File object processes an extended Unicode character with a value greater that 65535 as a Unicode surrogate pair (two characters in the range between 0xD700-0xDFFF).

Built-in encodings are:

US-ASCII, ASCII,ISO646-US,I SO-646.IRV:1991, ISO-IR-6,

ANSI-X3.4-1968,CP367,IBM367,US,ISO646.1991-IRV

UCS-2,UCS2, ISO-10646-UCS-2

UCS2LE,UCS-2LE,ISO-10646-UCS-2LE

UCS2BE,UCS-2BE,ISO-10646-UCS-2BE

UCS-4,UCS4, ISO-10646-UCS-4

UCS4LE,UCS-4LE,ISO-10646-UCS-4LE

UCS4BE,UCS-4BE,ISO-10646-UCS-4BE

UTF-8,UTF8,UNICODE-1-1-UTF-8,UNICODE-2-0-UTF-8,X-UNICODE-2-0-UTF-8

UTF16,UTF-16,ISO-10646-UTF-16

UTF16LE,UTF-16LE,ISO-10646-UTF-16LE

UTF16BE,UTF-16BE,ISO-10646-UTF-16BE

CP1252,WINDOWS-1252,MS-ANSI

ISO-8859-1,ISO-8859-1,ISO-8859-1:1987,ISO-IR-100,LATIN1

MACINTOSH,X-MAC-ROMAN

BINARY

The ASCII encoder raises errors for characters greater than 127, and the BINARY encoder simply converts between bytes and Unicode characters by using the lower 8 bits. The latter encoder is convenient for reading and writing binary data.

Additional encodings

In Windows, all encodings use code pages, which are assigned numeric values. The usual Western character set that Windows uses, for example, is the code page 1252. You can select Windows code pages by prepending the number of the code page with "CP" or "WINDOWS": for example, "CP1252" for the code page 1252. The File object has many other built-in encoding names that match predefined code page numbers. If a code page is not present, the encoding cannot be selected.

In Mac OS, you can select encoders by name rather than by code page number. The File object queries

Mac OS directly for an encoder. As far as Mac OS character sets are identical with Windows code pages,

Mac OS also knows the Windows code page numbers.

In UNIX, the number of available encoders depends on the installation of the iconv library.

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,ASMO-708,ARABIC

ISO-8859-7,ISO-8859-7,ISO-8859-7:1987,ISO-IR-126,ECMA-118,ELOT-928,GREEK8,GREEK

ISO-8859-8,ISO-8859-8,ISO-8859-8:1988,ISO-IR-138,HEBREW

Adobe Photoshop CS2

JavaScript Scripting Reference File and Folder Object Reference 264

ISO-8859-9,ISO-8859-9,ISO-8859-9:1989,ISO-IR-148,LATIN5,TURKISH

ISO-8859-10,ISO-8859-10,ISO-8859-10:1992,ISO-IR-157,LATIN6

ISO-8859-13,ISO-8859-13,ISO-IR-179,LATIN7

ISO-8859-14,ISO-8859-14,ISO-8859-14,ISO-8859-14:1998,ISO-IR-199,LATIN8

ISO-8859-15,ISO-8859-15,ISO-8859-15:1998,ISO-IR-203

ISO-8859-16,ISO-885,ISO-885,MS-EE

CP850,WINDOWS-850,IBM850

CP866,WINDOWS-866,IBM866

CP932,WINDOWS-932,SJIS,SHIFT-JIS,X-SJIS,X-MS-SJIS,MS-SJIS,MS-KANJI

CP936,WINDOWS-936,GBK,WINDOWS-936,GB2312,GB-2312-80,ISO-IR-58,CHINESE

CP949,WINDOWS-949,UHC,KSC-5601,KS-C-5601-1987,KS-C-5601-1989,ISO-IR-149,KOREAN

CP950,WINDOWS-950,BIG5,BIG-5,BIG-FIVE,BIGFIVE,CN-BIG5,X-X-BIG5

CP1251,WINDOWS-1251,MS-CYRL

CP1252,WINDOWS-1252,MS-ANSI

CP1253,WINDOWS-1253,MS-GREEK

CP1254,WINDOWS-1254,MS-TURK

CP1255,WINDOWS-1255,MS-HEBR

CP1256,WINDOWS-1256,MS-ARAB

CP1257,WINDOWS-1257,WINBALTRIM

CP1258,WINDOWS-1258

CP1361,WINDOWS-1361,JOHAB

EUC-JP,EUCJP,X-EUC-JP

EUC-KR,EUCKR,X-EUC-KR

HZ,HZ-GB-2312

X-MAC-JAPANESE

X-MAC-GREEK

X-MAC-CYRILLIC

X-MAC-LATIN

X-MAC-ICELANDIC

X-MAC-TURKISH

Additional Windows encoding names

CP437,IBM850,WINDOWS-437

CP709,WINDOWS-709,ASMO-449,BCONV4

EBCDIC

KOI-8R

KOI-8U

ISO-2022-JP

ISO-2022-KR

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.1990-0,JIS-X0212-1990,X0212,ISO-IR-159

CN,GB-1988-80,ISO646-CN,ISO-IR-57

ISO-IR-16,CN-GB-ISOIR165

KSC-5601,KS-C-5601-1987,KS-C-5601-1989,ISO-IR-149

EUC-CN,EUCCN,GB2312,CN-GB

EUC-TW,EUCTW,X-EUC-TW

UNIX encodings

In UNIX, the File object looks for the presence of the iconv library, and uses whatever encoding it finds there. If you need a special encoding in UNIX, make sure that there is an iconv encoding module installed that converts between UTF-16 (the internal format that the File object uses) and the desired encoding.

8

Scripting Constants

This section lists and describes the enumerations defined for use with Adobe Photoshop CS2 JavaScript properties and methods.

XXX

Constant type Values What it means

AdjustmentReference

AnchorPosition

ABSOLUTE

RELATIVE

BOTTOMCENTER

BOTTOMLEFT

BOTTOMRIGHT

MIDDLECENTER

MIDDLELEFT

MIDDLERIGHT

TOPCENTER

TOPLEFT

TOPRIGHT

Method to use for interpreting selective color adjustment specifications:

ABSOLUTE

= % of the whole;

RELATIVE

= % of the existing color amount.

The point on the object that does not move when the object is rotated or resized.

AntiAlias CRISP

NONE

SHARP

SMOOTH

STRONG

Method to use to smooth edges by softening the color transition between edge pixels and background pixels.

AutoKernType

BatchDestinationType

MANUAL

METRICS

OPTICAL

FOLDER

NODESTINATION

SAVEANDCLOSE

The type of kerning to use for characters.

BitmapConversionType

The destination, if any, for batch-processed files:

FOLDER

: Save modified versions of the files to a new location (leaving the originals unchanged);

NODESTINATIONTYPE

:

Leave all files open;

SAVEANDCLOSE

:

Save changes and close the files.

Specifies the quality of an image you are converting to bitmap mode.

BitmapHalfToneType

CUSTOMPATTERN

DIFFUSIONDITHER

HALFTHRESHOLD

HALFTONESCREEN

PATTERNDITHER

CROSS

DIAMOND

ELLIPSE

LINE

ROUND

SQUARE

Specifies the shape of the dots (ink deposits) in the halftone screen.

BitsPerChannelType The number of bits per color channel.

EIGHT

ONE

SIXTEEN

THIRTYTWO

265

JavaScript Scripting Reference

Constant type

BlendMode

BMPDepthType

ByteOrder

CameraRAWSettingsType

CameraRAWSize

ChangeMode

Adobe Photoshop CS2

Values

COLORBLEND

COLORBURN

COLORDODGE

DARKEN

DIFFERENCE

DISSOLVE

EXCLUSION

HARDLIGHT

HUE

LIGHTEN

LINEARBURN

LINEARDODGE

LINEARLIGHT

LUMINOSITY

MULTIPLY

NORMAL

OVERLAY

PASSTHROUGH

PINLIGHT

SATURATION

SCREEN

SOFTLIGHT

VIVIDLIGHT

BMP_A1R5G5B5

BMP_A4R4G4B4

BMP_A8R8G8B8

BMP_R5G6B5

BMP_R8G8B8

BMP_X1R5G5B5

BMP_X4R4G4B4

BMP_X8R8G8B8

EIGHT

FOUR

ONE

SIXTEEN

THIRTYTWO

TWENTYFOUR

IBM

MACOS

CAMERA

CUSTOM

SELECTEDIMAGE

EXTRALARGE

LARGE

MAXIMUM

MEDIUM

MINIMUM

SMALL

BITMAP

CMYK

GRAYSCALE

INDEXEDCOLOR

LAB

MULTICHANNEL

RGB

Scripting Constants 266

What it means

Controls how pixels in the image are blended.

The number of bits per channel (also called pixel depth or color depth). The number selected indicates the exponent of 2. For example, a pixel with a bit-depth of

EIGHT

has 2

8

, or 256, possible color values.

The order in which bytes will be read.

The default CameraRaw settings to use: the camera settings, custom settings, or the settings of the selected image.

The camera RAW size type options:

EXTRALARGE

=5120 x 1024

LARGE

=4096 x 1024

MEDIUM

=3072 x 1024

SMALL =2048 x 1024

MINIMUM

=1536 x 1024

The type of color mode to use.

Note: Color images must be changed to GRAYSCALE mode before you can change them to

BITMAP mode.

JavaScript Scripting Reference

Constant type

ChannelType

ColorBlendMode

ColorModel

ColorPicker

ColorProfile

ColorReductionType

Adobe Photoshop CS2

Values

COMPONENT

MASKEDAREA

SELECTEDAREA

SPOTCOLOR

Scripting Constants 267

What it means

The type of channel:

COMPONENT

: related to document color mode

MASKEDAREA

: Alpha channel where color indicates masked area

SELECTEDAREA : Alpha channel where color indicates selected are

SPOTCOLOR

:

Color blend mode type.

BEHIND

CLEAR

COLOR

COLORBURN

COLORDODGE

DARKEN

DIFFERENCE

DISSOLVE

EXCLUSION

HARDLIGHT

HUE

LIGHTEN

LINEARBURN

LINEARDODGE

LINEARLIGHT

LUMINOSITY

MULTIPLY

NORMAL

OVERLAY

PINLIGHT

SATURATION

SCREEN

SOFTLIGHT

VIVIDLIGHT

CMYK

GRAYSCALE

HSB

LAB

NONE

RGB

ADOBE

APPLE

PLUGIN

WINDOWS

CUSTOM

NONE

WORKING

ADAPTIVE

BLACKWHITE

CUSTOM

GRAYSCALE

MACINTOSH

PERCEPTUAL

RESTRICTIVE

SELECTIVE

WINDOWS

The color model to use.

The color picker to use.

The color profile type to use to manage this document.

The color reduction algorithm option to use.

JavaScript Scripting Reference

Constant type

ColorSpaceType

CopyrightedType

CreateFields

CropToType

DCSType

DepthMapSource

DescValueType

DialogModes

Direction

DisplacementMapType

Dither

Adobe Photoshop CS2

Scripting Constants 268

Values

ADOBERGB

COLORMATCHRGB

PROPHOTORGB

SRGB

COPYRIGHTEDWORK

PUBLICDOMAIN

UNMARKED

DUPLICATION

INTERPOLATION

ARTBOX

BLEEDBOX

BOUNDINGBOX

CROPBOX

MEDIABOX

TRIMBOX

COLORCOMPOSITE

GRAYSCALECOMPOSITE

NOCOMPOSITE

HORIZONTAL

VERTICAL

STRETCHTOFIT

TILE

What it means

The type of color space to use.

The copyright status of the document.

The method to use for creating fields.

The style to use when cropping a page.

IMAGEHIGHLIGHT

LAYERMASK

NONE

TRANSPARENCYCHANNEL

ALIASTYPE

BOOLEANTYPE

CLASSTYPE

DOUBLETYPE

ENUMERATEDTYPE

INTEGERTYPE

LISTTYPE

OBJECTTYPE

RAWTYPE

REFERENCETYPE

STRINGTYPE

UNITDOUBLE

ALL

ERROR

NO

The DCS format to use:

COLORCOMPOSITE

: Creates a color composite file in addition to DCS files;

GRAYSCALECOMPOSITE : Creates a grayscale composite file in addition to

DCS files;

NOCOMPOSITE

: Does not create a composite file.

What to use for the depth map.

The value type of an object.

Controls the type (mode) of dialogs

Photoshop displays when running scripts.

The orientation of the object.

Describes how the displacement map fits the image if the image is not the same size as the map.

The default type of dithering to use.

DIFFUSION

NOISE

NONE

PATTERN

JavaScript Scripting Reference

Constant type

DocumentFill

DocumentMode

EditLogItemsType

ElementPlacement

EliminateFields

ExportType

Extension

FileNamingType

Adobe Photoshop CS2

Scripting Constants 269

Values

BACKGROUNDCOLOR

TRANSPARENT

WHITE

BITMAP

CMYK

DUOTONE

GRAYSCALE

INDEXEDCOLOR

LAB

MULTICHANNEL

RGB

CONCISE

DETAILED

SESSIONONLY

What it means

The fill of the document.

The color mode of the open document.

INSIDE

PLACEATBEGINNING

PLACEATEND

PLACEBEFORE

PLACEAFTER

EVENFIELDS

ODDFIELDS

ILLUSTRATORPATHS

SAVEFORWEB

LOWERCASE

NONE

UPPERCASE

DDMM

DDMMYY

DOCUMENTNAMELOWER

DOCUMENTNAMEMIXED

DOCUMENTNAMEUPPER

EXTENSIONLOWER

EXTENSIONUPPER

MMDD

MMDDYY

SERIALLETTERLOWER

SERIALLETTERUPPER

SERIALNUMBER1

SERIALNUMBER2

SERIALNUMBER3

SERIALNUMBER4

YYDDMM

YYMMDD

YYYYMMDD

The history log edit options:

CONCISE : Save a concise history log.

DETAILED

: Save a detailed history log.

SESSIONONLY

: Save history log only for the session.

The object’s position in the Layers palette.

Note: Not all values are valid for all object types. Please refer to the object property definition in

JavaScript Object Reference to

make sure you are using a valid value.

The type of fields to eliminate.

The export options to use.

The formatting of the extension in the filename.

File naming options for the batch command.

Adobe Photoshop CS2

JavaScript Scripting Reference Scripting Constants 270

Constant type

FontPreviewType

ForcedColors

FormatOptions

Values

LARGE

MEDIUM

NONE

SMALL

BLACKWHITE

NONE

PRIMARIES

WEB

OPTIMIZEDBASELINE

PROGRESSIVE

STANDARDBASELINE

What it means

The type size to use for font previews in the type tool font menus.

The type of colors to be forced

(included) into the color table:

BLACKWHITE

: Pure black and pure white;

NONE ; PRIMARIES : Red, green, blue, cyan, magenta, yellow, black, and white;

WEB

: the 216 web-safe colors.

The option with which to save a JPEG file:

OPTIMIZEDBASELINE

: Optimized color and a slightly reduced file size;

PROGRESSIVE

: Displays a series of increasingly detailed scans as the image downloads;

STANDARDBASELINE

:

Format recognized by most web browsers.

The type of proportions to constrain for images.

The fonts to use for the Web photo gallery captions and other text.

GalleryConstrainType

GalleryFontType

GallerySecurityTextColorType BLACK

CUSTOM

WHITE

GallerySecurityTextPositionType CENTERED

LOWERLEFT

LOWERRIGHT

UPPERLEFT

UPPERRIGHT

GallerySecurityTextRotateType

GallerySecurityType

CONSTRAINBOTH

CONSTRAINHEIGHT

CONSTRAINWIDTH

ARIAL

COURIERNEW

HELVETICA

TIMESNEWROMAN

CLOCKWISE45

CLOCKWISE90

COUNTERCLOCKWISE45

COUNTERCLOCKWISE90

ZERO

CAPTION

COPYRIGHT

CREDIT

CUSTOMTEXT

FILENAME

NONE

TITLE

GalleryThumbSizeType CUSTOM

LARGE

MEDIUM

SMALL

The color to use for text displayed over gallery images as an antitheft deterrent.

The position of the text displayed over gallery images as an antitheft deterrent.

The orientation of the text displayed over gallery images as an antitheft deterrent.

The content to use for text displayed over gallery images as an antitheft deterrent.

Note: All types draw from the image’s file information except

CUSTOMTEXT

.

The size of thumbnail images in the web photo gallery.

JavaScript Scripting Reference

Constant type

Geometry

GridLineStyle

GridSize

GuideLineStyle

IllustratorPathType

Intent

JavaScriptExecutionMode

Justification

Language

LayerCompression

Adobe Photoshop CS2

Scripting Constants 271

Values

HEPTAGON

HEXAGON

OCTAGON

PENTAGON

SQUARE

TRIANGLE

What it means

Geometric options for shapes, such as the iris shape in the Lens Blur Filter.

DASHED

DOTTED

SOLID

The line style for the nonprinting grid displayed over images.

LARGE

MEDIUM

NONE

SMALL

The value of grid line spacing.

DASHED

SOLID

The line style for nonprinting guides displayed over images.

The paths to export. ALLPATHS

DOCUMENTBOUNDS

NAMEDPATH

ABSOLUTECOLORIMETRIC

PERCEPTUAL

RELATIVECOLORIMETRIC

SATURATION

The rendering intent to use when converting from one color space to another.

BEFORERUNNING

NEVER

ONRUNTIMEERROR

The debugger mode to use.

CENTER

CENTERJUSTIFIED

FULLYJUSTIFIED

LEFT

LEFTJUSTIFIED

RIGHT

RIGHTJUSTIFIED

The placement of paragraph text within the bounding box.

BRAZILLIANPORTUGUESE

CANADIANFRENCH

DANISH

DUTCH

ENGLISHUK

ENGLISHUSA

FINNISH

FRENCH

GERMAN

ITALIAN

NORWEGIAN

NYNORSKNORWEGIAN

OLDGERMAN

PORTUGUESE

SPANISH

SWEDISH

SWISSGERMAN

The language to use.

RLE

ZIP

Compression methods for data for pixels in layers.

JavaScript Scripting Reference

Constant type

LayerKind

LensType

MagnificationType

MatteType

NewDocumentMode

NoiseDistribution

OffsetUndefinedAreas

OpenDocumentMode

Adobe Photoshop CS2

Scripting Constants 272

Values

BRIGHTNESSCONTRAST

CHANNELMIXER

COLORBALANCE

CURVES

GRADIENTFILL

GRADIENTMAP

HUESATURATION

INVERSION

LEVELS

NORMAL

PATTERNFILL

POSTERIZE

SELECTIVECOLOR

SMARTOBJECT

SOLIDFILL

TEXT

THRESHOLD

MOVIEPRIME

PRIME105

PRIME35

ZOOMLENS

ACTUALSIZE

FITPAGE

BACKGROUND

BLACK

FOREGROUND

NETSCAPE

NONE

SEMIGRAY

WHITE

BITMAP

CMYK

GRAYSCALE

LAB

RGB

GAUSSIAN

UNIFORM

REPEATEDGEPIXELS

SETTOBACKGROUND

WRAPAROUND

What it means

The kind of artLayer

object.

Note: You can create a text layer only from an empty art layer.

The type of lens to use.

The type of magnification to use when viewing an image.

The color to use for matting.

The color profile to use for the document.

Distribution method to use when applying an Add Noise filter.

Method to use to fill the empty space left by offsetting a an image or selection.

The color profile to use. CMYK

GRAYSCALE

LAB

RGB

JavaScript Scripting Reference

Constant type

OpenDocumentType

OperatingSystem

Orientation

OtherPaintingCursors

PaintingCursors

Adobe Photoshop CS2

Scripting Constants 273

Values

ACROBATTOUCHUPIMAGE

ALIASPIX

BMP

CAMERARAW

COMPUSERVEGIF

ELECTRICIMAGE

EPS

EPSPICTPREVIEW

EPSTIFFPREVIEW

FILMSTRIP

JPEG

PCX

PDF

PHOTOCD

PHOTOSHOP

PHOTOSHOPDCS_1

PHOTOSHOPDCS_2

PHOTOSHOPEPS

PHOTOSHOPPDF

PICTFILEFORMAT

PICTRESOURCEFORMAT

PIXAR

PNG

PORTABLEBITMAP

RAW

SCITEXCT

SGIRGB

SOFTIMAGE

TARGA

TIFF

WAVEFRONTRLA

WIRELESSBITMAP

What it means

The format in which to open the document.

The operating system. OS2

WINDOWS

LANDSCAPE

PORTRAIT

PRECISEOTHER

STANDARDOTHER

The page orientation.

BRUSHSIZE

PRECISE

STANDARD

The pointer for the following tools:

Eraser, Pencil, Paintbrush, Healing

Brush, Rubber Stamp, Pattern Stamp,

Smudge, Blur, Sharpen, Dodge, Burn,

Sponge.

The pointer for the following tools:

Marquee, Lasso, Polygonal Lasso, Magic

Wand, Crop, Slice, Patch Eyedropper,

Pen, Gradient, Line, Paint Bucket,

Magnetic Lasso, Magnetic Pen,

Freeform Pen, Measure, Color Sampler.

JavaScript Scripting Reference

Constant type

Palette

PathKind

PDFCompatibility

PDFEncoding

PDFResample

PDFStandard

PhotoCDColorSpace

PhotoCDSize

Adobe Photoshop CS2

Scripting Constants 274

Values

EXACT

LOCALADAPTIVE

LOCALPERCEPTUAL

LOCALSELECTIVE

MACOSPALETTE

MASTERADAPTIVE

MASTERPERCEPTUAL

MASTERSELECTIVE

PREVIOUSPALETTE

UNIFORM

WEBPALETTE

WINDOWSPALETTE

CLIPPINGPATH

NORMALPATH

TEXTMASK

VECTORMASK

WORKPATH

PDF13

PDF14

PDF15

PDF16

JPEG

JPEG2000HIGH

JPEG2000LOSSLESS

JPEG2000LOW

JPEG2000MED

JPEG2000MEDHIGH

JPEG2000MEDLOW

JPEGHIGH

JPEGLOW

JPEGMED

JPEGMEDHIGH

JPEGMEDLOW

NONE

PDFZIP

PDFZIP4BIT

NONE

PDFAVERAGE

PDFBICUBIC

PDFSUBSAMPLE

NONE

PDFX1A2001

PDFX1A2003

PDFX32002

PDFX32003

LAB16

LAB8

RGB16

RGB8

EXTRALARGE

LARGE

MAXIMUM

MEDIUM

MINIMUM

SMALL

What it means

The palette type to use.

The type of path.

The PDF version to make the document compatible with.

The type of compression to use when saving a document in PDF format.

The down sample method to use.

The PDF standard to make the document compatible with.

The color space to use when creating a

Photo CD.

The pixel dimensions of the image.

JavaScript Scripting Reference

Constant type

PICTBitsPerPixels

PICTCompression

PicturePackageTextType

PointKind

PointType

PolarConversionType

Preview

PrintEncoding

PurgeTarget

QueryStateType

RadialBlurMethod

RadialBlurQuality

Adobe Photoshop CS2

Scripting Constants 275

Values

EIGHT

FOUR

SIXTEEN

THIRTYTWO

TWO

What it means

The number of bits per pixel to use when compression a PICT file.

Note: Use 16 or 32 for RGB images; use

2, 4, or 8 for bitmap and grayscale images.

The type of compression to use when saving an image as a PICT file.

JPEGHIGHPICT

JPEGLOWPICT

JPEGMAXIMUMPICT

JPEGMEDIUMPICT

NONE

CAPTION

COPYRIGHT

CREDIT

FILENAME

NONE

ORIGIN

USER

CORNERPOINT

SMOOTHPOINT

POSTSCRIPT

TRADITIONAL

The function or meaning of text in a

Picture Package.

POLARTORECTANGULAR

RECTANGULARTOPOLAR

EIGHTBITTIFF

MACOSEIGHTBIT

MACOSJPEG

MACOSMONOCHROME

MONOCHROMETIFF

NONE

ASCII

BINARY

JPEG

ALLCACHES

CLIPBOARDCACHE

HISTORYCACHES

UNDOCACHES

ALWAYS

ASK

NEVER

SPIN

ZOOM

BEST

DRAFT

GOOD

The role a pathPoint plays in a pathItem

.

The kind of measurement to use for type points:

POSTSCRIPT = 72 points/inch;

TRADITIONAL

= 72.27 points/inch.

The method of polar distortion to use.

The type of image to use as a low-resolution preview in the destination application.

The type of encoding to use.

Cache to be targeted in a purge operation.

Permission state for queries.

The blur method to use.

The smoothness or graininess of the blurred image.

JavaScript Scripting Reference

Constant type

RasterizeType

ReferenceFormType

ResampleMethod

ResetTarget

RippleSize

SaveBehavior

SaveDocumentType

Adobe Photoshop CS2

Scripting Constants 276

Values

ENTIRELAYER

FILLCONTENT

LAYERCLIPPINGPATH

LINKEDLAYERS

SHAPE

TEXTCONTENTS

CLASSTYPE

ENUMERATED

IDENTIFIER

INDEX

NAME

OFFSET

PROPERTY

BICUBIC

BICUBICSHARPER

BICUBICSMOOTHER

BILINEAR

NEARESTNEIGHBOR

NONE

ALLTOOLS

ALLWARNINGS

EVERYTHING

LARGE

MEDIUM

SMALL

ALWAYSSAVE

ASKWHENSAVING

NEVERSAVE

ALIASPIX

BMP

COMPUSERVEGIF

ELECTRICIMAGE

JPEG

PCX

PHOTOSHOP

PHOTOSHOPDCS_1

PHOTOSHOPDCS_2

PHOTOSHOPEPS

PHOTOSHOPPDF

PICTFileFORMAT

PICTRESOURCEFORMAT

PIXAR

PNG

PORTABLEBITMAP

RAW

SCITEXCT

SGIRGB

SOFTIMAGE

TARGA

TIFF

WAVEFRONTRLA

WIRELESSBITMAP

What it means

The layer element to rasterize.

The type of an ActionReference object.

The method to use for image interpolation.

The type of object or objects to reset to default settings.

The size of undulations to use.

The application’s behavior when a save()

method is called.

The format in which to save a document.

Note: The format

property of the

ExportOptionsSaveForWeb class uses only the following values: COMPUSERVEGIF , JPEG ,

PNG-8

,

PNG-24

, and

BMP

.

See

ExportOptionsSaveForWeb

.

JavaScript Scripting Reference

Constant type

SaveEncoding

SaveLogItemsType

SaveOptions

SelectionType

ShapeOperation

SmartBlurMode

SmartBlurQuality

SourceSpaceType

SpherizeMode

StrikeThruType

StrokeLocation

TargaBitsPerPixels

TextCase

Adobe Photoshop CS2

Scripting Constants 277

HIGH

LOW

MEDIUM

DOCUMENT

PROOF

HORIZONTAL

NORMAL

VERTICAL

STRIKEBOX

STRIKEHEIGHT

STRIKEOFF

CENTER

INSIDE

OUTSIDE

SIXTEEN

THIRTYTWO

TWENTYFOUR

ALLCAPS

NORMAL

SMALLCAPS

Values

ASCII

BINARY

JPEGHIGH

JPEGLOW

JPEGMAXIMUM

JPEGMEDIUM

LOGFILE

LOGFILEANDMETADATA

METADATA

DONOTSAVECHANGES

PROMPTTOSAVECHANGES

SAVECHANGES

DIMINISH

EXTEND

INTERSECT

REPLACE

SHAPEADD

SHAPEINTERSECT

SHAPESUBTRACT

SHAPEXOR

EDGEONLY

NORMAL

OVERLAYEDGE

What it means

The type of encoding to use when saving a file.

The location of history log data.

The ’save’ method to use when closing a document.

The selection behavior when a selection already exists:

DIMINISH

:

Remove the selection from the already selected area; EXTEND : Add the selection to an already selected area;

INTERSECT

: Make the selection only the area where the new selection intersects the already selected area; REPLACE :

Replace the selected area.

A subPathItem object’s behavior when it intersects another subPathItem object.

The method to use for smart blurring:

EDGEONLY

,

OVERLAYEDGES

: Apply blur only to edges of color transitions;

NORMAL

: Apply blur to entire image.

The blur quality to use.

The curve (or stretch shape) to use for the distortion.

The style of strikethrough to use.

The placement of path or selection boundary strokes.

The resolution to use when saving an image in Targa format.

The case usage for type.

JavaScript Scripting Reference

Constant type

TextComposer

TextType

TextureType

TIFFEncoding

ToolType

TransitionType

TrimType

Adobe Photoshop CS2

Scripting Constants 278

Values

ADOBEEVERYLINE

ADOBESINGLELINE

PARAGRAPHTEXT

POINTTEXT

What it means

The composition method to use to optimize the specified hyphenation and justification options.

The type of text:

PARAGRAPHTEXT

: Text that wraps within a bounding box;

POINTTEXT : Text that does not wrap.

The type of texture or glass surface image to load for a texturizer or glass filter.

BLOCKS

CANVAS

FILE

FROSTED

TINYLENS

JPEG

NONE

TIFFLZW

TIFFZIP

The encoding to use for TIFF files.

ARTHISTORYBRUSH

BACKGROUNDERASER

BLUR

BRUSH

BURN

CLONESTAMP

COLORREPLACEMENTTOOL

DODGE

ERASER

HEALINGBRUSH

HISTORYBRUSH

PATTERNSTAMP

PENCIL

SHARPEN

SMUDGE

SPONGE

The tool selection.

The method to use to transition from one image to the next in a PDF presentation.

BLINDSHORIZONTAL

BLINDSVERTICAL

BOXIN

BOXOUT

DISSOLVE

GLITTERDOWN

GLITTERRIGHT

GLITTERRIGHTDOWN

NONE

RANDOM

SPLITHORIZONTALIN

SPLITHORIZONTALOUT

SPLITVERTICALIN

SPLITVERTICALOUT

WIPEDOWN

WIPELEFT

WIPERIGHT

WIPEUP

BOTTOMRIGHT

TOPLEFT

TRANSPARENT

Type of pixels to trim around an image:

BOTTOMRIGHT

= bottom right pixel color;

TOPLEFT = top left pixel color.

JavaScript Scripting Reference

Constant type

TypeUnits

UndefinedAreas

UnderlineType

Units

Urgency

WarpStyle

WaveType

Adobe Photoshop CS2

Scripting Constants 279

CM

INCHES

MM

PERCENT

PICAS

PIXELS

POINTS

FOUR

HIGH

LOW

NONE

NORMAL

SEVEN

SIX

THREE

TWO

ARC

ARCH

ARCLOWER

ARCUPPER

BULGE

FISH

FISHEYE

FLAG

INFLATE

NONE

RISE

SHELLLOWER

SHELLUPPER

SQUEEZE

TWIST

WAVE

SINE

SQUARE

TRIANGULAR

Values

MM

PIXELS

POINTS

REPEATEDGEPIXELS

WRAPAROUND

UNDERLINELEFT

UNDERLINEOFF

UNDERLINERIGHT

What it means

The unit to use for measuring text characters.

The method to use to treat undistorted areas or areas left blank in an image to which the a filter in the Distort category has been applied.

The placement of text underlining.

Note:

UnderlineType.UNDELINELEFT and

UnderlineType.UNDELINERIGHT are valid only when direction = Direction.VERTICAL

.

The measurement unit for type and ruler increments.

The editorial urgency of the artwork.

The warp style to use.

The type of wave to use.

JavaScript Scripting Reference

Constant type

WhiteBalanceType

ZigZagType

Adobe Photoshop CS2

Values

ASSHOT

AUTO

CLOUDY

CUSTOM

DAYLIGHT

FLASH

FLUORESCENT

SHADE

TUNGSTEN

AROUNDCENTER

OUTFROMCENTER

PONDRIPPLES

Scripting Constants 280

What it means

The lighting conditions to use (affects color balance).

The method of zigzagging to use.

9

ExtendScript Tools and Features

ExtendScript is Adobe’s extended implementation of JavaScript, and is used by all Adobe Creative Suite 2 applications that provide a scripting interface. In addition to implementing the JavaScript language according to the W3C specification, ExtendScript provides certain additional features and utilities.

● For help in developing, debugging, and testing scripts, ExtendScript provides:

The ExtendScript Toolkit

, an interactive development and testing environment for ExtendScript.

A global debugging object, the Dollar ($) Object

.

A reporting utility for ExtendScript elements, the ExtendScript Reflection Interface

.

In addition, ExtendScript provides these tools and features:

A localization utility for providing user-interface string values in different languages. See

Localizing

ExtendScript Strings .

Global functions for displaying short messages in dialog boxes. See

User Notification Helper

Functions

.

An object type for specifying measurement values together with their units. See Specifying

Measurement Values .

Tools for combining scripts, such as a

#include

directive, and import

and export

statements. See

Modular Programming Support

.

Support for extending or overriding math and logical operator behavior on a class-by-class basis.

See

Operator Overloading .

ExtendScript provides a common scripting environment for all Adobe Creative Suite 2 applications, and allows interapplication communication through scripts.

To identify specific Adobe Creative Suite 2 applications, scripts must use Application and

Namespace Specifiers

.

Applications can run scripts automatically on startup. See Script Locations and Checking

Application Installation .

For details about interapplication communication, see the Bridge JavaScript Reference, available with Adobe Creative Suite 2.

The ExtendScript Toolkit

The ExtendScript Toolkit provides an interactive development and testing environment for ExtendScript in all Adobe Creative Suite 2 applications. It includes a full-featured, syntax-highlighting editor with Unicode capabilities and multiple undo/redo support. The Toolkit allows you to:

Single-step through JavaScripts inside a CS2 application.

Inspect all data for a running script.

Set and execute breakpoints.

The Toolkit is the default editor for ExtendScript files, which use the extension

.jsx

. You can use the

Toolkit to edit or debug scripts in JS or JSX files.

281

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 282

When you double-click a JSX file in the platform’s windowing environment, the script runs in the Toolkit, unless it specifies a particular target application using the

#target

directive. For more information, see

Selecting a debugging target and

Preprocessor directives .

Configuring the Toolkit window

The ExtendScript Toolkit initially appears with a default arrangement of panes, containing a default configuration of tabs. You can adjust the relative sizes of the panes by dragging the separators up or down, or right or left. You can regroup the tabs. To move a tab, drag the label into another pane.

Drag a tab to a new pane Destination pane is highlighted, and the new tab is added to the tab stack

If you drag a tab so that the entire destination pane is highlighted, it becomes another stacked tab in that pane. If you drag a tab to the top or bottom of a pane (so that only the top or bottom bar of the destination pane is highlighted), that pane splits to show the tabs in a tiled format.

Select target application Invoke tab flyout menus

Split pane shows Browser and Editor tabs

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 283

Each tab has a flyout menu, accessed through the arrow icon in the upper right corner. The same menu is available as a context menu, which you invoke with a right click in the tab. This menu always includes a

Hide Pane command to hide that pane. Use the Window menu to show a hidden pane, or to bring it to the front.

The Editor, which has a tab for each script, has an additional context menu for debugging, which appears when you right-click in the line numbers area.

The Toolkit saves the current layout when you exit, and restores it at the next startup. It also saves and restores the open documents, the current positions within the documents, and any breakpoints that have been set.

If you do not want to restore all settings on startup, hold

SHIFT

while the Toolkit loads to restore default settings. This reconnects to the last application and engine that was selected.

If you want to restore the layout settings on startup, but not load the previously open documents, choose Start with a clean workspace in the Preferences dialog.

Selecting a debugging target

The Toolkit can debug multiple applications at one time. If you have more than one Adobe Creative Suite 2 application installed, use the drop-down list at the upper left under the menu bar to select the target application. All installed applications that use ExtendScript are shown in this list. If you select an application that is not running, the Toolkit prompts for permission to run it.

All available engines in the selected target application are shown in a drop-down list to the right of the application list, with an icon that shows the current debugging status of that engine. A target application can have more than one ExtendScript engine, and more than one engine can be active, although only one is current. An active engine is one that is currently 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. If there is more than one engine available in the target application, you can select an engine in the list to make it current.

When you open the Toolkit, it attempts to reconnect to the same target and engine that was set last time it closed. If that target application is not running, the Toolkit prompts for permission to launch it. If permission is refused, the Toolkit itself becomes the target application.

If the target application that you select is not running, the Toolkit prompts for permission and launches the application. Similarly, if you run a script that specifies a target application that is not running (using the

#target

directive), the Toolkit prompts for permission to launch it. If the application is running but not selected as the current target, the Toolkit prompts you to switch to it.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 284

If you select an application that cannot be debugged in the Toolkit (such as Adobe Help), an error dialog reports that the Toolkit cannot connect to the selected application.

The ExtendScript Toolkit is the default editor for JSX files. If you double-click a JSX file in a file browser, the

Toolkit looks for a

#target

directive in the file and launches that application to run the script; however, it first checks for syntax errors in the script. If any are found, the Toolkit displays the error in a message box and quits silently, rather than launching the target application. For example:

Selecting scripts

The Scripts tab offers a list of debuggable scripts for the target application, which can be JS or JSX files or

(for some applications) HTML files that contain embedded scripts.

Select a script in this tab to load it and display its contents in the editor pane, where you can modify it, save it, or run it within the target application.

Tracking data

The Data Browser tab is your window into the JavaScript engine. It displays all live data defined in the current context, as a list of variables with their current values. If execution has stopped at a breakpoint, it shows variables that have been defined using var

in the current function, and the function arguments. To show variables defined in the global or calling scope, use the Call Stack to change the context (see

The call stack ).

You can use the Data Browser to examine and set variable values.

Click a variable name to show its current value in the edit field at the top of the tab.

● To change the value, enter a new value and press ENTER . If a variable is read-only, the edit field is disabled.

Display or modify selected variable’s value

Object opened to show properties

The flyout menu for this tab lets you control the amount of data displayed:

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 285

Show Global Functions toggles the display of all global function definitions.

Show Object Methods toggles the display of all functions that are attached to objects. Most often, the interesting data in an object are its callable methods.

Show JavaScript Language Elements toggles the display of all data that is part of the JavaScript language standard, such as the Array constructor or the Math object. An interesting property is the

__proto__

property, which reveals the JavaScript object prototype chain.

Each variable has a small icon that indicates the data type. An invalid object is a reference to an object that has been deleted. If a variable is undefined, it does not have an icon. null

Boolean

Number

String

Object

Invalid object

You can inspect the contents of an object by clicking its icon. The list expands to show the object's properties (and methods, if Show Object Methods is enabled), and the triangle points down to indicate that the object is open.

Note: In Photoshop CS2 the Data Browser pane is populated only during the debugging of a JavaScript program within Photoshop.

The JavaScript console

The JavaScript console is a command shell and output window for the currently selected JavaScript engine. It connects you to the global namespace of that engine.

JavaScript command line

JavaScript output

The command line entry field accepts any JavaScript code, and you can use it to evaluate expressions or call functions. Enter any JavaScript statement on the command line and execute it by pressing E

NTER

. The statement executes within the stack scope of the line highlighted in the Call Stack tab, and the result appears in the output field.

The command line input field keeps a command history of 32 lines. Use the Up and Down Arrow keys to scroll through the previous entries.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 286

Commands entered in this field execute with a timeout of one second. If a command takes longer than one second to execute, the Toolkit generates a timeout error and terminates the attempt.

The output field is standard output for JavaScript execution. If any script generates a syntax error, the error is displayed here along with the file name and the line number. The Toolkit displays errors here during its own startup phase. The tab’s flyout menu allows you to clear the contents of the output field and change the size of the font used for output.

The call stack

The Call Stack tab is active while debugging a program. When an executing program stops because of a breakpoint or runtime error, the tab displays the sequence of function calls that led to the current execution point. The Call Stack tab shows the names of the active functions, along with the actual arguments passed in to that function.

For example, this stack pane shows a break occurring at a breakpoint in a function dayOfWeek

:

The function containing the breakpoint is highlighted in both the Call Stack and the Editor tabs.

You can click any function in the call hierarchy to inspect it. In the Editor, the line containing the function call that led to that point of execution is marked with a green background. In the example, when you select the line

[Top Level]

in the call stack, the Editor highlights the line where the dayOfWeek

function was called.

Switching between the functions in the call hierarchy allows you to trace how the current function was called. The Console and Data Browser tabs coordinate with the Call Stack pane. When you select a function in the Call Stack:

The Console pane switches its scope to the execution context of that function , so you can inspect and modify its local variables. These would otherwise be inaccessible to the running JavaScript program from within a called function.

The Data Browser pane displays all data defined in the selected context.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 287

The Script Editor

You can open any number of Script Editor tabs; each displays one Unicode source code document. The editor supports JavaScript syntax highlighting, JavaScript syntax checking, multiple undo and redo operations, and advanced search and replace functionality.

You can use the mouse or special keyboard shortcuts to move the insertion point or to select text in the editor.

Mouse navigation and selection

Click the left mouse button in the editor to move the position caret.

To select text with the mouse, click in unselected text, then drag over the text to be selected. If you drag above or below the currently displayed text, the text scrolls, continuing to select while scrolling. You can also double-click to select a word, or triple-click to select a line.

To initiate a drag-and-drop of selected text, click in the block of selected text, then drag to the destination.

You can drag text from one editor pane to another. You can also drag text out of the Toolkit into another application that accepts dragged text, and drag text from another application into a Toolkit editor.

You can drop files from the Explorer or the Finder onto the Toolkit to open them in an editor.

Keyboard navigation and selection

Besides the usual keyboard input, the editor accepts these special movement keys. You can also select text by using a movement key while pressing S HIFT .

Enter

Backspace

Delete

Left arrow

Right arrow

Up arrow

Down arrow

Page up

Page down

C TRL + Up arrow

Ctrl + Down arrow

C TRL + Page up

C TRL + page down

C TRL + Left arrow

C

TRL

+ right arrow

Insert a Line Feed character

Delete character to the left

Delete character to the right

Move insertion point left one character

Move insertion point right one character

Move insertion point up one line; stay in column if possible

Move insertion point down one line; stay in column if possible

Move insertion point one page up

Move insertion point one page down

Scroll up one line without moving the insertion point

Scroll down one line without moving the insertion point

Scroll one page up without moving the insertion point

Scroll one page down without moving the insertion point

Move insertion point one word to the left

Move insertion point one word to the right

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 288

Home

End

C TRL + Home

C

TRL

+ End

Move insertion point to start of line

Move insertion point to end of line

Move insertion point to start of text

Move insertion point to end of text

The editor supports extended keyboard input via IME (Windows) or TMS (Mac OS). This is especially important for Far Eastern characters.

Syntax checking

Before running the new script or saving the text as a script file, you can check whether the text contains

JavaScript syntax errors. Choose Check Syntax from the Edit menu or from the Editor’s right-click context menu.

If the script is syntactically correct, the status line shows "No syntax errors".

● If the Toolkit finds a syntax error, such as a missing quote, it highlights the affected text, plays a sound, and shows the error message in the status line so you can fix the error.

Debugging in the Toolkit

You can debug the code in the currently active Editor tab. Select one of the debugging commands to either run or to single-step through the program.

When you run code from the Editor, it runs in the current target application’s selected JavaScript engine.

The Toolkit itself runs an independent JavaScript engine, so you can quickly edit and run a script without connecting to a target application.

Evaluation in help tips

If you let your mouse pointer rest over a variable or function in an Editor tab, 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. During debugging, however, this is an extremely useful way to display the current value of a variable, along with its current data type.

You can turn off the display of help tips using the Display JavaScript variables and Enable UI help tips checkboxes on the Help Options page of the Preferences dialog.

Controlling code execution

The debugging commands are available from the Debug menu, from the Editor’s right-click context menu, through keyboard shortcuts, and from the toolbar buttons. Use these menu commands and buttons to control the execution of code when the JavaScript Debugger is active.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 289

Run

Continue

F5 (Windows)

Ctrl R (Mac OS)

Starts or resumes execution of a script.

Disabled when script is executing.

Break Ctrl-F5 (Windows)

Cmd . (Mac OS)

Halts the currently executing script temporarily and reactivates the JavaScript Debugger.

Enabled when a script is executing.

Stop Shift F5 (Windows)

Ctrl K (Mac OS)

Stops execution of the script and generates a runtime error.

Enabled when a script is executing.

Step Over F10 (Windows)

Ctrl S (Mac OS)

Halts after executing a single JavaScript line in the script. If the statement calls a JavaScript function, executes the function in its entirety before stopping (do not step into the function).

Step Into F11 (Windows)

Ctrl T (Mac OS)

Halts after executing a single JavaScript line statement in the script or after executing a single statement in any JavaScript function that the script calls.

Step Out Shift F11 (Windows)

Ctrl U (Mac OS)

When paused within the body of a JavaScript function, resumes script execution until the function returns.

When paused outside the body of a function, resumes script execution until the script terminates.

Visual indication of execution states

While the engine is running, an icon script is active.

in the upper right corner of the Toolkit window indicates that the

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 Editor displays the current script with the current line highlighted in yellow.

If the script encounters a runtime error, the Toolkit halts the execution of the script, displays the current script with the current line highlighted in red, displays the error message in the status line, and plays a sound.

JavaScript Scripting Reference

Adobe Photoshop CS2

ExtendScript Tools and Features 290

Scripts often use a try

/ catch

clause to execute code that may cause a runtime error, in order to catch the error programmatically rather than have the script terminate. You can choose to allow regular processing of such errors using the catch

clause, rather than breaking into the debugger. To set this behavior, choose

Debug > Don't Break On Guarded Exceptions. Some runtime errors, such as Out Of Memory , always cause the termination of the script, regardless of this setting.

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.

To stop execution of a script at a given line, click to the left of the line number to set a breakpoint. A filled dot indicates the breakpoint.

Click a second time to temporarily disable the breakpoint; the icon changes to an outline.

● Click a third time to delete the breakpoint. The icon is removed.

Some breakpoints need to be conditional. For example, if you set a breakpoint in a loop that is executed several thousand times, you would not want to have the program stop each time through the loop, but only on each 1000th iteration.

You can attach a condition to a breakpoint, in the form of a JavaScript expression. Every time execution reaches the breakpoint, it runs the JavaScript expression. If the expression evaluates to a nonzero number or true

, execution stops.

To set a conditional breakpoint in a loop, for example, the conditional expression could be

"i >= 1000"

, which means that the program execution halts if the value of the iteration variable i is equal to or greater than 1000.

You can set breakpoints on lines that do not contain any code, such as comment lines. When the Toolkit runs the program, it automatically moves such a breakpoint down to the next line that actually contains code.

Breakpoint icons

Each breakpoint is indicated by an icon to the left of the line number. The icon for a conditional breakpoint is a diamond, while the icon for an unconditional breakpoint is round. Disabled breakpoints are indicated by an outline icon, while active ones are filled.

Unconditional breakpoint. Execution stops here.

Unconditional breakpoint, disabled. Execution does not stop.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 291

Conditional breakpoint. Execution stops if the attached JavaScript expression evaluates to true

.

Conditional breakpoint, disabled. Execution does not stop.

The Breakpoints tab

The Breakpoints tab displays all breakpoints set in the current Editor tab. You can use the tab’s flyout menu to add, change, or remove a breakpoint.

You can edit a breakpoint by double-clicking it, or by selecting it and choosing Add or Change from the context menu. A dialog allows you to change the line number, the breakpoint’s enabled state, and the condition statement.

Whenever execution reaches this breakpoint, the debugger evaluates this condition. If it does not evaluate to true , the breakpoint is ignored and execution continues. This allows you to break only when certain conditions are met, such as a variable having a particular value.

Profiling

The Profiling tool helps you to optimize program execution. When you turn profiling on, the JavaScript engine collects information about a program while it is running. It counts how often the program executed a line or function, or how long it took to execute a line or function. You can choose exactly which profiling data to display.

:

Because profiling significantly slows execution time, the Profile menu offers these profiling options.

Off Profiling turned off. This is the default.

Functions

Lines

The profiler counts each function call. At the end of execution, displays the total to the left of the line number where the function header is defined.

The profiler counts each time each line is executed. At the end of execution, displays the total to the left of the line number.

Consumes more execution time, but delivers more detailed information.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 292

Add Timing Info

No Profiler Data

Show Hit Count

Show Timing

Instead of counting the functions or lines, records the time taken to execute each function or line. At the end of execution, displays the total number of microseconds spent in the function or line, to the left of the line number.

This is the most time-consuming form of profiling.

When selected, do not display profiler data.

When selected, display hit counts.

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.

When execution halts (at termination, at a breakpoint, or due to a runtime error), the Toolkit displays this information in the Editor, line by line. The profiling data is color coded:

Green indicates the lowest number of hits, or the fastest execution time.

Red indicates trouble spots, such as a line that has been executed many times, or which line took the most time to execute.

This example displays timing information for the program, where the fastest line took 4 microseconds to execute, and the slowest line took 29 microseconds. The timing might not be accurate down to the microsecond; it depends on the resolution and accuracy of the hardware timers built into your computer.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 293

Dollar ($) Object

This global ExtendScript object provides a number of debugging facilities and informational methods. The properties of the

$

object allow you to get global information such as the most recent run-time error, and set flags that control debugging and localization behavior. The methods allow you to output text to the

JavaScript Console during script execution, control execution and other ExtendScript behavior programmatically, and gather statistics on object use.

Dollar ($) object properties build buildDate error

Number

Date

Error

String flags global level locale

Number

Object

Number

String

The ExtendScript build number. Read only.

The date ExtendScript was built. Read only.

The most recent run-time error information, contained in a

JavaScript Error object.

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.

Gets or sets low-level debug output flags. A logical AND of the following bit flag values:

0x0002

(2): Displays each line with its line number as it is executed.

0x0040 (64): Enables excessive garbage collection. Usually, garbage collection starts when the number of objects has increased by a certain amount since the last garbage collection. This flag causes ExtendScript to garbage collect after almost every statement. This impairs performance severely, but is useful when you suspect that an object gets released too soon.

0x0080

(128): Displays all calls with their arguments and the return value.

0x0100

(256): Enables extended error handling (see

strict

).

0x0200

(512): Enables the localization feature of the toString

method. Equivalent to the localize

property.

Provides access to the global object, which contains the JavaScript global namespace.

Enables or disables the JavaScript debugger. One of:

0: No debugging

1: Break on runtime errors

2: Full debug mode

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.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 294 localize memCache objects os screens strict version

Boolean

Number

Number

String

Array

Boolean

String

Enable or disable the extended localization features of the built-in toString

method. See Localizing ExtendScript Strings

.

Gets or sets the ExtendScript memory cache size in bytes.

The total count of all JavaScript objects defined so far. Read only.

The current operating system version. Read only.

An array of objects containing information about the display screens attached to your computer. Each object has the properties left , top , right

, and bottom

, which contain the four corners of each screen in global coordinates. A property primary

is true

if that object describes the primary display.

When true , any attempt to write to a read-only property causes a runtime error. Some objects do not permit the creation of new properties when true

.

The version number of the ExtendScript engine as a three-part number and description; for example: "3.6.5 (debug)" Read only.

Dollar ($) object functions about

$.about () bp

$.bp ([condition])

Displays the About box for the ExtendScript component, and returns the text of the About box as a string.

Executes a breakpoint at the current position. Returns undefined

.

If no condition is needed, it is recommended that you use the JavaScript debugger

statement in the script, rather than this method. condition Optional. A string containing a JavaScript statement to be used as a condition. If the statement evaluates to true

or nonzero when this point is reached, execution stops.

clearbp

$.clearbp ([line])

Removes a breakpoint from the current script. Returns undefined

.

line gc

$.gc ()

Optional. The line at which to clear the breakpoint. If 0 or not supplied, clears the breakpoint at the current line number.

Initiates garbage collection. Returns undefined .

getenv

$.getenv (envname) envname

Returns the value of the specified environment variable, or null if no such variable is defined.

The name of the environment variable.

list

$.list ([classname]) classname

Collects object information into a table and returns this table as a string.

See Object statistics below.

Optional. The type of object about which to collect information. If not supplied, collects information about all objects currently defined.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 295 setbp

$.setbp

([line, condition]) line condition

Sets a breakpoint in the current script. Returns undefined

.

If no arguments are needed, it is recommended that you use the

JavaScript debugger

statement in the script, rather than this method.

Optional. The line at which to stop execution. If 0 or not supplied, sets the breakpoint at the current line number.

Optional. A string containing a JavaScript statement to be used for a conditional breakpoint. If the statement evaluates to true

or nonzero when the line is reached, execution stops.

sleep

$.sleep (milliseconds) milliseconds

Suspends the calling thread for the given number of milliseconds.

Returns undefined

.

During a sleep period, checks at 100 millisecond intervals to see whether the sleep should be terminated. This can happen if there is a break request, or if the script timeout has expired.

The number of milliseconds to wait.

summary

$.summary ([classname])

Collects a summary of object counts into a table and returns this table as a string. The table shows the number of objects in each specified class. For example:

3 Array

5 String classname Optional. The type of object to count. If not supplied, counts all objects currently defined.

Writes the specified text to the JavaScript Console. Returns undefined

.

write

$.write

(text[, text...]...) 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. Returns undefined

.

text One or more strings to write, which are concatenated to form a single string.

Object statistics

The output from

$.list()

is formatted as in the following example.

Address L Refs Prop Class Name

0092196c 4 0 Function [toplevel]

00976c8c 2

00991bc4 L 1

0099142c L 2

00991294 1

1

1

2

0

Object

LOTest

Function

Object

Object

LOTest

LOTest

Object workspace

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 296

The columns show the following object information.

Address

L

Refs

Prop

Class

Name

The physical address of the object in memory.

This column contains the letter "L" if the object is a LiveObject (which is an internal data type).

The reference count of the object.

A second reference count for the number of properties that reference the object. The garbage collector uses this count to break circular references. If the reference count is not equal to the number of JavaScript properties that reference it, the object is considered to be used elsewhere and is not garbage collected.

The class name of the object.

The name of the object. This name does not reflect the name of the property the object has been stored into. The name is mostly relevant to Function objects, where it is the name of the function or method. Names in brackets are internal names of scripts. If the object has an

ID, the last column displays that ID.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 297

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.

Reflection Object

Every object has a reflect

property that returns a reflection

object that reports the contents of the object. You can, for example, show the values of all the properties of an object with code like this: var f= new File ("myfile"); var props = f.reflect.properties; for (var i = 0; i < props.length; i++) {

$.writeln('this property ' + props[i].name + ' is ' + f[props[i].name]);

}

Reflection object properties

All properties are read only.

description help methods name properties

String

String

Array of

ReflectionInfo

String

Array of

ReflectionInfo

Short text describing the reflected object, or undefined if no description is available.

Longer text describing the reflected object more completely, or undefined

if no description is available.

An Array of ReflectionInfo Object

s containing all methods of the reflected object, defined in the class or in the specific instance.

The class name of the reflected object.

An Array of ReflectionInfo Object

s containing all properties of the reflected object, defined in the class or in the specific instance. For objects with dynamic properties (defined at runtime) the list contains only those dynamic properties that have already been accessed by the script. For example, in an object wrapping an HTML tag, the names of the HTML attributes are determined at run time.

Reflection object functions

find

reflectionObj.find

(name ) name

Returns the ReflectionInfo Object for the named property of the

reflected object, or null

if no such property exists. Use this method to get information about dynamic properties that have not yet been accessed, but that are known to exist.

The property for which to retrieve information.

Examples

This code determines the class name of an object: obj = new String ("hi"); obj.reflect.name; // => String

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 298

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").type; // => number

ReflectionInfo Object

This object contains information about a property, a method, or a method argument.

You can access

ReflectionInfo

objects in a Reflection Object ’s

properties

and methods

arrays, by name or index: obj = new String ("hi"); obj.reflect.methods[0]; obj.reflect.methods["indexOf"];

You can access the

ReflectionInfo

objects for the arguments of a method in the arguments

array of the

ReflectionInfo

object for the method, by index: obj.reflect.methods["indexOf"].arguments[0];

ReflectionInfo object properties

arguments dataType defaultValue description

Array of

ReflectionInfo

String any

String

For a reflected method, an array of ReflectionInfo Object

s describing each method argument.

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. Thus, the value string stands for a JavaScript string, while String is a

JavaScript

String

wrapper object.

* : Any type. This is the default.

null undefined

: Return data type for a function that does not return any value.

unknown

The default value for a reflected property or method argument, or undefined

if there is no default value, if the property is undefined, or if the element is a method.

Short text describing the reflected object, or undefined

if no description is available.

JavaScript Scripting Reference help isCollection max min name type

String

Boolean

Number

Number

String

Number

String

Adobe Photoshop CS2

ExtendScript Tools and Features 299

Longer text describing the reflected object more completely, or undefined

if no description is available.

When true

, the reflected property or method returns a collection; otherwise, false

.

The maximum numeric value for the reflected element, or undefined

if there is no maximum or if the element is a method.

The minimum numeric value for the reflected element, or undefined

if there is no minimum or if the element is a method.

The name of the reflected element. A string, or a number for an array index.

The type of the reflected element. One of: readonly

: A read-only property.

readwrite : A read-write property.

createonly

: A property that is valid only during creation of an object.

method

: A method.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 300

Localizing ExtendScript Strings

Localization is the process of translating and otherwise manipulating an interface so that it looks as if it had been originally designed for a particular language. ExtendScript gives you the ability 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.

For portions of your user interface that are displayed on the screen, you may want to localize the displayed

text. You can localize any string explicitly using the Global localize function

, which takes as its argument a

localization object containing the localized versions of a string.

A localization object is a JavaScript object literal whose property names are locale names, and whose property values are the localized text strings. The locale name is a standard language code with an optional region identifier. For details of the syntax, see

Locale names

.

In this example, a msg

object contains localized text strings for two locales. This object supplies the text for an alert dialog. msg = { en: "Hello, world", de: "Hallo Welt" }; alert (msg);

ExtendScript matches the current locale and platform to one of the object's properties and uses the associated string. On a German system, for example, the property de: "Hallo Welt"

is converted to the string "Hallo Welt" .

Variable values in localized strings

Some localization strings need to contain additional data whose position and order may change according to the language used.

You can include variables in the string values of the localization object, in the form

% n . The variables are replaced in the returned string with the results of JavaScript expressions, supplied as additional arguments to the localize

function. The variable

%1

corresponds to the first additional argument,

%2

to the second, and so on.

Because the replacement occurs after the localized string is chosen, the variable values are inserted in the correct position. 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()));

Enabling automatic localization

ExtendScript offers an automatic localization feature. When it is enabled, you can specify a localization object directly as the value of any property that takes a localizable string, without using the localize function. For example: msg = { en: "Yes", de: "Ja", fr: "Oui" }; alert (msg);

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 301

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 $.localize value alert ( localize (msg));

If you need to include variables in the localized strings, use the localize

function.

Locale names

A locale name is an identifier string in that contains an ISO 639 language specifier, and optionally an ISO

3166 region specifier, separated from the language specifier by an underscore.

The ISO 639 standard defines a set of two-letter language abbreviations, such as en

for English and de for German.

The ISO 3166 standard defines a region code, another two-letter identifier, which you can optionally append to the language identifier with an underscore. For example, en_US

identifies U.S. English, while en_GB

identifies British English.

This object defines one message for British English, another for all other flavors of English, and another for all flavors of German: message = { en_GB: "Please select a colour." en: "Please select a colour." de: "Bitte wählen Sie eine Farbe."

};

If you need to specify different messages for different platforms, you can append another underline character and the name of the platform, one of

Win

,

Mac

, or

Unix

. For example, this objects defines one message in British English to be displayed in Mac OS, one for all other flavors of English in Mac OS, and one for all other flavors of English on all other platforms: pressMsg = { en_GB_Mac: "Press Cmd-S to select a colour.", en_Mac: "Press Cmd-S to select a color.", en: "Press Ctrl-S to select a color."

};

All of these identifiers are case sensitive. For example,

EN_US

is not valid.

How locale names are resolved

1. ExtendScript gets the hosting application’s locale; for example, en_US

.

2. It appends the platform identifier; for example, en_US_Win

.

3. It looks for a matching property, and if found, returns the value string.

4. If not found, it removes the platform identifier (for example, en_US ) and retries .

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 302

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.

To test your localized strings, you can temporarily reset the locale. To restore the original behavior, set the variable to null

, false

, 0, or the empty string. An example:

$.locale = "ru"; // try your Russian messages

$.locale = null; // restore to the locale of the app

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 303

Global localize function

The globally available localize function can be used to provide localized strings anywhere a displayed text value is specified. localize localize (localization_obj[,

args]) localize (ZString) localization_obj

Returns the localized string for the current locale.

A JavaScript object literal whose property names are locale names, and whose property values are the localized text strings. The locale name is an identifier as specified in the ISO 3166 standard, a set of two-letter language abbreviations, such as " en

" for English and " de

" for German.

For example: btnText = { en: "Yes", de: "Ja", fr: "Oui" }; b1 = w.add ("button", undefined, localize (btnText));

The string value of each property can contain variables in the form

%1

,

%2

, and so on, corresponding to additional arguments. The variable is replaced with the result of evaluating the corresponding argument in the returned string.

args Optional. Additional JavaScript expressions matching variables in the string values supplied in the localization object. The first argument corresponds to the variable %1 , the second to %2 , and so on.

Each expression is evaluated and the result inserted in the variable’s position in the returned string.

Example

today = { en: "Today is %1/%2", de: "Heute ist der %2.%1."

}; d = new Date(); alert (localize (today, d.getMonth()+1, d.getDate()));

ZString Internal use only. A ZString is an internal Adobe format for localized strings, which you might see in Adobe scripts. It is a string that begins with $$$ and contains a path to the localized string in an installed ZString dictionary. For example: w = new Window ("dialog", localize ("$$$/UI/title1=Sample"));

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 304

User Notification Helper Functions

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:

Alert: Displays a dialog containing a short message and an OK button.

Confirm : Displays a dialog containing a short message and two buttons, Yes and No, allowing the user to accept or reject an action.

Prompt: Displays a dialog containing a short message, a text entry field, and OK and Cancel buttons, allowing the user to supply a value to the script.

These dialogs are customizable to a small degree. The appearance is platform specific.

Global alert function alert alert (message[, title,

errorIcon]); message title errorIcon

Displays a platform-standard dialog containing a short message and an OK button. Returns undefined

.

The string for the displayed message.

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".

Optional. When true , the platform-standard alert icon is replaced by the platform-standard error icon in the dialog. Default is false

.

Examples

This figure shows simple alert dialogs in Windows and Mac OS.

This figure shows alert dialogs with error icons.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 305

Global confirm function confirm confirm (message[,noAsDflt ,title

]); message

Displays a platform-standard dialog containing a short message and two buttons labeled Yes and No. Returns true if the user clicked Yes, false if the user clicked No.

The string for the displayed message.

noAsDflt title

Optional. When true

, the No button is the default choice, selected when the user types E NTER . Default is false

, meaning that Yes is the default choice.

Optional. A string to appear as the title of the dialog, if the platform supports a title. Mac OS does not support titles for confirmation dialogs. The default title string is "Script Alert".

Examples

This figure shows simple confirmation dialogs in Windows and Mac OS.

This figure shows confirmation dialogs with No as the default button.

Global prompt function prompt prompt (message, preset[, title

]); message

Displays a platform-standard dialog containing a short message, a text edit field, and two buttons labeled OK and

Cancel. Returns the value of the text edit field if the user clicked OK, null

if the user clicked Cancel.

The string for the displayed message.

preset title

The initial value to be displayed in the text edit field.

Optional. A string to appear as the title of the dialog. In Windows, this appears in the window’s frame, while in Mac OS it appears above the message. The default title string is "Script Prompt".

Adobe Photoshop CS2

JavaScript Scripting Reference

Examples

This figure shows simple prompt dialogs in Windows and Mac OS.

ExtendScript Tools and Features 306

This figure shows confirmation dialogs with a title

value specified.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 307

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.

UnitValue object constructor

The UnitValue constructor creates a new UnitValue object. The keyword new is optional: myVal = new UnitValue (value, unit); myVal = new UnitValue ("value unit"); myVal = new UnitValue (value, "unit");

The value is a number, and the unit is specified with a string in abbreviated, singular, or plural form, as shown in the following table.

ci px

% pt pc tpt tpc mm cm m km

Abbreviation Singular in inch ft yd mi foot yard mile cicero pixel percent

Plural inches feet yards miles

Comments

2.54 cm

30.48 cm

91.44 cm

1609.344 m millimeter centimeter meter kilometer millimeters centimeters meters kilometers point pica points picas inches / 72 points * 12 traditional point traditional points inches / 72.27

traditional pica traditional picas 12 tpt ciceros pixels percent

12.7872 pt baseless (see below) baseless (see below)

If an unknown unit type is supplied, the type is set to

"?"

, and the

UnitValue

object prints as "UnitValue

0.00000".

For example, all of the following formats are equivalent: myVal = new UnitValue (12, "cm");

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 308 myVal = new UnitValue ("12 cm"); myVal = UnitValue ("12 centimeters");

UnitValue object properties

baseUnit type value

UnitValue

A UnitValue Object that defines the size of one pixel, or a total size to use as a

base for percentage values. This is used as the base conversion unit for pixels and percentages; see

Converting pixel and percentage values

.

Default is 0.013889 inches (1/72 in), which is the base conversion unit for pixels at 72 dpi. Set to null to restore the default.

String The unit type in abbreviated form; for example, "cm" or "in".

Number The numeric measurement value.

UnitValue object functions

as

unitValueObj.as (unit)

Returns the numeric value of this object in the given unit.

If the unit is unknown or cannot be computed, generates a run-time error.

unit unit

The unit type in abbreviated form; for example, "cm" or "in".

convert

unitValueObj.convert

( unit)

Converts this object to the given unit, resetting the type

and value accordingly. Returns true

if the conversion is successful. If the unit is unknown or the object cannot be converted, generates a run-time error and returns false .

The unit type in abbreviated form; for example, "cm" or "in".

Converting pixel and percentage values

Converting measurements among different units requires a common base unit. For example, for length, the meter is the base unit. All length units can be converted into meters, which makes it possible to convert any length unit into any other length unit.

Pixels and percentages do not have a standard common base unit. Pixel measurements are relative to display resolution , and percentages are relative to an absolute total size.

To convert pixels into length units, you must know the size of a single pixel. The size of a pixel depends on the display resolution. A common resolution measurement is 72 dpi, which means that there are 72 pixels to the inch. The conversion base for pixels at 72 dpi is 0.013889 inches (1/72 inch).

● 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. The baseUnit

value is itself a unitValue

object, containing both a magnitude and a unit.

For a system using a different dpi, you can change the baseUnit

value in the

UnitValue

class, thus changing the default for all new unitValue

objects. For example, to double the resolution of pixels:

UnitValue.baseUnit = UnitValue (1/144, "in"); //144 dpi

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 309

To restore the default, assign null

to the class property:

UnitValue.baseUnit = null; //restore default

You can override the default value for any particular unitValue

object by setting the property in that object. For example, to create a unitValue object for pixels with 96 dpi: pixels = UnitValue (10, "px"); myPixBase = UnitValue (1/96, "in"); pixels.baseUnit = myPixBase;

For percentage measurements, set the baseUnit

property to the measurement value for 100%. For example, to create a unitValue

object for 40 % of 10 feet: myPctVal = UnitValue (40, "%"); myBase = UnitValue (10, "ft") myPctVal.baseUnit = myBase;

Use the as method to get to a percentage value as a unit value:

myFootVal = myPctVal.as ("ft"); // => 4 myInchVal = myPctVal.as ("in"); // => 36

You can convert a unitValue

from an absolute measurement to pixels or percents in the same way: myMeterVal = UnitValue (10, "m"); // 10 meters myBase = UnitValue (1, "km"); myMeterVal.baseUnit = myBase; //as a percentage of 1 kilometer pctOfKm = myMeterVal.as ('%'); // => 1 myVal = UnitValue ("1 in"); // Define measurement in inches

// convert to pixels using default base myVal.convert ("px"); // => value=72 type=px

Computing with unit values

UnitValue

objects can be used in computational JavaScript expressions. The way the value is used depends on the type of operator.

Unary operators (

~

,

!

,

+

,

-

)

~unitValue

!unitValue

+unitValue

-unitValue

The numeric value is converted to a 32-bit integer with inverted bits.

Result is true

if the numeric value is nonzero, false

if it is not.

Result is the numeric value.

Result is the negated numeric value.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 310

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

. For example: val = new UnitValue ("10 cm"); res = val * 20;

// res is a UnitValue (200, "cm");

If both operands are unitValue

objects, JavaScript converts the right operand to the same unit as the left operand and applies the operation to the resulting values. The expression returns a new unitValue object with the unit of the left operand, and the result value . For example: a = new UnitValue ("1 m"); b = new UnitValue ("10 cm"); a + b;

// res is a UnitValue (1.1, "m"); b + a;

// res is a UnitValue (110, "cm");

Comparisons (

=

,

==

,

<

,

>

,

<=

,

>=

)

If one operand is a unitValue object and the other is a number, JavaScript compares the number with the unitValue

’s numeric value.

If both operands are unitValue objects, JavaScript converts both objects to the same unit, and compares the converted numeric values.

For example: a = new UnitValue ("98 cm"); b = new UnitValue ("1 m"); a < b; // => true a < 1; // => false a == 98; // => true

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 311

Modular Programming Support

ExtendScript provides support for a modular approach to scripting by allowing you to include one script in another as a resource, and allowing a script to export definitions that can be imported and used in another script.

Preprocessor directives

ExtendScript provides preprocessor directives for including external scripts, naming scripts, specifying an

ExtendScript engine, and setting certain flags. You can specify these in two ways:

With a C-style statement starting with the

#

character:

#include "file.jsxinc"

In a comment whose text starts with the @ character:

// @include "file.jsxinc"

When a directive takes one or more arguments, and an argument contains any nonalphanumeric characters, the argument must be enclosed in single or double quotes. This is generally the case with paths and file names, for example, which contain dots and slashes.

#engine name

#include file

Identifies the ExtendScript engine that runs this script. This allows other engines to refer to the scripts in this engine by importing the exported functions and variables. See

Importing and exporting between scripts

.

Use JavaScript identifier syntax for the name. Enclosing quotes are optional.

For example:

#engine library

#engine "$lib"

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.jsxinc"

To set one or more paths for the

#include

statement to scan, use the

#includepath

preprocessor directive.

If the file to be included cannot be found, ExtendScript throws a run-time error.

Included source code is not shown in the debugger, so you cannot set breakpoints in it.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 312

#includepath path

#script name

#strict on

#target name

One or more paths that the

#include

statement should use to locate the files to be included. The semicolon (

;

) separates path names.

If a

#include

file name starts with a slash (

/

), it is an absolute path name, and the include paths are ignored. Otherwise, ExtendScript attempts to find the file by prefixing the file with each path set by the #includepath statement.

For example:

#includepath "include;../include"

#include "file.jsxinc"

Multiple

#includepath

statements are allowed; the list of paths changes each time an #includepath statement is executed.

As a fallback, ExtendScript also uses the contents of the environment variable JSINCLUDE as a list of include paths.

Some engines can have a predefined set of include paths. If so, the path provided by #includepath is tried before the predefined paths. If, for example, the engine has a predefined path set to predef;predef/include

, the preceding example causes the following lookup sequence: file.jsxinc

: literal lookup include/file.jsxinc

: first

#includepath

path

../include/file.jsxinc:

second

#includepath

path predef/file.jsxinc

: first predefined engine path predef/include/file.jsxinc

: second predefined engine path

Names a script. Enclosing quotes are optional, but required for names that include spaces or special characters. For example:

#script SetupPalette

#script "Load image file"

The name

value is displayed in the Toolkit Editor tab. An unnamed script is assigned a unique name generated from a number.

Turns on strict error checking. See the

Dollar ($) Object

’s strict property.

Defines the target application of 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. A user can open a file by double-clicking it in a file browser, and a script can open a file using a File object’s execute method.

Importing and exporting between scripts

The ExtendScript JavaScript language has been extended to support function calls and variable access across various source code modules and ExtendScript engines. A script can use the export statement to make its definitions available to other scripts, which use the import

statement to access those definitions.

To use this feature, the exporting script must name its ExtendScript engine using the

#engine preprocessor statement. The name must follow JavaScript naming syntax; it cannot be an expression.

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 313

For example, the following script could serve as a library or resource file. It defines and exports a constant and a function:

#engine library export random, libVersion; const libVersion = "Library 1.0"; function random (max) { return Math.floor (Math.random() * max);

}

A script running in a different engine can import the exported elements. The import statement identifies the resource script that exported the variables using the engine name: import library.random, library.libVersion; print (random (100));

You can use the asterisk wildcard (

*

) to import all symbols exported by a library: import library.*

Objects cannot be transferred between engines. You cannot retrieve or store objects, and you cannot call functions with objects as arguments. However, you can use the JavaScript toSource function to serialize objects into strings before passing them. You can then use the JavaScript eval

function to reconstruct the object from the string.

For example, this function takes as its argument a serialized string and constructs an object from it: function myFn (serialized) { var obj = eval (serialized);

// continue working…

}

In calling the function, you deconstruct the object you want to pass into a serialized string: myFn (myObject.toSource()); // pass a serialized object

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 314

Operator Overloading

ExtendScript allows you to extend or override the behavior of a math or a Boolean operator for a specific class by defining a method in that class with same name as the operator. For example, this code defines the addition (

+

) operator for the class

MyClass

. In this case, the addition operator simply adds the operand to the property value:

// define the constructor method function MyClass (initalValue) { this.value = initialValue;

}

// define the addition operator

MyClass.prototype ["+"] = function (operand) { return this.value + operand;

}

This allows you to perform the "+" operation with any object of this class: var obj = new MyClass (5);

Result: [object Object] obj + 10;

Result: 15

You can override the following operators:

Unary

Binary

+, -

~

+, -

*, /, %, ^

<, <=, ==

<<, >>, >>>

&, |, ===

The operators

>

and

>=

are implemented by executing NOT operator

<=

and NOT operator

<

.

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

.

Unary operator functions work on the this object, while binary operators work on the this object and the first argument. The + and - operators have both unary and binary implementations. If the first argument is undefined, the operator is unary; if it is supplied, the operator is binary.

For binary operators, a second argument indicates the order of operands. For noncommutative operators, either implement both order variants in your function or return undefined for combinations that you do not support. For example: this ["/"] = function (operand, rev) { if (rev) {

// do not resolve operand / this return;

} else {

// resolve this / operand return this.value / operand;

}

}

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 315

Application and Namespace Specifiers

All forms of interapplication communication use Application specifiers to identify Adobe applications.

● In all ExtendScript scripts, the

#target

directive can use an specifier to identify the application that should run that script. See

Preprocessor directives .

In interapplication messages, the specifier is used as the value of the target

property of the message object, to identify the target application for the message.

Bridge (which is integrated with all Adobe Creative Suite 2 applications) uses an application specifier as the value of the document.owner

property, to identify another Creative Suite 2 application that created or opened a Bridge browser window. For details, see the Bridge JavaScript Reference, available with

Adobe Creative Suite 2.

When a script for one application invokes Cross-DOM or exported functions, it identifies the exporting application using

Namespace specifiers

.

Application specifiers

Application specifiers are strings that encode the application name, a version number and a language code. They take the following form: appname [version [locale ]] appname An Adobe application name. One of: acrobat aftereffects atmosphere audition bridge encore golive illustrator incopy indesign photoshop premiere version locale

Optional. A number indicating at least a major version. If not supplied, the most recent version is assumed. The number can include a minor version separated from the major version number by a dot; for example, 1.5

.

Optional. An Adobe locale code, consisting of a 2-letter ISO-639 language code and an optional 2-letter ISO 3166 country code separated by an underscore. Case is significant. For example, en_US

, en_UK

, ja_JP

, de_DE

, fr_FR

.

If not supplied, ExtendScript uses the current platform locale.

Do not specify a locale for a multilingual application, such as Bridge, that has all locale versions included in a single installation.

The following are examples of legal specifiers: photoshop bridge-1 bridge-1.0

illustrator-12.2

bridge-1-en_us golive-8-de_de

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 316

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.

appname[majorVersion].functionName(args)

For example:

● To call the cross-DOM function quit

in Photoshop CS2, use photoshop.quit()

, and to call it in

GoLive® CS2, use golive.quit() .

● To call the exported function place

, defined for Illustrator CS version 12, call illustrator12.place(myFiles) .

For information about the cross-DOM and exported functions, see the Bridge JavaScript Reference, available with Adobe Creative Suite 2.

Script Locations and Checking Application Installation

On startup, all Adobe Creative Suite 2 applications execute all JSX files that they find in the user startup folder:

In Windows, the startup folder is:

%APPDATA%\Adobe\StartupScripts

In Mac OS®, the startup folder is

~/Library/Application Support/Adobe/StartupScripts/

A script in the startup directory is executed on startup by all applications. If you place a script here, it must contain code to check whether it is being run by the intended application. You can do this using the appName

static property of the

BridgeTalk

class. For example: if( BridgeTalk.appName == "bridge" ) {

//continue executing script

}

In addition, individual applications may look for application-specific scripts in a subfolder named with that application’s specifier and version, in the form:

%APPDATA%\Adobe\StartupScripts\appname\version

~/Library/Application Support/Adobe/StartupScripts/appname/version/

The name and version in these folder names are specified in the form required for

Application specifiers

.

For example, in Windows, GoLive CS2 version 8.2 would look for scripts in the directory:

%APPDATA%\Adobe\StartupScripts\golive\8.2

The version portion of the Bridge-specific folder path is an exact version number. That is, scripts in the folder bridge/1.5

are executed only by Bridge version 1.5, and so on.

Individual applications may also implement a path in the installation directory for application-specific startup scripts. For example:

IllustratorCS2_install_dir\Startup Scripts

IllustratorCS2_install_dir/Startup Scripts/

Adobe Photoshop CS2

JavaScript Scripting Reference ExtendScript Tools and Features 317

If a script that is run by one application will communicate with another application, or add functionality that depends on another application, it must first check whether that application and version is installed.

You can do this using the BridgeTalk.getSpecifier

static function. For example: if( BridgeTalk.appName == "bridge" ) {

// Check that PS CS2 is installed if( BridgeTalk.getSpecifier("photoshop",9)){

// add PS automate menu to Bridge UI

}

}

For details of interapplication communication, see the Bridge JavaScript Reference, available with Adobe

Creative Suite 2.

Appendix A: Event ID Codes

The following table lists events and their four-character ID codes or string identifiers for use with the notifier object.

Note: Do not include single quotes (

'

) with four-character IDs in your code. The single quotes are used in this table to illustrate the placement of required spaces in codes that do not contain four letters. However, string identifiers, which are longer than four characters, require double quotes in the code.

Event 4-char ID or String

3DTransform

Average

'TdT '

'Avrg'

ApplyStyle

Assert

AccentedEdges

Add

AddNoise

AddTo

Align

All

AngledStrokes

ApplyImage

BasRelief

Batch

BatchFromDroplet

Blur

BlurMore

Border

Brightness

CanvasSize

ChalkCharcoal

ChannelMixer

Charcoal

Chrome

Clear

'AngS'

'AppI'

'BsRl'

'Btch'

'BtcF'

'Blr '

'BlrM'

'Brdr'

'ASty'

'Asrt'

'AccE'

'Add '

'AdNs'

'AddT'

'Algn'

'All '

'BrgC'

'CnvS'

'ChlC'

'ChnM'

'Chrc'

'Chrm'

'Cler'

318

Adobe Photoshop CS2 JavaScript Scripting Reference

Photoshop CS2

Event

Close

Crosshatch

Crystallize

Curves

Custom

Cut

CutToLayer

Cutout

DarkStrokes

DeInterlace

DefinePattern

Defringe

Delete

Desaturate

Deselect

Despeckle

DifferenceClouds

Clouds

ColorBalance

ColorHalftone

ColorRange

ColoredPencil

ContactSheet

ConteCrayon

Contract

ConvertMode

Copy

CopyEffects

CopyMerged

CopyToLayer

Craquelure

CreateDroplet

Crop

Appendix A: Event ID Codes 319

4-char ID or String

'Cls '

'Dntr'

'DfnP'

'Dfrg'

'Dlt '

'Dstt'

'Dslc'

'Dspc'

'DrfC'

'Crsh'

'Crst'

'Crvs'

'Cstm'

'cut '

'CtTL'

'Ct '

'DrkS'

'CnvM'

'copy'

'CpFX'

'CpyM'

'CpTL'

'Crql'

'CrtD'

'Crop'

'Clds'

'ClrB'

'ClrH'

'ClrR'

'ClrP'

"0B71D221-F8CE-11d2-B21B-0008C75B322C"

'CntC'

'Cntc'

Adobe Photoshop CS2 JavaScript Scripting Reference

Photoshop CS2

Appendix A: Event ID Codes 320

Event

Diffuse

4-char ID or String

'Dfs '

DiffuseGlow

DisableLayerFX

Displace

Distribute

Draw

DryBrush

Duplicate

DustAndScratches

'DfsG'

'dlfx'

'Dspl'

'Dstr'

'Draw'

'DryB'

'Dplc'

'DstS'

Emboss

Equalize

Exchange

Expand

'Embs'

'Eqlz'

'Exch'

'Expn'

Export

Jumpto

'Expr'

'Jpto'

ExportTransparentImage "02879e00-cb66-11d1-bc43-0060b0a13dc4"

Extrude 'Extr'

Facet

Fade

Feather

Fibers

Fill

FilmGrain

Filter

FindEdges

'Fct '

'Fade'

'Fthr'

'Fbrs'

'Fl '

'FlmG'

'Fltr'

'FndE'

FitImage "3caa3434-cb67-11d1-bc43-0060b0a13dc4"

FlattenImage 'FltI'

Flip

Fragment

'Flip'

'Frgm'

Fresco

GaussianBlur

Get

Glass

'Frsc'

'GsnB'

'getd'

'Gls '

Adobe Photoshop CS2 JavaScript Scripting Reference

Photoshop CS2

Appendix A: Event ID Codes 321

Event

GlowingEdges

4-char ID or String

'GlwE'

Gradient

GradientMap

Grain

GraphicPen

Group

Grow

HalftoneScreen

Hide

HighPass

HSBHSL

HueSaturation

ImageSize

Import

InkOutlines

Intersect

IntersectWith

'HghP'

'HsbP'

'HStr'

'ImgS'

'Impr'

'InkO'

'Intr'

'IntW'

'Grdn'

'GrMp'

'Grn '

'GraP'

'GrpL'

'Grow'

'HlfS'

'Hd '

Inverse

Invert

LensFlare

Levels

LightingEffects

Link

Make

Maximum

'Invs'

'Invr'

'LnsF'

'Lvls'

'LghE'

'Lnk '

'Mk '

'Mxm '

Median

MergeLayers

MergeLayersOld

MergeSpotChannel

'Mdn '

'Mrg2'

'MrgL'

'MSpt'

MergeVisible

Mezzotint

'MrgV'

'Mztn'

Minimum 'Mnm '

ModeChange "8cba8cd6-cb66-11d1-bc43-0060b0a13dc4"

Adobe Photoshop CS2 JavaScript Scripting Reference

Photoshop CS2

Event

Mosaic

PasteEffects

PasteInto

PasteOutside

Patchwork

Photocopy

PicturePackage

Pinch

Place

Plaster

PlasticWrap

Play

Pointillize

Polar

PosterEdges

Posterize

Previous

Mosaic_PLUGIN

MotionBlur

Move

NTSCColors

NeonGlow

Next

NotePaper

Notify

Null

OceanRipple

Offset

Open

Paint

PaintDaubs

PaletteKnife

Paste

Appendix A: Event ID Codes 322

4-char ID or String

'Msc ' typeNull

'OcnR'

'Ofst'

'Opn '

'Pnt '

'PntD'

'PltK'

'past'

'MscT'

'MtnB'

'move'

'NTSC'

'NGlw'

'Nxt '

'NtPr'

'Ntfy'

'Plst'

'PlsW'

'Ply '

'Pntl'

'Plr '

'PstE'

'Pstr'

'Prvs'

'PaFX'

'PstI'

'PstO'

'Ptch'

'Phtc'

"4C1ABF40-DD82-11d2-B20F-0008C75B322C"

'Pnch'

'Plc '

Adobe Photoshop CS2 JavaScript Scripting Reference

Photoshop CS2

Event

Print

Rotate

RoughPastels

Save

Select

SelectiveColor

Set

SharpenEdges

Sharpen

SharpenMore

Shear

Show

Similar

SmartBlur

Smooth

SmudgeStick

Solarize

ProfileToProfile

Purge

Quit

RadialBlur

Rasterize

RasterizeTypeSheet

RemoveBlackMatte

RemoveLayerMask

RemoveWhiteMatte

Rename

ReplaceColor

Reset

ResizeImage

Reticulation

Revert

Ripple

Appendix A: Event ID Codes 323

4-char ID or String

'Prnt'

'ShrM'

'Shr '

'Shw '

'Smlr'

'SmrB'

'Smth'

'SmdS'

'Slrz'

'Rtte'

'RghP'

'save'

'slct'

'SlcC'

'setd'

'ShrE'

'Shrp'

'PrfT'

'Prge'

'quit'

'RdlB'

'Rstr'

'RstT'

'RmvB'

'RmvL'

'RmvW'

'Rnm '

'RplC'

'Rset'

"1333cf0c-cb67-11d1-bc43-0060b0a13dc4"

'Rtcl'

'Rvrt'

'Rple'

Adobe Photoshop CS2 JavaScript Scripting Reference

Photoshop CS2

Event

Spatter

Tiles

TornEdges

TraceContour

Transform

Trap

Twirl

Underpainting

Undo

Ungroup

Unlink

UnsharpMask

Variations

Wait

WaterPaper

Watercolor

Wave

Spherize

SplitChannels

Sponge

SprayedStrokes

StainedGlass

Stamp

Stop

Stroke

Subtract

SubtractFrom

Sumie

TakeMergedSnapshot

TakeSnapshot

TextureFill

Texturizer

Threshold

4-char ID or String

'Spt '

'Ungr'

'Unlk'

'UnsM'

'Vrtn'

'Wait'

'WtrP'

'Wtrc'

'Wave'

'Tls '

'TrnE'

'TrcC'

'Trnf'

'Trap'

'Twrl'

'Undr'

'undo'

'Sbtr'

'SbtF'

'Smie'

'TkMr'

'TkSn'

'TxtF'

'Txtz'

'Thrs'

'Sphr'

'SplC'

'Spng'

'SprS'

'StnG'

'Stmp'

'Stop'

'Strk'

Appendix A: Event ID Codes 324

Adobe Photoshop CS2 JavaScript Scripting Reference

Photoshop CS2

Event

Wind

ZigZag

BackLight

FillFlash

ColorCast

4-char ID or String

'Wnd '

'ZgZg'

'BacL'

'FilE'

'ColE'

Appendix A: Event ID Codes 325

JavaScript Scripting Reference

Index

A

absolute pathnames 243

Action Manager 184

Action manager 184

actions

command lists 46

descriptions 49

descriptors 43

playing 53

Actions, palette 183

active document 51

Add Noise filter

adjustments

brightness 58

color 265

color balance 58, 64

contrast 58, 62 curves 58

highlights 65

levels 59, 62

shadows 65

temperature 64

Adobe Illustrator, exporting paths to 102

alerts 195, 220, 304

aliases, referencing 246

alpha channels

defined 75

from transparency (TIFF documents) 181

opacity 75

saving

in BMP documents 72

in PDF documents 143

in PICT documents 148

in PICT resources 149

in Pixar documents 151

in PSD documents 147

in RAW documents 159

in SGIRGB documents 166

in Targa documents 171

in TIFF documents 181

anchor points

adding 139

specifying position of 265

annotations 90

annotations, importing 91

anti aliasing

options 265

text 174

application

activating 53

defaults 153

location 52

preferences 153

specifiers 315

applications

Adobe Photoshop CS2

as script execution targets 312

calling exported functions 316

communication between 315

debugging 283

artLayers, See layers

Asian text 156

authors 95

auto kerning 174, 265

auto leading 180

auto spacing, contact sheets 83

automatic layout of UI controls 201, 242

available memory 51

Average filter 59

B background color

application 51

galleries 106

background layers 57

backslashes in pathnames 244

baseline shift 174

batch command 53

batches

destination folder 69, 265 specifying options 69

beeping 153

bitmap documents

converting to 265

depth type 266

halftone type 265

opening 273

saving 72

bitmap images

See bitmap documents

black and white images 65

blending modes

layer sets 125

layers 57

options 266

Blur filter 59

blur filters

Average 59

Blur 59

Blur More 59

Gaussian Blur 60

Lens Blur 60

Motion Blur 60

Radial Blur 61

Smart Blur 61

Blur More filter 59

BMP documents

See bitmap documents

breakpoints 290

brightness 58 adjusting 58

equalizing 63

Lens Blur filter 129

button objects 192, 227

Index 326

JavaScript Scripting Reference

C caches

histograms 154 images 154

purging 54

call stack for execution 286

camera raw documents

opening 73

settings 266 size options 266

canvas

flipping 91 resizing 91

canvas, defined 87

captions

contact sheets 83

documents 95

gallery images 107

gallery thumbnails 111

images 95

channels

activating 87

adding 77

adjusting 58

alpha See alpha channels

creating 77

deleting 76

displaying in color 153

duplicating 76 making visible 76 merging 76

mixing 63

splitting 92

spot See spot channels types of 75

character encoding 246

checkbox objects 193, 227

clipping paths

from paths 135

from text 180

Clouds filter 59

CMYKColor 82

color balance, adjusting 64

color picker 153

color profiles

Also see individual document formats

changing 90

determining type of 88

naming 87

colors

active links 106

adjusting 265

balancing 58

channels 75

custom settings 109

in galleries 106

inverting 63

modifying 64

none 130

preserving (GIF only) 112

Adobe Photoshop CS2

reduction 103

settings 51

solid color objects 167 testing if equal 167

visited links 106

command line

for JavaScript 285

comments, layer comps 121

compatibility, maximizing 155

component channels

color balance 58

defined 75

listing 87

See component channels

composite channels 75

See composite channels

Compuserve GIF documents

opening 273

saving

confirmation dialogs 195, 220, 304

console 285

contact sheets

captions 83 columns 83

dimensions 84

making 53

rows 83

containers for UI controls 191

contrast

adjusting 58

adjusting automatically 62

camera raw settings 73

midtones 65

control types for ScriptUI windows 191

copyrights 95

cropping 90

cross-DOM

specifying application 316

CS2 version changes 39

cursors 155

curves, adjusting 58

Custom filters 59

D

data, tracking while debugging 284

DCS 1 documents, saving 85

debugging

call stack 286

in ExtendScript Toolkit 288

optimization tools 291

selecting target application 283

setting breakpoints 290

debugging tools

Dollar ($) object 293

ExtendScript Toolkit 281

Reflection object 297

De-Interlace filter 59

depth map

Lens Blur filter 129

Index 327

JavaScript Scripting Reference

desaturate 62

Despeckle filter 59

dialogs

creating with ScriptUI 187

displaying 51

modal and modeless

ScriptUI 195

predefined 220

Difference Clouds filter 59

Diffuse Glow filter 59

directories, referencing 257

directory specifications 243

Displace filter 59

distort filters

Diffuse Glow 59

Displace 59

Glass Effect 60

Ocean Ripple 60

Pinch 61

Polar Coordinates 61

Ripple 61

Shear 61

Spherize 61

Twirl 62

Wave 62

Zigzag 62

document formats

See also Individual formats

DocumentInfo 95

documents 87

activating 51

adding 99

closing 89

code sample 93

color profiles 87

cropping 90

dimensions 87

duplicating 90 exporting 90

info 95

loading 53

managed 88 metadata 88, 95

opening 54

optimizing for web 103

printing 91 resizing 91

resolution 88

saving 91, 92

trapping (CMYK) 92 trimming 92

Dollar ($) object 293

drives, specifying in paths 245

dropdownlist objects 194, 228

Dust and Scratches filter 60

E

edittext objects 192, 228

encoding 246

Adobe Photoshop CS2

Index 328

engine ExtendScript directive 311

engines, JavaScript 283

EPSSaveOptions 101

equalize 63

error handling

filesystem 247, 262

setting strict 312

events

in ScriptUI windows 199

Events Manager 52

executing JavaScript

about 316

in ExtendScript Toolkit 281, 288

executing scripts 38

execution call stack 286

exif 95

exported functions

specifying application 316

exporting

documents, to Illustrator 90

documents, to Web 103

paths 102

exporting and importing scripts 312

ExtendScript

command line 285

Dollar ($) object 293

engines 311

multiple engines 283

operator overloading 314

preprocessor directives 311

Reflection object 297

ScriptUI module 187, 219

ExtendScript Toolkit

about 281

configuring window 282

debugging 288

editing scripts 287

optimization tools 291

setting breakpoints 290

F file extensions

format 156

including 153

file info 95

File object 248

files

distinguishing from folders 243

extensions for valid scripts 37

merging 54

name and path specifications 243 files and folders, platform-independent reference objects 243

filesystem

aliases 246

error handling 247, 262

object references 243, 248

filetypes

macOS 51

Windows 52

JavaScript Scripting Reference filling

paths 134

selections 162

filters

See also individual filter names

Folder object 257

fonts

detecting 51

determining family of 172 determining style of 172

PostScript name of 172

formats

See document formats

frames for UI controls 188, 191

functions

call stack for debugging 286

G

galleries 109

background color 106

banners 105

captions 107

color options 106

credits 107 dimensions 107 filenames 107

link colors 106

making 53

metadata 109

photographer 105

security text 110

thumbnail images 111

GalleryBannerOptions 105

GalleryCustomColorOptions 106

GalleryImagesOptions 107, 108

GalleryOptions 109

GallerySecurityOptions 110

GalleryThumbnailOptions 111

Gaussian Blur filter 60

GIF documents

See Compuserve GIF documents

GIFSaveOptions 113

Glass Effect filter 60

global dialogs 195, 220, 304

global localize function 303

global object 293

glyph scaling 174–178

GrayColor 114

grids 154

grouped layers 57

grouping controls 191, 229

guides 154

H

halftone screen 71

handlers

for ScriptUI events 199

hanging punctuation 176

High Pass filter 60

Adobe Photoshop CS2 highlights

adjusting 65

color balance 58

histograms

channels 75

image cache 154

history log 156

history states

activating 87

allowing nonlinear 155 default number of 155

snapshot 115

HSBColor 117

hypenation 176

I

I/O, unicode 246

iconbutton objects 192, 229

icons, displaying in ScriptUI windows 194

IDs

getting 43

PICT Resource 149

property 49

runtime 53

runtime to string 54 string to runtime 54 string to type 54 type to char 54

Illustrator

See Adobe Illustrator

image

resizing 91

image objects 193, 229

image pyramids 181

images

bitmap 71

black and white 65

cache 154 caches 154

captions 107

definition of 87

desaturating 62

equalizing 63

filetypes 51

from split channels 92

inverting colors 63

previewing 154

pyramids 181

resizing 91

resizing in galleries 108

thumbnails 111

importing and exporting scripts 312

include ExtendScript directive 311

includepath ExtendScript directive 312

indexed color model 118

IndexedConversionOptions 118

info 95

installing scripts 38

interapplication communication

Index 329

JavaScript Scripting Reference

about 315

checking application installation 317

specifying target applications 316

Interface 41

internationalization

in ScriptUI windows 217

internationalization, ExtendScript utilities 300

interpolation 154

item objects 194, 229

J

JavaScript

changes in Illustrator CS2 39

console 285

debugging 281

editing scripts 287

engines 311

multiple engines 283

supported features 38

JPEG

quality 119

JPEG documents

quality 119 saving 119

JPEG options

scans 119

JPEGSaveOptions 119

justification 176

K

kerning 174

text

auto kerning 265

keyboard behavior 155

L

LabColor 120

languages 176

layer comps 121

adding 123

applying 121

in documents 88

layer sets

adding 127

art layers in 125

duplicating 126

in documents 88

linked layers in 125

linking 126

locking contents 125

making visible 326

moving 126

nesting 125 opacity 125

unlinking 126

layer styles, applying 61

LayerComps 123

layered TIFFdocuments, saving 153

Adobe Photoshop CS2

Layers 124

layers

adding 68

applying styles 61

background 57 blending mode 57 bounds 57

clipboard commands 62

comps 121

copying 62

duplicating 63

flattening 91

grouping 57

in documents 88

inverting 63

kind 57

linking 63

locking contents 57–58

making visible 58

merging 63

merging visible 91

moving 63

rasterizing 91

rasterizing contents 64

removing 68

resizing 64 rotating 64

saving in PDF documents 143

unlinking 65

LayerSet 125

LayerSets 127

layersets

merging 126

layout of user interface controls 188, 201, 242

layout properties in ScriptUI windows 202

leading 176, 180

Lens Blur filter

applying 60

brightness 129 iris shape 129 noise amount 129 options 129 radius 129 rotation 129

Lens Flare filter 60

letter spacing 175–178

levels

adjusting 58 adjusting automatically 58

ligatures 174–176

linked layers 63

links

unlinking 65

colors 106

listbox objects 194, 230

listitem objects 194

locale identifiers 301

localization

in ScriptUI windows 217

localization, ExtendScript utilities 300

Index 330

JavaScript Scripting Reference

localize function 303

locations of startup scripts 316

M

MacOS

filetypes 51

managed documents 88

maximizing compatibility 155

Maximum filter 60

measurement values 307

Median Noise filter 60

memory 51

merging

layers 63

visible layers 91

messaging other applications 315

metadata

document 88

galleries 109

xmp 89, 182

methods

batch 52

midtones

color balance 58

Minimum filter 60

modal and modeless dialogs

ScriptUI 195

Motion Blur filter 60

N namespaces

global 293

specifiers for interapplication communication 316

naming scripts 312

noise filters

Add Noise

Despeckle 59

Dust and Scratches 60

Median Noise 60

nonlinear history 155

notifications 304

notifiers

adding 133

event IDs 326

removing 131

NTSC filter 60

O object model

changes in Illustrator CS2 39

objects

creation properties 190

file and folder reference 243, 248, 257

global object 293

retrieving information about 297

user interface 187, 219

user interface controls 227

windows 220

Adobe Photoshop CS2

Ocean Ripple filter 60

Offset filter 61

old style type 179

olors

CMYK 82

opacity

channels 75

gallery security text 110

layer fill 57

layer sets 125

layers 58

picture packages 150

operator overloading in ExtendScript 314

optimization tools 291

optimizing 103

other filters

Custom 59

High Pass 60

Maximum 60

Minimum 60

Offset 61

P

palettes 155

panel objects 188, 191, 230

pasting 91

path items

adding 138

deselecting 134 filling 134

from text 180

making selection 135

path points 169

selecting 135

specifying path kind 134

stroking 135

sub items 134

sub path info 168

sub path items 169

work path from selection 162

path point info

anchor points 140 left direction 140 right direction 140

path points

anchor points 139 left direction 139 right direction 139

path specifications 243

PathItems 138

pathnames

separator characters 244 special characters 244

paths

See path items

PDF documents

opening 142

saving 143

PDF presentations

Index 331

JavaScript Scripting Reference

auto advance 157

making 53

output format 157 transition type 157

Photo CD discs, opening 146

photo filtering 64

photo galleries

See galleries

photomerge 54

Photoshop documents

opening 273

saving 147

Photoshop files, maximizing compatibility 155

PICT documents

opening 273

saving 148

PICT resources

opening 273

saving 149

picture packages

contents 150 flattening 150

making 54

opacity 150 options 150 text properties 150

Pinch filter 61

Pixar documents

opening 273

saving 151

PixarSaveOptions 151

pixels

aspect ratio 88

doubling 155

equalizing 63

interpolation 154

locking 58

unit measures 279

placing windows and controls 240

platform-independent paths 243

playback options 52

plug-in folder

additional plug-in folder 156

PNG 8 documents, saving 104

PNG documents

saving 152

PNGSaveOptions 152

Polar Coordinates filter 61

portability of file references 246

postrerize 64

postscript encoding 91

PostScript names 172

Preferences 153 preferences 153

PresentationOptions 157

presentations

making 53

PDF presentations

printing, documents 91

profiling for script optimization 291

Adobe Photoshop CS2

progressbar objects 193, 231

prompts 195, 221, 304

PSD documents

opening 273

saving 147

purging 54

Q

quote style 156

R

Radial Blur filter 61

radiobutton objects 193, 231

rasterize 64

rasterizing

document layers 91

RAW documents

opening 158

RawSaveOptions 159

Reflection object 297

relative pathnames 243

render filters

Clouds 59

Difference Clouds 59

Lens Flare 60

resolution

bitmap conversions 71

documents 88

resource strings for ScriptUI elements 197

RGBColor 160

Ripple filter 61

rotation 64

ruler units 155

S

save as 92

saving 91

Also see individual document formats.

script execution, setting target application 312 script ExtendScript directive 312

scripts

checking application installation 317

command line 285

debugging 281

editing in ExtendScript Toolkit 287

executing 38, 316

file extensions 37

importing and exporting definitions 312

including in other scripts 311

installing 38

menu 37

naming 312

output 285

startup 38, 316

support in Photoshop CS2 37

Scripts Events Manager 52

ScriptUI

about 187

Index 332

JavaScript Scripting Reference

control types 191

layout properties 202

object reference 219

programming model 187

resource strings 197

responding to user interaction 199

scrollbar objects 194, 232

selected areas 88

selections 161 boundaries 161 clearing 161 copying 161 cutting 161 deselecting 161 feathering 161

filling 162

from paths 135

making work path from 162

resizing 161, 162

rotating 162

smoothing 163 stroking 163

selective color 64

SGIRGB documents

saving 166

SGIRGB documents, saving 276

SGIRGBSaveOptions 166, 265

shadows

adjusting 65

color balance 58

Sharpen Edges filter 61

Sharpen filter 61

sharpen filters

Sharpen 61

Sharpen Edges 61

Sharpen More 61

Unsharp Mask 62

Sharpen More filter 61

Shear filter 61

sizing and placing windows and controls 240

slashes in pathnames 244

slider objects 193, 233

Smart Blur filter 61

smart quotes 156

special characters in pathnames 244

Spherize filter 61

spot channels

defined 75

merging into component channels 76

opacity 75

saving

in DCS 2 documents 86

in PDF documents 144

in PSD documents 147

in RAW documents 159

in SGIRGB documents 166

in TIFF documents 181

spotColors 166

startup script locations 316

startup scripts 38

Adobe Photoshop CS2

statictext objects 192, 233

strict ExtendScript directive 312

strike thru 179

string translation

in ScriptUI windows 217

string translation, ExtendScript utilities 300

stroking

default stroke color 51

path items 135

selections 163

styles, applying 61

sub path items 134

T

Targa documents, saving 171

target ExtendScript directive 312

targets

message 315

script execution 312

selecting application for debugging 283

temperature 64

testing

in ExtendScript Toolkit 288

scripts 281

text

Asian 156

auto kerning 174

auto leading 180

captions 107

color

composer 179

content 174

creating paths from 180

formatting 179

gallery security 110, 270

hyphenation 176

in picture packages 150

justification 176 languages 176

offset 174

orientation 175

spacing 175–178

tracking 179

wrapping 176

text composer 179

text fonts

See fonts

text items

See text

text layers

adding contents 174

creating 57

Texture Fill filter 62 texture filters, Texture Fill 62

threshold 65

thumbnails 111

Mac OS 155

Windows 156

TIFF documents

Index 333

JavaScript Scripting Reference

layered 153

saving 181

tool tips 156

Toolkit, ExtendScript 281

tracking, text 179

translation of UI strings 217, 300

transmission info 95

trapping 92

Twirl filter 62

type units 156

U

underlining 179

unicode I/O 246

units

ruler 155

type 156

units of measurement 307

UnitValue object 307

Unsharp Mask filter 62

URI notation 243

URLs, document 95

user interaction

ScriptUI events and handlers 199

user interface controls 227

accessing 190

adding 189

automatic layout 242

creation properties 190

grouping 188, 191

methods 238

placing 240

properties 234

removing 190

responding to user interaction 239

size and location 188

types 191

user interface elements 187, 219

user prompts 195, 221, 304

UTF8 Encoding 109

Utilities 183

V

variable values during execution 284

version

application 52 scripting interface 52

Adobe Photoshop CS2

video alpha 156

video filters

De-Interlace 59

NTSC 60

visibility

channels 76

layer comps 121

layer sets 326

layers 58

volumes, specifying in paths 245

W

warp 180

Wave filter 62

Web photo galleries

See galleries.

webSnap 104

Window class 220

Windows

filetypes 52

windows

accessing child controls 190

adding controls 224

automatic layout 201

controlling 221 creating 187, 221

creation properties 190

grouping controls 188, 223 layout 188

placing 240

removing child controls 190

responding to user interaction 225

reusing 220

word spacing 175–178

work paths

designating 274

from selected area 162

wrapping, text 176

X

xml 182

xmp metadata 89, 182

Z

Zigzag filter 62

zoom 155

Index 334

JavaScript Scripting Reference

Adobe Photoshop CS2

Index 335

advertisement

Key Features

  • Automate repetitive tasks
  • Extend Photoshop's functionality
  • Integrate Photoshop into workflows
  • Create custom scripts
  • JavaScript scripting language support

Frequently Answers and Questions

What is JavaScript scripting?
JavaScript scripting is a way to automate tasks in Photoshop using the JavaScript programming language. It allows you to write scripts that can perform actions, manipulate images, and interact with Photoshop's interface.
How do I execute a script?
You can execute a script by opening it in Photoshop's Scripting Listener or by using the File > Scripts menu.
Where can I find more information about scripting in Photoshop?
The Adobe Photoshop CS2 JavaScript Scripting Reference provides a comprehensive guide to all the scripting features and objects available in Photoshop.

Related manuals