Macromedia Bridge - CS2 User Manual

2
Creative Suite
®
Bridge JavaScript Reference
Adobe
bbc
© 2005 Adobe Systems Incorporated. All rights reserved.
Bridge JavaScript 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, InDesign, and Version Cue are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
Apple, Mac, Macintosh, and Mac OS 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

Welcome ..................................................................................................................................... 19
About This Book............................................................................................................................................................................19
Who should read this book ................................................................................................................................................19
What is in this book ...............................................................................................................................................................19
Document conventions .......................................................................................................................................................20
Typographical conventions .........................................................................................................................................20
JavaScript conventions..................................................................................................................................................20
Where to go for more information ..................................................................................................................................21
1 Scripting Bridge .........................................................................................................................22
Scripting Overview ......................................................................................................................................................................22
Executing Scripts....................................................................................................................................................................22
Communicating with Other Applications.....................................................................................................................23
The Bridge Document Object Model ...................................................................................................................................23
The application and documents.......................................................................................................................................24
Thumbnails in documents..................................................................................................................................................25
Thumbnails as node references .................................................................................................................................25
Using and accessing thumbnails ...............................................................................................................................25
User interface objects...........................................................................................................................................................26
Navigation bars ................................................................................................................................................................26
Dialogs.................................................................................................................................................................................26
Menus ..................................................................................................................................................................................27
Events.........................................................................................................................................................................................27
Application preferences ......................................................................................................................................................27
The Bridge DOM and the Bridge Browser Window..........................................................................................................28
2 Event Handling and Script-Defined Browse Schemes ............................................................ 31
Event Handling in Bridge...........................................................................................................................................................31
Defining event handlers......................................................................................................................................................31
Registering event handlers.................................................................................................................................................32
Event handling examples....................................................................................................................................................32
User-interface events............................................................................................................................................................35
Script-Defined Browse Schemes.............................................................................................................................................36
Defining and registering a browse scheme .................................................................................................................36
3 Creating a User Interface ..........................................................................................................38
User Interface Options for Scripts...........................................................................................................................................38
Navigation Bars.......................................................................................................................................................................38
Dialogs Boxes ..........................................................................................................................................................................39
Content Pane...........................................................................................................................................................................39
ScriptUI User Interfaces ..............................................................................................................................................................40
Displaying ScriptUI Dialogs ................................................................................................................................................40
Displaying ScriptUI elements in a navigation bar ......................................................................................................40
Displaying HTML in Bridge........................................................................................................................................................42
Defining callbacks for HTML scripts ................................................................................................................................42
Executing script functions defined on HTML UI pages ............................................................................................43
Displaying HTML in Bridge Dialogs........................................................................................................................................44
3
Adobe Creative Suite 2
Bridge JavaScript Reference 4
Communicating with Bridge from dialog JavaScript................................................................................................44
Using callbacks in an HTML dialog ..................................................................................................................................45
Calling functions defined in an HTML dialog ........................................................................................................47
Displaying HTML in a Navigation Bar ....................................................................................................................................47
Using callbacks from an HTML navigation bar............................................................................................................47
Calling functions defined in an HTML navigation bar..............................................................................................48
Displaying HTML in the Content Pane..................................................................................................................................50
Callback example: Requesting specific metadata value for a file.........................................................................50
Passing Complex Values in Remote Calls ............................................................................................................................51
Passing an object from Bridge to HTML/JavaScript ..................................................................................................52
Scheduling tasks from callbacks .............................................................................................................................................53
Scheduling a remote function execution......................................................................................................................54
4 Using File and Folder Objects ................................................................................................... 56
Overview .........................................................................................................................................................................................56
Specifying Paths............................................................................................................................................................................56
Absolute and relative path names...................................................................................................................................56
Character interpretation in paths.....................................................................................................................................57
The home directory...............................................................................................................................................................57
Volume and drive names ....................................................................................................................................................58
Mac OS volumes...............................................................................................................................................................58
Windows drives ................................................................................................................................................................58
Aliases.........................................................................................................................................................................................59
Portability issues.....................................................................................................................................................................59
Unicode I/O ....................................................................................................................................................................................59
File Error Handling ......................................................................................................................................................................60
5 Using ScriptUI ............................................................................................................................61
Overview .........................................................................................................................................................................................61
ScriptUI Programming Model ..................................................................................................................................................61
Creating a window ...............................................................................................................................................................61
Container elements...............................................................................................................................................................62
Window layout .......................................................................................................................................................................62
Adding elements to containers ........................................................................................................................................63
Creation properties.........................................................................................................................................................64
Accessing child elements ............................................................................................................................................64
Removing elements ..............................................................................................................................................................65
Types of controls ...................................................................................................................................................................65
Containers ..........................................................................................................................................................................65
Panel...................................................................................................................................................................................65
Group .................................................................................................................................................................................65
User interface controls...................................................................................................................................................65
StaticText ..........................................................................................................................................................................66
EditText .............................................................................................................................................................................66
Button ................................................................................................................................................................................66
IconButton .......................................................................................................................................................................66
Image .................................................................................................................................................................................67
Checkbox ..........................................................................................................................................................................67
RadioButton.....................................................................................................................................................................67
Progressbar......................................................................................................................................................................67
Slider...................................................................................................................................................................................67
Scrollbar ............................................................................................................................................................................68
Adobe Creative Suite 2
Bridge JavaScript Reference 5
ListBox................................................................................................................................................................................68
DropDownList.................................................................................................................................................................68
ListItem..............................................................................................................................................................................68
Displaying icons......................................................................................................................................................................68
Prompts and alerts ...............................................................................................................................................................69
Modal dialogs .........................................................................................................................................................................69
Creating and using modal dialogs ............................................................................................................................69
Dismissing a modal dialog ...........................................................................................................................................70
Default and cancel elements.......................................................................................................................................70
Resource Specifications ............................................................................................................................................................71
Defining Behavior for Controls with Event Callbacks .....................................................................................................73
Defining event handler functions ....................................................................................................................................73
Simulating user events.........................................................................................................................................................73
Automatic Layout ........................................................................................................................................................................75
Default layout behavior .......................................................................................................................................................75
Automatic layout properties..............................................................................................................................................76
Container orientation.....................................................................................................................................................76
Aligning children .............................................................................................................................................................76
Setting margins ................................................................................................................................................................78
Spacing between children ...........................................................................................................................................79
Determining a preferred size.......................................................................................................................................79
Creating more complex arrangements ...................................................................................................................79
Creating dynamic content............................................................................................................................................81
Custom layout manager example....................................................................................................................................82
The AutoLayoutManager algorithm ...............................................................................................................................84
Automatic layout restrictions ............................................................................................................................................85
Example scripts .............................................................................................................................................................................86
Alert box builder.....................................................................................................................................................................86
Resource specification example.................................................................................................................................89
Localization in ScriptUI Objects ..............................................................................................................................................91
Variable values in localized strings ..................................................................................................................................91
Enabling automatic localization .......................................................................................................................................91
6 Bridge DOM Object Reference.................................................................................................. 93
App Object......................................................................................................................................................................................94
App object properties ..........................................................................................................................................................94
displayDialogs.................................................................................................................................................................94
document .........................................................................................................................................................................94
documents .......................................................................................................................................................................94
eventHandlers.................................................................................................................................................................94
favorites.............................................................................................................................................................................94
language ...........................................................................................................................................................................94
locale ..................................................................................................................................................................................95
name...................................................................................................................................................................................95
preferences ......................................................................................................................................................................95
version ...............................................................................................................................................................................95
App object functions ............................................................................................................................................................95
beep....................................................................................................................................................................................95
browseTo ..........................................................................................................................................................................95
buildFolderCache ..........................................................................................................................................................96
cancelTask ........................................................................................................................................................................96
Adobe Creative Suite 2
Bridge JavaScript Reference 6
hide.....................................................................................................................................................................................96
preflightFiles....................................................................................................................................................................96
purgeAllCaches ..............................................................................................................................................................96
purgeFolderCache.........................................................................................................................................................96
quit......................................................................................................................................................................................97
registerBrowseScheme................................................................................................................................................97
scheduleTask...................................................................................................................................................................97
system................................................................................................................................................................................97
Dialog Object ................................................................................................................................................................................98
Dialog object constructor ...................................................................................................................................................98
Dialog object properties......................................................................................................................................................98
active ..................................................................................................................................................................................98
closing................................................................................................................................................................................98
height.................................................................................................................................................................................98
modal .................................................................................................................................................................................98
title ......................................................................................................................................................................................98
width ..................................................................................................................................................................................98
Dialog object functions .......................................................................................................................................................98
center .................................................................................................................................................................................98
close....................................................................................................................................................................................98
execJS.................................................................................................................................................................................99
open ..................................................................................................................................................................................99
place ...................................................................................................................................................................................99
print ....................................................................................................................................................................................99
Document Object...................................................................................................................................................................... 100
Document object properties .......................................................................................................................................... 100
allowDrags .................................................................................................................................................................... 100
contentPaneMode ..................................................................................................................................................... 100
context............................................................................................................................................................................ 100
id ....................................................................................................................................................................................... 100
jsFuncs ............................................................................................................................................................................ 100
maximized..................................................................................................................................................................... 100
minimized...................................................................................................................................................................... 100
navbars ........................................................................................................................................................................... 101
noItems........................................................................................................................................................................... 101
owner .............................................................................................................................................................................. 101
previewLooping.......................................................................................................................................................... 101
selections....................................................................................................................................................................... 101
showThumbnailName .............................................................................................................................................. 101
sorts ................................................................................................................................................................................. 102
status............................................................................................................................................................................... 102
thumbnail ...................................................................................................................................................................... 102
thumbnailViewMode ................................................................................................................................................ 102
visible .............................................................................................................................................................................. 102
visibleThumbnails ...................................................................................................................................................... 103
visitUrl ............................................................................................................................................................................. 103
Document object functions ............................................................................................................................................ 103
bringToFront ................................................................................................................................................................ 103
close................................................................................................................................................................................. 103
deselect .......................................................................................................................................................................... 104
deselectAll..................................................................................................................
................................................... 104
Adobe Creative Suite 2
Bridge JavaScript Reference 7
execJS.............................................................................................................................................................................. 104
maximize........................................................................................................................................................................ 104
minimize ........................................................................................................................................................................ 104
refresh............................................................................................................................................................................. 104
resetToDefaultWorkspace ....................................................................................................................................... 104
restore............................................................................................................................................................................. 104
reveal............................................................................................................................................................................... 105
select ............................................................................................................................................................................... 105
selectAll .......................................................................................................................................................................... 105
Event Object................................................................................................................................................................................ 106
Event object properties .................................................................................................................................................... 106
appPath.......................................................................................................................................................................... 106
document ...................................................................................................................................................................... 106
favorites.......................................................................................................................................................................... 106
isContext........................................................................................................................................................................ 106
location........................................................................................................................................................................... 106
object .............................................................................................................................................................................. 107
type.................................................................................................................................................................................. 107
url...................................................................................................................................................................................... 107
where .............................................................................................................................................................................. 107
Event Object Types............................................................................................................................................................. 107
App events ...................................................................................................................................................................... 107
close................................................................................................................................................................................. 107
destroy............................................................................................................................................................................ 107
Document events ......................................................................................................................................................... 108
complete........................................................................................................................................................................ 108
create .............................................................................................................................................................................. 108
deselect .......................................................................................................................................................................... 108
destroy............................................................................................................................................................................ 108
empty.............................................................................................................................................................................. 108
failed................................................................................................................................................................................ 108
loaded............................................................................................................................................................................. 108
loading............................................................................................................................................................................ 108
open ................................................................................................................................................................................ 108
select ............................................................................................................................................................................... 108
stopped .......................................................................................................................................................................... 108
uploading ...................................................................................................................................................................... 108
Thumbnail events......................................................................................................................................................... 109
add ................................................................................................................................................................................... 109
deselect .......................................................................................................................................................................... 109
hover ............................................................................................................................................................................... 109
modify............................................................................................................................................................................. 109
move................................................................................................................................................................................ 109
open ................................................................................................................................................................................ 109
openWith ....................................................................................................................................................................... 109
preview........................................................................................................................................................................... 109
remove............................................................................................................................................................................ 110
select ............................................................................................................................................................................... 110
PreferencesDialog events.......................................................................................................................................... 110
cancel .............................................................................................................................................................................. 110
create .......................................................................................................................
....................................................... 110
Adobe Creative Suite 2
Bridge JavaScript Reference 8
destroy............................................................................................................................................................................ 110
ok ...................................................................................................................................................................................... 110
Favorites Object......................................................................................................................................................................... 111
Favorites object properties ............................................................................................................................................. 111
length.............................................................................................................................................................................. 111
section ............................................................................................................................................................................ 111
Favorites object functions ............................................................................................................................................... 111
addChild......................................................................................................................................................................... 111
clearAll ............................................................................................................................................................................ 111
insert................................................................................................................................................................................ 111
remove............................................................................................................................................................................ 112
Metadata Object ........................................................................................................................................................................ 113
Metadata object properties............................................................................................................................................. 113
Label ................................................................................................................................................................................ 113
namespace.................................................................................................................................................................... 114
xmpPropertyName ...................................................................................................................................................... 114
Examples.......................................................................................................................................................................... 114
Metadata object functions .............................................................................................................................................. 115
applyMetadataTemplate ......................................................................................................................................... 115
NavBar Object............................................................................................................................................................................. 116
NavBar object properties ................................................................................................................................................. 116
file..................................................................................................................................................................................... 116
height.............................................................................................................................................................................. 116
jsFuncs ........................................................................................................................................................................... 116
type.................................................................................................................................................................................. 117
visible .............................................................................................................................................................................. 117
NavBar object functions ................................................................................................................................................... 117
add ................................................................................................................................................................................... 117
execJS.............................................................................................................................................................................. 118
print ................................................................................................................................................................................. 118
Preferences Object.................................................................................................................................................................... 119
Preferences object properties ........................................................................................................................................ 119
extraMetadata.............................................................................................................................................................. 119
showName .................................................................................................................................................................... 119
BackgroundColor........................................................................................................................................................ 120
FileSize............................................................................................................................................................................ 120
HideEmptyFields......................................................................................................................................................... 120
Label1.............................................................................................................................................................................. 120
Label2.............................................................................................................................................................................. 120
Label3.............................................................................................................................................................................. 120
Label4.............................................................................................................................................................................. 120
Label5.............................................................................................................................................................................. 120
Language....................................................................................................................................................................... 120
MRUCount..................................................................................................................................................................... 120
ShowLabels................................................................................................................................................................... 120
ShowName.................................................................................................................................................................... 120
UseLocalCaches........................................................................................................................................................... 121
anyPropertyName........................................................................................................................................................ 121
Preferences object functions ...................................................................................................
....................................... 121
clear ................................................................................................................................................................................. 121
PreferencesDialog Object ...................................................................................................................................................... 122
Adobe Creative Suite 2
Bridge JavaScript Reference 9
PreferencesDialog object functions............................................................................................................................. 122
addPanel ........................................................................................................................................................................ 122
close................................................................................................................................................................................. 122
Thumbnail Object ..................................................................................................................................................................... 123
Thumbnail object constructor ....................................................................................................................................... 123
Node specifiers .............................................................................................................................................................. 123
Multiple references to the same node .................................................................................................................. 124
Thumbnail object properties .......................................................................................................................................... 125
aliasType ........................................................................................................................................................................ 125
children .......................................................................................................................................................................... 125
container........................................................................................................................................................................ 125
creationDate................................................................................................................................................................. 125
displayMode ................................................................................................................................................................. 125
displayPath.................................................................................................................................................................... 125
hidden............................................................................................................................................................................. 125
lastModifiedDate ........................................................................................................................................................ 125
location........................................................................................................................................................................... 126
metadata........................................................................................................................................................................ 126
mimeType...................................................................................................................................................................... 126
name................................................................................................................................................................................ 126
parent.............................................................................................................................................................................. 126
path.................................................................................................................................................................................. 126
spec.................................................................................................................................................................................. 126
synchronousMetadata.............................................................................................................................................. 126
type.................................................................................................................................................................................. 126
Thumbnail object functions............................................................................................................................................ 126
copyTo ............................................................................................................................................................................ 126
moveTo .......................................................................................................................................................................... 127
open ................................................................................................................................................................................ 127
openWith ....................................................................................................................................................................... 127
refresh............................................................................................................................................................................. 127
remove............................................................................................................................................................................ 128
resolve............................................................................................................................................................................. 128
7 File and Folder Object Reference ...........................................................................................129
Overview ...................................................................................................................................................................................... 129
File Object .................................................................................................................................................................................... 129
File object constructors .................................................................................................................................................... 129
File class properties............................................................................................................................................................ 130
fs........................................................................................................................................................................................ 130
File class functions.............................................................................................................................................................. 130
decode............................................................................................................................................................................ 130
encode............................................................................................................................................................................ 130
isEncodingAvailable .................................................................................................................................................. 130
openDialog ................................................................................................................................................................... 131
saveDialog..................................................................................................................................................................... 131
File object properties......................................................................................................................................................... 132
absoluteURI................................................................................................................................................................... 132
alias .................................................................................................................................................................................. 132
created............................................................................................................................................................................ 132
creator............................................................................................................................................................................. 132
Adobe Creative Suite 2
Bridge JavaScript Reference 10
encoding........................................................................................................................................................................ 132
eof .................................................................................................................................................................................... 132
error ................................................................................................................................................................................. 132
exists................................................................................................................................................................................ 132
fsName............................................................................................................................................................................ 132
hidden............................................................................................................................................................................. 132
length.............................................................................................................................................................................. 132
lineFeed.......................................................................................................................................................................... 132
modified......................................................................................................................................................................... 132
name................................................................................................................................................................................ 132
parent.............................................................................................................................................................................. 132
path.................................................................................................................................................................................. 133
readonly ......................................................................................................................................................................... 133
relativeURI ..................................................................................................................................................................... 133
type.................................................................................................................................................................................. 133
File object functions........................................................................................................................................................... 133
close................................................................................................................................................................................. 133
copy ................................................................................................................................................................................. 133
createAlias..................................................................................................................................................................... 133
execute ........................................................................................................................................................................... 133
getRelativeURI ............................................................................................................................................................. 133
open ................................................................................................................................................................................ 134
openDlg ......................................................................................................................................................................... 135
read.................................................................................................................................................................................. 135
readch ............................................................................................................................................................................. 135
readln .............................................................................................................................................................................. 135
remove............................................................................................................................................................................ 135
rename............................................................................................................................................................................ 136
resolve............................................................................................................................................................................. 136
saveDlg........................................................................................................................................................................... 136
seek.................................................................................................................................................................................. 136
tell..................................................................................................................................................................................... 136
write................................................................................................................................................................................. 137
writeln............................................................................................................................................................................. 137
Folder Object ............................................................................................................................................................................. 138
Folder object constructors............................................................................................................................................... 138
Folder class properties ...................................................................................................................................................... 138
appData.......................................................................................................................................................................... 138
commonFiles................................................................................................................................................................ 138
current ............................................................................................................................................................................ 138
fs........................................................................................................................................................................................ 138
myDocuments ............................................................................................................................................................. 138
startup............................................................................................................................................................................. 138
system............................................................................................................................................................................. 139
temp ................................................................................................................................................................................ 139
trash................................................................................................................................................................................. 139
userData......................................................................................................................................................................... 139
Folder class functions ........................................................................................................................................................ 139
decode............................................................................................................................................................................ 139
encode............................................................................................................................................................................ 139
isEncodingAvailable ..........................................................................................................
........................................ 139
Adobe Creative Suite 2
Bridge JavaScript Reference 11
selectDialog .................................................................................................................................................................. 140
Folder object properties................................................................................................................................................... 140
absoluteURI................................................................................................................................................................... 140
alias .................................................................................................................................................................................. 140
created............................................................................................................................................................................ 140
error ................................................................................................................................................................................. 140
exists................................................................................................................................................................................ 140
fsName............................................................................................................................................................................ 140
modified......................................................................................................................................................................... 140
name................................................................................................................................................................................ 140
parent.............................................................................................................................................................................. 140
path.................................................................................................................................................................................. 140
relativeURI ..................................................................................................................................................................... 140
Folder object functions..................................................................................................................................................... 141
create .............................................................................................................................................................................. 141
execute ........................................................................................................................................................................... 141
getFiles ........................................................................................................................................................................... 141
getRelativeURI ............................................................................................................................................................. 141
remove............................................................................................................................................................................ 141
rename............................................................................................................................................................................ 141
resolve............................................................................................................................................................................. 141
selectDlg ........................................................................................................................................................................ 142
File and Folder Error Messages ............................................................................................................................................ 143
File and Folder Supported Encoding Names .................................................................................................................. 144
Additional encodings ........................................................................................................................................................ 144
8 ScriptUI Object Reference ....................................................................................................... 146
Overview ...................................................................................................................................................................................... 146
Window Class.............................................................................................................................................................................. 147
Window class properties .................................................................................................................................................. 147
coreVersion ................................................................................................................................................................... 147
version ............................................................................................................................................................................ 147
Window class functions .................................................................................................................................................... 147
alert.................................................................................................................................................................................. 147
confirm ........................................................................................................................................................................... 147
find................................................................................................................................................................................... 147
getResourceText ......................................................................................................................................................... 148
prompt............................................................................................................................................................................ 148
Window Object .......................................................................................................................................................................... 148
Window object constructor ............................................................................................................................................ 148
Window object properties ............................................................................................................................................... 149
defaultElement............................................................................................................................................................ 149
cancelElement ............................................................................................................................................................. 149
frameBounds................................................................................................................................................................ 149
frameLocation.............................................................................................................................................................. 149
frameSize ....................................................................................................................................................................... 149
Container properties.......................................................................................................................................................... 150
alignChildren................................................................................................................................................................ 150
children .......................................................................................................................................................................... 150
layout .............................................................................................................................................................................. 150
margins........................................................................................................................................................................... 150
Adobe Creative Suite 2
Bridge JavaScript Reference 12
orientation..................................................................................................................................................................... 151
spacing ........................................................................................................................................................................... 151
Window object functions................................................................................................................................................. 151
add ................................................................................................................................................................................... 151
center .............................................................................................................................................................................. 151
close................................................................................................................................................................................. 151
hide.................................................................................................................................................................................. 152
notify ............................................................................................................................................................................... 152
remove............................................................................................................................................................................ 152
show ................................................................................................................................................................................ 152
Window event-handling callbacks ............................................................................................................................... 152
onClose........................................................................................................................................................................... 152
onMove .......................................................................................................................................................................... 152
onMoving ...................................................................................................................................................................... 152
onResize ......................................................................................................................................................................... 152
onResizing..................................................................................................................................................................... 153
onShow .......................................................................................................................................................................... 153
Control Objects ......................................................................................................................................................................... 154
Control object constructors ............................................................................................................................................ 154
add ................................................................................................................................................................................... 154
Control types and creation parameters................................................................................................................ 154
button ............................................................................................................................................................................. 154
checkbox........................................................................................................................................................................ 154
dropdownlist................................................................................................................................................................ 155
edittext ........................................................................................................................................................................... 155
group............................................................................................................................................................................... 156
iconbutton .................................................................................................................................................................... 156
image .............................................................................................................................................................................. 156
item.................................................................................................................................................................................. 156
listbox.............................................................................................................................................................................. 157
panel................................................................................................................................................................................ 157
progressbar................................................................................................................................................................... 157
radiobutton................................................................................................................................................................... 158
scrollbar.......................................................................................................................................................................... 158
slider ................................................................................................................................................................................ 159
statictext ........................................................................................................................................................................ 159
Control object properties................................................................................................................................................. 160
active ............................................................................................................................................................................... 160
alignment ...................................................................................................................................................................... 160
bounds............................................................................................................................................................................ 160
enabled .......................................................................................................................................................................... 160
helpTip............................................................................................................................................................................ 160
icon .................................................................................................................................................................................. 161
index................................................................................................................................................................................ 161
items................................................................................................................................................................................ 161
itemSize.......................................................................................................................................................................... 161
jumpdelta ...................................................................................................................................................................... 161
justify............................................................................................................................................................................... 161
location........................................................................................................................................................................... 161
maxvalue ....................................................................................................................................................................... 161
minvalue .....................................................................................................................
................................................... 162
Adobe Creative Suite 2
Bridge JavaScript Reference 13
parent.............................................................................................................................................................................. 162
preferredSize ................................................................................................................................................................ 162
properties ...................................................................................................................................................................... 162
selected .......................................................................................................................................................................... 162
selection......................................................................................................................................................................... 162
size ................................................................................................................................................................................... 162
stepdelta ........................................................................................................................................................................ 162
text ................................................................................................................................................................................... 163
textselection ................................................................................................................................................................. 163
type.................................................................................................................................................................................. 163
value ................................................................................................................................................................................ 163
value ................................................................................................................................................................................ 163
visible .............................................................................................................................................................................. 163
Control object functions................................................................................................................................................... 164
add ................................................................................................................................................................................... 164
find................................................................................................................................................................................... 164
hide.................................................................................................................................................................................. 164
notify ............................................................................................................................................................................... 164
remove............................................................................................................................................................................ 164
removeAll ...................................................................................................................................................................... 164
show ................................................................................................................................................................................ 164
toString........................................................................................................................................................................... 165
valueOf ........................................................................................................................................................................... 165
Control event-handling callbacks................................................................................................................................. 165
onClick ............................................................................................................................................................................ 165
onChange ...................................................................................................................................................................... 165
onChanging.................................................................................................................................................................. 165
Size and Location Objects ...................................................................................................................................................... 166
Bounds............................................................................................................................................................................ 166
Dimension ..................................................................................................................................................................... 166
Margins........................................................................................................................................................................... 167
Point ................................................................................................................................................................................ 167
LayoutManager Object ........................................................................................................................................................... 168
AutoLayoutManager object constructor.................................................................................................................... 168
AutoLayoutManager object properties ...................................................................................................................... 168
AutoLayoutManager object functions ........................................................................................................................ 168
layout .............................................................................................................................................................................. 168
MenuElement Object............................................................................................................................................................... 169
MenuElement class functions......................................................................................................................................... 169
create .............................................................................................................................................................................. 169
find................................................................................................................................................................................... 170
remove............................................................................................................................................................................ 170
Creating new menu elements.................................................................................................................................. 170
MenuElement object properties ................................................................................................................................... 171
altDown.......................................................................................................................................................................... 171
checked .......................................................................................................................................................................... 171
cmdDown ...................................................................................................................................................................... 171
ctrlDown ........................................................................................................................................................................ 171
enabled .......................................................................................................................................................................... 171
id ....................................................................................................................................................................................... 172
onDisplay....................................................................................................................
................................................... 172
Adobe Creative Suite 2
Bridge JavaScript Reference 14
optionDown ................................................................................................................................................................. 172
onSelect.......................................................................................................................................................................... 172
shiftDown ...................................................................................................................................................................... 172
text ................................................................................................................................................................................... 172
type.................................................................................................................................................................................. 172
Bridge menu and command identifiers...................................................................................................................... 172
Bridge menu identifiers.............................................................................................................................................. 172
Bridge submenu and command identifiers ....................................................................................................... 173
9 Interapplication Communication with Scripts ...................................................................... 180
Cross-DOM Functions .............................................................................................................................................................. 181
Cross-DOM API Reference...................................................................................................................................................... 181
executeScript ............................................................................................................................................................... 181
open ................................................................................................................................................................................ 181
openAsNew .................................................................................................................................................................. 182
print ................................................................................................................................................................................. 182
quit................................................................................................................................................................................... 182
reveal............................................................................................................................................................................... 182
Application-Specific Exported Functions ......................................................................................................................... 182
Communicating Through Interapplication Messages ................................................................................................ 184
Sending messages.............................................................................................................................................................. 184
Receiving messages ........................................................................................................................................................... 186
Handling unsolicited messages ..................................................................................................................................... 186
Handling responses from the message target......................................................................................................... 187
Passing values between applications.......................................................................................................................... 190
Passing simple types ................................................................................................................................................... 190
Passing complex types ............................................................................................................................................... 191
Interapplication Message API Reference .......................................................................................................................... 193
BridgeTalk Class................................................................................................................................................................... 193
BridgeTalk class properties ....................................................................................................................................... 193
appLocale ...................................................................................................................................................................... 193
appName ....................................................................................................................................................................... 193
appVersion .................................................................................................................................................................... 193
onReceived ................................................................................................................................................................... 194
BridgeTalk class functions ......................................................................................................................................... 194
bringToFront ................................................................................................................................................................ 194
getSpecifier................................................................................................................................................................... 194
getTargets ..................................................................................................................................................................... 195
isRunning....................................................................................................................................................................... 196
launch ............................................................................................................................................................................. 196
pump............................................................................................................................................................................... 196
BridgeTalk Message Object ............................................................................................................................................. 197
BridgeTalk message object constructor ............................................................................................................... 197
BridgeTalk message object properties ................................................................................................................. 197
body................................................................................................................................................................................. 197
headers........................................................................................................................................................................... 197
sender ............................................................................................................................................................................. 197
target............................................................................................................................................................................... 198
timeout........................................................................................................................................................................... 198
type.................................................................................................................................................................................. 198
BridgeTalk message object callbacks .................................................................................................................... 198
Adobe Creative Suite 2
Bridge JavaScript Reference 15
onError............................................................................................................................................................................ 198
onReceived ................................................................................................................................................................... 199
onResult ......................................................................................................................................................................... 199
BridgeTalk message object functions ................................................................................................................... 200
send ................................................................................................................................................................................. 200
sendResult..................................................................................................................................................................... 200
Messaging Error Codes ..................................................................................................................................................... 201
Sample Workflow Automation Scripts .............................................................................................................................. 202
10 ExtendScript Tools and Features............................................................................................203
The ExtendScript Toolkit......................................................................................................................................................... 203
Configuring the Toolkit window ................................................................................................................................... 204
Selecting a debugging target ........................................................................................................................................ 205
Selecting scripts................................................................................................................................................................... 206
Tracking data ........................................................................................................................................................................ 206
The JavaScript console ..................................................................................................................................................... 207
The call stack ........................................................................................................................................................................ 208
The Script Editor .................................................................................................................................................................. 209
Mouse navigation and selection ............................................................................................................................. 209
Keyboard navigation and selection ....................................................................................................................... 209
Syntax checking ............................................................................................................................................................ 210
Debugging in the Toolkit ................................................................................................................................................. 210
Evaluation in help tips................................................................................................................................................. 210
Controlling code execution ...................................................................................................................................... 210
Visual indication of execution states ..................................................................................................................... 211
Setting breakpoints .................................................................................................................................................... 212
Profiling .................................................................................................................................................................................. 213
Dollar ($) Object ........................................................................................................................................................................ 215
Dollar ($) object properties ............................................................................................................................................. 215
build................................................................................................................................................................................. 215
buildDate ....................................................................................................................................................................... 215
error ................................................................................................................................................................................. 215
flags ................................................................................................................................................................................. 215
global .............................................................................................................................................................................. 215
level.................................................................................................................................................................................. 215
locale ............................................................................................................................................................................... 215
localize............................................................................................................................................................................ 216
memCache .................................................................................................................................................................... 216
objects ............................................................................................................................................................................ 216
os ...................................................................................................................................................................................... 216
screens............................................................................................................................................................................ 216
strict................................................................................................................................................................................. 216
version ............................................................................................................................................................................ 216
Dollar ($) object functions ............................................................................................................................................... 216
about............................................................................................................................................................................... 216
bp ..................................................................................................................................................................................... 216
clearbp............................................................................................................................................................................ 216
gc ...................................................................................................................................................................................... 216
getenv............................................................................................................................................................................. 216
list ..................................................................................................................................................................................... 216
setbp................................................................................................................................................................................ 217
Adobe Creative Suite 2
Bridge JavaScript Reference 16
sleep ................................................................................................................................................................................ 217
summary ........................................................................................................................................................................ 217
write................................................................................................................................................................................. 217
writeln............................................................................................................................................................................. 217
Object statistics ............................................................................................................................................................. 217
ExtendScript Reflection Interface ........................................................................................................................................ 219
Reflection Object................................................................................................................................................................. 219
Reflection object properties ..................................................................................................................................... 219
description .................................................................................................................................................................... 219
help.................................................................................................................................................................................. 219
methods......................................................................................................................................................................... 219
name................................................................................................................................................................................ 219
properties ...................................................................................................................................................................... 219
Reflection object functions ....................................................................................................................................... 219
find................................................................................................................................................................................... 219
ReflectionInfo Object......................................................................................................................................................... 220
ReflectionInfo object properties ............................................................................................................................. 220
arguments ..................................................................................................................................................................... 220
dataType ........................................................................................................................................................................ 220
defaultValue ................................................................................................................................................................. 220
description .................................................................................................................................................................... 220
help.................................................................................................................................................................................. 221
isCollection.................................................................................................................................................................... 221
max .................................................................................................................................................................................. 221
min ................................................................................................................................................................................... 221
name................................................................................................................................................................................ 221
type.................................................................................................................................................................................. 221
Localizing ExtendScript Strings............................................................................................................................................ 222
Variable values in localized strings ............................................................................................................................... 222
Enabling automatic localization .................................................................................................................................... 222
Locale names........................................................................................................................................................................ 223
Testing localization ............................................................................................................................................................ 224
Global localize function .................................................................................................................................................... 225
localize............................................................................................................................................................................ 225
User Notification Helper Functions..................................................................................................................................... 226
Global alert function .......................................................................................................................................................... 226
alert.................................................................................................................................................................................. 226
Global confirm function.................................................................................................................................................... 227
confirm ........................................................................................................................................................................... 227
Global prompt function.................................................................................................................................................... 227
prompt............................................................................................................................................................................ 227
Specifying Measurement Values ........................................................................................................................................ 229
UnitValue Object ................................................................................................................................................................. 229
UnitValue object constructor ................................................................................................................................... 229
UnitValue object properties...................................................................................................................................... 230
baseUnit ......................................................................................................................................................................... 230
type.................................................................................................................................................................................. 230
value ................................................................................................................................................................................ 230
UnitValue object functions........................................................................................................................................ 230
as....................................................................................................................................................................................... 230
convert......................................................................................................................
...................................................... 230
Adobe Creative Suite 2
Bridge JavaScript Reference 17
Converting pixel and percentage values ................................................................................................................... 230
Computing with unit values ........................................................................................................................................... 231
Modular Programming Support .......................................................................................................................................... 233
Preprocessor directives..................................................................................................................................................... 233
#engine name .............................................................................................................................................................. 233
#include file ................................................................................................................................................................... 233
#includepath path...................................................................................................................................................... 234
#script name ................................................................................................................................................................. 234
#strict on ........................................................................................................................................................................ 234
#target name ................................................................................................................................................................ 234
Importing and exporting between scripts................................................................................................................. 234
Operator Overloading ............................................................................................................................................................ 236
Application and Namespace Specifiers............................................................................................................................. 237
Application specifiers ........................................................................................................................................................ 237
Namespace specifiers ........................................................................................................................................................ 238
Script Locations and Checking Application Installation ............................................................................................. 238
Index .........................................................................................................................................240
Adobe Creative Suite 2
Bridge JavaScript Reference 18

Wel com e

Welcome to the Bridge JavaScript Reference. This book describes how to use JavaScript to manipulate and extend Adobe® Bridge for Adobe Creative Suite 2.

About This Book

The Bridge JavaScript Reference describes how to use the scripting API to extend and manipulate Adobe Bridge, but it is not a user’s guide for the Bridge application and its user interface.
This book provides complete reference information for the JavaScript objects, properties, and functions defined by Adobe Bridge, and for various utilities and tools that are part of ExtendScript, the Adobe extended implementation of JavaScript.
This book also describes how to use the interapplication communication framework that is defined by Adobe Bridge and included in each Adobe Creative Suite 2 application. You can use this framework to write scripts that call on functionality from different applications, or to send scripts and data from one application to another. A set of Sample Workflow Automation Scripts Suite 2, which demonstrate how scripts can be used to create a workflow that takes advantage of functionality in different applications.
is provided with Adobe Creative

Who should read this book

This book is for developers who want to extend the capabilities of Adobe Bridge using JavaScript, call Bridge functionality from scripts, and use scripts to communicate between Adobe Creative Suite 2 applications. It assumes a general familiarity with the following:
JavaScript
C and C++ programming
Adobe Bridge
Any other Adobe Creative Suite 2 applications you are using, such as Illustrator® CS2, Photoshop® CS2,
or InDesign® CS2. The scripting API details for each application are included with the scripting documentation for that product.

What is in this book

This book provides conceptual information about the scripting Adobe Bridge and detailed reference information about the JavaScript objects that Adobe Bridge provides. It also provides both usage and reference information for the tools, utilities, and objects that are part of ExtendScript, the Adobe extended implementation of JavaScript.
This book contains the following chapters:
Chapter 1, “Scripting Bridge,” introduces some important concepts in Adobe Bridge scripting and
describes the Bridge JavaScript document object model (DOM).
Chapter 2, “Event Handling and Script-Defined Browse Schemes,” describes how Adobe Bridge
generates user-interaction events, and how you can respond to these events by defining handlers in
19
Adobe Creative Suite 2
Bridge JavaScript Reference Welcome 20
your scripts. In addition, it describes how to define browse schemes that allow you to extend or modify what is shown in the Bridge Favorites pane.
Chapter 3, “Creating a User Interface,” describes the various options available to scripts for interaction
with Bridge users, such as dialog boxes and navigation bars.
Chapter 4, “Using File and Folder Objects,” describes how to use the ExtendScript objects that provide
platform-independent access to the underlying file system.
Chapter 5, “Using ScriptUI,” describes how to use the ExtendScript user interface module, a set of
objects which provide windows and user-interface controls for the scripting environment.
Chapter 6, “Bridge DOM Object Reference,” provides a complete API reference for the objects,
properties, and functions defined in the Bridge document object model.
Chapter 7, “File and Folder Object Reference,” provides a complete API reference for the ExtendScript
file-system access objects, properties, and functions.
Chapter 8, “ScriptUI Object Reference,” provides a complete API reference for the ExtendScript
user-interface objects, properties, and functions.
Chapter 9, “Interapplication Communication with Scripts,” describes how to use the interapplication
communication framework, and provides a complete API reference for the Cross-DOM and for the messaging framework.
Chapter 10, “ExtendScript Tools and Features,” describes the ExtendScript Toolkit debugging
environment, and provides a complete API reference for the ExtendScript utilities and features that are available to all Adobe Creative Suite 2 applications.

Document conventions

Typographical conventions
Monospaced font
Italics Variables or placeholders in code. For example, in
Blue underlined text
Sans-serif bold font The names of Bridge UI elements (menus, menu items, and buttons).
Note: Notes highlight important points that deserve extra attention.
A hyperlink you can click to go to a related section in this book or to a URL in
Literal values and code, such as JavaScript code, HTML code, filenames, and pathnames.
name="myName", the text
myName represents a value you are expected to supply, such as name="Fred".
Also indicates the first occurrence of a new term.
your web browser.
> symbol is used as shorthand notation for navigating to menu items. For
The example,
Edit > Cut refers to the Cut item in the Edit menu.
JavaScript conventions
This reference does not list properties and methods provided by the JavaScript language itself. For example, it is common for JavaScript objects to provide a the SDK supplies implement this method. However, this book does not describe such methods unless they differ from the standard JavaScript implementation.
toString method, and many of the objects
Adobe Creative Suite 2
Bridge JavaScript Reference Welcome 21
Similarly, because most objects provided by the SDK have a name property, the reference does not list
name properties explicitly.
When a JavaScript function returns a value, it is listed.When there is no return value listed, the function does not return a value.

Where to go for more information

This book does not describe the JavaScript language. For documentation of the JavaScript language or descriptions of how to use it, see any of numerous works on this subject, including the following:
JavaScript: The Definitive Guide, 4th Edition; Flanagan, D.; O’Reilly 2001; ISBN 0-596-00048-0
JavaScript Programmer’s Reference; Wootton, C.; Wrox 2001; ISBN 1-861004-59-1
JavaScript Bible. 5th Edition; Goodman, D. and Morrison, M.; John Wiley and Sons1998; ISBN
0-7645-57432
1

Scripting Bridge

This chapter introduces some important concepts in Adobe Bridge scripting and describes the Bridge JavaScript document object model (DOM).

Scripting Overview

Adobe Bridge provides a configurable, extensible browser platform that allows users to search for and select files by navigating among files and folders in the local file system, those on remote file systems, and also web pages accessible over the Internet.
Bridge is integrated with Adobe Creative Suite 2, and various applications bring up the Bridge browser window in response to specific user actions that require file selection. You can also bring up a Bridge browser window independently, by invoking it interactively or through a script.
The Bridge browser is highly configurable and extensible, using ExtendScript, the Adobe extended implementation of JavaScript. ExtendScript files are distinguished by the offers all standard JavaScript features, plus additional features and utilities, such as:
Platform-independent file and folder representation
Tools for building a user interface to a script
.jsx extension. ExtendScript
An interactive development and debugging environment (the ExtendScript Toolkit)
You can use ExtendScript to manipulate browser windows and their contents programmatically, and to change and extend their functionality. This manual describes what you can do, and provides a complete reference for the ExtendScript objects and functions that you can use to program Bridge.

Executing Scripts

Bridge executes scripts in any of these ways:
On startup, Bridge executes all JSX files that it finds in the startup folders.
In Windows
%APPDATA%\Adobe\StartupScripts %APPDATA%\Adobe\StartupScripts\bridge\version
In Mac OS
~/Library/Application Support/Adobe/StartupScripts/ ~/Library/Application Support/Adobe/StartupScripts/bridge/version/
Note: If your script is in the main startup folder, it is also executed by all other Adobe Creative Suite 2
applications at startup; see Script Locations and Checking Application Installation
The version portion of the Bridge-specific folder path is an exact version number. That is, scripts in the
bridge/1.5 are executed only by Bridge version 1.5, and so on.
folder
®
, the startup folders are:
®
, the startup folders are:
.
You can pass a script to the Bridge executable to be executed on startup, by dragging the JSX file icon
onto the Bridge executable file icon or shortcut. This script is executed after all startup scripts.
22
Adobe Creative Suite 2
Bridge JavaScript Reference Scripting Bridge 23
When the Bridge browser window displays a JSX file, you can double-click that file thumbnail to run the
script in its target application. It runs in Bridge if the script specifies Bridge as its target application by including the directive:
#target "bridge"
If the script specifies another Adobe Creative Suite 2 application as its target, ExtendScript starts that application if necessary. If the script does not specify a target application, it opens in the ExtendScript Toolkit. For details, see Preprocessor directives
You can load and run a script in the ExtendScript Toolkit, specifying Bridge as the target application.
For details, see The ExtendScript Toolkit
You can add a menu command that runs a script to a menu or submenu in the Bridge browser, using
the MenuElement Object
.
and The ExtendScript Toolkit.
.

Communicating with Other Applications

Adobe Bridge provides an interapplication communication framework, a way for scripts to communicate with other Adobe applications, from Bridge or among themselves.
A script can call certain basic functions exported by all Adobe Creative Suite 2 applications. For
example, a Bridge script could ask the user to select an image file, then open that file in Photoshop Illustrator
® by calling the photoshop.open or illustrator.open function. These basic exported
functions are called the Cross DOM.
® or
Individual applications export additional functions to make more complex functionality available to
scripts. For example, a Bridge script can request a photo-merge operation in Photoshop by calling
photoshop.photomerge with a set of selected image files. The set of functions available for each
application varies widely.
A messaging protocol provides a general and extensible framework for passing any kind of data
between messaging enabled applications. All Creative Suite 2 applications are messaging enabled. You can send messages that contain JavaScript scripts. The target application can evaluate a script that it receives, and send results back in a response message.
For additional information, see Chapter 9, “
Interapplication Communication with Scripts."

The Bridge Document Object Model

A document object model (DOM) is an application programming interface (API), which allows you to programmatically access various components of a document (as defined for that application) through a scripting language such as JavaScript.
Each application in the Creative Suite 2 has its own DOM, which consists of a hierarchical representation of the application, and of the documents used in the application. The DOM allows you to programmatically access and manipulate the document and its components. Since the use of a document varies for each application, the DOM terminology varies for each application. For example, each application's DOM includes a class has different properties and methods for each application.
Document class, but the object referred to is different for each application, and the Document
Applications typically define a images, or PDF documents. However, Bridge uses a different approach. In the Bridge DOM, the class refers to a Bridge browser window, and the properties and methods of
Document class to deal with files of a particular type, such as HTML pages,
Document
Document refer to various
components of the Bridge user interface (UI). The browser window displays icons that reference the files
Adobe Creative Suite 2
Bridge JavaScript Reference Scripting Bridge 24
that other applications consider documents—HTML pages, images, PDFs, and so on. In the Bridge DOM, these icons are represented by the
Thumbnail class.
Having a good understanding of the Bridge DOM, and how each aspect of the API relates to the Bridge browser, will greatly enhance your ability to write scripts. In the Bridge DOM shown below, each node in the hierarchy represents a class in the Bridge DOM API.
AppApp
Document
Event
Dialog
MenuElement
Preferences
PreferencesDialog
Favorites
Thumbnail
NavBar
Thumbnail
File, Folder
MetaData
BrowseSchemeEvent
ScriptUI Element

The application and documents

The Bridge App Object is the root of the hierarchy, and represents the Bridge application. A single global instance of the global values. Even though the user can create multiple Bridge browser windows by selecting the File > New Window command, making it appear that separate Bridge applications are running in parallel, only a single instance of the application is running, which is reflected by a single instance of the
The Document Object
document object is created. When multiple Bridge browser windows are open, the user can select
a new which window to use by clicking the window to make it active. In a script, you can access the active, or most recently used, browser window through the windows is available through the
App class, named app, is created when the application is started, and provides access to
represents a Bridge browser window. Each time a user selects File > New Window,
app.documents array.
app object.
app.document property. The set of all open browser
Adobe Creative Suite 2
Bridge JavaScript Reference Scripting Bridge 25

Thumbnails in documents

The Thumbnail Object type represents a node in the browser navigation hierarchy. It typically represents a a file or folder, but can also be associated with a web page. A document contains various collections of
Thumbnail objects.
Thumbnail objects can contain other Thumbnail objects, as for example, when a folder contains files. In
this case, the represent files and folders contained in the folder.
The Folders pane shows the full navigation hierarchy of folders and subfolders for the local file system. A script cannot add nodes to the Folders pane (except by creating new folders on disk), but your script can access the selected thumbnail through the navigation hierarchy by accessing the
The Favorites pane shows a selection of high-level nodes, some predefined and some chosen by the user. These can represent web pages and remote folders, as well as local folders. The Favorites Object represents the navigation nodes in the Favorites pane. A document contains a single which is an array of
children property of the Thumbnail contains a hierarchy of Thumbnail objects that
app.document.thumbnail property. It can walk the
parent and children properties of each Thumbnail object.
Favorites object,
Thumbnail objects. Access the Favorites object through app.favorites.
A script can add thumbnails to the lower part of the Favorites pane by using the
Favorites object’s
insert method, and one level of sub-nodes using the addChild method. A subnode can be any
thumbnail; it does not have to be part of the root node’s
children hierarchy.
Thumbnails as node references
The Thumbnail Object represents a navigation node. Thumbnails can represent entities such as files and folders, accessed through a local or remote file system, or web pages accessed over the internet and displayed in an embedded web browser. Each types of node identifier, which determines what happens when the user selects the icon:
File or folder objects; see Chapter 4, “Using File and Folder Objects," and Chapter 7, “File and Folder
Object Reference." Clicking a folder thumbnail in the Folders or Favorites pane displays the contents of
the folder in the Content pane.
URLs. Clicking the thumbnail in the Folders or Favorites pane displays the web page associated with
the URL in the Content pane. This can be a local or remote HTML page. See Displaying HTML in the
Content Pane.
Version Cue® nodes. Clicking a thumbnail in the Folders pane displays the contents of the Version Cue
workspace in the Content pane.
Script-defined navigation nodes, which are associated with script-defined browse schemes. The display
in the Content pane is determined by the browse scheme’s associated handler. See Script-Defined
Browse Schemes.
Thumbnail object is associated with one of the following
Using and accessing thumbnails
Thumbnails are used in a number of ways within a browser window, and the objects are referenced according to their use. For example:
Access thumbnails that appear in the Favorites pane through app.favorites
Access a thumbnail that is selected in the Folders pane through app.document.thumbnail
Access thumbnails that appear in the Content pane through
app.document.thumbnail.children
Adobe Creative Suite 2
Bridge JavaScript Reference Scripting Bridge 26
Access thumbnails that have been selected in the Content pane through app.document.selected
Access thumbnails that are associated with a context menu through app.document.context
A Thumbnail object is associated with a Metadata Object, which allows you to access the external data associated with the associated file, such a copyright owner, author, or camera settings. The
metadata
object also allows access to an image thumbnail’s label string, which you can define and set through the Bridge browser.

User interface objects

Your script can display information to or collect information from the user by configuring the supplied navigation bars, or by creating and displaying dialogs.
ExtendScript provides a set of user-interface objects in the ScriptUI module, which defines windows and user-interface controls. You can use these objects to define a user interface for your application, in the form of popup dialogs, persistent dialogs (called palettes), or as part of navigation bars. The usage of the ScriptUI objects is discussed in Chapter 5, “
Chapter 8, “
ScriptUI Object Reference."
You can also define a user interface using standard HTML. When integrating your user interface with the Bridge browser, you can use either ScriptUI or HTML controls for any window or pane, but cannot mix the two. For a complete discussion, see Chapter 3, “
Using ScriptUI," and complete syntax details are provided in
Creating a User Interface."
In addition to displaying a user interface for your script, you can script user interactions by extending the Bridge menus.
Navigation bars
The Bridge navigation bar immediately below the menubar cannot be scripted, but there are two configurable navigation bars, above and below the Content pane. They are represented by NavBar
Objects, which you can access through the Document object’s navbars property.
By default, the navigation bars are hidden and empty.
You can show and hide a navigation bar by setting the object’s visible property.
You can configure a navigation bar to display either ScriptUI user-interface controls, or straight HTML
controls. It cannot mix the two.
To display ScriptUI controls, set the type property to "scriptui", then use the NavBar.add
method to add controls.
To display HTML controls, set the type property to "html", and the file property to the HTML
file that defines the page you want to display.
You can program the controls to display information to or collect information from the user. For additional details, see Navigation Bars
.
Dialogs
Your script can define dialogs to display information to or get information from the user. There are two ways to define these:
ScriptUI Dialogs: Use the ScriptUI Window Object to define a dialog that displays ScriptUI controls.
Adobe Creative Suite 2
Bridge JavaScript Reference Scripting Bridge 27
Bridge Dialogs: The Dialog Object represents a window that displays an HTML page, rather than
ScriptUI controls.
You can invoke ScriptUI dialogs from a script as modal or nonmodal dialogs.
A modal dialog retains the input focus, and does not allow the user to interact with any other
application windows until the dialog is dismissed. The function that invokes it does not return until the dialog is dismissed.
A nonmodal dialog (known in ScriptUI as a palette), does not keep the input focus. The user can interact
with other application windows while the dialog is up. The function that invokes it returns immediately, leaving the dialog on screen until the user or script closes it.
Menus

Events

For details of programming dialogs, see Chapter 5, “
Using ScriptUI," a n d Displaying HTML in Bridge
Dialogs.
The MenuElement Object allows you to add new menus and commands. A script cannot remove or alter the behavior of predefined menu items, but you can add, remove, and modify script-defined menus and commands.
Most menubar menus and context menus can be extended by creating new
MenuElement objects that
reference existing menus and menu items. The identifiers of all menus and menu items that are accessible to scripts are listed with the description of the
MenuElement object.
When interacting with Bridge, a user takes actions such as copying a file, or creating a new Bridge browser window. For most of these actions, Bridge triggers a user-interaction event, represented by an Event Object of a particular event type, with a particular target object, such as an
App, Document, or Thumbnail object.
Some function calls can also trigger events.
Bridge defines default behavior for user-interaction events. You can extend or override the default behavior by defining and registering an event-handler function. This function receives the
Event object as
an argument, and returns a value that tells Bridge whether to continue with the default behavior or to ignore it.
For more information on event handling, see Event Handling in Bridge

Application preferences

The Preferences Object allows a script to access Bridge application preferences. These are the values that can be viewed interactively in the Preferences dialog, in response to the Edit > Preferences command. The settings are stored and persist across sessions. Your script can use the set existing preferences, or to add new preference fields. In general, when you modify persistent preference values, the new settings are not reflected in the browser window until the Bridge application is restarted.
When the user brings up a Preferences dialog, Bridge invokes a ScriptUI dialog window, and generates a
create event with the PreferencesDialog Object as its target. You can define and register an event
handler for this event that uses the object’s controls that show and allow the user to modify script-defined preference values.
.
Preferences object to view or
add method to add a ScriptUI panel containing ScriptUI
Adobe Creative Suite 2
Bridge JavaScript Reference Scripting Bridge 28

The Bridge DOM and the Bridge Browser Window

The following figure identifies parts of the Bridge browser window in a default configuration.
Menu bar
Upper
navigation bar
Favorites and Folder panes
User section of Favori tes pane
Preview pane
Metadata and Keywords panes
Flyout menus
Status line
Content pane
ThumbnailsThumbnails
Viewing mode
The following table describes how the Bridge API maps to the various parts and features of the Bridge browser window, and how a script can access each part or feature through the Bridge DOM.
Bridge window area Purpose Bridge DOM control
Browser window Displays files, folders, and web
pages.
Favorites pane Provides a place for users to
drag and drop favorite items (in the bottom half of the pane).
Displays only top-level containers and one level of subnodes.
Represented by the browser window is in
Document object. Current
app.document.
Access the visible thumbnails through the
app.favorites property, and traverse the
hierarchy through the
Thumbnail.children
properties.
Favorites object allows you to add
The thumbnails to this pane.
User interaction with a thumbnail in this pane generates an target object and a location of
event with a Thumbnail
favorites.
You can define your own browse scheme for a thumbnail in this pane, which allows you to extend or redefine the thumbnail’s behavior. See Script-Defined Browse Schemes
.
Adobe Creative Suite 2
Bridge JavaScript Reference Scripting Bridge 29
Folders pane Displays the navigation
hierarchy and controls navigation.
Displays only containers (such as folders and subfolders).
Access the currently selected thumbnail in the Folder pane through the
Document.thumbnail property. Traverse the
hierarchy through the
Thumbnail.children properties.
Thumbnail.parent and
User interaction with a thumbnail in this pane generates an target object and a location of
event with a Thumbnail
document.
Preview pane Displays image previews. User interaction with a thumbnail in this
Metadata pane Displays metadata
information.
pane generates an target object and a location of
Metadata is displayed and written for a specific thumbnail. Access metadata from the
Thumbnail.metadata property.
event with a Thumbnail
preview.
Keywords pane Displays keyword information. Not accessible to scripts.
Content pane Displays navigation results
when you select a node in the Folders or Favorites pane, or when you click on a navigable node (such as a folder) in the Content pane itself.
Controlled by the browse scheme associated with the thumbnail selected in the Folders or Favorites pane. The browse scheme uses the
Thumbnail properties displayMode and displayPath to determine what appears the
Content pane, and how it appears.
Displays both containers (such as subfolders) and leaf nodes (such as files and images).
Can display HTML pages for web-type thumbnails.
Thumbnails The labelled icons that appear
in the Folders/Favorites panes as navigation nodes, and in the Content pane to represent files and folders.
When the selected thumbnail has
displayMode="filesystem", its children
appear as icons in the Content pane. When a folder is selected in the Folders pane, access the current contents of the Content pane through
app.document.thumbnail.children[].
When the selected thumbnail has
displayMode="web", the associated HTML
page (local or remote) appears in the Content pane.
User interaction with a thumbnail in this pane generates an target object and a location of
event with a Thumbnail
document. The
selected thumbnails are available through
Document.selections.
The
Thumbnail object represents a node in
the browser navigation hierarchy. Thumbnails can represent
File or Folder
objects, Version Cue nodes, URLs, or script-defined nodes associated with script-defined browse schemes.
Adobe Creative Suite 2
Bridge JavaScript Reference Scripting Bridge 30
Menubar The menubar at the top of the
Bridge browser window.
Context menus The right-click menus
associated with thumbnails, and flyout menus for some tab panels.
Browser window upper navigation bar
The navigation bar immediately under the menubar. Not configurable.
Status line The bottom bar on the Bridge
browser window.
Content Pane Viewing Control
The bar next to the status line, where the viewing mode of the Content pane is controlled.
Top and bottom navigation bar s
Two configurable navigation bars that can appear above and below the Content pane.
While this is not an object under direct
Document control, you can add menus and
commands using the
MenuElement object, by
referring to existing menus and commands.
You can add submenus and commands to these menus using the
MenuElement object,
by referring to existing commands.
Not accessible to scripts.
Controlled by
The view mode is controlled by
app.document.thumbnailViewMode
Represented by predefined accessed through the
Document.status.
.
NavBar objects,
Document.navbars
property. By default, the navigation bars are invisible. You can make a bar visible, and add ScriptUI or HTML UI controls to it.
2

Event Handling and Script-Defined Browse Schemes

A script can extend and modify the behavior of Adobe Bridge at a number of levels:
At the highest level, the basic behavior of a thumbnail icon is determined by its browse scheme. There
are several predefined browse schemes that provide the most common kinds of behavior, such as displaying the contents of a folder, or displaying a web page (see Thumbnails as node references can select one of the predefined browse schemes to create a thumbnail that has the basic default behavior you require. (see Thumbnail object constructor
You can intercept user-interaction events to extend or override the default behavior. These events
include actions on thumbnails (such as selecting them), and also actions on the application (quitting) and on the browser window (such as activating it in the windowing system). See Event Handling in
Bridge below.
You can modify the displayed thumbnails in the Favorites pane by defining thumbnails with
Script-Defined Browse Schemes

Event Handling in Bridge

When a user takes certain actions in Bridge, such as copying a file, or creating a new Bridge browser window, Bridge generates a user-interaction event. You can modify the way Bridge responds to these events by defining your own event handlers. Scripts can also generate events through function calls, that simulate user activity, such as the Thumbnail Object method.
). You
).
.
’s open method, or the Document Object’s select

Defining event handlers

An event-handler function takes one argument, an Event Object. This object, which is passed to your registered handler when the event occurs, contains all of the context information about the event, such as which type of event occurred, the target object that generated it, and where that object was located within the browser window.
Your handler returns an object with a boolean
When an event handler returns {handled:true}, Bridge does not look for any more handlers, nor
does it execute the default handler.
When an event handler returns {handled:false}, Bridge continues to look for registered handlers,
and if no more script-defined handlers are registered, it executes the default handler. This is the default behavior if your handler does not return a value.
Using this mechanism, you can extend the default behavior of the Bridge objects. For example, when the user quits the Bridge application, your up structures you have made, or displaying status information. To extend the default behavior, your handler returns the object
In many cases, such as Thumbnail events, you can use the event handler to override the default behavior. You do this by returning the object handler.
handled property.
destroy event handler can take additional actions, such as cleaning
{handled:false}.
{handled:true}, which prevents Bridge from executing the default
31
Adobe Creative Suite 2
Bridge JavaScript Reference Event Handling and Script-Defined Browse Schemes 32
For some events, such as Document events, you cannot override the default behavior of the event. Even if your handler returns finished. The
{handled:true} return value does, however, prevent Bridge from executing any
{handled:true}, the default behavior still executes when your handler has
subsequent script-registered event handlers.

Registering event handlers

To register an event-handler function you have defined, create an EventHandler object and add it to the array property that specifies the name of the event-handler function. There is no constructor, it is a simple script-defined object. For example:
You can write one handler that responds to many different events, or write one handler for each type of event. When an event occurs, Bridge iterates through the handler in sequence, passing in the triggering event object. If one of the event handlers returns
{handled:true} Bridge stops the iteration.
app.eventHandlers. An EventHandler is a simple JavaScript object with a handler
var myEventHandler = { handler: doThisEvent }; app.eventHandlers.push (myEventHandler);
app.eventHandlers array, trying each

Event handling examples

Example: Separate handlers for separate events
This script defines separate event handlers for two Document events, select and create, and registers them by adding them to the which in this case does not override the default behavior of the events, but does tell the event handling mechanism to stop processing subsequent script-defined event handlers.
// define handlers onCreateDocument = function( event ) {
if( event.object.constructor.name == "Document" ) {
if( event.type == "create" ) {
// Action to take in the event of Document create Window.alert("new document"); return {handled:true}; //stop processing event handlers
}
}
}
onFocusDocument = function( event ) {
if( event.object.constructor.name == "Document" ) {
if( event.type == "select" ) {
// Action to take in the event of Document focus app.beep(); return {handled:true};//stop processing event handlers
}
} } // register handlers app.eventHandlers.push( { handler: onCreateDocument} ); app.eventHandlers.push( { handler: onFocusDocument} );
app.eventHandlers array. These handlers return {handled:true},
Adobe Creative Suite 2
Bridge JavaScript Reference Event Handling and Script-Defined Browse Schemes 33
Example: One handler for all document events
This script defines one event handler to handle several Document events, distinguishing the events internally.
onDocumentEvent = function( event ){
if( event.object.constructor.name == "Document" ){
if( event.type == "create" ) {
// Action to take in the event of Document create Window.alert("new document");
return {handled:true};//stop processing event handlers } else if( event.type == "focus" ){
// Action to take in the event of Document focus
app.beep();
return {handled:true};//stop processing event handlers } else if( event.type == "select" ){ // Action to take in the event of Document select Window.alert("document was selected"); return {handled:true};//stop processing event handlers }
} } // register the handler allDocEventHandlers = { handler: onDocumentEvent }; app.eventHandlers.push( allDocEventHandlers );
Example: Cancelling a quit operation using app close
This script defines a handler for the App close event, which occurs when Bridge receives a request for application shutdown. In this case, if the result object contains
handled: true, the shutdown is
cancelled. This handler queries the user, and only continues with the operation if the user confirms.
var myHandler = function(event){
if ((event.type == 'close') && (event.object instanceof App)) {
return { handled: Window.confirm("Really quit?") }; } return { handled: false };
} app.eventHandlers.push( { handler: myHandler } );
Example: Adding a service to Bridge using document create
This script defines a handler for the Document create event that adds a navigation bar to all new browser windows. The script is placed in the startup script directory, so that it runs each time Bridge is invoked. Whenever the user creates a new browser window, the event handler adds the navigation bar to it.
The navigation bar uses ScriptUI objects to display a text field in which the user can type a path. When
the user clicks Go or New in the navigation bar, the button’s onClick
A handler for the Thumbnail select event updates the navigation bar so that it always shows the
handler navigates to that path.
path of the currently selected thumbnail.
Note: This example is a variation of the navigation bar examples given in Chapter 3, “
Interface." See that chapter for more discussion of navigation bars.
Creating a User
Adobe Creative Suite 2
Bridge JavaScript Reference Event Handling and Script-Defined Browse Schemes 34
// Adds a path bar to all browser windows, which allows you to navigate // by typing a path, and shows the path of the current selection
// Change current document to browse the path in the path bar // (called when the Go button is clicked) function browseToPath( message ) {
try {
app.document.thumbnail = new Thumbnail(
app.document.topNavbar.pathPanel.browseField.text );
} catch ( error ) {
Window.alert (error ); }
} // Open a new window to browse the path on the path bar. // (called when the New button is clicked) function browseToPathNewWindow( message ) {
try {
app.browseTo( app.document.topNavbar.pathPanel.browseField.text ); } catch (error ) {
Window.alert (error); }
} // Create the PathBar panel on a nav bar function addTopBarPanel(bar) {
bar.pathPanel = bar.add( "panel", [5,5, 830, 35], undefined); bar.pathPanel.browseField = bar.pathPanel.add( "edittext",
[3, 3, 700, 22],""); bar.pathPanel.BrowseBtn = bar.pathPanel.add( "button",
[710, 3, 760, 22],"Go"); bar.pathPanel.BrowseBtnNewWin = bar.pathPanel.add( "button",
[770, 3, 820, 22],"New"); bar.pathPanel.BrowseBtn.onClick = browseToPath; bar.pathPanel.BrowseBtnNewWin.onClick = browseToPathNewWindow;
} // Create the PathBar on the top navbar of the document function addNavBar(doc) {
var topbar = doc.topNavbar; addTopBarPanel(topbar ); topbar.visible = true; topbar.pathPanel.browseField.text = theDocument.thumbnail.path;
} // Handle document create event to add path bar to new browser windows. onDocumentEvent = function( event ){
try {
if( (event != undefined) && (event.object != undefined)
&& (event.type != undefined) ) {
if( event.object.constructor.name == "Document" ){
if( event.type == "create" ) { // Action to take on document creation
addNavBar( event.object );
} } // (check for no documents to avoid thumbnail event // that occurs before first doc opens) else if( event.object.constructor.name == "Thumbnail" &&
Adobe Creative Suite 2
Bridge JavaScript Reference Event Handling and Script-Defined Browse Schemes 35
app.documents.length != 0 ) { if( event.type == "select") { // Action to take on Thumbnail selection // update the path bar to show the current path
if(app.document.topNavbar.pathPanel != 0 ) {
if(event.object.container) {
app.document.topNavbar.pathPanel.browseField.text =
event.object.path; } else {
app.document.topNavbar.pathPanel.browseField.text =
event.object.parent.path; }
}
} } else {
if( event == undefined ) {
Window.alert ("null event");
} }
}
} catch (error) {
Window.alert (error);
} } // Register the event handler app.eventHandlers.push( { handler: onDocumentEvent} );

User-interface events

The event handling mechanism described in this chapter applies only to the Bridge DOM objects. If your script defines its own user interface, events are handled differently, depending on what kind of object generated them:
For events generated by ScriptUI objects (such as controls in the navigation bar), see Chapter 5, “Using
ScriptUI."
For events generated by menu elements, see MenuElement Object.
Events generated by HTML controls in HTML navigation bars or dialogs are handled by their own
HTML-defined handlers. These can access Bridge DOM objects through a callback mechanism. See
Displaying HTML in Bridge
.
Adobe Creative Suite 2
Bridge JavaScript Reference Event Handling and Script-Defined Browse Schemes 36

Script-Defined Browse Schemes

A browse scheme (or navigation) protocol determines how Bridge performs navigation for each thumbnail—that is, exactly what happens internally when a user opens, closes, clicks, double-clicks, or otherwise interacts with the
Thumbnail objects that represent File or Folder objects, Version Cue nodes, and URLs have
predefined browse schemes. You can also create your own script-defined browse scheme, register it with the application, and specify it as part of the path when you create
Creating script-defined browse schemes allows you to create a navigation hierarchy that includes different types of
Thumbnail objects. This would typically be used to create a web service, where the root node
displays an HTML page that allows the user to make choices regarding the contents of contained folders.
Thumbnail object in the Folders, Favorites, or Content pane.
Thumbnail objects.
For example, you can create a hierarchy that contains a top-level sub-node
Thumbnail objects that point to file system folders, which you might use to save files
downloaded from the URL. You can use the Favorites Object script-defined thumbnail hierarchy to the Favorites pane, where users can interact with it.
Selecting a thumbnail that points to a URL displays the remote page in an embedded browser in the Content pane. Similarly, a thumbnail with a script-defined browse scheme can be used to display a locally-defined HTML page in the Content pane. For details, see User Interface Options for Scripts

Defining and registering a browse scheme

The function app.registerBrowseScheme registers a new script-defined browse scheme protocol with Bridge. To create a new protocol, simply assign it a name and register that name. You can then create
Thumbnail objects that use the registered name as the protocol part of the path argument (which takes
the form
For example, the following code registers a new browse scheme, objects that use that browse scheme.
Thumbnails with script-defined browse-scheme protocols can be added to the top level of the Favorites pane using the objects with the same script-defined browse-scheme protocol. To add a subnode, use the
Favorites.addChild method. You cannot make a subnode from a Thumbnail that uses a different
browse scheme from its parent node, or one that is associated with a
browseProtocol://pathSpecifier).
app.registerBrowseScheme( "bank" );
var bankRoot = new Thumbnail( "bank://root", "My Bank" ); var transactions = new Thumbnail( "bank://transactions", "Transactions" );
Favorites.insert method, or as subnodes of top-level nodes, if they are Thumbnail
Thumbnail that points to a URL, and
’s insert function to add the root of your
.
bank, and creates two new Thumbnail
Folder object.
This simple definition does not associate any new behavior with the browse scheme, but can still be useful. For this example to make use of existing browsing functionality in a new way, it simply assigns different display styles to the
The following code adds the new to the top level. The second,
bankRoot:
bankRoot.displayPath = "http://www.mybank.com"; bankRoot.displayMode = "web"; transactions.displayPath = "/C/BankTransactions";
Thumbnail objects at different levels of the hierarchy.
Thumbnail objects to the Favorites pane. The first, bankRoot, is added
transactions, is added both as a thumbnail child and as a sub-node to
Adobe Creative Suite 2
Bridge JavaScript Reference Event Handling and Script-Defined Browse Schemes 37
transactions.displayMode = "filesystem";
bankRoot.insert(transactions); //add thumbnail child
app.favorites.insert( bankRoot ); //add node app.favorites.addChild( bankRoot, transactions ); // add subnode
The top-level thumbnail displays a URL, and the child displays a file. Because no special handler has been associated with this browse scheme, the objects respond to events using the default browsing and event-handling behavior:
When the user selects the bankRoot thumbnail, Bridge navigates to the URL
http://www.mybank.com, and displays it in the Content pane. (You could set displayPath to
point to a locally-defined HTML page—see Displaying HTML in the Content Pane
When the user selects the transactions thumbnail, Bridge navigates to the directory
.)
C:\BankTransactions, and displays its contents in the Content pane.
3

Creating a User Interface

User Interface Options for Scripts

The Bridge scripting environment provides a number of options for interacting with users. You can handle a user’s interaction with Bridge objects, such as thumbnails, through the event-handling mechanism (Event Handling in Bridge commands (MenuElement Object
However, if you want to display your own window or pane to the user, you can do so in several ways: by creating popup or persistent dialogs; by configuring and displaying predefined navigation bars; or by defining user-interface controls to be displayed in the Content pane, in response to selection of specially defined thumbnails.
You can define user-interface controls in any of these places in two ways:
ScriptUI Elements: ScriptUI is a module that defines windows and user-interface controls. You can
create ScriptUI Dialogs Boxes existing Navigation Bars
If you use ScriptUI controls, you can take advantage of the ExtendScript localization feature; see
Localization in ScriptUI Objects
HTML Pages: An HTML page can contain standard HTML user-interface controls. You can display HTML
pages in Navigation Bars
), and you can extend the Bridge menus, adding your own submenus and
).
and populate them with ScriptUI controls, or add ScriptUI controls to the
.
.
, in Bridge Dialogs Boxes, or in the Content Pane.
You cannot use ExtendScript features or Bridge DOM objects directly in an HTML page; for details, see
Displaying HTML in Bridge
Your script-defined windows or panes must use one or the other of these methods. You cannot mix ScriptUI controls with HTML controls.

Navigation Bars

Bridge provides two configurable navigation bars, one of which can be displayed at the top of the Bridge browser window (below the application navigation bar), and one at the bottom (above the status bar). There are two versions of each bar, for use with the two display modes of the Content pane. Access these existing NavBar Object
When the Content pane is displaying a web page (Document.contentPaneMode="web"), use these
bars:
topbar = app.document.navbars.web.top
btmbar = app.document.navbars.web.bottom
When the Content pane is displaying a folder’s contents
(
Document.contentPaneMode="filesystem"), use these bars:
topbar = app.document.navbars.filesystem.top
btmbar = app.document.navbars.filesystem.bottom
The navigation bars are hidden by default. You can show and hide them by setting the NavBar object’s
visible
property.
.
objects through the Document Object’ s properties.
38
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 39
A navigation bar typically contains user-interface controls such as push buttons, radio buttons, scroll bars, list boxes, and so on. The
NavBar objects are initially empty.
A navigation bar can display either ScriptUI user-interface controls that you add as children of the object, or an HTML page that you reference from the you define the controls and program them to display information to or collect information from the user.
Set the NavBar.type to "scriptUI" to display ScriptUI controls. See Displaying ScriptUI elements
in a navigation bar.
Set the NavBar.type to "html" to display HTML controls. See Displaying HTML in a Navigation Bar.

Dialogs Boxes

A dialog box, like a navigation bar, can display either ScriptUI controls or HTML controls, but not both. In the case of dialogs, there are two different types of objects.
Create a ScriptUI Window Object to display ScriptUI controls. See Displaying ScriptUI Dialogs.
Create a Bridge DOM Dialog Object to display HTML controls. See Displaying HTML in Bridge Dialogs.

Content Pane

The Content pane display is determined by the current thumbnail. When you select a thumbnail in the Favorites or Folders pane (or invoke a Thumbnail Object
displayMode
You can define your own browse scheme and thumbnails that use that browse scheme, and add your thumbnails to the Favorites pane. (For details, see Script-Defined Browse Schemes can set the Thumbnail Object pane, it displays a user-interface panel in the Content pane.
NavBar
NavBar object. It cannot mix the two. In either case,
’s open function), that Thumbnail Object’s
property determines what the Content pane displays.
.) When you do this, you
’s displayMode property so that when the user selects it in the Favorites
If you set displayMode to web, the Content pane shows the HTML page referenced by
displayPath. You can define an HTML page containing user-interface controls. See Displaying HTML
in the Content Pane
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 40

ScriptUI User Interfaces

ScriptUI is a module that defines windows and user-interface controls. There are three ways to display ScriptUI elements:
You can create an independent ScriptUI window, populate it with ScriptUI controls, and invoke it from
your script using the window’s show
You can add ScriptUI controls to the existing Navigation Bars, and display them by setting by setting
the
NavBar object’s visible property to true.
You can add ScriptUI controls to the UI panel associated with the Content pane, and display that panel
by double-clicking a thumbnail whose displayMode

Displaying ScriptUI Dialogs

A script can define a window entirely in ScriptUI, by creating a Window Object and populating it with ScriptUI controls using its add
You can invoke a ScriptUI window from a script as a modal or nonmodal dialog.
A modal dialog retains the input focus, and does not allow the user to interact with any other windows
in the application (in this case, the Bridge browser window) until the dialog is dismissed. The function that invokes it does not return until the dialog is dismissed.
method.
function. See Displaying ScriptUI Dialogs
property is set to "script".
A nonmodal dialog (known in ScriptUI as a palette), does not keep the input focus. The user can interact
with the Bridge browser window while the dialog is up. The function that invokes it returns immediately, leaving the dialog on screen until the user or script closes it.
In ScriptUI, a modal dialog is a window of type
palette.
Invoke a dialog-type window as a modal dialog using the window object’s show function. In this
dialog, and a modeless dialog is a window of type
case, the function does not return until the user dismisses the dialog, or you close it from a control’s callback using the window’s hide which is passed to and returned from the call to
Invoke a palette-type window as a modeless dialog using the window object’s show function, which
or close function. The close function allows you to return a value,
show.
returns immediately, leaving the window on screen. The user can close the window using the OS-specific close icon on the frame, or you can close it from the script or a control’s callback using the window’s hide
function.
The usage of the ScriptUI objects is discussed fully in Chapter 5, “ details are provided in Chapter 8, “
ScriptUI Object Reference."

Displaying ScriptUI elements in a navigation bar

To display ScriptUI controls, set the type property to "scriptui", then use the NavBar Object’s add method to add controls. This is the same as the ScriptUI Window Object’s add method.
Using ScriptUI," and complete syntax
Example: Adding a path bar
This script defines a top navigation bar that uses ScriptUI objects to display a text field in which the user can type a path. When the user clicks Go or New in the navigation bar, the button’s onClick
handler
navigates to that path.
// Change current document to browse the path in the path bar // (called when the Go button is clicked)
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 41
function browseToPath( message ) {
try {
var topbar = app.document.navbars.filesystem.top app.document.thumbnail =
new Thumbnail( topbar.pathPanel.browseField.text );
} catch ( error ) {
Window.alert (error );
} }
// Open a new window to browse the path on the path bar. // (called when the New button is clicked) function browseToPathNewWindow( message ) {
try {
var topbar = app.document.navbars.filesystem.top app.browseTo(topbar.pathPanel.browseField.text );
} catch (error ) {
Window.alert (error);
} }
// Create the PathBar panel on a nav bar function addTopBarPanel(bar) {
bar.type = "scriptui" // this is the default, so not really needed
bar.pathPanel = bar.add( "panel", [5,5, 830, 35], undefined);
bar.pathPanel.browseField = bar.pathPanel.add( "edittext",
[3, 3, 700, 22],""); //theBrowseField = bar.pathPanel.browseField; bar.pathPanel.BrowseBtn = bar.pathPanel.add( "button",
[710, 3, 760, 22],"Go"); bar.pathPanel.BrowseBtnNewWin = bar.pathPanel.add( "button",
[770, 3, 820, 22],"New"); bar.pathPanel.BrowseBtn.onClick = browseToPath; bar.pathPanel.BrowseBtnNewWin.onClick = browseToPathNewWindow;
}
// Create the PathBar in the top navbar of the current document var topbar = app.document.navbars.filesystem.top; addTopBarPanel(topbar); topbar.visible = true; topbar.pathPanel.browseField.text = theDocument.thumbnail.path;
For detailed information on using the ScriptUI objects, see Chapter 5, “Using ScriptUI," and Chapter 8,
“ScriptUI Object Reference."
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 42

Displaying HTML in Bridge

There are three mechanisms you can use to display an HTML UI within Bridge:
A top or bottom NavBar displays HTML when navBar.file is set to the path of the HTML file, and
navBar.type="html".
A Dialog object always displays HTML UI controls (as opposed to a ScriptUI dialog object, which
displays ScriptUI controls). You specify the HTML file to display as the argument when creating the Dialog object. For example:
var myDialog = new Dialog("/C/BridgeScripts/HTML/dialogUI.html");
When you set thumbnail.displayPath to the path of an HTML file, and
thumbnail.displayMode= "web", then selecting that thumbnail in the Folders or Favorites pane
displays the HTML page in the Content pane.
In order to display the HTML, Bridge opens an embedded browser, which runs a standard JavaScript engine in a different process from the Bridge ExtendScript engine. The standard JavaScript engine can access only the standard HTML DOM. A script on the HTML page cannot directly access the Bridge DOM, or make use of ExtendScript features such as localization.
For a script in your UI page to communicate with the Bridge DOM, the HTML JavaScript engine and the Bridge ExtendScript engine must exchange values via remote calls.
For the JavaScript code to make remote calls to ExtendScript, you define callback functions on the
Bridge object, and invoke them from the HTML page with the JavaScript functions access Bridge objects on the Bridge side and pass values back to the HTML page. See

Defining callbacks for HTML scripts

Your HTML page can define its own JavaScript functions in a script. For the Bridge side to use these
.
functions, it must make a remote call using the Bridge object’s
functions defined on HTML UI pages.
The three mechanisms for displaying an HTML UI differ slightly in the details of how you define and pass callbacks and invoke script-defined functions. This section provides examples for a web page displayed in the Content pane, in response to selecting a web-type thumbnail. Examples for navigation bars and dialogs are given with the discussions of those objects above.
When you make remote calls, you can pass simple values such as strings and numbers directly. However, in order to pass complex values such as objects and arrays, you must deconstruct them on the passing side using the JavaScript function function
eval. Examples are given for callbacks; see Passing Complex Values in Remote Calls. The
toSource, and reconstruct them on the receiving side using the JavaScript
embedded browser does not support toSource, so you cannot pass complex values from the HTML page back to the Bridge ExtendScript engine.
Defining callbacks for HTML scripts
If you want to make use of Bridge DOM values to dynamically alter the HTML controls as the user works with them, you must make calls back to the Bridge DOM through a set of callbacks that you define. The
call function. The callback
execJS function. See Executing script
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 43
exact way that you define and store the callbacks depends on which of the HTML mechanisms you are using:
Defining callbacks for a dialog
For a dialog, you define callback functions in a structure that you pass to the
run
function when you invoke the dialog. The syntax for the callbacks argument is:
Dialog object's open or
{ fn_name1: function( args ) { fn1_definition }, fn_name2: function( args ) { fn2_definition } }
The dialog’s HTML page can invoke these functions using the JavaScript call method. See the Using
callbacks in an HTML dialog.
Defining callbacks for the Content pane or navigation bar
For HTML displayed in a navigation bar or in the Content pane, you define callback functions in the
jsFuncs property of the appropriate object:
When a Thumbnail Object displays an HTML page in the Content pane, the Document Object’s
jsFuncs
For a page displayed in a navigation bar, the callbacks are stored in theNavBar Object's jsFuncs
property. For examples, see Displaying HTML in a Navigation Bar
From the HTML page, you can invoke your defined callback functions using the JavaScript Typically, you will do this from a control's event handler, such as the
property stores callback functions for that page. See the examples given below.
.
call function.
onClick method for a button. For
example, suppose one of your callbacks is defined as:
{ myCB: function(x) { return x > 0 } }
This defines a function named myCB. Within the HTML page's JavaScript, invoke the myCB Bridge DOM method as follows:
var positive = call("myCB", 29);
You must use the JavaScript call method to invoke callback functions. You cannot simply invoke them by name.
A callback function can access the Bridge DOM and pass back a response, as shown in the examples. The callback functions can receive and return simple types directly, but must use types passed as arguments from the HTML side, and use wish to return. See Passing Complex Values in Remote Calls
toSource to serialize complex types that you
.

Executing script functions defined on HTML UI pages

An HTML page that displays user-interface controls within Bridge can itself contain a script that defines functions. The script to invoke a JavaScript method defined in an HTML page.
When a Thumbnail Object displays an HTML UI in the Content pane, use the Document Object’s execJS
method to execute functions defined in the script for that page. See the example below.
For a page displayed in a navigation bar, use the NavBar Object's execJS method to execute functions
defined in the script for that page.
For a modeless HTML dialog, use the Dialog Object's execJS method to execute functions defined in
the script for the dialog.
execJs method (defined on the Document, NavBar, and Dialog objects) allows a Bridge
eval to reconstruct complex
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 44
You should make sure that the HTML page which defines the remote function is actually loaded before you invoke the remote function with
execJS.
Caution: You cannot call the
execJS method from within a callback function. Doing so causes Bridge to
hang. For an alternative, see Scheduling tasks from callbacks
The
execJS method takes as its argument a string that contains the entire function call to be executed.
For example, this JavaScript code packages a call to the function displayed by
myDialog.execJS("updatePath('" + escape(tn.path) + "')");
myDialog:
In this case, it is passing a pathname that contains the backslash (\), which is an escape character. It uses the
escape function to create the argument string, and on the HTML side, the updatePath function uses
unescape to retrieve the path from the argument string:
<script> //define fns to be called from Bridge
function updatePath(path) { window.path.value = unescape(path) };
</script>
For a more complete version of this example, see Calling functions defined in an HTML navigation bar. The technique is exactly the same for a dialog as for a navigation bar, except for calling the function in the dialog object.

Displaying HTML in Bridge Dialogs

The Dialog Object represents a window that displays an HTML page. Use the open function to open the window as a modeless dialog. This function returns immediately, and the dialog remains on screen until the user or script dismisses it.
.
updatePath, defined in the HTML
The
open function takes as an argument a set of callback functions. These callbacks are used to respond to
a dialog-closing event, and to provide the dialog’s HTML JavaScript code with access to the Bridge DOM (see Communicating with Bridge from dialog JavaScript
You can provide special callback functions named
).
willClose and onClose. If they are provided, these
are called automatically when the dialog closes in response to a user action (such as clicking the window’s close icon, or clicking your button that sets
willClose takes no arguments and returns a Boolean value. If it returns true, Bridge calls the
onClose callback (if provided). If it returns false, the closing operation is aborted.
onClose takes no arguments and returns undefined. It should perform any cleanup operations for
closing to true).
the dialog and its associated code.

Communicating with Bridge from dialog JavaScript

The HTML page displayed in a dialog runs its own JavaScript engine, which has access only to the HTML DOM. If the page needs to exchange data with your Bridge DOM objects, you must use the remote call mechanisms.
You can define callbacks and pass them to the dialog as arguments to the run or open function that
invokes it. You can call them remotely from the HTML page’s JavaScript using the JavaScript function. These callback provide access to the Bridge DOM objects. See Using callbacks in an HTML
dialog.
call
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 45
You can define JavaScript functions in the HTML page’s script, and call them remotely from Bridge
using the Dialog Object
Calling functions defined in an HTML dialog
's execJS function—as long as you do not call them directly from a callback. See
and Scheduling tasks from callbacks.
Simple values such as strings and numbers can simply be passed back and forth, as shown in the examples below. Complex value such as arrays or objects must be deconstructed and reconstructed, using
toSource and eval. For details of how to pass objects in remote function calls, see Passing Complex
Values in Remote Calls.

Using callbacks in an HTML dialog

The callback functions that you define for a dialog are available to the code in the HTML page, which can invoke them using the objects.
call function. They run in Bridge’s JavaScript engine, and can use Bridge DOM
For example, suppose the
{ isGreater: function(x) { return x > myDialog.height } }
callback argument that you pass to the open function has the value:
A method in the HTML page (an event handler, for instance) can invoke the function and receive the result as follows:
var newHeightOK = call("isGreater", 29);
The following example creates a dialog that references an HTML page, which provides interface controls to select a file and a metadata key, and a button to request the metadata from the Bridge DOM.
Clicking the Get Metadata button invokes the Bridge DOM the
callbacks argument to the open or run method that invokes the dialog. The getMetadata
getMetadata callback, which is defined in
function retrieves the metadata for the specified file by creating and accessing a Thumbnail object for that file. It sends the results back to the HTML JavaScript, which displays those results in the a text-box control on the HTML page.
The user can close the dialog box by clicking the Done button, which sets the dialog’s
true. This in turn invokes the doClose callback, which is also defined in the callbacks argument.
to The
doClose callback allows you to take any cleanup actions necessary prior to the closing of the dialog
closing property
box. In this case, it simply demonstrates that it has been called by putting up an alert message.
Code in the HTML file
This HTML page is displayed by the two dialog examples below. This code, in the file
C:/BridgeScripts/HTML/dialogUI.html, defines the HTML controls, and includes event-handling
code that invokes the dialog’s callback functions.
<HTML> <HEAD> <META http-equiv="Content-Script-Type" content="text/javascript"> <TITLE>Bridge UI/HTML Integration</TITLE> </HEAD> <BODY>
For File: <INPUT type=file name="fname" size = "65"> <br><br> Get Metadata key:
<select name="mdkey">
<option value="FileSize">FileSize
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 46
<option value="FileName">FileName
<option value="DocumentKind">DocumentKind </select>
<INPUT type=button title="Get Metadata" name="go" value="Get Metadata"
onclick="var t = call('getMetadata',window.fname.value,
window.mdkey.value);
window.mresult.value = t;" >
<br><br> Result: <input type=text title="mresult" name="mresult" size = "50"> <br><br><br><br><br><br> <Input type=button title="Done" name="done" value="Done"
onclick="var d = call('closeDialog');" >
</BODY> </HTML>
Code in the Bridge script
This script defines the dialog and its callback functions, and invokes it using the open function, which opens it as a modeless dialog.
The
open function returns immediately, demonstrated by the fact that the alert message, "Return from
dialog.open", appears immediately after the dialog is opened. Although it is not demonstrated by this example, your Bridge script could close the dialog before the user dismisses it, using the
dialog.close
method. For example, you might want to close the dialog if the user opens a new Bridge Browser window, or as part of your cleanup in response to application shutdown. If you do this, the
doClose callback is
automatically executed.
myFile = File("/C/BridgeScripts/HTML/dialogUI.htm"); var mdDialog = new Dialog(myFile); var jsCallbacks = {
getMetadata: function(x,y) {
var tn = new Thumbnail( File(x) );
return(tn.metadata[y]);
}, closeDialog: function() {
Window.alert("Closing Dialog" + mdDialog);
mdDialog.closing = true;
},
doClose: function() {
/* do any cleanup before closing window */
/* called automatically by the dialog’s close function */
Window.alert("In doClose");
}
};
mdDialog.title = "Get Metadata"; mdDialog.width = 512; mdDialog.height = 512; mdDialog.modal = false;
mdDialog.open(jsCallbacks); // display as modeless dialog Window.alert("Returned from dialog.open ");
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 47
Calling functions defined in an HTML dialog
If the HTML page displayed in the dialog defines any JavaScript functions of its own, Bridge can make remote calls to those functions using the Dialog Object works exactly the same way as for a navigation bar or a page displayed in the Content pane. For an example, see Calling functions defined in an HTML navigation bar
’s execJS function. For a modeless dialog, this
.
Caution: You cannot call the
execJS method from within a callback function. Doing so causes Bridge to
hang. For an alternative, see Scheduling tasks from callbacks

Displaying HTML in a Navigation Bar

To display HTML controls, set, set the type property to "html", and the file property to the HTML file that defines the page you want to display.
When a navigation bar displays HTML, it runs its own JavaScript engine, which has access only to the HTML DOM. If the page needs to exchange data with your Bridge DOM objects, you must use the remote call mechanisms.
You can define and store callbacks in the NavBar Object's jsFuncs property and call them remotely from
the HTML page’s JavaScript using the JavaScript Bridge DOM objects. See Using callbacks from an HTML navigation bar
You can define JavaScript functions in the HTML page’s script, and call them remotely from Bridge
using the NavBar Object See Calling functions defined in an HTML navigation bar
These examples demonstrate HTML navigation bars that use remote calls in both directions.

Using callbacks from an HTML navigation bar

's execJS function—as long as you do not call them directly from a callback.
.
call function. These callback provide access to the
.
and Scheduling tasks from callbacks.
This example displays HTML controls in the top navigation bar, allowing the user to select a file and a metadata key, and to request the metadata value from the Bridge DOM by clicking a button. Clicking the button invokes the
jsFuncs
property.
getMetadata callback function, which is defined and stored in the NavBar Object's
When the callback is executed, it retrieves the metadata for the specified file, and sends the results back to HTML JavaScript. The HTML code displays the result in another control.
Code in the Bridge script
This code defines the navigation bar, and a callback to be invoked remotely from the HTML page.
var jsCallbacks = {
getMetadata: function(x,y) {
var tn = new Thumbnail( File(x) );
return(tn.metadata[y]); },
};
function addNavBar() {
var topbar = app.document.navbars.filesystem.top; topbar.height = 65; topbar.type = "html"; topbar.file = File("/C/BridgeScripts/HTML/navbarUI.html");
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 48
topbar.jsFuncs = jsCallbacks; topbar.visible = true;
}
addNavBar();
Code in the HTML file
This code defines the controls to be displayed in the bar and invokes the getMetadata callback function in response to a button click.
<HTML> <HEAD> <META http-equiv="Content-Script-Type" content="text/javascript"> <TITLE>Bridge UI/HTML Integration</TITLE> </HEAD> <BODY>
For File: <INPUT type=file name="fname" size = "100"> <br> Get Metadata key:
<select name="mdkey">
<option value="FileSize">FileSize
<option value="FileName">FileName
<option value="DocumentKind">DocumentKind
<option value="Creator">Creator </select>
<INPUT type=button title="Get Metadata" name="go" value="Get Metadata"
onclick="var t = call('getMetadata',window.fname.value,
window.mdkey.value);
window.mresult.value = t;" >
Result: <input type=text title="mresult" name="mresult" size = "50">
</BODY> </HTML>

Calling functions defined in an HTML navigation bar

If the HTML page displayed in a navigation bar defines any JavaScript functions of its own, Bridge can make remote calls to those functions using the NavBar Object example. If a Bridge HTML dialog displays the HTML page, use the same technique, but call the Dialog
Object's execJS function.
In this example, the HTML page displayed in the top navigation bar has two text boxes, a path and a quantity. Each time the user selects a
Thumbnail for a file or folder, the corresponding path name is
displayed in the Path box. If the user selects a folder, the number of items in the folder is displayed in the Number of Items box.
The HTML script defines two JavaScript functions,
updatePath and updateItemQty, to perform these
updates. However, these functions operate on values retrieved from Bridge objects, which must be passed in from the Bridge ExtendScript engine.
The update functions need to be invoked in response the user selecting a thumbnail. This action generates a
Thumbnail select event on the Bridge side, so the Bridge script defines a handler for that event,
which invokes the remote functions by calling
execJS. It gets the required values from Bridge DOM
's execJS function, as shown in the following
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 49
objects, packages the function call (the name and its argument list) as a string, and passes that string as the argument to
execJS.
Before you use
execJS to call functions defined in the HTML JavaScript code, you need to make sure that
the page is loaded, so that the functions are defined when you call them. In this example, the page uses the HTML/JavaScript
NavBar’s jsFuncs property), which sets a Bridge-script global variable, htmlLoaded. The event handler
onloaded event defined on the BODY tag to invoke a callback (defined in the
checks that variable before calling the remote functions.
If the page is loaded, the event handler invokes the HTML JavaScript function
updatePath, which writes
the path argument into the Path text box. If the event happened to a folder object, it invokes the HTML JavaScript function box. If the event was triggered by a noncontainer object, the script writes the string
Note: JavaScript uses the backslash (
updateItemQty, which writes the itemQty argument to the Number of Items text
"n/a" to the text box.
\) as the escape character, but the backslash is part of Windows
platform path names. Therefore, in order to pass the path name value, the script uses the JavaScript
escape function to encode the name it sends to HTML. On the HTML JavaScript side, unescape
decodes the string so it is properly displayed in the Path box with the backslash character.
Code in the Bridge script
The Bridge script points the navigation bar to the HTML page, and invokes functions defined on that page.
var htmlLoaded = false; var jsCallbacks = {
loaded: function() {
htmlLoaded = true; //set a global to make sure page is loaded }
}; function addNavBar() {
var topbar = app.document.navbars.filesystem.top; topbar.height = 65; topbar.type = "html"; topbar.file = File("/C/BridgeScripts/HTML/navbar2UI.html"); topbar.jsFuncs = jsCallbacks; topbar.visible = true;
}
onEvent = function( event ) {
try {
if( event.object.constructor.name == "Thumbnail") {
if( event.type == "select" && htmlLoaded) { // for thumbnail selection
var tn = event.object; var topNb = app.document.navbars.filesystem.top; //call fns defined in HTML page’s script
topNb.execJS("updatePath('" + escape(tn.path) + "')");
if(tn.container) {
topNb.execJS("updateItemQty(" + tn.children.length + ")");
} else{
topNb.execJS("updateItemQty('n/a')");
}
}
} } catch (error) {
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 50
alert (error);
}
} // Add the event handler to the application app.eventHandlers.push( { handler: onEvent} ); addNavBar(); //show the navigation bar
Code in the HTML file
The displayed HTML page defines two functions, which are invoked from the Bridge script.
<HTML> <HEAD> <META http-equiv="Content-Script-Type" content="text/javascript"> <TITLE>Bridge UI/HTML Integration</TITLE>
<script>
//define fns to be called from Bridge
function updatePath(path) { window.path.value = unescape(path) }; function updateItemQty(qty) { window.itemQty.value = qty };
</script>
</HEAD>
<BODY onload = "call('loaded')">
<!--use callback to set Bridge global-->
Path: <INPUT type=text name="path" size = "100"> <br> Number of Items: <input type=text title="itemQty" name="itemQty" size = "25">
</BODY> </HTML>

Displaying HTML in the Content Pane

The following examples use the Thumbnail and Content pane mechanism, and demonstrate how to pass simple and complex values between Bridge and an HTML UI page via callback functions. For similar examples that use the
Using callbacks in an HTML dialog

Callback example: Requesting specific metadata value for a file

This example shows how to use an HTML file as a user-interface to the Bridge DOM.
The Bridge DOM script creates a Thumbnail Object that uses a script-defined browse scheme. Its
displayPath is set to the path of the HTML file shown below, and its displayMode set to web. This
thumbnail is added to the Favorites pane.
NavBar and Dialog mechanisms, see Displaying HTML in a Navigation Bar and
.
When the user selects the "HTML Sample" icon in the Folders pane, the testUI.html page appears in
the Content pane. This HTML file provides interface controls to select a file and a metadata key, and a button to request the metadata from the Bridge DOM.
Clicking the button invokes the Bridge DOM getMetadata function, which is defined in the
Document.jsFuncs property. The getMetadata function retrieves the metadata for the specified
file, and sends the results back to HTML JavaScript, which displays the results on the HTML page.
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 51
Code in the Bridge DOM script
var jsCallbacks = {
getMetadata: function(x,y) {
var tn = new Thumbnail( File(x) );
return(tn.metadata[y]); },
}; app.document.jsFuncs = jsCallbacks;
app.registerBrowseScheme( "myScheme" ); var t = new Thumbnail("myScheme://root"); t.name = "HTML Sample"; t.displayMode = "web"; t.displayPath = "/C/myScripts/html/testUI.html"; app.favorites.insert(t); //add the thumbnail to Favorites
Code in the HTML file testUI.html
<HTML> <HEAD> <META http-equiv="Content-Script-Type" content="text/javascript"> <TITLE>Bridge UI/HTML Integration</TITLE> </HEAD> <BODY>
For File: <INPUT type=file name="fname" size = "65"> <br><br> Get Metadata key:
<select name="mdkey">
<option value="FileSize">FileSize
<option value="FileName">FileName
<option value="DocumentKind">DocumentKind </select>
<INPUT type=button title="Get Metadata" name="go" value="Get Metadata"
onclick="var t = call('getMetadata',window.fname.value,
window.mdkey.value);
window.mresult.value = t;" > <br><br> Result: <input type=text title="mresult" name="mresult" size = "50"> <br><br>
</BODY> </HTML>

Passing Complex Values in Remote Calls

To exchange simple values such as strings and numbers between Bridge and an HTML UI page, you can simply pass arguments and return values of those types in your callback and complex values such as objects and arrays must be broken down and reconstructed on the other side. This is true for communication in both directions—callbacks from HTML to Bridge, and execution of HTML script functions by Bridge using
execJs.
execJS functions. However,
For a callback to receive an object as an argument, the calling function on the HTML side must serialize the object into a string, using
toSource, and pass the serialized string. On the Bridge side, the callback
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 52
function uses eval to reconstruct the object from the serialized string. Similarly, to pass an object back, the callback function must use receiving code on the HTML side must in turn reconstruct the object using
toSource to serialize the object and return the serialized string. The
eval. See the example below.
Note: The embedded browser does not support the
toSource method, so you cannot use this
mechanism to pass complex values to and from HTML-page functions that you invoke using the
execJS method. Pass only simple values from the HTML JavaScript engine to the Bridge
ExtendScript engine.

Passing an object from Bridge to HTML/JavaScript

This example shows a Bridge Document Object callback that sends an object to a script on an HTML page being displayed in the Content pane.
Code in the Bridge DOM script
The callback function creates a JavaScript object and copies properties and values into it from file metadata, which it accesses through a string from the object, and returns that string.
var jsCallbacks = {
getFileInfo: function(x) {
var tn = new Thumbnail( File(x) );
var info = {}; info.fileName = tn.metadata.FileName; info.fileSize = tn.metadata.FileSize; info.fileKind = tn.metadata.DocumentKind; return(info.toSource());
} }; app.document.jsFuncs = jsCallbacks;
Thumbnail object. It then uses toSource to create a serialized
app.registerBrowseScheme( "myScheme" ); var t = new Thumbnail("myScheme://root"); t.name = "HTML Sample"; t.displayMode = "web"; t.displayPath = "/C/MyScripts/HTML/contentPaneUI.html"; app.favorites.insert(t); // add the thumbnail to Favorites
Code in the HTML page
The HTML code makes a call to the callback function. When it receives the string value, it reconstitutes the object using
<HTML> <HEAD> <META http-equiv="Content-Script-Type" content="text/javascript"> <TITLE>Bridge UI/HTML Integration</TITLE> </HEAD> <BODY>
For File: <INPUT type=file name="fname" size = "65"> <br><br> <INPUT type=button title="Get File Info" name="go" value="Get File Info"
eval.
onclick="var ret = call('getFileInfo',window.fname.value);
var info = eval(ret);
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 53
window.filename.value = info.fileName; window.filesize.value = info.fileSize;
window.filekind.value = info.fileKind;" > <br><br> File Name: <input type=text title="filename" name="filename" size = "50"> <br><br> File Size: <input type=text title="filesize" name="filesize" size = "50"> <br><br> Doc Kind: <input type=text title="filekind" name="filekind" size = "50"> <br><br>
</BODY> </HTML>

Scheduling tasks from callbacks

You cannot call the execJS method from within a callback function (either stored in a jsCallbacks property or passed as an argument to the Dialog JavaScript engine, which is already running and is not re-entrant. If you try to do this, Bridge will hang.
open or run method). This attempts to re-enter the
The alternative is to schedule a task, using the App Object callback function. From the function associated with the task, you can call
’s scheduleTask function, from within the
execJS. Because it is not
executed until the callback returns, the task is free to make another remote call.
The first argument to
scheduleTask is a string containing a script—in this case, a call to the execJS
function. For example:
var result = app.scheduleTask("myFn(3);", 10);
If the script itself contains any strings, those must be indicated by enclosed quotes. For example:
var result = app.scheduleTask("myFn('string argument');", 10);
If the enclosed string contains values derived from expressions, the script string must be concatenated, and can become quite complex:
var result = app.scheduleTask("myFn('" + escape(tn.path) + "')", 10);
The argument to execJS is also a string containing a script—in this case, a call to a function defined on an HTML page. When the arguments to that function are also strings, and those contain values derived from expressions, the resulting string is very complex.
The example below makes this string a little more manageable by breaking it down into modular pieces. First, it builds the argument string for the remote function:
var toRecordArg = "'For File: " + tn.metadata.FileName + "'";
It uses that to build the entire string for the remote function call, which is the argument to execJS:
var execFn = "recordData(" + toRecordArg + ")";
Building the string for the call to execJS requires an additional layer of embedded quotes, which is very difficult to achieve with only two types of quote character. To get around this, the example creates a variable for a string containing the double-quote character, and uses it to build the entire function call string, which is passed to
var quote = '"'; app.scheduleTask("app.document.execJS(" + quote + execFn + quote + ")")
scheduleTask:
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 54

Scheduling a remote function execution

This example defines a thumbnail that uses a script-defined browse scheme and displays a web page. That web page (shown below) defines a function defined in the script, and the callback function constructs and schedules calls to execJS after the callback returns.
Bridge Script
The callbacks for the page (defined in the Document Object’s jsFuncs property) include a function
getMetadata, which schedules two calls to the recordData function. For each task, it builds a string
containing a call to the Document Object function. (This is a very complex string, since the argument to complete function call to
recordData, which itself takes a string argument.)
After the callback has returned, the scheduled tasks execute the remote function, which writes out data to one of the HTML page’s controls.
htmlLoaded = false; // make sure page is loaded // Define callback functions var jsCallbacks = {
getMetadata: function(x,y) {
var quote = '"'; var tn = new Thumbnail( File(x) ); var toRecordArg = "'For File: " + tn.metadata.FileName + "'"; var execFn = "recordData(" + toRecordArg + ")";
app.scheduleTask("app.document.execJS("
+ quote + execFn + quote + ")",0, false);
toRecordArg = "' Metadata key " + y + " has value "
+ tn.metadata[y] + "'"; execFn = "recordData(" + toRecordArg + ")"; app.scheduleTask("app.document.execJS(" + quote + execFn
+ quote + ")",10, false);
return(tn.metadata[y]); }, loaded: function() {
htmlLoaded = true; //page is loaded
} };
recordData. The page makes a call to a callback function
, to be executed
’s execJS function, and passes it to the app.scheduleTask
execJS is also a string containing a
app.document.jsFuncs = jsCallbacks;
// define thumbnail to show the HTML page app.registerBrowseScheme( "myScheme" ); var t = new Thumbnail("myScheme://root"); t.name = "HTML Sample"; t.displayMode = "web"; t.displayPath = "/C/myScripts/HTM/testUISchedTask.html";
app.favorites.add(t); // add the thumbnail to the Favorites pane app.document.thumbnail= t; // browse to the thumbnail
Adobe Creative Suite 2
Bridge JavaScript Reference Creating a User Interface 55
HTML code
This page, which is displayed by the thumbnail, defines a script function, recordData. The button’s
onClick method calls the getMetadata callback, which schedules the recordData function to be
executed remotely after the callback has returned.
<HTML> <HEAD> <META http-equiv="Content-Script-Type" content="text/javascript"> <TITLE>Bridge UI/HTML Integration</TITLE>
<script> function recordData(logString) {
window.dataLog.value = window.dataLog.value + '\n' + unescape(logString); }
</script>
</HEAD> <BODY onload="call('loaded')">
For File: <INPUT type=file name="fname" size = "65"> <br><br> Get Metadata key:
<select name="mdkey">
<option value="FileSize">FileSize
<option value="FileName">FileName
<option value="DocumentKind">DocumentKind </select>
<INPUT type=button title="Get Metadata" name="go" value="Get Metadata"
onclick="var t = call('getMetadata',window.fname.value,
window.mdkey.value);
window.mresult.value = t;" >
<br><br>
Result: <input type=text title="mresult" name="mresult" size = "50">
<br><br>
DataLog: <br>
<textarea type="dataLog" name = "dataLog" rows = "15"
cols = "75"></textarea> <br><br>
</BODY> </HTML>
4

Using File and Folder Objects

Overview

Because path name syntax is very different in Windows®, Mac OS®, and UNIX®, Adobe ExendScript defines the
File Object
The Folder object supports file system functionality such as traversing the hierarchy; creating,
The File object supports input/output functions to read or write files.
File and Folder objects to provide platform-independent access to the underlying file system. A
represents a disk file; a Folder Object represents a directory or folder.
renaming, or removing files; or resolving file aliases.
There are several ways to distinguish between a
if (f instanceof File) ... if (typeof f.open == "undefined") ...// Folders do not open
and Folder objects can be used anywhere that a path name is required, such as in properties and
File
arguments for files and folders. For details about the objects and their properties and methods, see
Chapter 7, “
Note: When you create two
File and Folder Object Reference."
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.
File and a Folder object. For example:
File objects that refer to the same disk file, they are treated as distinct

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 ( following describes an absolute location for the file
/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 the special names dot (
property of the Folder class. It starts with a folder or file name, or with one of
.) for the current directory, or dot dot (..) for the parent of the current directory. A
/), and a slash separates path elements. For example, the
myFile.jsx:
56
Adobe Creative Suite 2
Bridge JavaScript Reference Using File and Folder Objects 57
slash (/) separates path elements. For example, the following paths describe various relative locations for the file
myFile.jsx:
myFile.jsx ./myFile.jsx
../myFile.jsx
../../myFile.jsx
../dir1/myFile.jsx
In the current directory.
In the parent of the current directory.
In the grandparent of the current directory.
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 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.
//myhost/mydir/myfile refers to the path /mydir/myfile on the server
Folder.current property, and use relative
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 that 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
This encoding scheme is compatible with the global JavaScript functions

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 directory is Extend Script assigns the home directory value directly from the platform value.
In Windows, the name or a path name referring to a remote server (such as variable is undefined, the Extend Script default is the user's home directory, usually the
and Settings\username
/Users/username. In UNIX, it is typically /home/username or /users/username.
HOME environment variable is optional. If it is assigned, its value must be a Windows path
%)
ä is encoded as %E4, so the file name "Bräun" is specified as "Br%E4un".
encodeURI and decodeURI.
HOME environment variable according to the user login. In Mac OS, the default
\\myhost\mydir). If the HOME environment
C:\Documents
folder.
Adobe Creative Suite 2
Bridge JavaScript Reference Using File and Folder Objects 58
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 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.
/Volumes directory. The File and Folder objects use these
URI path name Mac OS 9 path name Mac OS X path name
/MacOSX/dir/file MacOSX:dir:file /dir/file
/Remote/dir/file Remote:dir:file /Volumes/Remote/dir/file
/root/dir/file Root:dir:file /root/dir/file
~/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
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
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
/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.
C:\temp\file.
/c/c for C:\C.
D:\C, and if the current drive is D:, the URI path
These examples assume that the current drive is
D:
Adobe Creative Suite 2
Bridge JavaScript Reference Using File and Folder Objects 59
URI path name Windows path name
/c/dir/file c:\dir\file
/remote/dir/file D:\remote\dir\file
/root/dir/file D:\root\dir\file
~/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
File object represents an alias, the alias property of the object returns true, and the resolve
method returns the
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.
rename and remove, and setting properties readonly and hidden. When a
File or Folder object for the target of the alias.
For example, suppose there is a shortcut to the file full Windows file name of the shortcut file is
To access the shortcut from a object’s
open method opens the linked file (in /folder1). Calling the File object’s rename method
renames the shortcut file itself (leaving the
However, Windows permits a file and its shortcut to reside in the same folder. In this case, the always accesses the original file. You cannot create a same folder as its linked file.
A script can create a file alias by creating a 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 in the root directory of same data location, the path name
/folder1/some.txt in the folder /folder2. The
\folder2\some.txt.lnk.
File object, specify the path /folder2/some.txt. Calling that File
.lnk extension intact).
File object
File object to access the shortcut when it is in the
File object for a file that does not yet exist on disk, and using
myServer for data storage. If you set up an alias share
myServer, and if you set up a Windows-accessible share at share pointing to the
//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 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 a complete list, see File and Folder Supported Encoding Names
encoding property of a File object returns the current encoding. You can set the
ASCII, X-SJIS, or ISO-8859-1. For
.
Adobe Creative Suite 2
Bridge JavaScript Reference Using File and Folder Objects 60
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 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 ( 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, 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.
\uFEFF). The File.open method reads a few bytes of a file looking for this
open() reads the first 2 KB of the file and checks
1000, which
When using UTF-8 encoding or 16-bit Unicode, always write the BOM character " 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
\uFEFF" as the first
.
5

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® CS2 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 8, “ 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 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 resizeable, holds focus when shown.
Floating palettes: also called modeless dialogs, not resizeable. (Photoshop CS2 does not support script
Main windows: resizeable, suitable for use as an application's main window. (Main windows are not
To create a new window, use the the window. The type is palette. You can supply optional arguments to specify an initial window title and bounds.
Button and StaticText, that represent user-interface controls. These objects share a common
creation of palette windows.)
normally created by script developers for Adobe Creative Suite 2 applications. Photoshop CS2 does not support script creation of main windows.)
Window constructor function. The constructor takes the desired type of
"dialog" for a modal dialog, or "palette" for a modeless dialog or floating
ScriptUI Object Reference,"
The following example creates an empty dialog with the variable name 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]);
dlg, which is used in subsequent
61
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 62
Newly created windows are initially hidden; the show method makes them visible and responsive to user interaction. For example:
dlg.show();

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: 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
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.
Panels and Groups. These can contain control
edittext box and its descriptive
You might create a 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 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: undefined, and a script that employs Automatic Layout 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 within a window or other container is defined as the origin point specified in the container’s coordinate system. That is, the
The following examples show equivalent ways of placing the content region of an existing window at screen coordinates [10, 50]:
Panel and populate it with several Groups, each with their own elements. You can
add method (see Adding elements to containers). An
location, size, and bounds. These properties are initially
should leave them undefined for the main window
location of an element
x and y values are relative to the origin of the container.
win.location = [10, 50]; win.location = {x:10, y:50}; win.location = "x:10, y:50";
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 63
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;
The bounds of an element are defined by a Bounds object containing both the origin point (x, y) and
width, height) To define the size and location of windows and controls in one step, use the
size (
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 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
bounds property for a Window refers only to its
Push buttons with text or icons, radio buttons, checkbox buttons
Static text or images, edit text
Progress bars, scrollbars, sliders
Lists, which include list boxes and drop-down (also called popup) lists. Each item in a list is a control of
item, and the parent list’s items property contains an array of child items. You can add list items
type 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.
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 64
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
text value, but no bounds value:
dlg.btnPnl = dlg.add('panel', undefined, 'Build it'); dlg.btnPnl.testBtn = dlg.btnPnl.add('button', undefined, 'Test');
Panel and Button elements with an initial
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.
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 element. For example, the following creates a new
dlg.btnPnl.buildBtn =
dlg.btnPnl.add('button', undefined, 'Build', {name:'ok'});
name, which assigns a name for identifying that
Button element with the name 'ok':
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
In this example, the object at index 0 of the parent’s
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
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";
children collection is empty.
msgPnl panel was the first element created in dlg, so the script can access the panel
children property to set the text for the title:
children array of its parent, or directly as a property of its parent. For example, the
For list controls (type list and dropdown), you can access the child list-item objects through the items array.
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 65

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
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.
children collection (see Accessing child elements).
To remove list items from a list, use the parent list control’s remove the item from the parent’s

Types of controls

The following sections introduce the types of controls you can add to a Window or other container element ( 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
panel or group). For details of the properties and functions, and of how to create each type of
method in the same way. It removes
items list, hides it from view, and deletes the item object.
.
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 those with
var dlg = new Window('dialog', 'Alert Box Builder',[100,100,480,245]);
dlg.msgPnl = dlg.add('panel', [25,15,355,130], 'Messages');
Panels as separators: those with width = 0 appear as vertical lines and
height = 0 appear as horizontal lines.
Group
Used to visually organize related controls. Unlike Panels, Groups have no title or visible border. You can use them to create hierarchies of controls, and for fine control over layout attributes of certain groups of controls within a larger panel. For examples, see Creating more complex arrangements
.
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 Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 66
StaticText
EditText
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
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();
Panel and adds several StaticText elements:
Allows users to enter text, which is returned to the script when the dialog is dismissed. Text in
Set the text property to assign the initial displayed text in the element, and read it
EditText elements can be selected, copied, and pasted.
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.
Button
IconButton
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 Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 67
Image
Checkbox
RadioButton
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
When you create a
value=true when it is selected (checked) and false when it is not.
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 group becomes state of one of them
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();
false. When you create a group of radio buttons, you should set the
true:
true, the value of all other buttons in the
Progressbar
Slider
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 the visible area is colored, relative to the maximum value ( range is 0 to 100, so the
value=50 when the operation is half done.
value property reflects and controls how much of
maxvalue). By default the
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 within the range determined by 100, so setting
value property reflects and controls the position of the indicator,
minvalue and maxvalue. By default the range is 0 to
value=50 moves the indicator to the middle of the bar.
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 68
Scrollbar
ListBox DropDownList
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
You can create scrollbars with horizontal or vertical orientation; if
height, it is horizontal, otherwise it is vertical.
than
Scrollbars are often created with an associated
jumpdelta property.
width is greater
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.
ListItem

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 property, either to a named icon resource, a File Object image (see Specifying Paths
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 object’s remove
method. You can remove items programmatically with the list
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 a drop-down list.
Although it has a
text property, the value is ignored, and the item is displayed as a
horizontal line.
icon
, or the pathname of a file containing the iconic
).
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 69
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
The scripting environment can define icon resources, which are available to scripts by name. To specify an icon resource, set a control’s name when creating the control. For example, to create a button with an application-defined icon resource:
myWin.upBtn = myWin.add ("iconbutton", undefined, "SourceFolderIcon");
If a script does not explicitly set the preferredSize or size property of an element that displays a icon image, the value of 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 own messages. You do not need to create a
icon property at any time to change the image displayed in the element.
icon property to the resource’s JavaScript name, or refer to the resource by
preferredSize is determined by the dimensions of the iconic image. If the size
, confirm, and prompt on the Window class to invoke these dialogs with your
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 you to pass a value to be returned by the
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.
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 of the
onClick or onChange property of the control.
For example, if you need to validate a value that the user enters in a
onChange callback handler function for that control. The callback can perform the validation, and
perhaps display an alert to inform the user of errors.
or hide method to close the dialog. The close method allows
show method.
or onChange. The callback function is the value
edittext control, you can do so in an
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 70
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 closed. If the function returns
event handler for the dialog. This callback function is invoked whenever a window is
true, the window is closed, but if it returns false, the close operation is
cancelled and the window remains open.
Yo ur
onClose handler can examine the states of any controls in the dialog to determine their correctness,
and can show alert corrected. It can then return
messages or use other modal dialogs to alert the user to any errors that must be
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 You have the option of sending a value to the from the show
method that invoked the dialog. This return value allows your script to distinguish different
callbacks for the buttons that close the parent dialog by calling its close method.
close method, which is in turn passed on to and returned
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 this case, the system will execute a call to the dialog’s
onClick handlers do not function properly, a user can still dismiss the dialog by typing ESC. In
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 typing E the associated
SC is the same as clicking Cancel. The keyboard shortcut has the same effect as calling notify for
button control.
NTER is the same as clicking OK or the default button, and
To determine which control is notified by which keyboard shortcut, set the
defaultElement
and cancelElement properties. The value is the control object that should be notified
dialog object’s
when the user types the associated keyboard shortcut.
For buttons assigned as the defaultElement, if there is no onClick handler associated with the
button, clicking the button or typing E to be returned by the show
For buttons assigned as the cancelElement, if there is no onClick handler associated with the
call that opened the dialog.
button, clicking the button or typing E be returned by the show
call that opened the dialog.
NTER calls the parent dialog’s close method, passing a value of 1
SC calls the parent dialog’s close method, passing a value of 2 to
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 71
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 element, it looks for a button whose 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
name or text value is "ok" (disregarding case). For the cancel
name or text value is "cancel" (disregarding case). Because it looks
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 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
Window() or add() constructor function.
The general structure of a resource specification is an element type specification (such as 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
testBtn: Button { text: 'Test' }
The following resource string specifies a panel that contains several StaticText and EditText controls:
Button:
name creation property
type parameter to the
dialog),
"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
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}
An inline object contains one or more properties, in the form:
{propertyName:propertyValue,propertyName:propertyValue,... }
null, true, false, a string, a number, an inline array, or an object.
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 72
The Resource specification example shows how to build a complete window and all its contents with a resource specification. 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 Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 73

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 closing the window, define callback functions for onShow
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

Defining event handler functions

, onMoving, onResize, and onResizing. To respond to the user opening or
and onClose.
.
and onChanging.
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
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.
notify method invokes it.
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 74
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 clicked. For example, if the
false:
notify() to simulate a click, the value changes just as if the user had
value of a checkbox hasBtnsCb is true, this code changes the value to
if (dlg.hasBtnsCb.value == true) dlg.hasBtnsCb.notify(); // dlg.hasBtnsCb.value is now false
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 75

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 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

layout property. The layout manager controls the
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
You can nest 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 container, and the 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 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.
Panel and Group containers to create more complex organizations. For example, to display
alignment property of the individual controls. The alignChildren property
orientation property, which can have the value row, column, or stack.
.
alignChildren property of the
preferredSize
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 Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 76

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 controls the alignment of all children within that container, unless it is overridden by the value set on an individual child element.
alignment in each child. The alignChildren value in the parent container
alignment
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 77
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 Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 78
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
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:
alignChildren, by setting the
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 container.
The following figure shows the results of creating the sample window with row orientation and margins of 5 and 15 pixels:
object, which allows you to specify different margins for each edge of the
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 Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 79
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 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 strings (see Localization in ScriptUI Objects 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 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.
size property is not defined, the layout manager uses the value of preferredSize to
text properties of your UI elements using localizable
). The width and height of each element are calculated at
preferredSize property to give hints to the layout manager
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 a simple dialog in which a user can enter information into two
EditText fields, each arranged in a row
) shows
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 80
with 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 fields is to align the child rows in the
Panel specification:
the
info: Panel { orientation: 'column', alignChildren:'right', \
Panel to the right of the panel. In the example, add the following to
StaticText labels for your EditText
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', \
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 81
text: 'Personal Info', \ name: Group { orientation: 'row', \
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
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
The following script creates this dialog. It compresses the "Personal Info" and "Work Info" panels from the previous example into a single 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.
stack orientation to present different views in the same region of a dialog.
DropDownList.
Panel that has two Groups arranged in a stack. A DropDownList allows
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 82
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'} } \
} \
}"; 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 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.
layout property for the last Group
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 83
/* Define a custom layout manager that arranges the children ** of 'container' in a stair-step fashion.*/
function StairStepButtonLayout (container) { this.initSelf(container); }
// Define its 'method' functions function SSBL_initSelf (container) { this.container = container; }
function SSBL_layout() {
var top = 0, left = 0; var width; var vspacing = 10, hspacing = 20; for (i = 0; i < this.container.children.length; i++) {
var child = this.container.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] } \
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 84
} \
}, \
}, \ 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; 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 the elements and their containers.
The default initial call to a
1. Read the
defined, assume that the script has explicitly placed the elements in this container, and cancel the
layout operation (if both the
the
2. Determine the container’s margins and inter-element spacing from its
properties, and the orientation and alignment of its child elements from the container’s
and
obtained from platform and UI framework-specific default values.
AutoLayoutManager’s layout method performs these steps when invoked during the
window object’s show method:
bounds property for the managed container; if undefined, proceed with auto layout. If
location and size property have been set, this is equivalent to setting
bounds property, and layout does not proceed).
alignChildren properties. If any of these properties are undefined, use default settings
layout method is called to assign locations and sizes for all
margins and spacing
orientation
3. Enumerate the child elements, and for each child:
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 85
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
Read its size property: if defined, use it to determine the child’s dimensions. If undefined, read its
alignChildren property.
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
8. Set the container’s
bounds property for each child element.
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
manager to recalculate the sizes of all child containers by passing the optional argument as
The layout mechanism does not support re-layout if a dialog window is resized.
layout method, and can force the
true.
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 86

Example scripts

These examples demonstrate two ways of building and populating a ScriptUI dialog. The first creates each control with a separate 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.
add method, while the second defines a resource string that creates the control

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];
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 87
msg.st = msg.add('statictext', undefined, 'Alert message:'); msg.et = msg.add('edittext', undefined, '<your message here>',
{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 */
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 88
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 =
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";
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 89
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") +"}" +
" }"; } // 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 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();
add method of a container element. To use this
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 90
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} } \ }, \ 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 Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 91

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 MenuElement Object and efficiently, using the Global localize function containing the localized versions of a string.
. This function takes as its argument a localization object
s) simply
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 supplies the text for a
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
When your script uses localization to provide language-appropriate strings for UI elements, it should also take advantage of the Automatic Layout UI element based on its localized dialogs to allow for the varying widths of strings for different languages.
btnText object contains localized text strings for several locales. This object
Button to be added to a window w:
de provides the string "Ja".
feature. The layout manager can determine the best size for each
text value, automatically adjusting the layout of your script-defined

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
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);
localize function. For example:
Adobe Creative Suite 2
Bridge JavaScript Reference Using ScriptUI 92
//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.
6

Bridge DOM Object Reference

This chapter provides a complete reference for the objects of the The Bridge Document Object Model (DOM). The Bridge DOM objects are presented alphabetically. For each object, complete syntax details are provided for the constructor, properties, and functions.
App Object
Dialog Object
Document Object
Event Object
Favorites Object
Metadata Object
NavBar Object
Preferences Object
PreferencesDialog Object
Thumbnail Object
The Bridge application.
A dialog that displays an HTML page.
A Bridge browser window.
A user-interaction event.
An array of the thumbnails shown in the Favorites pane.
Access to file metadata through a thumbnail.
A configurable navigation bar that can display user-interface controls.
Access to application preferences.
Access to the Preferences dialog.
A navigable node representing a file, folder, or web page.
Other available objects are discussed separately:
Chapter 7, “File and Folder Object Reference," describes the ExtendScript File and Folder objects
that provide portable access to the file system.
Chapter 8, “ScriptUI Object Reference," describes the ExtendScript ScriptUI objects that provide
user-interface capability, including the MenuElement Object
Chapter 9, “Interapplication Communication with Scripts," describes the BridgeTalk class and
that allows you to extend Bridge menus.
message object that provides the ability to communicate among Adobe Creative Suite 2 applications using JavaScript.
Chapter 10, “ExtendScript Tools and Features," describes various ExtendScript utilities, including:
For debugging, the Dollar ($) Object and ExtendScript Reflection Interface
The Global localize function and the localization object that allow you to provide language versions
of displayed strings for different locales.
The UnitValue Object for specifying and working with measurement values
93
Adobe Creative Suite 2
Bridge JavaScript Reference Bridge DOM Object Reference 94

App Object

The App object represents the Bridge application. A single global instance is created on startup; access it using the
app global variable.
There is only one on
Document, and can be accessed with the app.document or app.documents properties.
App object. Multiple Bridge browser windows are represented by instances of

App object properties

displayDialogs
document
documents
eventHandlers
String The policy for the display of modal dialogs. Read/Write.
One of:
all (default): Modal dialogs should always be
displayed.
none: Modal dialog should never be displayed. error: Only dialogs that report an error to the user
should be displayed.
Document The active (top-most) Document Object, representing the
active Bridge browser window. Read/Write.
Array of Document
Array of EventHandler
A collection of Document Objects representing the set of all open Bridge browser windows. Read/Write.
A collection of event handlers installed by scripts. Add an event handler to this array to register it with Bridge. Registered handler functions are called when any user-interaction event is triggered. See Event Handling in
Bridge. Read/Write.
favorites
language
Each event handler is specified by a JavaScript object with one property, the handler function name:
{ handler:
fnName
}
The handler function takes one argument, an Event
Object, and returns a result object {handled:
When true, the event has been completely handled
boolean
}.
and Bridge does not look for more handlers or call the default handler.
When false (or when the handler returns undefined),
Bridge continues to call registered handlers, or if there are no more, calls the default handler.
Favorites The top-level object for the navigation hierarchy displayed
in the Favorites pane. This Favorites Object
Thumbnail Object
s. Read only.
is an array of
String The display name of the language for the current locale, as
configured by the operating system. This is the name as it appears in the Preferences dialog. Read only.
Adobe Creative Suite 2
Bridge JavaScript Reference Bridge DOM Object Reference 95
locale
name
preferences
version

App object functions

beep
app.beep ()
browseTo
app.browseTo (
path
String The Adobe locale code for the current locale, as
configured by the operating system. Read only.
An Adobe locale code consists 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.
String The CS2 application specifier for this application, "bridge".
Read only.
Preferences The Preferences Object, which provides access to the user
preferences shown in the Preferences dialog (invoked from the Edit > Preferences command). Read only.
String The version number of the Bridge application. Read only.
Calls on the operating system to emit a short audio tone. Returns
undefined.
Opens a new Bridge browser window and navigates to the specified
)
file or folder.
path
For a folder, the Folders pane shows the hierarchy of containment
ending at this folder. The Content pane shows the contents of this folder, and no file is selected.
For a file, the Folders pane shows the hierarchy of containment for
the file. The Content pane shows the contents of the containing folder, with this file scrolled into view and selected.
If path specifies a file or folder that does not exist on disk, the
browser navigates to a default path; Desktop in Windows, User Home in Mac OS.
Creates the new Document Object current
app.document. Returns undefined.
for the window and makes it the
A File Object orFolder Object, or the path to a file or folder in platform-specific or portable path format (URI notation). For example:
// using Windows platform-specific notation app.browseTo("C:\\MyFolder"); // using URI notation app.browseTo("/c/MyFolder/MyFile"); // the Folder object returns URI notation app.browseTo(Folder.selectDialog("Browse to?"));
For more information on path notations, see Specifying Paths.
Adobe Creative Suite 2
Bridge JavaScript Reference Bridge DOM Object Reference 96
Note: There are two ways to browse programmatically from a Bridge script:
Call the App Object’s browseTo function. This creates a new browser window and sets it to display
the location you specify.
Set the Document Object’s thumbnail property. This causes the current Folders pane to show and
select the specified node.
Starting the Bridge application from a script also opens a browser window. If you use an interapplication message to call the
browseTo function from a script that also starts the Bridge
application, you can inadvertently open two browser windows. To avoid this, use code such as the following:
if( BridgeTalk.isRunning('bridge') )
// create new browser window if needed bt.body = "if( app.documents.length == 0 )" +
else //reuse window created by upcoming launch
bt.body = "app.document.thumbnail = new Thumbnail('" + target + "');";
" app.browseTo('" + target + "'); " + "else" + " app.document.thumbnail = new Thumbnail('" + target + "');";
For details of how to send and receive interapplication messages, see Chapter 9, “Interapplication
Communication with Scripts."
buildFolderCache
app.buildFolderCache
(
path
[,
recurse
path
])
The folder. A Folder Object, Thumbnail Object for a folder, or string of the form:
If this specifies a file, the cache is built for the containing folder.
recurse
Optional. When true, builds the thumbnail cache recursively for all subfolders. Default is
cancelTask
app.cancelTask
taskId
(
taskId
)
The task ID number, as returned from app.scheduleTask.
hide
app.hide ()
preflightFiles
app.preflightFiles (
files
An array of strings, each of which is a file or folder specification. See Specifying
Paths.
Forces Bridge to create thumbnail images for the specified folder, and optionally for all subfolders. These are stored in a cache file in the folder to which they apply. Returns
"
browseProtocol
false.
Cancels a task that has been scheduled using scheduleTask. Returns
undefined.
In Mac OS, performs the platform-specific hide gesture. In Windows, does the equivalent of
For each specified file or folder, if it refers to a resource that does not
files
have a local copy (such as the files referenced by VersionCue nodes),
)
downloads the specified resource. Returns
://
pathSpecifier
undefined.
"
app.document.minimize(). Returns undefined.
true on success.
purgeAllCaches
app.purgeAllCaches ()
purgeFolderCache
app.purgeFolderCache
path
([
])
Purges the thumbnail caches for all folders. See also buildFolderCache and purgeFolderCache
. Returns undefined.
Purges the thumbnail caches for the specified folder. See also
buildFolderCache
and purgeAllCaches. Returns undefined.
Adobe Creative Suite 2
Bridge JavaScript Reference Bridge DOM Object Reference 97
path
Optional. The folder to purge. A Folder Object, Thumbnail Object for a folder, or string of the form:
"
browseProtocol
If this specifies a file, the cache is purged for the containing folder. If not supplied, purges all folder caches.
quit
app.quit ()
registerBrowseScheme
app.registerBrowseScheme
name
[,
(
name
browseHandler
The name of the browse scheme protocol. Used in the protocol portion of the path argument when creating a Thumbnail Object For example, if the browse scheme name is "
myScheme://
"
browseHandler
Optional. Used internally.
scheduleTask
app.scheduleTask (
delay
[,
repeat
script,
])
])
://
pathSpecifier
"
Shuts down the Bridge application. All Bridge browser windows are closed. Returns
undefined.
Registers a new script-defined browse scheme with Bridge. For additional information, see Script-Defined Browse Schemes
true on success, false if the scheme was previously registered.
. Returns
object that uses this browse scheme.
myScheme" the path argument is
filename
",
Executes a script after a specified delay. The script can be executed repeatedly, stopping when it returns the task using cancelTask
.
undefined, or when you cancel
Returns the task ID number, which can be used to cancel the scheduled task.
script
delay
repeat
system
app.system (
commandLine
For an example, see Scheduling tasks from callbacks
.
A string containing the script to be run.
A number of milliseconds to wait before executing the script. If 0, waits the default number of milliseconds, which is 10.
Optional. When true, execute the script repeatedly after each elapsed delay. Stop when a script execution returns
app.cancelTask. Default is false, which means execute the script only once.
undefined, or when this task is cancelled by calling
Issues the argument to the operating system, as if it were entered on
commandLine
)
the command line in a shell. Control does not return to Bridge until this function returns. Returns
undefined.
The command to pass to the operating system.
Adobe Creative Suite 2
Bridge JavaScript Reference Bridge DOM Object Reference 98

Dialog Object

Represent’s a script-defined dialog that displays HTML user-interface controls. This allows some additional flexibility, as an alternative to that available through the ScriptUI Window Object
Note: The Bridge-DOM dialog object can contain only HTML controls; it cannot contain ScriptUI controls.
Similarly, the ScriptUI

Dialog object constructor

To create a new Bridge dialog object, use the new constructor:
new Dialog (path);
window object can contain only ScriptUI controls, not straight HTML.
.
path
A string containing the path and file name of the HTML page to display in the dialog.

Dialog object properties

active
closing
height
modal
title
width
Boolean When true, the dialog is visible and frontmost on the screen, when false it is
Boolean When set to true, the dialog closes, first invoking the willClose and doClose
Number The height of the dialog in pixels. Read/write.
Boolean When false (the default), the dialog is modeless, meaning that the
String The text displayed in the dialog’s title bar. Read/write.
Number The width of the dialog in pixels. Read/write.
not. Set to
callbacks, if supplied. Read/write.
invocation function returns immediately, but the dialog stays up until dismissed. A modeless dialog does not prevent input in other windows. Read/write.
When while it is up, and the user must dismiss it before taking any other action in the application.
Note: Modal Bridge dialogs are not supported in this release.
true to make a dialog active. Read/write.
true, the dialog is modal, meaning that it retains the keyboard focus

Dialog object functions

center
dialogObj
close
dialogObj
.center ()
.close ()
Centers the dialog on the screen.
Forces the dialog to close, without invoking the willClose or
doClose callbacks. Returns undefined.
Use this to close a modeless dialog from elsewhere in the Bridge script, in response to some external circumstance. From within the dialog’s HTML page, set
closing to true instead.
Adobe Creative Suite 2
Bridge JavaScript Reference Bridge DOM Object Reference 99
execJS
dialogObj
script
open
dialogObj
callbacks
.execJS (
.open (
callbacks
Executes a JavaScript function that is defined within the HTML
script
)
page displayed in the dialog. If the page that defines the function is not currently displayed, causes a run-time error.
Note: Do not call this method from a dialog callback function.
This attempts to re-enter the JavaScript engine, which is not allowed, and causes Bridge to hang. A callback can, instead, schedule a task using
execJS from the function associated with the task. See
Scheduling tasks from callbacks
app.scheduleTask, and call
.
Returns the result of the executed JavaScript function, which must be a Boolean, Number, or String, or
null.
A string containing a script to execute. This typically contains the name and arguments of the JavaScript function to execute, but can have multiple statements, including variable declarations, assignments and so on.
Opens a modeless dialog, which means that a user can take other
)
actions in the Bridge user interface, as well as manipulating the dialog. Returns
When you open a dialog box with the subsequently close it with the
closing property to true.
undefined.
open method, you can
close method, or by setting the
A JavaScript object containing the function definitions for one or more callbacks, in the form:
{
fnName1 fnName2
... }
: function( [args] ) { : function( [args] ) {
fn1_definition fn2_definition
}, }
These functions are available to the code in the HTML page, which can invoke them using the
call function. They run in Bridge’s ExtendScript engine, and can
use Bridge DOM objects. See Communicating with Bridge from dialog JavaScript
.
place
dialogObj
x, y
print
dialogObj
.place (
.print ()
You can provide special callback functions named
willClose and onClose., which
are invoked when the user closes the dialog. See Displaying HTML in Bridge
Dialogs.
Places the dialog on the screen at the specified position.
x, y
)
A position expressed as a percentage offset from the origin (left top) of the screen. Real numbers between 0.0 and 1.0. Thus, (0.0, 0.0) specifies the left top, (1.0, 1.0) the right bottom, and (0.5, 0.5) the center of the screen.
Negative values and values greater than 1 are allowed, but are normalized to on-screen values. For example, (-0.5, 17.25) is the same as (0.5, 0.25).
Invokes the platform-specific Print dialog box to print the HTML page displayed in this dialog. Returns
true on success.
Adobe Creative Suite 2
Bridge JavaScript Reference Bridge DOM Object Reference 100

Document Object

Represents a Bridge browser window.The user can create multiple browser windows by selecting the File > New Window command. For each Bridge browser window, there is one
Access the object for the active Bridge browser window using app.document
Access an array of objects for all open Bridge browser windows in app.documents
For a discussion of how the parts of the browser window map to JavaScript objects, see The Bridge DOM
and the Bridge Browser Window.

Document object properties

Document instance.
allowDrags
contentPaneMode
context
id
jsFuncs
Boolean When true (the default), drag-and-drop of thumbnails is
allowed in this browser window. When
false, thumbnails
cannot be dragged within or from this browser window.
String The type of content displayed in the Content pane. One of:
filesystem (default): The Content pane displays files and
folders.
web: The Content pane displays a web page.
Thumbnail The Thumbnail Object a user has right-clicked to invoke a
context menu. Otherwise
undefined. Read only.
Number Read only. A unique identifier for the browser window, valid for
the life of the window. It is possible for more than one
Document
object to reference the same window.
Object A JavaScript object containing the function definitions for one
or more callbacks, in the form:
{
fnName1 fnName2
... }
: function( [args] ) { : function( [args] ) {
fn1_definition fn2_definition
}, }
These functions are available to the code in an HTML page displayed in the Content pane, which can invoke them using the
call function. They run in Bridge’s ExtendScript engine, and can
use Bridge DOM objects. See Displaying HTML in Bridge
.
Read/Write.
maximized
minimized
Boolean When true, this Bridge browser window is in the zoomed or
maximized state. Read only.
Boolean When true, this Bridge browser window is in the collapsed or
minimized state. Read only.
Note: In Mac OS, a window can be in the zoomed state, and still
be minimized. If both call the document’s restore
maximized and minimized are true,
method to un-zoom the
window.
Loading...