ShapeUp JavaScript Object Model and Reference

 

 

 


Version 0.75 DRAFT

2008-06-30


Contents

 

Contents. 2

Introduction. 3

Class overview.. 3

Class Workspace. 4

Workspace properties. 4

Workspace methods. 4

Class Layer 7

Layer properties. 7

Layer methods. 7

Class Shape. 10

Shape properties. 10

Shape methods. 10

Class Coord. 12

Coord properties. 12

Coord methods. 12

Class Color 13

Color properties. 13

Color methods. 13

Class File. 14

File properties. 14

File methods. 14

Class Plugin. 16

Plugin properties. 16

Plugin methods. 16

Global methods overview.. 17

Global methods. 17

JavaScript Samples. 21

Tracing number of layers. 21

Toggling visibility of all layers. 21

Loading a shape file and adding empty layers. 21

Listing countries starting with an ‘A’ 21

Dumping object properties. 22

Running an external program.. 22

Changing a layers color 22

Getting shapes in the order they were selected. 23

Reading data from a file. 23

Adding other JavaScript files to the current context 24

Handy ShapeUp Console Commands. 25

Run. 25

Debug. 25

Target 25

Alias. 25

 


Introduction

The ShapeUp main application has from version 0.6.00 been extended with JavaScripting functionality. In order to access these new features the user will need the js32.dll containing the SpiderMonkey JavaScript engine from mozilla.org. This dll should be located in a directory in the search path, or at the same location as the ShapeUp.exe file. If this dll is missing, JavaScripting will be unavailable to the user, but all other functions will work just as usual. If the dll is present however, and the user tries to run a script from the console, the extension of the script file name determines whether to execute it as a JavaScript or not. Files with the extension ‘.js’ will be sent to the JavaScript environment, while all other files will be treated as normal ShapeUp script files.

 

If a JavaScript is very general to its nature, it can be published as a ShapeUp Tool. If  moved to the Tools subdirectory, the script will be available directly from the ToolsŕJavaScript menu, and thus, does not require to be started from the console. However, script output and error messages will still end up in the console.

 

The work on the object model exposed to the JavaScripting environment is in progress, and is likely to change under the first few releases of ShapeUp after v0.6.00.

 

NOTICE: Running a script with errors might leave ShapeUp data in an unwanted state. I.e. some data updated while other is not. It’s a good practice to test scripts on test data before using on the target data.

 

Class overview

The following classes are described in this document.

 

 

For each class, its properties and methods are described.

 

 

 

 

 

 

 

 

 

 

 



Class Workspace

The Workspace class is reflecting the workspace or document in the ShapeUp application. A global variable named ‘workspace’ is exposed to the scripting environment.

 

Workspace properties

Property name

Type

Description

name

Readonly String

Title of the workspace

layerCount

Readonly integer

Number of layers currently loaded.

bkgndColor

Color

Workspace background color.

 

Workspace methods

Function name

Return value

Arguments

Description

getLayer(i)

Layer

I, integer

Gets the layer at index i.

browseLayer([s])

Layer

s, String, optional

Opens a dialog containing current layers and lets the user select one. This layer is returned. If the user cancels, null is returned. If s is supplied, this will be the title of the dialog.

refresh()

void

void

Refreshes all graphics, including legend and attribute data views.

println([x])

void

x, optional string to print

Prints a value and adds a newline. ShapeUp Console debugging must be turned on for scripts.

addNewLayer(type [, name, [attrSrc]])

Layer

type, String

name, optional String

attrSrc, optional Layer

type is a String containing one of

‘Point’

‘Polyline’

‘Polygon’

name is an optional String containing the initial name of the added Layer.

If attrSrc is specified, the attribute set of that layer will be copied to the new layer.

loadShapeFile(file)

Layer

file, String

Loads a shape file into the workspace as a new Layer. If the function succeeds the Layer is returned, otherwise it returns null.

removeLayer(ly)

Boolean

ly, Layer

Removes the specified Layer from this workspace. Returns true if successful, false otherwise.

Ly, and all other references to this object, will be invalidated and destroyed.

moveLayer(ly, i)

Boolean

ly, Layer

i, Integer

Change z-order of layer ly. It will be moved to position i, where position 0 is topmost.

setProgress(i)

void

i, Integer

Creates a progress bar in the status bar. This can be used for lengthy operations. 0 <= i <= 100.

centerMap(c)

centerMap(x, y)

void

c, Coord

x, y Number

Centers the current map around the coordinate c or the coordiante (x, y).

zoom(d)

void

d, double

Zooms in or out depending on the argument d. A value of 1.0 does nothing. A value between 0 and 1.0 will zoom in, and a value greater than 1.0 will zoom out. E.g, d = 2 will double the scale, and d = 0.5 will half it. d <= 0.0 is not allowed. Zooming is always relative the center of the screen. To zoom around another point, use one of the centerMap() functions before and /or after the zooming.

saveMapImage(s [, c])

Boolean

s, String

c, Color

Saves the current map as an image with the file name s. Thepending on the file extension, the image can be saved in different formats. E.g. s=’C:\\img.png’ will save the map as a png file. If the Color argument,c, is supplied, ShapeUp tries to use that color as transparency. Note that not all image formats supports transparency. The code handling the transparency parameter should be considered experimental.

The function returns true on success, or false if an error occurred.

 


Class Layer

The Layer class corresponds to a single layer within the workspace object.

 

Layer properties

Property name

Type

Description

name

String

Name of this layer.

visible

Boolean

True if the layer is shown, false otherwise.

readOnly

Boolean

True if read-only, false if the layer was enabled for editing. Once this is set to false, it cannot be set to true again.

comment

String

Comment, as found in the layer property dialog. When adding newline to a comment, a \r\n-pair should be used.

dataSource

Readonly String

Information on from where this layer was loaded. Possible values are:

‘ST_Unknown’

‘ST_ShapeFile’

‘ST_CustomLoader’

‘ST_ParentTheme’

‘ST_Native’

If  a layer has been enabled for editing, ‘ST_Native’ is always returned.

shapeCount

Integer, readonly

Number of shapes in this layer

selectionCount

Integer, readonly

Number of shapes currently selected in this layer.

selected

Boolean

Selection status of this layer.

color

Color

Layer main color.

lineWidth

Integer

Line width for the pen used to draw polylines and outline polygons.

 

Layer methods

Function name

Return value

Arguments

Description

getShape(i)

Shape

i, integer

Gets the shape at index i.

getSelectedShape(i)

Shape

i, integer.

Gets a selected shape. 0 <= i < Layer.selectionCount. The index, i, has nothing to do with the selection order.

getAttribute(i)

String

i, integer

Gets the attribute name at index i.

addAttribute(s)

Integer

s, String

Adds a new attribute field, named s, and returns the index of it and –1 if an error occurred.

createShape(c)

Shape

c, Coord

Creates a new shape for this point layer and appends it last in the shape array. Returns the Shape on success. Otherwise null.

createShape(a)

Shape

a, Array of Coords

Creates a new shape for this polyline or polygon layer and appends it last in the shape array. Returns the Shape on success. Otherwise null.

createShape(s)

Shape

s, Shape

Creates a copy of the shape s, which may be from this, or from another layer. The shape type of s and this layer must match. Returns the Shape on success. Otherwise null.

moveShape(s, i)

Boolean

s, Shape

i, integer

Changes a shapes z-order within its theme. The shape s is moved to the new record index i, where 0 is bottom z-order and Layer.shapeCount is top z-order.

recalcBoundingBox()

void

void

Recalculates the layers bounding rectangle. It is important that this function gets called after its shapes coordinates have been changed.

findClosestShapes(c)

Array of type Shape

c, Coord

Get an array of the Shapes closest to c from this layer.

If the returned array contains more than one Shape, they all have the same shortest distance to c.

To do: It’s a bit slow at the moment since it doesn’t use the internal spatial index.

getIntersectingShapes(s)

Array of type Shape

s, Shape

Returns an Array of Shapes, all intersecting the target shape s. If no shapes are found, null is returned.

browseAttribute([s])

Integer

s, string

Allows the user to select an attribute column. The string, s, is optional and will, if supplied, be the title of the selection dialog. The zero-based index of the attribute is returned, or -1 if the user cancels the dialog.

 


Class Shape

The Shape class corresponds to a single shape.

 

Shape properties

Property name

Type

Description

type

String, readonly

Type of shape.

attributeCount

Integer, readonly

Number of attributes.

partCount

Integer, readonly

Number of parts this shape has.

selected

Boolean

Selection status of this shape.

selectionIndex

Integer, readonly

This value indicates the order of the selection made by either a user or a script.

The first selected Shape has selectionIndex 0.

Trying to get this value on a non-selected Shape gives an error. Always check the ‘selected’ status before using this property.

color

Color, readonly

The color of this shape, which can be different from the Layer.color.

index

Integer, readonly

This shapes hidden index. Make no other assumptions about this value than it being unique for each shape in its layer.

 

Shape methods

Function name

Return value

Arguments

Description

getAttribute(x)

String

x, integer or String

Gets the attribute at index x or with column name = string x.

setAttribute(i, s)

Boolean

i, integer

s, String

Sets the attribute at index, i, to the value of string, s. Returns true on success, otherwise false.

getCoordCount(p)

Integer

p, integer

Gets the number of coordinates for part p.

getCoord(p, c)

Coord

p, integer

c, integer

Get coordinate at index c for shape part p.

recalcBoundingBox()

void

void

Recalculates the shapes bonding rectangle. It is important that this function gets called after its coordinates have been changed.

translate(x, y)

void

x, y, number

Translates the shape using deltax = x and deltay = y. The shape must be contained within an editable layer. After shapes have been transformed, a call to their layers recalcBoundingBox() method is required.

rotate(c, f)

void

c, Coord

f, number

Rotates the shape f degrees clockwise, around the point at coordinate c. The shape must be contained within an editable layer. After shapes have been transformed, a call to their layers recalcBoundingBox() method is required.

intersects(s)

Boolean

s, Shape

Returns true if this intersects s, otherwise false.

addPart(a)

Boolean

a, Array of Coords

Adds a new part to an existing shape of type Polyline or Polygon.

The function returns true on success, or false otherwise.

 


Class Coord

The Coord class corresponds to a single (x, y)-coordinate. The Coord constructor takes 2 arguments, x and y, representing the initial coordinate values.

 

Coord properties

Property name

Type

Description

x

Number

left-to-right coordinate

y

Number

down-to-up coordinate

 

 

Coord methods

Function name

Return value

Arguments

Description

isEqual(c)

Boolean

c, Coord

Test if self has the same coordinates as c.

 


Class Color

The Color class corresponds to a color within ShapeUp. The Color constructor takes 3 arguments, r, g, and b, representing the initial color ingredients red, green and blue.

 

Color properties

Property name

Type

Description

red

Integer

Red portion of this color.

green

Integer

Green portion of this color.

blue

Integer

Blue portion of this color.

 

 

Color methods

Function name

Return value

Arguments

Description

isEqual(c)

Boolean

c, Color

Test if self has the same color as c.

 


Class File

The File class handles reading and writing to a file. The constructor takes 0, 1 or 2 arguments. See open() for argument details.

 

File properties

Property name

Type

Description

isOpen

Boolean, readonly

True if the file is opened. False otherwise.

eof

Boolean, readonly

True if end-of-file is reached. False otherwise.

name

String, readonly

The name of the file.

SEEK_SET

Integer, readonly

Used in File.seek() function to seek from beginning of the file.

SEEK_CUR

Integer, readonly

Used in File.seek() function to seek from current file position.

SEEK_END

Integer, readonly

Used in File.seek() function to seek from end of file.

 

 

File methods

Function name

Return value

Arguments

Description

open(s1, [s2])

Boolean

s1, String for file name.

s2, String, optional for mode. Defaults to “r”. Available options are: r, w, a, r+, w+, a+.

Opens the file s1. Returns true on success. Otherwise false.

openTempFile([s])

Boolean

s, String, file mode. Available options are w, w+.

Opens a temporary file. The name of the file can later be accessed through the name property. Returns true on success. Otherwise false.

close()

void

void

Flushes and closes an opened file.

readln([s])

String

s, String, optional, specifies a set of delimiters to be used.

Reads a set of characters from the file until one of the delimiting characters in s or end-of-file is encountered. This set of characters is returned from the function. readln() may not be called if eof is true.

write(s)

Boolean

s, String

Writes a formatted string, s, to the file. Returns true on success, false otherwise.

writeln([s])

Boolean

s, String, optional

Writes a formatted string, s, to the file appending newline at the end. Returns true on success, false otherwise. If s is omitted, a newline is written to the file.

flush()

Boolean

void

Flushes the current stream buffer. Returns true on success. If an error occurred, such as disk full etc. false is returned.

seek(n1, [n2])

Integer

n1, Integer for file position.

n2, Integer, optional, for seeking offset. See File Properties for valid values.

Moves the file pointer to the specified position. Returns true on success, otherwise false.

tell()

Integer

void

Returns the current file pointer position. A value less than 0 indicates an error.

 


Class Plugin

The Plugin class handles communication with a ShapeUp GPI plug-in. The constructor takes 1 argument, which is the GPI GUID identifier as a string. This value can manually be accessed from Tools | Options | Plugins | GPI, and then right clicking on the plug-in and chose Copy GUID.

 

Plugin properties

Property name

Type

Description

GUID

String, readonly

The GUID the Plugin object was constructed with.

name

String, readonly

The name of the GPI, as defined by the plug-in.

file

String, readonly

The GPI file name.

 

Each JavaScript aware GPI plug-in may expose additional properties. Please see the GPI documentation for further details.

 

Plugin methods

Each JavaScript aware GPI plug-in exposes its own set of methods. Please see the GPI documentation for further details.

 

Common to all methods accepting parameters is that the parameters can either be sent horizontally or vertically. Horizontally meaning:

 

var plugin = new Plugin('{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}');

plugin.method(1, 2, 3, 4);

 

and vertically meaning:

 

var plugin = new Plugin('{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}');

var args = new Array(1, 2, 3, 4);

plugin.method(args);

 

The Array elements need not be of the same type. Use the vertical method if you want to supply a variable number of arguments.


Global methods overview

ShapeUp JavaScript environment comes with some predefined ‘global’ functions, accessible without an object.

 

Global methods

Function name

Return value

Arguments

Description

gc()

void

void

Invoke garbage collector.

alert([s])

void

s, any type, optional

Display a message box with the argument, s, converted to a string.

confirm([s])

Boolean

s, String, optional

Display a message box with the text, s, and two buttons OK an Cancel.

Returns true if the user pressed OK, otherwise false.

option(t, s1 [,s2[…]])

option(t, a)

String

t, String

sn, String

a, Array

Open a dialog showing the text, t, and with buttons s1, s2, … The other version of this function allows an Array of button text strings to be passed as the second parameter. Return value is the text on the button the user selects.

input(t [, s])

String

t, String

s, String, optional

Ask the user for input. A dialog is opened with the message t, and the user can enter a value. If parameter s is supplied, this is considered a default value for the edit control. Return value is the string in the edit control if the user presses OK, otherwise it returns null.

browseFileRead([s])

String

s, String, optional

Opens a file browser and lets the user pick a file to open for reading. Return value is a String containing the full path of the file. If the user cancels the operation, null is returned.

If s is supplied, this will be the title of the dialog.

browseFileWrite([s])

String

s, String, optional

Opens a file browser and lets the user pick a file to open for writing. Return value is a String containing the full path of the file. If the user cancels the operation, null is returned.

If s is supplied, this will be the title of the dialog.

browseFolder()

String

void

Opens a folder browser and lets the user select an existing folder, or create a new one. Return value is a string containing the full path of the selected folder, or null if the user pressed cancel.

browseColor()

Color

void

Opens a color picker dialog and lets the user select a color. A Color object is returned if the user presses OK, otherwise null.

sleep(ms)

void

ms, positive Integer

Wait ms milliseconds.

executeAndWait(p [,a])

Boolean

p, String

a, String, optional

Execute a program, p, optionally with arguments, a, and wait for the newly created process to terminate.

Returns true if the process could be created, and false if there was a problem.

getExitCode()

Number

void

Returns the exit code from the last process run with executeAndWait().

external(s)

Result from evaluated script

s, String

Used to include other scripts into the current script. The argument, s, is a string containing a file name, with or without a full or relative path.

Note: Double backslashes are needed to separate directories and files. When including another JavaScript file, it is run in the same context as the current script, thus, functions and objects in the included script will be visible to the current script. Script files given relative paths are first looked for relative the referring script file location. If not found there, it is looked for relative the ShapeUp scripts subdirectory.

invokePlugin(g [, v])

 

deprecated

use class Plugin instead.

Array

g, String

v, value list or Array of values

Invokes a JavaScript aware plug-in with the GUID g, and optional arguments. The arguments can either be added in a normal fashion, or collected in an Array which in turn is sent as the only argument. The return value is the plug-ins result as an Array of values. Return values are all specified by the plug-in designer. Please consult plug-in specific documentation for more information.


JavaScript Samples

In some of the samples it’s assumed that the shape files country.shp, country.shx and country.dbf from ESRI are available in the ‘C:\’ root directory.

 

Tracing number of layers

workspace.println('Number of layers: ' + workspace.layerCount);

 

Toggling visibility of all layers

for (var idx = 0; idx < workspace.layerCount; ++idx)

{

    with (workspace)

    {

        getLayer(idx).visible = !getLayer(idx).visible;

    }

}

 

 

Loading a shape file and adding empty layers

newlayer1 = workspace.loadShapeFile('C:\MyShape.shp');

newLayer2 = workspace.addNewLayer('Point');

newLayer3 = workspace.addNewLayer('Polyline', 'Initial layer name');

 

var newlayer4;

var filename = browseFileOpen('Open Shape File');

if (filename != null)

   newLayer4 = workspace.loadShapeFile(filename);

 

 

Listing countries starting with an ‘A’

function getAttributeIndex(l, attr)

{

   // l is of type Layer

   // attr is a String containing the attribute name

   for (var a = 0; a < l.attributeCount; ++a)

   {

      if (attr == l.getAttribute(a))

         return a;

   }

   workspace.println('Error: Could not locate attribute field: ' + attr);

   return -1;

}

 

function listCountries()

{

   world = workspace.loadShapeFile('C:\\country.shp');

   if (world == null)

   {

      workspace.println('Error: Could not load shape file.');

      return;

   }

   world.visible = false;

   workspace.println('Processing ' + world.shapeCount + ' countries...');

   nameIndex = getAttributeIndex(world, 'CNTRY_NAME');

   workspace.println('Name index is ' + nameIndex);

   if (nameIndex >= 0)

   {

      workspace.println('Countries starting with the letter A are:');

      found = 0;

      for (var c = 0; c < world.shapeCount; ++c)

      {

         with (workspace)

         {

           if (world.getShape(c).getAttribute(nameIndex).charAt(0) == 'A')

           {

              println(' * ' + world.getShape(c).getAttribute(nameIndex));

              ++found;

           }

         }

      }

      workspace.println(found + ' countries found');

   }

   workspace.removeLayer(world);

}

 

listCountries();

 

 

Dumping object properties

function dump_props(obj, obj_name)

{

   var result = "---- Property Dump ----\r\n";

   for (var i in obj)

   {

       result += obj_name + "." + i + " = " + obj[i] + "\r\n"

   }

   result += "-----------------------";

   return result

}

 

workspace.println(dump_props(workspace, 'workspace'));

 

 

Running an external program

var ok = executeAndWait("C:\\MyProgram.exe", "argument1 argument2");

alert(ok ? "Process started OK\nExit code: " + getExitCode() :

           "Process startup failed");

 

Changing a layers color

layer = workspace.browseLayer(‘Select a layer to colorize’);

 

if (layer != null)

{

   // Either:

   layer.color = new Color(255, 100, 0);

 

   // or:

   layer.color.red = 255;

   layer.color.green = 100;
   layer.color.blue = 0;

 

   // or:

   var clr = browseColor();

   if (clr != null)

      layer.color = clr;

}

 

Getting shapes in the order they were selected

function getSortedSelection(layer)

{

   var ret = new Array();

 

   var ret = new Array();

   for(var i=0; i < layer.selectionCount; i++)

       ret[layer.getSelectedShape(i).selectionIndex] =

                                   layer.getSelectedShape(i);

   return ret;

}

 

function printSortedSelection(layer, attr)

{

   var selectionArray = getSortedSelection(layer);

 

   if (selectionArray.length == 0)

   {

      workspace.println('No shapes selected.');

      return;

   }

 

   workspace.println('Selection was made in the following order:');

 

   for (var i = 0; i < selectionArray.length; i++)

   {

      workspace.println(selectionArray[i].getAttribute(attr));

   }

}

 

var layer = workspace.loadShapeFile('C:\country.shp');

if (layer != null)

   printSortedSelection(layer, 2);

else

   workspace.println('Error loading shape file.');

 

Reading data from a file

function readFromFile()

{

   var filename = browseFileRead();

   if (filename  == null)

      return;

   var f = new File;

   if (f.open(filename))

   {

      workspace.println("File opened successfully!");

      var line;

      while (!f.eof)

      {

         line = f.readln();

         workspace.println(line);

      }

   }

   else

   {

      alert("Could not open file!");

   }

   f.close();

}

 

Adding other JavaScript files to the current context

external('C:\\full\\path\\file.js');

external('relative\\path\\file.js');

external('..\\path\\file.js');

 

var result = external('file.js');

 


Handy ShapeUp Console Commands

When running JavaScripts, there are a few console commands that come in handy. A description of those are listed below. The full description of the commands is not supplied, only parts regarding scripting. For full description, type ‘help <command>‘ in the console.

 

Run

Runs a script file.

Syntax:

run [<filename>]

where <filename> is the name of the script file. If omitted, an open file dialog will prompt you for one.

 

Debug

Turn on (script) debugging output.

Syntax:

debug [(on|off) [scripts]]

debug will turn on/off scripts ability to communicate with the console for output.

 

Target

Tell the console where debug info will be dumped.

Syntax:

target [file [<filename>] | console]

Tells the console whether to print script output to the console or to a file. If <filename> is omitted, a save file dialog will prompt you for one.

 

Alias

Create an alias for a common command.

Syntax:

alias [<name> [<target>]]

Creates an alias for <target> with the name <name>.

E.g. > alias r run myscript.js