SVG 1.2 - 27 October 2004

Previous | Top | Next

Appendix B: API enhancements

B.1 SVGTimer Interface

The SVGTimer interface provides an API for scheduling execution.

interface SVGTimer : events::EventTarget // emits "timer" event
{
         // initial delay before the first execution is fired
         // 0 means fire as soon as possible
         attribute long delay;
  
         // period between each execution, if -1, no additional
         // execution will be fire
         attribute long interval;
 
         // the current state of the timer
         readonly attribute boolean running;

         // start the timer
         void start()

         // stop the timer
         void stop()

};

An SVGTimer object is always either in the running (attribute running is true) or waiting (attribute running is false) state.

delay

This property specifies the time delay in milliseconds. After delay period has passed while the object is in the "running" state, the object will fire a "timer" event. In the "running" state this attribute is dynamically updated to reflect the remaining delay. It also can be dynamically assigned. If this attribute is 0, it means that event will fire as soon as possible. Assigning negative value is equivalent to calling the stop() method.

interval

This property contains the time interval in milliseconds. If the timer is in the "running" state, then it will fire regularly on the interval.

running

Timer state. Value is true if the timer is running (and will fire in delay milliseconds), false if the timer is waiting. Note that the interval and delay properties can be non-negative if the timer is stopped (but if delay is negative, the timer is stopped).

start()

Change the timer state into "running". If the timer is already in the running state, it has no effect.

stop()

Change the timer state into "waiting". If the timer is already in the waiting state, it has no effect.

Since SVGTimer is an event target, event listeners can be registered on it using regular addEventListener call using "timer" as the event type. Event listeners can access their corresponding SVGTimer object through event object's target property.

Timer events are never fired while some other DOM event is being processed (and are delayed instead). Also, timer events are fired only when the timer is in the "running" state.

SVGTimer instances are created using the SVGGlobal interface.

B.2 Network interfaces

There are two interfaces for sending and retrieving data over the network. The URLRequest interface is a high level API for communications that can be defined by a URI. The Socket interface is a low level API for socket-level communications.

B.2.1 URLRequest interface

The URLRequest interface enables a client to retrieve data that is addressable by a URI.

interface URLRequest : events::EventTarget // emits "URLResponse" event 
with target set to the request
{
  const unsigned short INITIAL   = 0; // after it is created 
                                      // or after init is called
  const unsigned short PENDING   = 1; // after submit is called
  const unsigned short COMPLETED = 2; // after URLResponse event comes
  const unsigned short ERROR     = 3; // on lower-level protocol error 
                                      // (e.g. connection refused)

  // initialize request, not allowed in PENDING state, 
  // sets the state to INITIAL
  void init(  in DOMString method, in DOMString uri ); 

  readonly attribute unsigned short requestState;

  // body of the request, can only 
  // be set in INITIAL state 
  // Setting causes file content to be removed.
  attribute DOMString requestText; 

  void addRequestHeader( in DOMString header, in DOMString value ); 
                                   // only in INITIAL state

  // body of the response, only in COMPLETED state
  readonly attribute DOMString responseText; 

  // 3-digit status code, only in COMPLETED state
  readonly attribute unsigned long status; 

  // status text, only in COMPLETED state
  readonly attribute DOMString statusText; 

  // response header count, only in COMPLETED state
  readonly attribute unsigned long responseHeaderCount; 

  // response header iterator, only in COMPLETED state
  NameValuePair getResponseHeader( in unsigned long index ) 
     raises (DOMException); 

  // abort the request, only in PENDING state, 
  // sets the state to ERROR
  void abort() raises (DOMException); 

  // submit the request, sets the state to PENDING
  void submit() raises (DOMException); 

  // add the content from the given file object
  // calling this method sets requestText to become null
  // Only valid in INITIAL state
  void addContentFromFile( in SVGFile file ) raises (DOMException);

  // clone this request
  URLRequest cloneRequest();

};

An URLRequest object can be in one of 5 states: INITIAL, PENDING, COMPLETED, ERROR or ABORTED. When an URLRequest object is created its state is set to INITIAL.

The following methods/attributes are present on URLRequest:

requestState

The URLRequest object state.

init()

Initialize this URLRequest object. The "uri" parameter is the URI of the resource to access. The "method" parameter is an access method for the resource. For the HTTP protocol the method names are "GET", "POST", "HEAD" and "PUT" (case insensitive). If this method is called when the object state is PENDING, then an SVG Exception is raised.

requestText

This property is the body of the request. Some URLs and/or access methods don't allow a request body, in which case this property will be ignored. The property is only valid in the INITIAL state.

addRequestHeader()

Adds a header to the request. Some URLs and/or access methods don't allow certain headers; Any header that isn't allowed is ignored. This method is only valid in the INITIAL state.

addContentFromFile()

Add file content to the request body. This method is only valid in the INITIAL state.

submit()

Submit this request for processing. This method is only valid in the INITIAL state, and changes the state to PENDING. When the request is processed the status becomes one of:

Once the status is changed from PENDING to either COMPLETED or ERROR, the URLResponse event is fired. The request status never changes while a DOM event is being processed. Only errors that are outside of the domain of URL protocol should cause state to be changed to ERROR; for instance HTTP status 500 should be passed through as COMPLETED (with status field set to 500). Redirection on the protocol level should happen automatically.

responseText

The body of the response to the request. If the response cannot be represented as text, reading this property will raise an DOMException. This property only can be read in the COMPLETED state. Reading the property with any other state raises an DOMException.

status

The protocol-level status code. For HTTP, this is the HTTP-defined three-digit status. This property only can be read in the COMPLETED or ERROR state. Reading the property with any other state raises an DOMException.

statusText

The protocol-level status text. This property only can be read in the COMPLETED state. Reading the property with any other state raises an DOMException.

responseHeaderCount

The number of headers in the reply. This property only can be read in the COMPLETED state. Reading the property with any other state raises an DOMException.

getResponseHeader()

Access the reply headers by index. This method can only be used in the COMPLETED state. Using the method with any other state raises an DOMException. A DOMException is raised if the index is out of bounds.

abort()

Abandon the request and change the state to ABORTED. The URLResponse event is not fired (unless the request is reinitialized and resubmitted). Note that the actual network request might have been already processed by the server; there is no way to reliably cancel network requests once they have been submitted. This method can only be used in the PENDING state. Using the method with any other state raises an DOMException.

cloneRequest()

Create an exact duplicate of this URLRequest object, with the exception of event listeners, which are not cloned. This method can only be used in the INITIAL state. Using the method with any other state raises an DOMException.

The headers used by a URLRequest are defined by the following API:

interface URLHeader
{
   readonly attribute DOMString name;
   readonly attribute DOMString value;
};
name
The header's name
value
The header's value.

A URLRequest object is created using the "createURLRequest" method on the SVGGlobal interface.

The following code provides an example of how the URLRequest API can be used to emulate the common getURL() and postURL methods.

function callback(evt) {
   if (evt.target.requestState == URLRequest.COMPLETED 
      && evt.target.status == 200) {
      alert("OK: " + evt.target.responseText);
   } else {
      alert("ERROR!");
   }
}

function getURL(url, callback) {
    var req = createURLRequest();
    req.addEventListener("URLResponse", callback, false);
    req.init("GET", url);
    req.submit();
}

function postURL(url, body, callback) {
    var req = createURLRequest();
    req.addEventListener("URLResponse", callback, false);
    req.init("POST", url);
    req.requestText = body;
    req.submit();
}

function putURL(url, file, callback) {
    var req = createURLRequest();
    req.addEventListener("URLResponse", callback, false);
    req.init("PUT", url);
    req.addContentFromFile(file);
    req.submit();
}

B.2.2 Security Concerns

Note that these interfaces expose possible security concerns. The security model that these interfaces work under is defined by the user agent. However, there are a well-known set of security guidelines used by the browser implementations in this area. For example, most do not allow access to hosts other than the host from which the document was retrieved.

In general the User Agent should prevent access to URLs that refer to host names different from the host name of the actual URL of the corresponding SVGGlobal::document. This applies not only to original URL, but also to any redirected URLs. The access to protocols, different from the protocols of the SVGGlobal::document URL also should be restricted (e.g., a document loaded through HTTP should not have access to HTTPS resources).

B.2.3 Socket Connections

The Connection interface provides an API for socket-level communication.

interface ConnectionEvent : events::Event // "ConnectionData" event
{
   readonly attribute DOMString data;
};

interface Connection : events::EventTarget
{
   readonly attribute boolean connected;

   void setEncoding( DOMString value ); // might be called before connect

   void connect( in DOMString url ) raises(DOMException)
   void send( in DOMString data );
   void close();
};

A Connection object is created using the SVGGlobal interface.

B.3 Monitoring download progress

Many resources, such as raster images, movies and complex SVG content can take a substantial amount of time to download. In some use cases the author would prefer to delay the display of content or the beginning of an animation until the entire contents of a file have been downloaded. In other cases, the author may wish to give the viewer some feedback that a download is in progress (e.g. a loading progress screen).

B.3.1 The Progress event

The ProgressEvent occurs when the user agent makes progress loading a resource (local or external) referenced by an xlink:href attribute.

The user agent must dispatch a ProgressEvent at the beginning of a load operation (i.e., just before starting to access the resource). This event is of type 'preload'. The value of the 'preload' event's progress property is 0.

The user agent must dispatch a ProgressEvent at the end of a load operation (i.e. after load is complete and the user agent is ready to render the corresponding resource). This event is of type 'postload' event. The value of the 'postload' event's progress property is 1.

The user agent may dispatch a loadProgress event between the 'preload' event and the 'postload' events. Such events are of type 'loadprogress'.

All 'loadprogress' events must follow to the following constraints:

In the case where the size of the downloading resource is known, such as from HTTP headers, then the progress property reflects the proportion of the current download that has been completed.

In the case where the size of the downloading resource is not known, then the progress property will only ever have the value 0 or 1.

The ProgressEvent has three corresponding event attributes on elements: onpreload, onpostload and onloadprogress.

Below is an example of the ProgressEvent:

<svg xmlns="http://www.w3.org/2000/svg" version="1.2"
     xmlns:xlink="http://www.w3.org/1999/xlink">
   
   <script type="text/ecmascript"><![CDATA[
   function showImage(imageHref) {
       var image = document.getElementById('myImage');
       image.setAttributeNS(xlinkNS, "href", imageHref);
   }           

   function imageLoadStart(evt) {
       var progressBar = document.getElementById('progressBar');
       progressBar.setAttributeNS(svgNS, "width", 0);
       var loadAnimation = document.getElementById('loadAnimation');
       loadAnimation.beginElement();
   }
               
   function imageLoadProgress(evt) {  
       var progressBar = document.getElementById('progressBar');
       progressBar.setAttributeNS(svgNS, "width", 100*evt.progress);
   }
               
   function imageLoadComplete(evt) {
       var progressBar = document.getElementById('progressBar');  
       progressBar.setAttributeNS(svgNS, "width", 100);
        var loadAnimation = document.getElementById('loadAnimation');
       loadAnimation.endElement();
               
   }
   ]]></script>

   <image id="myImage" xlink:href="imageA.png" width="300" height="400"
          onpreload="imageLoadStart(evt)"
          onloadprogress="imageLoadProgress(evt)"
          onpostload="imageLoadComplete(evt)"/>

   <rect onclick="showImage('imageB.png')" width="120" 
         height="30" y="400"/>

   <animate id="loadAnimation" ... />

   <rect id="progressBar" ... />
</svg>

IDL Definition
interface ProgressEvent : events::Event {
     readonly attribute DOMString       typeArg;
     readonly attribute unsigned long   loaded;
     readonly attribute unsigned long   total;
     readonly attribute float   progress;
     void               initProgressEvent(in DOMString typeArg,
                                          in unsigned long loaded,
                                          in unsigned long total);
};

Attributes
readonly DOMString typeArg
Specifies the event type. One of 'preload', 'loadprogress' or 'postload'.
readonly unsigned long total
Specifies the expected total number of bytes expected in a load operation. This value is ignored for a 'preload' and a 'postload' event. For a 'loadprogress' event, it should specify the total number of bytes expected or be -1 which means that it cannot be computed (for example when the size of the downloaded resource is unknown).
readonly unsigned long loaded
Specifies the number of bytes downloaded since the beginning of the download. This value is ignored for a 'preload' or 'postload' event. For a 'loadprogress' event, this value must be positive.
Methods
initProgressEvent
The initProgressEvent method is used to initialize the value of a ProgressEvent created through the DocumentEvent interface. This method may only be called before the ProgressEvent has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary. If called multiple times, the final invocation takes precedence.
Parameters
in DOMString typeArg Specifies the event type.
in unsigned long loaded Specifies the number of bytes that have been retrieved. This is a positive value.
in unsigned long total Specifies the expected total number of bytes in this load operation.
No Return Value
No Exceptions

B.4 File Upload

It is desirable for Web applications to have the ability to manipulate as wide as possible a range of user input, including files that a user may wish to upload to a remote server or manipulate inside a rich application. This interface provides application writers with the means to trigger a file selection prompt with which the user can select one or more files. Unlike the file upload forms control available to HTML, this API can be used for more than simply inserting a file into the content of a form being submitted but also allows client-side manipulation of the content, for instance to display an image or parse an XML document.

B.4.1 Interface FileDialog

The FileDialog interface is created with a call to SVGWGlobal::createFileDialog. Its purpose is to control the apparition of a file dialog, and to register the event listeners that will handle the selection of files. The FileDialog object inherits from EventTarget and it is this possible to attach event listeners to it using the addEventListener method.

 interface FileDialog : events::EventTarget {
    void open ( );
 }

The open method takes no parameter and returns nothing. On being called, it prompts the user with a means to select one or more files. It does not need to be a GUI control, but rather whichever input method the user has at his disposal to select files present on the device. On devices that have no file system, it may still open a dialog for data acquisition, eg an interface to a built-in camera. The user agent should make sure that the user cannot forget about the file upload prompt's existence, for instance in the case of a GUI file selection widget by maintaining it on top of the SVG document.

This method operates in an asynchronous manner so that the files that are selected will be communicated to handlers registered on the FileDialog object to listen to the FilesSelected event. An example follows in which when file selection is performed, the handleEvent method of the listener object will be called with a FilesSelectionEvent object.

 var fd = createFileDialog();
 fd.addEventListener("FilesSelected", listener, false);
 fd.open();

B.4.2 Interface FilesSelected

This is an event dispatched for FilesSelected events. It adds a single field fileList which points to the SVGFileList containing the list of selected files. If the file dialog is cancelled, or if no files are selected, the FileList will be defined but its length will be zero.

 interface FilesSelected : events::Event {
     readonly attribute FileList fileList;
 }

B.4.3 Interface FileList

This interface exposes the list of files that has been selected through the file dialog. When none have been selected, its length is zero. It is possible that some platforms will only allow for one file to be selected at a time, however when possible a user agent should provide the option to select multiple files in one pass.

 interface FileList {
    readonly attribute unsigned long numberOfItems;
    File getItem    ( in unsigned long index ) raises( DOMException );
    File removeItem ( in unsigned long index ) raises( DOMException );
 }

The length of the collection can be obtained through the numberOfItems field. Items can be retrieved using getItem, and removed using removeItem. The latter can be used to filter out files that do not match certain criteria (mime type, file extension, etc).

B.4.4 Interface File

This interface describes a single file in a FileList, and allows you to know its name, mime type, and to access its content in various convenient ways.

Please note that in order to be memory-efficient, implementations are not required to load the content of files into memory as soon as they have been selected, but only when their content is required by the program. Even then using the network interfaces an implementation may stream the content of a file to a socket and never need to hold more than a few of its bytes in memory. Note however that in case the implementation only provides the content of the file on demand, since the state of the file system may have changed since the pointer was obtained the content may no longer be available, or might have been modified.

 interface File {
    readonly attribute DOMString fileName;
    readonly attribute DOMString mimeType;
    readonly attribute DOMString fileSize;
    DOMString getDataAsString    (  ) raises(SVGException);
    DOMString getDataAsBase64    (  ) raises(SVGException);
    DOMString getDataAsHexBinary (  ) raises(SVGException);
 }

The fileName field provides the name of the file, exclusive of its path.

The mimeType field provides the MIME type of the file, if it is known to the user agent. Where available, it must be provided so as to allow users to filter the content of FileLists based on this criterion as is possible in XForms.

The fileSize field provides the size of the file in bytes. User agents should provide it when it is available, but users should keep in mind that it may not always be possible for a user agent to know it before the data has been read.

The getDataAsString, getDataAsBase64, and getDataAsHexBinary methods return the content of the file. Since the file may not be a text file, it is possible that getDataAsString might produce unexpected effects in some languages. Note however that languages such as Ecmascript and Java use a simple array of 16-bit bytes to store their string types, and can thus accomodate any binary data. getDataAsBase64 and getDataAsHexBinary are respectively Base64 and hex-binary encoded versions of the content returned by getDataAsString.

If the implementation detects a problem when trying to gain access to the file's content (file is not readable by user, has been removed since the pointer to it was obtained, etc) it must throw an exception. An empty file results in an empty string.

B.4.5 URLRequest additions

In order to avoid costly copying of file content, it is possible to feed files directly into network requests.

 interface URLRequest {
    ...
   void addContentFromFile ( in File file ); // adds to the body, body illegal
+(discarded) for some methods
    ...
 }

The addContentFromFile method takes a file and adds it to the body of a request. Note that for some request types (eg GET, HEAD...) it is illegal to have a payload and thus the content will be discarded. If the file cannot be read, an exception will be thrown.

B.4.6 Connection additions

In order to avoid costly copying of file content, it is possible to stream files directly to a socket.

interface Connection {
   ...
   void sendFile ( in File file )  raises(SVGException);
   ...
};    

The sendFile method takes a file and streams it to the socket. If the file cannot be read, an exception will be thrown.

B.4.7 Security considerations

The file upload feature has security implications. However it does not add any security-related issues above those in the common HTML file upload form widget. Rather, it removes the potential risk of having script access to or setting the default value of the form component which has been a cause for concern in a number of HTML user agents.

B.5 Persistent Client-side Data storage

Many applications benefit from the ability to store data between sessions on the client machine. SVG 1.2 adds a simple set of methods to store data specific to the SVG Document in the client. These methods are setPersistentValue and getPersistenValue on the SVGGlobal interface.

The allowed names for persistent values follow the same rules as XML identifiers. The allowed values can be any string, including an XML serialization (which can be consumed by the parseXML() method and generated by the printNode() method).

The user agent keeps a table of persistent values separate for each domain. There is no set limit to how much data can be stored per domain, nor how long. The minimum limits are 10 names, 500 characters and 60 days expiration. If the storage fills beyond the user agent limits, then values may be silently discarded by the user agent.

B.6 Global Interface

The majority of scripted SVG documents in existence make use of the browser specific Window interface, which includes methods such as parseXML and alert. SVG 1.2 specifies an SVGGlobal interface, taking into account the de-facto standard that already exists, as well as adding the new features present in SVG 1.2. SVGGlobal inherits from the Global interface, which is currently defined to be empty. The Global interface is designed to be the parent interface for language specific window objects. In scripting implementations, the methods and attributes defined by the Global object are normally part of the global execution context.

Interface SVGGlobal provides a global object for scripts embedded in a SVG document.


IDL Definition
interface Global {}


interface SVGGlobal : Global { 

  readonly  attribute dom::Document document;
  readonly  attribute Global        parent;
  readonly  attribute DOMString     location;

  // Move to a new document
  void gotoLocation(in DOMString newURL);

  Node  parseXML(in DOMString source, in Document document);
  DOMString         printNode(in Node node);

  // Timer method.
  SVGTimer createTimer(in long delay, in long interval, in boolean start);

  // Network methods
  URLRequest createURLRequest();
  Connection createConnection();

  // Mouse capture
  void startMouseCapture(in dom::EventTarget, in boolean sendAll, 
                         in boolean autorelease);
  void stopMouseCapture();

  // File dialog
  FileDialog createFileDialog();

  // Filtering of events
  SVGEventFilter createEventFilter();

  // Persistent client-side data storage
  void setPersistentValue(in DOMString name, in DOMString value);
  DOMString getPersistentValue(in DOMString name);

};

Attributes
readonly dom::Document document
The Document that this SVGGlobal operates on.
readonly SVGGlobal parent
The SVGGlobal context of this document's parent.
readonly DOMString location
The URI of the current document.
Methods
gotoLocation
Request that the user agent navigates to the given URL. The user agent should handle the resource in the same way as a user navigation and it is not limited to SVG resources.
Parameters
in DOMString newURL The URL of the new location
No Return Value
No Exceptions
parseXML
Convert the given source string into DocumentFragment that belongs to the given XML document. This document fragment does not get inserted in the tree; this can be done with DOM methods like appendChild or insertBefore. If the second parameter is null, a new XML document is created and the given string is parsed as a standalone XML document.
Parameters
in DOMString source A string containing a XML document fragment.
in Document document The Document context for parsing the XML fragment.
Return Value
Node A Node representing a Document or Document Fragment converted from the original DOMString.
No Exceptions
printNode
Converts a Node into a DOMString. The string is an XML representation of the Node.
Parameters
in Node node The Node to be converted.
Return Value
DOMString A serialized version of the original Node.
No Exceptions
createTimer
Creates an SVGTimer with the given delay and interval.
Parameters
in long delay Corresponds to the delay attribute on SVGTimer.
in long interval Corresponds to the interval attribute on SVGTimer.
in boolean start If true, the returned SVGTimer will be started, otherwise it will be in the waiting state.
Return Value
SVGTimer An SVGTimer object.
No Exceptions
createURLRequest
Creates an URLRequest object with default parameters.
No Parameters
Return Value
URLRequest An URLRequest object.
No Exceptions
createConnection
Creates a Connection object with default parameters.
No Parameters
Return Value
Connection A Connection object.
No Exceptions
startMouseCapture
Limit the dispatch of mouse events to a subtree whose root is defined by the target parameter. Note that this does not affect the platform behaviour of mouse capture, which typically sends all drag-like mousemove events the the widget that received the mousedown. This method only affects events within the SVG canvas.
Parameters
in dom::EventTarget target The subtree that will receive all the captured events.
in boolean sendAll If true, send all mouse events, even those that do not intersect with the specified subtree. For example, scrollbars typically get sent events after they are activated even when the mouse moves outside the scrollbar.
in boolean autorelease Release the mouse capture once a mouseup event is fired.
No Return Value
No Exceptions
stopMouseCapture
Cancels any mouse capture
No Parameters
No Return Value
No Exceptions
createFileDialog
Creates a FileDialog object.
No Parameters
Return Value
FileDialog A FileDialog object.
No Exceptions
createEventFilter
Creates an EventFilter object.
No Parameters
Return Value
EventFilter An EventFilter object.
No Exceptions
startMouseCapture
Limit the dispatch of mouse events to a subtree whose root is defined by the target parameter. Note that this does not affect the platform behaviour of mouse capture, which typically sends all drag-like mousemove events the the widget that received the mousedown. This method only affects events within the SVG canvas.
Parameters
in dom::EventTarget target The subtree that will receive all the captured events.
in boolean sendall If true, send all mouse events, even those that do not intersect with the specified subtree.
in boolean autorelease Release the mouse capture once a mouseup event is fired.
No Return Value
No Exceptions
setPersistentValue
Store the given (name, value) pair in the user agent's persistent data store, associated with the domain from which the current document was loaded.
Parameters
in DOMString name The name of the property to be stored.
in DOMString value The value of the property to be stored.
No Return Value
No Exceptions
getPersistentValue
Retrieve the value for the given name in the user agent's persistent data store, associated with the domain from which the current document was loaded.
Parameters
in DOMString name The name of the property to be retrieved.
Return Value
DOMString The value for the given name.
No Exceptions

NOTE:

SVG 1.2 no longer supports the alert, confirm and prompt methods, which were mainly used for debugging purposes, due to their synchronous behaviour and accessibility problems. The SVG Working Group understands that many implementations may still support the methods, but content developers should know that these methods will produce a non-conformant document.

The SVGDocument interface provides access to the SVGGlobal object.

interface SVGDocument { 
  ...
  readonly  attribute SVGGlobal     global
  ...
};