Coding with Standard Classes and Libraries


Take a look inside the Configuration folder, which is in the same folder as the Dreamweaver application, and you'll see two important folders: one named JSExtensions, and one named Shared. Inside these folders are a treasure trove of JavaScript and C++ code and other resources that you can employ in your own extensions. Indeed, much of this code is already in use by many of the standard extensions that ship with Dreamweaver. In this section, we'll examine some of these prebuilt libraries and classes and how they can be used by your own projects.

The Dreamweaver Standard Libraries

Inside the Shared folder of the Dreamweaver MX Configuration folder, you will find a couple of folders named Common and MM. This is where Macromedia stores the JavaScript libraries and other resources that are shared among the Macromedia extensions and provided for use by third parties. The general convention is that, if you create your own code libraries and want to make them available to other developers, you should create your own folder inside the Shared folder with the name of your company or other identifying name and store the code in there.

Inside the Common folder are two other folders: Cache and Scripts. The Cache folder won't be of use to you, but the Scripts folder contains a tremendous number of resources that other extensions can use, such as functions, objects, and classes. You'll also find a Script folder within the MM folder, but this contains versions of some of the same JavaScript files in the Common\ Scripts folder and is included for backwards -compatibility with Dreamweaver 4 and its extensions. The MM\Script folder, however, also contains numerous useful scripts not duplicated in the Common\Scripts folder.

NOTE

DO NOT store your shared code in the MM folder. It is reserved for use by Macromedia.


Shared Images

There is one resource within the MM folder that could prove usefulthe Images folder. The Images folder contains several images that represent common user interface- related icons and pictures. To use these in your extensions, simply include an image in your extension's HTML user interface and define the src attribute as a folder-relative path to the image you want to use. For example, to use the "confirm" icon in one of your extensions, you would use an image tag like this:

 <img src="../Shared/MM/Images/confirmIcon.gif"> 

Using the shared images provided in the Shared/MM/Images folder ensures that your user interface is consistent with that of Dreamweaver's, and that your extension will automatically pick up any changes that are made to those images.

Shared Scripts in the MM folder

The Scripts folder contains two subfolders : Class and CMN. The Class folder contains several JavaScript object class definitions for common objects such as check boxes, files, and list controls. The Class folder contains JavaScript source files that provide object prototypes for several useful classes (more on what prototypes are later). These classes provide functionality that encapsulates the behavior of check boxes, files, tree controls, list controls, radio buttons , and even tabbed dialogs. You can use these classes in your own Dreamweaver extensions just like you would use the regular JavaScript source files in the CMN folder.

The following table lists the files in the Class folder and the functionality they provide. Those files marked with an asterisk (*) have parallel files in the Shared\Common\Scripts folder.

File

Description

classCheckbox.js

Provides methods for working with check boxes and sets of check boxes.

FileClass.js

Provides methods for working with files as objects.

GridClass.js

Contains methods for working with tree control user interface objects.

GridControlClass.js*

Offers methods for working with parameter dialogs.

ImageButtonClass.js*

Provides support for image buttons.

ListControlClass.js*

Contains methods for working with list boxes.

NameValuePairClass.js

Provides a general mechanism for working with lists of name/value pairs.

PreferencesClass.js

Provides an object-based interface for working with sets of preferences for an extension. Uses the MMNotes extension, discussed later.

PageControlClass.js

Provides support for a page of controls, as seen in Windows-style property sheets.

RadioGroupClass.js*

Provides methods for working with radio button groups.

TabControlClass.js

Provides support for a tab control, like those seen in tabbed dialog boxes.

The CMN folder contains common JavaScript source files that are organized by area of functionality. In addition to scripts created specifically for use by Macromedia, general-purpose scripts are available for working with documents, user interface controls, files, forms, strings, and more. This table lists the more useful script files in the CMN folder and what they contain.

File

Contents

docInfo.js

Contains methods for getting information about a given document, such as extracting lists of tags, getting the selected object, and creating unique object names for a document.

DOM.js

Implements several useful methods for working with a document's DOM structure, such as traversing all document tags, determining if a tag has a certain parent, and creating lists of tags.

file.js

Provides methods for working with documents and files, such as getting a file's full path, determining whether a given file is open in Dreamweaver, and extracting a file's name from its path.

form.js

Contains methods for working with forms, such as determining if a FORM tag encloses the current selection.

string.js

Provides several string-manipulation functions.

UI.js

Provides methods for working with user interface elements in extension dialogs.

Although not officially documented anywhere , the code provided in these files is reasonably well commented, and examples of its usage can almost always be found in the standard Dreamweaver extensions that ship with the application ships. You can use Dreamweaver's Find feature to search through the Configuration folder for examples of each script's usage patterns.

Shared Code Highlights

The following functions and objects are among the more useful provided by the Dreamweaver Standard Libraries and shouldn't be overlooked:

File

Function

Description

docInfo.js

selectionInsideTag

Checks to see whether the current selection is contained within a given tag name.

 

createUniqueName

Creates a name attribute for an object that is unique throughout the document.

DOM.js

getRootNode

Returns the root node of the document. Equivalent to dw.getDocumentDOM ('document').documentElement.

 

findTag

Searches the document for a tag with the same name as the given one. If also given a node to start searching from, it will only search below that tag.

 

traverse

Traverses the entire document structure, calling handler functions for each type of node encountered .

 

isInsideTag

Checks to see whether a given tag is inside another tag.

file.js

getFullPath

Converts relative paths into full paths that start with "file://".

 

fileIsCurrentlyOpen

Returns true if the file specified by the given path is open in Dreamweaver.

form.js

checkForFormTag

Checks to see whether the selection is currently enclosed by a form tag, and returns the input string wrapped by a form tag if not. Useful when inserting form controls into a document.

 

IPIsInsideOfForm

Returns true if the selection is inside a form.

string.js

escQuotes/unescQuotes

Finds quote characters such as ' , " , and \ in a string and escapes them by placing a backslash (\) character in front of them; unescQuotes performs the opposite function.

 

reformat

Reformats a string by inserting substrings after a given number of source charactersfor example, reformat("7604346267", 0, "(", 3, ")", 3, "-") returns "(760)434-6267" .

 

Trim

Removes whitespace from the front and back of a string.

 

entityNameEncode/

entityNameDecode

Encodes and decodes a string of characters that has high-ASCII characters or other special characters in it.

UI.js

findObject

Locates a named object and returns a reference to it. For example, instead of using document. forms[0].elementName to refer to an element, you can just use findObject("elementName") to obtain its reference. Then, if you move the element elsewhere in the document, the references to it won't break.

 

loadSelectList

Takes a select list object reference and an array of strings and populates the list with the contents of the array.

The Dreamweaver Standard JavaScript Extensions

In addition to the standard JavaScript classes and libraries, Dreamweaver ships with a standard set C++ shared libraries that live inside the Configuration\JSExtensions folder. These JSExtensions provide JavaScript programmers with access to such things as native platform files, Fireworks scripting, HTTP connectivity, and Design Notes. Chapter 10, "Beyond JavaScript: Interfacing with Dreamweaver Through C++," contains more information about creating your own JSExtensions, but in this section, we'll concentrate on how to best take advantage of all the work that the Dreamweaver development team has already done for you.

The Standard JSExtensions

Every copy of Dreamweaver comes with these standard JSExtensions:

  • DWfile, which provides access to platform-native files. You can create, delete, read data from, write data to, and otherwise manipulate files and directories on the user's system.

  • MMNotes, which exposes Dreamweaver's Design Notes functionality to extensions. Using MMNotes, you can manipulate Design Note information for files directly.

  • MMHttp*, a set of methods that provides HTTP connectivity to extensions. Using MMHttp, your extension can communicate with any web server in the world.

  • FWLaunch, which provides access to Fireworks scripting from within Dreamweaver.

    *MMHttp is not technically an actual JSExtension fileits functionality is built directly into Dreamweaver. It is, however, a useful extension to the JavaScript language, so we elected to include it in this chapter.

You may notice that the JSExtensions folder has many more JSExtensions than the four listed here; most of them are used internally to the Dreamweaver application or have specialized uses. These four JSExtensions are the most commonly used by developers and will be the focus of this section.

Manipulating Files and Directories with DWfile

The DWfile JSExtension allows JavaScript extension developers to manipulate files and directories on the user's system directly. DWfile provides methods for reading, writing, copying, deleting, and displaying the attributes of files. In addition, you can create folders and retrieve the contents of a folder as a list.

The following table lists the file-related methods available in DWfile.

Method

Description

exists

Tests for the existence of a file at a given path.

read

Reads the entire contents of a file as a single text string.

write

Writes the contents of a file. Can either replace the existing content or append it to the end of the file.

copy

Copies a file from one location to another.

remove

Deletes a file by placing it in the operating system's trash bin.

getAttributes

Retrieves the attributes of a file.

getModificationDate

Retrieves the date a file was last modified.

getCreationDate

Retrieves the date a file was created.

The following table lists the folder-related methods available in DWfile.

Method

Description

createFolder

Creates a new empty folder at a specified path.

listFolder

Retrieves the contents of a folder. You can specify files only, folders only, or both.

The following table lists the utility methods available in DWfile.

Method

Description

getPlatform

Returns the platform that Dreamweaver is currently running on. This method has been deprecated in favor of navigator.platform, now a part of the core Dreamweaver API.

runCommandLine

Unsupported (and undocumented), available on Windows systems only. Executes a DOS command line.

Creating and Working with Files

No explicit method is available to create a file in Dreamweaver; you simply use the write() method to write data out to a given file path, and the file is created automatically. You can use the exists() method to first see if the file exists before it is written out. When writing data to a file, you have the choice of either writing the entire contents of the file, or appending data to the end of an existing file.

The following function prompts the user for a place to save a file and then writes out some sample data:

graphics/09icon01.gif

The data is written out using two forms of the write() method. In the first case, the last argument is omitted, which causes DWfile to replace the contents of the file with the string being written. In the second case, the last argument is "append" , which tells DWfile to add the data to the end of the file. No method is provided to randomly access the file stream.

Reading files with DWfile is straightforward: The read() method reads the entire contents of the file. It's impossible to read individual chunks of a file.

The following function prompts the user for a file to read and then reads the contents of the file:

 function readDataFile()  {     var pathToFile = dw.browseForFileURL("open","Select File");     if (pathToFile.length > 0)     {        var str = DWfile.read(pathToFile);        alert(str);     }  } 
Working with Folders

DWfile includes two methods for working with folders: createFolder() and listFolder() . The createFolder() function creates a new folder at the location given by a file:// URL that you supply as the only argument to the function. The listFolder() function lists the entire contents of a folder, optionally including in the list only files or only other folder names.

Example: Using DWfile to Process an Entire Folder

The following example demonstrates how to use DWfile to process all of the files in a particular folder.

graphics/09icon02.gif

An Undocumented Function

The DWfile JSExtension contains one undocumented (and unsupported) function that can be particularly useful, although it only works on Windows: runCommandLine() . This function takes one argument, a string that contains the DOS commands that you want to execute in the Windows command shell. Using this function, you can start up other applications with arguments. For example, in a Windows copy of Dreamweaver, the JavaScript code snippet

 DWfile.runCommandLine("regsvr32 SomeControlName.ocx") 

registers an OCX control with the Windows registry. This can be particularly useful if your set of extensions requires complex installation that you want to place inside a Dreamweaver Startup command.

Working with Design Notes via MMNotes

The Design Notes feature of Dreamweaver allows you to store notes about files that you work on and have them automatically maintained for a particular site. Other users can then read these notes when they synchronize their local machines with the site, providing a rudimentary form of collaboration. This feature is implemented in Dreamweaver by the MMNotes shared library, which exposes an API for use by extensions. Using the MMNotes JSExtension, your extension can manipulate the design note information for all of the files in a particular site, just as Dreamweaver does.

How Design Notes Are Stored

All design notes are stored in a folder named _notes , which is inside the folder for which a particular file has designed notes attached. For example, if you have a folder named Joe's Documents , and inside that folder is a file named index.html , then any design notes attached to that file will be stored in a folder named _notes inside the Joe's Documents folder.

If you look inside one of these folders, you'll find files that end with the suffix .mno , indicating that this is a design note file. The part of the filename that precedes the .mno is the name of the file to which the design note is attached.

If you open a design note file, you will see that it is essentially an XML file that contains one root tag ( < info > ). That root tag has one or more subtags ( <infoitem> ), each of which has two attributes: key and value . key and value hold the name and value of each design note.

For example, this design note file contains two design notes:

 <?xml version="1.0" encoding="iso-8859-1" ?>  <info>     <infoitem key="status" value="needs attention" />     <infoitem key="notes" value="This file looks good, but needs     work." />  </info> 

One of the nice features of Design Notes is that Dreamweaver's sitemanagement functionality automatically uploads and downloads these notes from the web site that they are defined for (but only, of course, if you are using Macromedia's built-in Site Windowthese files are not automatically picked up by other FTP tools). This means that your extensions can add design notes to files for a given site and have them automatically tracked and managed by the Dreamweaver application.

The Design Notes API

The Design Notes interface provides methods for creating, setting, retrieving, and removing design notes for a file, as well as determining which site a file belongs to, getting information about the keys stored in a document, and converting file paths from platform-specific paths into file:// URLs.

The methods for working with design note information are set forth in the following table.

Method

Description

open

Opens a design note file for a specified file. Optionally creates one if none exists.

set

Creates or updates a design note in the specified design note file.

get

Retrieves a design note for the specified design note file.

remove

Removes a design note from the specified design note file.

The next table details the methods for working with file paths.

Method

Description

filePathToLocalURL

Converts a platform-specific file path into a local file:// URL.

localURLToFilePath

Converts a file:// URL into a platform-specific file path.

getSiteRootForFile

Retrieves the local file:// URL for the site root folder for the site that contains the specified file.

The following table shows the methods for working with design note keys.

Method

Description

getKeys

Returns an array of all of the key names in the specified design note file.

getKeyCount

Returns the number of key/value pairs in the specified design note file.

The miscellaneous methods can be found in the next table.

Method

Description

getVersionName

Returns the version of the MMNotes JSExtension as a string indicating the name of the application that implemented it.

getVersionNum

Returns a string containing the version number of the MMNotes JSExtension in the form of "majorVer.minorVer". Currently, this is 2.0.

Example: Using Design Notes to Store Extension Preferences

In addition to storing design-related information about a particular file in a site (which is what Design Notes were intended for), they can store just about any information about any file. After all, Design Note files are simply XML files, and they store key/value pairs that can correspond to any set of information an extension wants to store.

You can use these characteristics of Design Notes to store preference information for your extensions. For example, the following are three functions that can create a preferences file and read and write preference settings to the file:

 var prefsFile = 0;  function createPrefsFile()  {     // document.URL is a file URL path to your extension     // force the prefs to be created if they aren't already there     prefsFile = MMNotes.open(document.URL, true);  }  // given an array of objects that contain preference data, write  // each one out to the preference file.  // Assume each object has two properties: prefName and prefData.  function writePreferences(prefObjArray)  {     var numPrefs = prefObjArray.length;     var c=0;     for (c=0; c<numPrefs;c++)     {        MMNotes.set(prefsFile,prefObjArray[c].prefName,  prefObjArray[c].prefData);     }  }  // read in all the preferences from the file and pass them back  // as an array of Objects, each with two properties: prefName  // and prefData.  function readPreferences()  {     var prefObjArray = new Array();     var keysList = MMNotes.getKeys();     var c=0;     var prefData;     for (c=0; c<keysList.length; c++)     {        prefData = MMNotes.get(prefsFile, keysList[c]);        prefObjArray[c] = new Object();        prefObjArray[c].prefName = keysList[c];        prefObjArray[c].prefData = prefData;     }     return prefObjArray;  } 

To use these routines, you would just store your preferences as an array of objects that had prefName and prefData properties, and call these routines to read them from and write them to the preferences file.

Connecting to the Internet via MMHttp

If you've ever found yourself thinking, "Gosh, my extension would be so much more useful if it could connect directly to the Internet!," then the MMHttp object is just what you've been looking for. With this JSExtension, your Dreamweaver extensions can communicate directly with any web server anywhere in the world.

NOTE

MMHttp does not currently support the secure HTTPS method of communication.


The MMHttp API is deceptively simple because Dreamweaver takes care of most of the work your extension needs to do when communicating with the Internet. MMHttp exposes the methods listed in the following table in its API.

Method

Description

getFile()

Retrieves a file from a given web address and saves it inside the Configuration/Temp folder. This method automatically creates the necessary folder structure that mirrors the server address of the file. For example, if you retrieve a file index.html from the address www.somedomain.com/ documents , then the index.html file is saved inside the documents folder, which will be inside the www.somedomain.com folder. You can also prompt the user for the location to save the file.

getText()

Retrieves the contents of the document at the specified web address.

GetFileCallback()

Performs the same function as the getFile() method, but allows you to specify a function that should be called when the HTTP request is completed.

GetTextCallback()

Performs the same function as the getText() method, but allows you to specify a function that should be called when the HTTP request is completed.

PostText()

Sends a given string of text to the server at the specified web address.

PostTextCallback()

Performs the same function as postText() , but allows you to specify a function to call when the HTTP request is complete.

ClearTemp()

Deletes the contents of the Configuration/Temp folder.

All of the MMHttp methods return an object as the function result, except for the clearTemp() method. This object has two properties: statusCode and data . The statusCode property contains the status code that is returned by the web server. The following table lists the codes that might be returned.

Code

Meaning

200

Okay. Everything was fine, and request processed normally.

400

Unintelligible request. The server could not understand the HTTP request.

404

File not found. The requested URL could not be found.

Code

Meaning

405

Server doesn't understand the requested method (GET or POST). Try using a different request method.

500

Unknown server error.

503

Server capacity reached.

Using these methods, your extensions can post and retrieve text to and from any web server right from within Dreamweaver. For example, your extensions could retrieve Help text or examples from your web site, allow users to post registration information to your site, or even download updated versions of themselves automatically.

NOTE

Posting information via the postXXX() methods assumes that you've encoded the text string using HTTP form encoding. Dreamweaver does not do this for you.


Example: Creating a New Document Based on a Web Page

This example shows how to create a new document based on an existing web page. The function uses the MMHttp object to download the text for the web page and then creates a new document in Dreamweaver and sets its content to the text returned from the MMHttp object.

graphics/09icon03.gif

Scripting Fireworks with FWLaunch

One of the most useful features of Dreamweaver is its ability to communicate and work directly with Fireworks, Macromedia's web graphics editing application. Like Dreamweaver, Fireworks has a JavaScript interpreter built in and has an extensibility API. To get Fireworks to perform a function, you send it some JavaScript code, which it executes and then returns a result. This communication is provided by the FWLaunch JSExtension and can be used by extension developers who want to use Fireworks to manipulate web graphics. In fact, Macromedia's own Create Web Photo Album extension uses the FWLaunch object to implement all of its features.

The following table lists the functions that make up the FWLaunch API.

Method

Description

ValidateFireworks

Ensures that a particular version of Fireworks is installed on the user's computer.

MayLaunchFireworks

Determines whether a Fireworks optimization session can be launched.

OptimizeInFireworks

Optimizes a given image in Fireworks and optionally resizes it.

BringDWToFront

Brings the Dreamweaver application to the front.

BringFWToFront

Brings the Fireworks application to the front.

ExecJSInFireworks

Executes the given JavaScript code in Fireworks. This can either be a string of actual JavaScript code or a file:// URL reference to a .jsf file on the user's computer.

GetJSResponse

Gets the result of the JavaScript call to Fireworks.

To execute JavaScript code in Fireworks, your extension follows these general steps:

  1. Determine that the proper version of Fireworks is installed. Each version of Fireworks has greater capabilities than the previous version, so you must make sure that the features your extension needs are present in the Fireworks version that the user has installed on his system.

  2. If the correct version of Fireworks is installed, launch it and give it some JavaScript code to execute, either in the form of a string or a file:// URL to a .jsf file.

  3. Periodically check to see if Fireworks is finished running the script. If it is, the script will either have executed correctly or generated an error.

  4. Report any errors to the user, or take action based upon the successful execution of the JavaScript code.

The validateFireworks() function is used to make sure that the proper version of Fireworks is installed. It accepts a floating-point number that corresponds to the version of Fireworks you want to test against. For example, to make sure that the user has at least Fireworks 3 installed, you would write this:

 var isFW3 = FWLaunch.validateFireworks(3.0); 
Example: Executing JavaScript in Fireworks

This example shows how to pass a string of JavaScript code to Fireworks for execution and check for a response. Because the getJsResponse() function returns immediately and doesn't wait for Fireworks to finish, we use the setTimeout() method on the window object to repeatedly check the Fireworks response until we either get a number (indicating an error code) or a string (indicating success).

 var gFWJSResult = null;  function FireworksAlert() {     var isFireworks3 = FWLaunch.validateFireworks(3.0);     if (!isFireworks3)        return;        // Tell Fireworks to execute the alert() method.     gFWJSResult = FWLaunch.execJsInFireworks        ("alert('Dreamweaver told me to alert!')");     // A null result means FW wasn't launched,     // a number result means an error code     if (gFWJSResult == null         typeof(gFWJSResult) == "number")  {        alert("an error occurred");        gFWJSResult = null;     } else {        // bring Fireworks to the front        FWLaunch.bringFWToFront();        // Check to see if Fireworks is done yet        checkIfFinished();     }  }  function checkIfFinished () {     // Call checkJsResponse() every 1/2 second to see     // if Fireworks is done yet     window.setTimeout("checkFWResponse();", 500);  }  function checkFWResponse() {     var response = null;     // We're still going; ask Fireworks how it's doing     if (gFWJSResult!= null)     {        response = FWLaunch.getJsResponse(gFWJSResult);        if (response == null) {           // still waiting for a response, reset timer           checkIfFinished();        } else if (typeof(response) == "number") {           // if the response was a number, an error           // occurred           // the user cancelled in Fireworks           window.close();           alert("an error occurred:" + response);        } else {           // Valid response           window.close();           // bring Dreamweaver to the front           FWLaunch.bringDWToFront();           alert("Got a valid response!");        }     }  } 


Joseph Lowery's Beyond Dreamweaver
Joseph Lowerys Beyond Dreamweaver
ISBN: B000H2MWYS
EAN: N/A
Year: 2001
Pages: 87
Authors: Joseph Lowery

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net