Skip to end of metadata
Go to start of metadata

Deploying RAMP JavaScript VMs

When deploying a RAMP JavaScript app a switch is needed to trigger the use of JavaScript.

Creating a JavaScript app on the deployment platform

When using an ant script to create a new app add the javascript option to the build target.

 

    <target name="createapp">

        <build

                        appId="ramptest"

                        description="RAMP QA Test app"

                        vmSource="trunk"

                        javascript="true"/>

    </target>

Android and J2ME

When using the deployment platform, a JavaScript capable VM will be created for JavaScript apps created as above.

iOS

When building an .ipa file for distribution add the following line to the ramp_config.cfg file:

config._scripting_language=javascript

Windows Phone 7

When building an .xap file for distribution add the following line to the ramp_config.cfg file:

config._scripting_language=javascript

 

Ramp JavaScript Applications

JavaScript compatibility

The RAMP JavaScript implementation is a subset of JavaScript (ECMAScript 262 Edition 5.1).

The implementation supports the following JavaScript features:

  • Functions
  • Closures
  • Objects and Object literals
  • Arrays
  • The 'new', 'if', 'do', 'while', 'for', 'switch', 'typeof', 'delete' and 'throw' statements

The following JavaScript language features are not supported:

  • The Global object
  • The JSON object
  • Property Attributes (for Named Data and Named Accessor Properties)
  • Regular expressions
  • Call, Eval, Bind
  • The 'try/catch', 'for-in', 'with' and 'debugger' statements
  • Floating point operations are not supported on basic J2ME devices without floating point support.

Developing RAMP applications with Javascript

RAMP applications can either be implemented in RampScript or in JavaScript.

JavaScript applications will not be able to access any code written in RampScript.

If a VM is configured for JavaScript (as above) it will execute the JavaScript files in the application (any RampScript files will be ignored).

JavaScript files

A RAMP application contains one or more JavaScript files ending in a '.js' suffix.

For example, your application may contain:

login.js
main.js
error.js

main.js and global variables

When the RAMP application is loaded all the statements (except for function declarations) in the javascript files are executed.

The contents of the JavaScript files are ordered so that the contents of the main.js file occur before any of the others.

If you would like to create global variables that are shared across your JavaScript files, you should put them in the main.js file.

Special functions

main() function

After the statements in all JavaScript files are executed the RAMP VM will execute a main() function if it is present.

The main() function should be used to initialize the program and to display the first UI component.

Example:

/* Global variable containing the user name.
   Visible in all the JavaScript files */

var loginUserName;

function main()
{
	//Read a stored user name if available
	loadUserName();

	//If no stored user name was found, set it to "guest" 
	if(!loginUserName)
		loginUserName = "guest";

	//Show the login form
	RAMP.gotoForm("login");
}

error(errorMessage) function

If an error occurs while executing a RAMP application the RAMP VM will invoke the error() function with an error message. The error might be a network error or a security error (e.g. a digital signature couldn't be verified). Typically you should display the error to the user and offer appropriate options (e.g. try again or exit or go back to the main menu). You can also use the error function for reporting your own errors (e.g. the supplied credit card number had the wrong length or a bad check digit). By reusing the error function, you ensure that your error messages have a consistent look-and-feel and reduce the amount of code in your application.

function error(errorMessage)
{
   RAMP.uxmlSet("error.message.text", errorMessage);
   RAMP.gotoForm("error");   
} 

Compatibility

JavaScript is only available on RAMP VMs with a version number of 5.0.0 or later.

The RAMP JavaScript implementation is a subset of JavaScript and only the functions described below are supported.

 

Standard JavaScript functions

Utility functions

parseInt(string, radix)

http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2

Use of the radix argument is not supported and always defaults to 10

parseFloat(string, radix)

http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2

Use of the radix argument is not supported and always defaults to 10

Number(string)

http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.1.1

Object

Object.keys(object)

http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.14

Math

Math.random()

- http://www.ecma-international.org/ecma-262/5.1/#sec-15.8.2.14

Only supported on phones with floating point support

Array

join, pop, push, reverse, shift, slice, sort, splice

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4

String 

charAt, charCodeAt, concat, fromCharCode, indexOf, split, substring, toLowerCase, toUpperCase, trim

http://www.ecma-international.org/ecma-262/5.1/#sec-15.5

Non-standard Javascript functions

Utility functions

hasOwnProperty(obj, key)

Returns true if obj has a property defined with the same name as key.

var car = { color: "red", type: "sedan" };

print(hasOwnProperty(car, "color"));
//true
print(hasOwnProperty(car, "age"));
//false

print(value)

Prints a string representation of value to the output stream.

RAMP platform functions

The following functions are available on the RAMP object.

Web service functions

webservice(serviceName, {parameterKey: parameterValue, ...})

Invokes a web service with a specified name. An arbitrary number of parameters can be passed. For example,

RAMP.webService("foo", {firstname: "vmt"})

invokes the foo service with a single parameter pair. Similarly

RAMP.webService("foobar", {firstname: "vmt", age: "5"}) 

 

invokes the foobar service with two parameters. The order of parameters is not significant.

The corresponding RAMP handler should implement ServiceRequestHandler.

webServiceSecure(serviceName, {parameterKey: parameterValue, ...})

The same as webService, except sends the data securely. The corresponding RAMP handler should extend SecureHandler.

webServiceAsync(serviceName, callbackFunction, {parameterKey: parameterValue, ...})

Invokes a web service with a specified name asynchronously. Invoking a web service can be slow; to make your application more responsive you can invoke the service asynchronously. When the service call has completed, a callback function will be invoked. An arbitrary number of parameters can be passed. For example,

RAMP.webServiceAsync("foo", "fooCallback", {firstname: "vmt"})

invokes the foo service asynchronously.

The corresponding RAMP handler should implement ServiceRequestHandler.

The callback function takes two parameters: a response and an error message. For example,

Callback
function fooCallback(response, error) {
    if (error) {
        displayError(error);
    } else {
        process(response);
    }
}

webServiceSecureAsync(serviceName, callbackFunction, {parameterKey: parameterValue, ...})

The same as webServiceAsync, except sends the data securely. The corresponding RAMP handler should extend SecureHandler.

webServiceSecureSetKey(keyId)

Sets the RSA transport key ID that will be used by the webServiceSecure and webServiceSecureAsync functions. If this function isn't called, the default key ID is "keyexchange".

RAMP.webServiceSecureSetKey("key1");

Secure session management

The webServiceSecure and webServiceSecureAsync functions will automatically establish a secure session if there isn't one already. The VM achieves this by calling the "establishSessionHandler" on the RAMP Server. See the following guide to make sure your RAMP Server is configured correctly: Advanced Guide#WiringuptheSecureHandler.

If the session expires due to the maximum session idle time being exceeded (this time is 30 minutes by default and is configurable on the RAMP Server), and webServiceSecure or webServiceSecureAsync are subsequently called, they will not succeed and a "_session_expired" key will be sent back in the response. One can decide on an appropriate action to take when this key is present in the response, e.g. one could either resend the request or require a user to sign in again.

If the VM exits and restarts, a new session will be established when webServiceSecure or webServiceSecureAsync is called.

Navigation functions

exit()

Closes the application. This command immediately terminates the running function, any statements after this call will not be executed.

RAMP.exit();

back()

Navigates away from the currently displayed UI component to display the previous component. This command immediately terminates the running function, any statements after this call will not be executed.

RAMP.back();

show(formName)

Displays a UI component with the specified identifier. The UI component must be a Form, a Menu or a splash screen.

RAMP.show("menu");

gotoForm(formName)

Displays a UI component with the specified identifier. The UI component must be a Form, a Menu or a splash screen.

After executing this statement no further statements will be executed.

To continue executing, use RAMP.show(formName) instead.

RAMP.gotoForm("error");
//No further statements will be executed after the call to gotoForm

Set focus function

setFocus(componentName)

This function can be used to set the UI component which will have focus when a form is displayed. The componentName parameter must contain the fully qualified name of the UI component. E.g. to set the focus to a TextInput component with ID "textinput1" which is on a Form component with ID "form1", and then to navigate to the form, one would use the following:

...
RAMP.setFocus("form1.textinput1");
RAMP.gotoForm("form1");
...

Cryptographic functions

wssRandomKey()

Returns a 16 byte random TDES key.

var key = RAMP.wssRandomKey();

wssSha1(data)

Performs a SHA-1 hash  function on data, where data can be any RAMP data type. The 160-bit hash value that is produced is returned as a 40 character string of hexadecimal numbers.

var keyHash = RAMP.wssSha1(key);

wssEncrypt(key, data)

Encrypts data using TDES in CBC mode using the XML encryption padding scheme. The data is a JavaScript object. The function returns a JavaScript object where the keys of the object are the same as for the supplied data but where the values contain encrypted data.

var data = { message: "Message to be encrypted" };
var cipherText = RAMP.wssEncrypt(key, data);

wssDecrypt(key, data)

Decrypts data using TDES in CBC mode using the XML encryption padding scheme. The data is a JavaScript object. The function returns a JavaScript object where the keys of the object are the same as for the supplied data but where the values contain decrypted data.

var decryptedData = RAMP.wssDecrypt(key, cipherText);
var message = decryptedData.message;

Utility Functions

isFunctionSupported(functionName)

Returns true if a specific RAMP VM plugin function is supported and false if it is not supported. e.g.

 

RAMP.isFunctionSupported("vmt_takePicture");

 

 will return true on a VM that includes the VMT camera plugin and false on a VM that doesn't.

callFunction(functionName, arg1, arg2, ...)

Calls a function provided by a RAMP VM plugin with the specified arguments.

For example, call the openUrl function defined by the OpenUrlPlugin.

RAMP.callFunction("openUrl", "http://virtualmobiletech.com");

randomInteger(min, max)

Generates a random value in the range (min, max) (both inclusive).

var v = RAMP.randomInteger(0, 10);

isStringNumeric(str)

Checks whether all the characters in str are decimal digits. Returns true if they are, otherwise false. Note that white space is significant; if a string contains whitespace the string will be regarded as non-numeric.

if(RAMP.isStringNumeric(str))
{
	var num = Number(str);
    ...
}

strToChars(str)

Creates an array containing character codes for each character in the given string.

var chars = RAMP.strToChars(str);
// 104,101,108,108,111

strFromChars(chars)

var str = RAMP.strFromChars([104,101,108,108,111]);
// hello

Takes an array of character codes and returns a string formed from the corresponding characters.

Event Handlers/Callback Functions

setErrorHandler(callbackFunction, type)

A RAMP program should supply an error() function to handle errors. However some errors (e.g. network errors) could be regarded as outside the scope of the usual error handling. For this reason certain error events can be registered to call a function other than the error() function.

The value of the callbackFunction parameter is the name of a function to call when an error of a specific type occurs.

The value of the type parameter is the type of error to handle. The following are valid values:

  • network

  • security

setErrorHandler
RAMP.setErrorHandler("errorHandler", "network");

Timer Events

It can be useful to have code run every few seconds (e.g. to update the image in a slide show) or every few minutes (invoke a web service to check for new emails or updated share prices). For this reason, RAMP provides various timer functions.

timerStartTask(callbackFunction, delay)

Invokes a callback function every delay milliseconds.

This function returns a handle to the task (which you'll need if you want to stop the task later on).

For example,

var timer = RAMP.timerStartTask("timerCallback", 60000);

will ensure that the function "timerCallback" gets called once a minute (every 60000 ms).

The function "timerCallback" could be implemented as

function timerCallback(time)
{
  RAMP.uxmlSet("l1.text", (time / 60000) + " minutes have elapsed");
}

timerStopTask(timer)

This function ensures that a callback function will no longer be called. For example, it can be used as:

function timerCallback(time)
{
    if (time > 36000000) {
         RAMP.timerStopTask(timer);
    } else {
         RAMP.uxmlSet("l1.text", (time / 60000) + " minutes have elapsed");
    }
}

getTime()

This function returns the time (in milliseconds) since the application started running.

print(RAMP.getTime());
// 17456

getDeviceTime()

This function returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

print(RAMP.getDeviceTime());
// 1416396382433

Dynamic UXML

uxmlGet(key)

The uxmlGet(key) function allows the value of a UXML attribute specified in key to be determined.

var text = RAMP.uxmlGet("main.inputbox.text");

uxmlSet(key, value)

The uxmlSet(key, value) function allows the value of a UXML attribute specified in key to be set at runtime (i.e. dynamically).

For example,

for (var i = 1; i <= 30; i++) {
  var attr = "label" + i + ".stylename";
  RAMP.uxmlSet(attr, "largeFontStyle");
}

uxmlNewNode(type, id, attributes)

This function allows a UXML node to be created dynamically and supports all UXML components since 4.1.0.

id is the identifier for the element.

attributes is a object containing (name, value) pairs specifying attributes of the element such as "stylename" for a label, or "click" for a button.

The code below shows how to create a button dynamically:

attributes = {label: "Exit", click: "exit()"};
button = uxmlNewNode("button", "button1", attributes);

uxmlNewNode(type, id, attributes, childNodes)

This function allows a UXML node that contains child nodes to be created dynamically. The type must be one of the following standard UXML components:

  • form
  • horizontallayout
  • listview (since 4.1.0)
  • menu (since 4.1.0)
  • serviceform (since 4.1.0)
  • valuestepper

Or it can be one of the following smart phone components (since 4.0.0, unless otherwise stated):

  • alert
  • animatedview
  • canvas (since 4.1.0)
  • horizontalscrollview
  • navigationbar
  • smartform
  • tabbar
  • toolbar (can have children of smart phone component type "toolbaritem")
  • verticallayout
  • verticalscrollview

id is the identifier for the element.

attrs is a object containing (name, value) pairs specifying attributes of the element such as "stylename".

childNodes is a list of child nodes

The code below shows how to create a form with a heading and a button dynamically:

var attributes = {label: "My form heading", stylename: "headstyle"};
var formheading = RAMP.uxmlNewNode("formheading", "fh1", attributes);
 
attributes = {label: "Exit", click: "exit()"};
var button = RAMP.uxmlNewNode("button", "b1", attributes);
 
var childNodes = [formheading, button];
 
attributes = {stylename: "formstyle"};
 
var form = RAMP.uxmlNewNode("form", "f1", attributes, childNodes);

After creating a UXML element dynamically it can be accessed in the usual ways; e.g. RAMP.gotoForm("f1") would render the form created above.

Note that if a UXML element is created with the same ID as an existing element, the old element is deleted.

Aliased Forms of uxmlNewNode

Using uxmlNewNode can be tedious for creating elements since an attribute object must be created before the node can be instantiated. Convenience methods are provided that create the object and populate it.

uxmlButton(id, label, click)

Creates a Button with the specified id, label and the associated click event for the button.

uxmlForm(id, children, stylename)

Creates a Form with the specified id, child nodes and styling. The children parameter must contain a list of child nodes (e.g. Labels, TextInputs, ValueSteppers and Buttons).

uxmlFormHeading(id, label, stylename)

Creates a FormHeading with the specified id, label and styling.

uxmlLabel(id, text, stylename)

Creates a Label with the specified id, text and styling.

uxmlTextInput(id, text, maxchars, isnumeric, ispassword, stylename)

Creates a TextInput with the specified id, (default) text, maximum number of characters, styling and whether the field accepts only numeric characters or is a password field. The isnumeric and ispassword values must take the string values "true" or "false".

uxmlValueStepper(id, values, defaultvalue, stylename)

Creates a ValueStepper populated with the specified values. The values parameter must contain a list of values to display. The defaultvalue is the value that should be displayed before the user has made a selection.

uxmlHorizontalLayout(ratio, children)

Creates a Horizontal Layout with the specified ratio and child nodes. The ratio parameter must contain a colon delimited string of relative lengths of the child nodes (e.g. "1:2:3"). The children parameter must contain a list of child nodes (e.g. Labels, TextInputs, ValueSteppers, Pictures and Horizontal Rules).

uxmlPicture(id, image, stylename, click)

Creates a Picture with the specified id, image identifier, styling and click attribute. The click attribute is optional.

uxmlHorizontalRule(id, stylename)

Creates a Horizontal Rule with the specified id and styling.

uxmlTicker(id, text stylename)

Creates a Ticker with the specified id, text and styling.

uxmlNodeSupported(type)

Returns true if a specific UXML node type is supported and false if it is not supported. e.g. uxmlNodeSupported("label") will return true.

This is typically used to check for the availability of UXML components provided by UI plugins to the RAMP VM.

RAMP Environment Functions

getVersion()

Returns the version of the RAMP platform as a string; e.g. "3.5.0".

print(RAMP.getVersion())
//5.0.0

 

directInput()

Indicates whether native or direct input is used. The function returns 1 if direct input is used, otherwise 0.

print(RAMP.directInput())
//1

isMidp2()

Returns 1 if RAMP is running on a MIDP 2.0 device.

print(RAMP.isMidp2())
//1

getPersistentValue(name)

Get the value of a persistent variable.

var password = RAMP.getPersistentValue("password")

setPersistentValue(name, value)

Set the value of a persistent variable.

RAMP.setPersistentValue("password", "abc123")

Device Functions

The device functions are only supported on smart phones.

getDeviceOrientation()

Returns the current orientation of the device running the RAMP app as one of the following values: "portrait", "landscape" or "unknown".

print(RAMP.getDeviceOrientation());
//portrait

 

Properties

List of RAMP properties

Each key listed references a RAMP property. The property value can be retrieved by calling RAMP.getProperty(). Some of these properties can also be modified with the RAMP.setProperty() function.

Keys for properties that can be modified at runtime:

  • "config._screen_size" : The dimensions of the device's screen in the format "width,height".
  • "config._screen_ppi" : The pixels per inch of the device's screen in the X and Y dimension. It is in the format "xppi,yppi". (Since 4.2.0. Only on smart phones, excluding Windows Phone where an empty string is returned due to the inability to determine the PPI programmatically.)
  • "config._locale" : The ISO code of the locale that is set on the device.
  • "locale" : This property can be set if the locale used by the RAMP application for internationalization etc. should differ from the locale set on the device.
  • "config._os_name" : The name of the operating system running on the device.
  • "config._os_version" : The version of the operating system running on the device.
  • "config._device_model" : The device's model.
  • "config._device_make" : The device's make.
  • "http.header.Connection" : Http header field. Informs if http connections are set to be kept alive ("Keep-Alive") or a http connection is closed after each request ("Close"). The default is "Close". (since 3.7.2)
  • "http.header.Accept" : Http header field. Content-Types that are acceptable
  • "http.header.Content-Type" : Http header field. The mime type of the body of a request.
  • "http.header.X-Wap-Proxy-Cookie" : Http header field. Indicate whether the Cookie Proxy should store cookies from origin servers.

Keys for properties that cannot be modified at runtime:

  • "config._ramp_version" : The version of the RAMP platform.
  • "config.feature.name" : The name of the app's feature.
  • "feature.host" : The address of the feature server, the server where the app fetches its feature.
  • "feature.persist" : "1" if the app's feature is persisted on the device, "0" if the feature is fetched for each session.
  • "rsa.testkey1.mod" : Security key for the feature server.
  • "secure.host.(n-1)" : The address of the nth defined service server, e.g. the address for the 1st service server is referenced by the key "secure.host.0".
  • "rsa.(keyname).mod" : The key string for for a defined security key, i.e. replace "(keyname)" with the name of the defined key.
  • "rsa.(keyname).version" : The version of a defined security key i.e. replace "(keyname)" with the name of the defined key.

getProperty(key)

Get the value of one the properties defined above.

RAMP.getProperty("config._ramp_version")
//5.0.0

setProperty(key, value),

Set the value of one of the properties defined above.

RAMP.setProperty("http.header.Connection","Keep-Alive");

Canvas Functions

The canvas functions are only supported on smart phones.

The Canvas component is based on the HTML5 canvas element. Therefore all methods on the CanvasRenderingContext2D interface are available as JavaScript methods.

To get a Canvas context, call RAMP.getCanvasContext() for the appropriate component.

getCanvasContext(formName)

Returns a RAMP Javascript object representing the underlying canvas

For example, the canvas context for the Canvas component in this UXML form can be accessed as below:

<Form id="uxml" stylename="formstyle" backkey="back()">
		<Canvas id="canvas" width="230" height="210" stylename="cstyle">
            <CanvasContext id="context" />
        </Canvas>
</Form>
var context = RAMP.getCanvasContext("uxml.canvas.context");

Canvas

Non-HTML5 Functions

invalidateCanvas()

Drawings made on the canvas will not be displayed immediately. This function needs to be called when drawing to the canvas is complete and should be displayed.

context.invalidateCanvas();
getCanvasImageSrc(sx, sy, sw, sh)

Returns a byte array of a PNG encoded image taken from the given dimensions of the canvas. If the dimensions fall outside the bounds of the canvas, the image will be transparent in these regions.

var imgsrc = context.getCanvasImageSrc(0, 0, 400, 400);

 

Canvas State Functions

save()

Pushes the current canvas state onto the stack.

context.save();
restore()

Pops the top state on the stack, restoring the canvas to that state.

context.restore();

 

scale(x, y)

Changes the transformation matrix to apply a scaling transformation with the given characteristics.

context.scale(0.5, 0.5);
rotate(angle)

Changes the transformation matrix to apply a rotation transformation with the given characteristics. The angle is in radians.

context.rotate(3.14);
translate(x, y)

Changes the transformation matrix to apply a translation transformation with the given characteristics.

context.rotate(3.14);
transform(a, b, c, d, e, f)

Changes the transformation matrix to apply the matrix given by the arguments as described below.

context.transform(1, 2, 3, 4, 5, 6);
setTransform(a, b, c, d, e, f)

Changes the transformation matrix to the matrix given by the arguments as described below.

context.setTransform(1, 0, 0, 1, 0, 0);

Style Functions

createLinearGradient(x0, y0, x1, y1)

Returns a gradient component that represents a linear gradient that paints along the line given by the coordinates represented by the arguments.

var g = context.createLinearGradient(140, 0, 180, 0);
g.addColorStop(0, "0xFF0000");
g.addColorStop(1, "0x00FF00");
RAMP.uxmlSet("composites.canvas.ctx.fillStyle", g);
createRadialGradient(x0, y0, r0, x1, y1, r1)

Returns a gradient component that represents a radial gradient that paints along the cone given by the circles represented by the arguments.

var grad = context.createRadialGradient(1, 1, 100, 400, 400, 50);
grad.addColorStop( 0, "0xFFFF00");
grad.addColorStop( 0.5, "0x00FFFF");
grad.addColorStop( 1.0, "0xFF00FF");
    
RAMP.uxmlSet("paintstyles.canvas.ctx.fillStyle", grad);
createPattern(image, repetition)

Returns a pattern component that uses the given image and repeats in the direction(s) given by the repetition argument.

The allowed values for repetition are "repeat" (both directions), "repeat-x" (horizontal only), "repeat-y" (vertical only), and "no-repeat" (neither). If the repetition argument is empty or null, the value "repeat" is used.

The image argument must be the UXML ID of an Image component.

RAMP.uxmlSet("composites.canvas.ctx.fillStyle",  context.createPattern("imagename", "repeat"));

 

Simple Shape Functions

clearRect(x, y, w, h)

Clears all pixels on the canvas in the given rectangle to transparent black.

context.clearRect(50, 50, 100, 50);
fillRect(x, y, w, h)

Paints the given rectangle onto the canvas, using the current fill style.

context.fillRect(100, 100, 25, 80);
strokeRect(x, y, w, h)

Paints the box that outlines the given rectangle onto the canvas, using the current stroke style.

context.strokeRect(30, 30, 100, 100);

Path Functions

beginPath()

Resets the current path.

context.beginPath();
moveTo(x, y)

Creates a new subpath with the given point.

context.moveTo(1, 100);
closePath()

Marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.

context.closePath();
lineTo(x, y)

Adds the given point to the current subpath, connected to the previous one by a straight line.

context.lineTo(110, 115);
quadraticCurveTo(cpx, cpy, x, y)

Adds the given point to the current subpath, connected to the previous one by a quadratic Bézier curve with the given control point.

context.quadraticCurveTo(200, 1, 100, 100);
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Adds the given point to the current subpath, connected to the previous one by a cubic Bézier curve with the given control points.

context.bezierCurveTo(175, 200, 125, 1, 200, 100);
arcTo(x1, y1, x2, y2, radius)

Adds an arc with the given control points and radius to the current subpath, connected to the previous point by a straight line.

Throws an error if the given radius is negative.

context.arcTo(100, 175, 125, 175, 25);
arc(x, y, radius, startAngle, endAngle [, anticlockwise ] )

Adds points to the subpath such that the arc described by the circumference of the circle described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction (defaulting to clockwise), is added to the path, connected to the previous point by a straight line.

Throws an error if the given radius is negative.

context.arc(100, 100, 25, 0.0, 1.57, true);
rect(x, y, w, h)

Adds a new closed subpath to the path, representing the given rectangle.

context.rect(6, 91, 6, 6);
fill()

Fills the subpaths with the current fill style.

context.fill();
stroke()

Strokes the subpaths with the current stroke style.

context.stroke();
clip()

Further constrains the clipping region to the given path.

context.clip();
isPointInPath(x, y)

Returns true if the given point is in the current path.

if (context.isPointInPath(110, 45))
{
	...
}

Text Functions

fillText(text, x, y [, maxWidth ] )

Fills the given text at the given position. If a maximum width is provided, the text will be scaled to fit that width if necessary.

context.fillText("Hello world", 100, 40);
strokeText(text, x, y [, maxWidth ] )

Strokes the given text at the given position. If a maximum width is provided, the text will be scaled to fit that width if necessary.

context.strokeText("Hello world", 1, 30);
measureText(text)

Returns the float width of the given text in the current font.

var width = context.measureText("hello");

Image Functions

drawImage(image, dx, dy)

Draws the given image onto the canvas at the destination point.

The image argument must be the UXML ID of an Image component.

context.drawImage("imagename", 20, 20);
drawImage(image, dx, dy, dw, dh)

Draws the given image onto the canvas at the destination point, with the destination dimensions, scaling if necessary.

The image argument must be the UXML ID of an Image component.

context.drawImage("imagename", 50, 60, 20, 20);
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)

Draws a subsection of the given image onto the canvas at the destination point, with the destination dimensions, scaling if necessary.

The image argument must be the UXML ID of an Image component.

context.drawImage("imagename", 50, 50, 30, 30, 101, 101, 98, 98);

Pixel Manipulation Functions

createImageData(sw, sh)

Returns a list of ints representing the RGBA pixel values, in the range 0 to 255, of a transparent black image with the given coordinates.

var data = context.createImageData(50, 50);
getImageData(sx, sy, sw, sh)

Returns a list of ints representing the RGBA pixel values, in the range 0 to 255, of the given rectangle of the canvas.

var data = context.getImageData(1, 1, 99, 99);
putImageData(imagedata, imageWidth, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight ])

Paints the data from the given imagedata list onto the canvas. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

An imageWidth argument which is not present in the corresponding HTML5 method is required here since the imagedata list doesn't include an indication of the dimensions of the image it represents.

context.putImageData(data, 99, 100, 100);

Gradient

addColorStop(offset, color)

This method provides the same functionality as the addColorStop(offset, color) method on the HTML5 CanvasGradient interface.

It adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end.

The gradient object is created using either the createLinearGradient or the createRadialGradient methods.

The color argument must be a color string. It can be specified as "0xRRGGBB" or "0xAARRGGBB", like usual RAMP colors, where AA, RR, GG, and BB are hexadecimal values between 00 and FF. It can also be specified using the "rgb(r, g, b)", or "rgba(r, g, b, a)" format where r, g and b are integer decimal values between 0 and 255, and a is a decimal floating point value between 0.0 and 1.0.

Throws an error if the offset is out of range or if the color cannot be parsed.

var g = context.createLinearGradient(140, 0, 180, 0);
g.addColorStop(0, "0xFF0000");
g.addColorStop(1, "0x00FF00");

Plugin functions

openUrl(url)

Attempts to open a connection to a specified URL. E.g. openUrl("tel:0840123456") attempts to make a telephone call. openUrl("http://example.com") will attempt to open the browser.

The function returns:

  • "0" if the connection could be opened.
  • "1" if the connection type isn't supported
  • "2" if some error prevented the connection being opened.
RAMP.callFunction('openUrl', 'http://virtualmobiletech.com');

 

WebView JavaScript Support

Performing RAMP actions from JavaScript in HTML

The WebView UXML component supports the performing of RAMP actions from JavaScript in the HTML document it is rendering. This functionality is only possible when the WebView's property jscallenabled is set to "true" (default is "false").

To perform a RAMP action from within JavaScript, call the Ramp.execute(action, param, callback) function. The param and callback parameters are optional.

The action parameter is the RAMP action to perform, which is either the name of a UXML component to navigate to, or a RAMP function to call. To indicate it is a RAMP function it must end with open and close parentheses (e.g. "function1()"). 

The param parameter is a String that gets passed to the RAMP function as a parameter.

The callback parameter is the name of the HTML JavaScript callback function which will be called when the RAMP function finishes executing. It will be called with a single parameter set to the return value of the RAMP function.

If RAMP actions need to be performed within the HTML JavaScript that is executed during the web page loading, the calls to Ramp.execute() should be placed in a function named rampOnReady() within the JavaScript. This ensures that the WebView is ready to accept calls to Ramp.execute().

Calling HTML JavaScript functions from RAMP

The WebView UXML component also supports calling HTML JavaScript functions from RAMP. To do this, the following RAMP function can be used:

webViewInvoke(webViewId, functionName, parameters)

Invokes a WebView's HTML JavaScript function with any number of parameters.

parameters is a list of parameters for functionName.

Example

The example below demonstrates the use of the bidirectional RAMP-JavaScript interaction just described.

When the WebView has loaded, the rampOnReady() HTML JavaScript function is executed, which calls the RAMP appendRandom() function, with the parameter "abc". The appendRandom() function appends a random value to the parameter passed in and returns the result. The appendRandomCallback() HTML JavaScript function is then called with this returned value as its parameter and sets the "h1" heading to this value.

Clicking on the button within the WebView navigates to the RAMP login form.

Clicking on the RAMP smart button invokes the HTML JavaScript function with 2 parameters. The first is the callback function it wishes to be called by the HTML JavaScript and the second is a JSON string. The func() HTML JavaScript function parses the JSON string, setting the "h2" heading text to the concatenation of the map's "key1" and "key2" values, then calls the RAMP setButtonText() callback function with the map's "key1" value.

 

WebView HTML
<!DOCTYPE html>
<html>
	<head>
		<title> Example </title>
		<script type="application/javascript">
			// Special function that gets called when the WebView is ready for JavaScript
			// to execute RAMP actions
			function rampOnReady()
			{
				Ramp.execute("appendRandom()", "abc", "appendRandomCallback");
			}

			// Called when the RAMP appendRandom() function is completed. The
			// param is the value returned by the appendRandom() function.
			function appendRandomCallback(param)
			{
				document.getElementById("h1").innerHTML = param;
			}

			// Using Ramp.execute to navigate to a new form.
			function login()
			{ 
				Ramp.execute("login");
			}

			// A function that is called from RAMP
			function func(callback, json)
			{
				var map = JSON.parse(json);

				document.getElementById("h2").innerHTML = map["key1"] + map["key2"];

				Ramp.execute(callback, map["key1"]);
			}
		</script>  
	</head>
	<body> 
		<h3>The value below gets set by the appendRandomCallback() JavaScript function on page load:</h3>
		<h4 id="h1">value</h4>
		<h3>The value below gets set by the func() JavaScript function which is called when the RAMP button is pressed:</h3>
		<h4 id="h2">value</h4>

		<button type="button" onclick="login();">Login</button>
	</body>
</html>
RAMP main.js
function main()
{
	RAMP.gotoForm("form");
}

function appendRandom(value)
{
	return value + RAMP.randomInteger(0, 1000000);
}

function buttonClick()
{
	RAMP.webViewInvoke("webscript.webview", "func", ["setButtonText()", '{"key1":"value1", "key2":"value2"}']);
}

function setButtonText(text)
{
	RAMP.uxmlSet("button1.text", text);
	RAMP.gotoForm("form");
}
webscript form UXML
<SmartForm id="webscript" stylename="formstyle" backkey="exit()"
		xmlns="http://virtualmobiletech.com/ramp/uxml"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://virtualmobiletech.com/ramp/uxml http://resources.virtualmobiletech.com/rampide/uxml_smart_4.4.0.xsd"> 
    <VerticalLayout expand="true">
        <NavigationBar text="WebView + HTML Javascript" stylename="navbarstyle">
        </NavigationBar>
        <VerticalScrollView expand="true">
            <SmartButton id="button1" text="Click" click="buttonClick()"/>
            <WebView id="webview" url="http://www.example.com/index.html" jscallenabled="true"/>
        </VerticalScrollView>
    </VerticalLayout>
</SmartForm>

 

 

  • No labels