Skip to end of metadata
Go to start of metadata

RAMPScript

RAMPScript is the scripting language compiled for the RAMP mobile client.

Syntax

RAMPScript is a dynamically-typed procedural language that resembles C syntactically; however its syntax should also be comfortable for people coming from a JavaScript or any C/C++-like language.

Variables

RAMPScript is a dynamically-typed language; however variables can be crudely regarded as containing int values, Strings or Collections. Float values are also supported on smart phones. A variable can have one of four scopes:

  • Function (a.k.a local) scope which are visible only within a function.
  • Global scope where variables are visible to all functions.
  • Persistent scope. Persistent variables retain their values even after closing a Ramp application.
  • UXML scope; these are variables that are used to read or update values in UXML components (e.g. they can be used to set the text in a TextField or to read the value of a selected Menu item).

Local variables are identified by a name that starts with an upper or lower case letter. Subsequent valid characters in the variable name are letters, digits and the underscore character. Examples of valid local variable names are x, pi, a3 and a_b.

Global variable names start with a '@' and subsequent characters must conform to a valid local variable name. Valid global variable names are @b, @ab3 and @b_3. The following are not valid names: @, @3 or @a@.

Persistent variable names start with a '#' and subsequent characters must conform to a valid local variable name. Valid persistent variable names are #b, #b1, #c_.

UXML variables are identified by a UXML identifier followed by a '.' followed by a UXML attribute. For example if l1 is a label, the l1.text references the text field of the label; the presence of a dot in a variable name identifies it as a UXML variable. For example, l1.text = "Hello, world!" is a valid assignment. Note that some UXML attributes contain hyphens. Unfortunately the hyphen character is interpreted as the arithmetic subtract operation so hyphens must be omitted in UXML assignments. If textstyle is a UXML style element, then textstyle.focusedfontcolor = "0x0000FF" is a valid assignment; textstyle.focused-font-color = "0x0000FF" is invalid.

The Assignment Operator

The operator to assign a value to a variable is '='.

E.g. x = 3 or x = "3" assigns the String "3" to the variable x. Note that integer values like 3 or 5 or -7 are equivalent to the Strings "3", "5" and "-7", and on smart phones float values like 3.0 or -5.5 are equivalent to the Strings "3.0" and "-5.5".

To assign a non-ASCII character to a value in a String, use the escape sequence "\uXXXX" where XXXX denotes 4 hexadecimal digits. E.g. x = "\u00A9 VMT" assigns the value "© VMT" to the variable x.

Mathematical operators

The following operators are supported:

  • + Addition
  • - Subtraction
  • * Multiplication
  • / Division
  • % Modular Reduction

Note that, unlike Java, + always denotes addition. Use the strCat function or the ++ operator for String concatenation. The assignment x = "3" + "5" assigns "8" to x (as does x = 3 + 5). If you want to concatenate the Strings "3" and "5", use x = "3" ++ "5".

The ++ operator for String concatenation is supported since 3.7

RAMPScript does not support the unary pre- and post-increment/decrement operators (++ and --). In fact, the operator ++ is a binary operator used for string concatenation.

The following assigment operations are supported with the mathematical operators

  • +=; e.g. x = x + 3 is equivalent to x += 3
  • -=
  • *=
  • /=
  • %=

String concatenation operator

The operator ++ is used to concatenate strings.

For example, x = "hello," ++ " world" assigns "hello, world" to the variable x. Similarly x = 3 ++ 5 assigns the value "35" to x (as does x = "3" ++ "5" or x = 3 ++ "5" or x = "35" ++ "").

The following assignment operator is also supported:

  • ++=; e.g. s = s ++ "!" is equivalent to s ++= "!".

Conditional statements

RAMPScript supports if and if-else constructs. The following comparison operations can be used to create boolean expressions:

  • == Equal
  • != Not Equal
  • > Greater Than
  • < Less Than
  • >= Greater Than or Equal
  • <= Less Than or Equal

Boolean expressions can be combined using the logical and (&&) and logical or (||) operations. && has precedence over ||.

Example:

Conditionals
if (((x%2)==1) && (x > 0))
  form1.label1 = "x is a positive, odd integer";
else if (x > 0)
  form1.label1 = "x is a positive, even integer";
else
  form1.label1 = "x is negative";

Loop Constructs

RAMPScript supports "while" and two forms of "for" loops.

Example 1
binaryString = "";
while (x > 0)
{
  binaryString = (x % 2) ++ binaryString;
  x = x / 2;
}
Example 2
sum = 0;
for (i = 0; i < 1000; i=i+1)
{
  sum = sum + i;
}
Example 2 equivalent
sum = 0;
for (i = 0; i < 1000; i+=1)
{
  sum += i;
}
Example 3: RAMPScript supports a form of "for" loop that iterates over the elements of a List.
names = List("vmt", "app1", "app2");
for (name : names)
{
//
// Do something with the name variable
//
}

Functions

A RAMPScript program is a collection of functions.

Functions are declared JavaScript-style:

function addValues(x, y)
{
  return x + y;
}

Note that the function does not declare a return type.

Special Functions

A RAMPScript application should implement a main and an error function. The error function is the most important.

main()

If a RAMPScript application has a main function, it will be executed immediately after loading an application. The main function should specify which UI component to display (using the goto() function) but should also do initialisation of forms (e.g. populate a user's login name on a login form after reading it from a persistent variable).

error(errorMsg)

If an error occurs while executing a RAMPScript, the RAMP virtual machine will invoke the error function with a 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.

Built-in Functions

Collections Functions

List()

Returns an empty List in which elements can be accessed via a numeric index. This is similar to a Java Vector or an array.

An overloaded List function also exists that populates the List with the specified values. E.g. x = List(1,"two") assigns a List to x so that x contains two entries (1 and "two").

Map()

Returns a Map in which elements can be accessed via a key which is a String. This is similar to a Java Map or an associative array.

An overloaded Map function also exists that populates the Map with the specified (key, value) pairs. E.g. x = Map("name","ramp", "age", 5) assigns a Map to x so that x contains two keys ("name" and "age") and two associated values ("ramp" and 5).

Note that the Map function always takes an even number of arguments. Invoking it with an odd number of arguments will generate a compiler error.

listPut(list, index, value)

Inserts a value into a List at a specified index. The index must be non-negative and not greater than the size of the List.

listAdd(list, value)

Appends a value to a List. This is equivalent to listPut(list, listSize(list), value).

mapPut(map, key, value)

Inserts an value into a Map where the key is mapped to the value.

listGet(list, index)

Retrieves a value from a List at a specified index.

mapGet(map, key)

Retrieves a value from a Map associated with the specified key. If the key is not in the Map, the empty String is returned.

mapKeys(map)

Returns a List that contains all the keys of the specified Map.

listDelete(list, index)

Deletes the element in a List at the specified index. The size of the list is reduced by 1.

mapDelete(map, key)

Deletes the element in a Map associated with the specified key.

listSize(list)

Returns the number of elements in a list.

mapSize(map)

Returns the number of key/value pairs in a specified map.

listSort(list) (since 4.5.0)

Returns a sorted list of strings in ascending order using a Unicode ordinal lexicographic comparison.

listSortNumeric(list) (since 4.5.0)

Returns a sorted list of numbers (int or float) in ascending order.

listReverse(list) (since 4.5.0)

Returns a reversed list.

String Functions

strLen(string)

Returns the number of characters in a string.

strCat(string1, string2)

This function is deprecated; your code will be more readable if you use the ++ operator.

Concatenates two strings. The function returns the value string1 || string2 where || denotes concatenation. string1 and string2 are left unchanged.

strSub(string, startIndex, endIndex)

Returns the substring of a string, starting at the the specified start index (inclusive) and ending at the specified end index (exclusive). The end index must be greater than or equal to the start index. Neither index must be greater than the length of the string.

strToChars(string)

Returns a list where each entry in the list corresponds to a character in the string. The characters returned are encoded in unicode.

strFromChars(list)

Constructs a string from a list of characters.

strIsNumeric(string)

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

strUpper(string) (since 4.5.0)

Returns an uppercase version of the specified string.

strLower(string) (since 4.5.0)

Returns a lowercase version of the specified string.

strIndexOf(string, searchString) (since 4.5.0)

Returns the index of searchString within string, or -1 if not found.

strTrim(string) (since 4.5.0)

Returns a version of the string where all leading and trailing white-space characters have been removed.

strCharAt(string, index) (since 4.5.0)

Returns a string of length 1 containing the character within the specified string at the specified index.

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, webService("foo", "firstname", "vmt") invokes the foo service with a single parameter pair. Similarly webService("foobar", "firstname", "vmt", "age", "5") invokes the foobar service with two parameters. The order of parameters is insignificant. e.g. we could invoke the foobar service as webService("foobar", "age", "5", "firstname", "vmt"). Note that the webService function always takes an odd number of arguments. Invoking it with an even number of arguments will generate a compiler error. The corresponding RAMP handler should implement ServiceRequestHandler.

webServiceSecure(serviceName, {parameterKey, parameterValue}*) (since 4.5.0)

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, webServiceAsync("foo", "fooCallback", "firstname", "vmt") invokes the foo service asynchronously.

Note that the webServiceAsync function always takes an even number of arguments and at least two arguments. Invoking it with an odd number or zero arguments will generate a compiler error.

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}*) (since 4.5.0)

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

webServiceSecureSetKey(keyId) (since 4.5.0)

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

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 also exits from the RAMP script, any instructions after this call will be ignored.

back()

Navigates away from the currently displayed UI component to display the previous component. This command also exits from the RAMP script, any instructions after this call will be ignored.

goto(componentName)

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

Set focus function

setFocus(componentName) (since 3.7.1)

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

...
setFocus("form1.textinput1");
goto("form1");
...

Cryptographic functions

wssRandomKey()

Returns a 16 byte random TDES key.

wssTransportKey(publicKeyId, symmetricKey)

Encrypts a symmetric key using a key with a specified identifier. The public key must have been installed with the RAMP client.

wssUnwrapKeys(kek, keys)

Unwraps one or more encrypted triple DES keys using a TDES key encrypting key (kek). The encrypted keys must be in a Map. The function returns a map where the keys are the same as in the original map but the values are now the cleartext key values. The use of a map allows this function to unwrap more than one key in a single function call.

The key wrapping algorithm used is the Triple-DES key wrap algorithm specified in the XML Encryption standard.

wssVerifySignature(publicKeyId, list, data, signature)

Verifies a PKCS#1, v1.5 signature signed using the specified public key. The public key must have been installed with the RAMP client.

The data is a Map containing (key, value) pairs. The list contains the keys of the Map in the order in which the data to be signed was supplied to the signing algorithm. The signature contains the signature associated with the data. This method does not return a value. It reports an error if the signature is wrong or cannot be verified.

wssSha1(data) (Since 4.4.0)

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.

wssEncrypt(key, data)

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

wssDecrypt(key, data)

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

eaxInit(key)

EAX is a NIST approved mode for block ciphers that provides encryption and authentication with a single key. VMT recommends using this mode for encrypting data between client and server since it is conceptually simple and provably secure.

The key is a double-length, triple-DES key.

eaxEncrypt(data)

This function uses triple-DES in EAX mode to encrypt and MAC data. The EAX mode must have been initialised with a call to eaxInit.

eaxDecrypt(data, nonce)

This function uses triple-DES in EAX mode to authenticate and decrypt ciphertext (data). The nonce is a number-used-once that the server must supply with the encrypted data.

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

random(min, max)

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

Event Handlers/Callback Functions

Event handlers allow a RAMPScript application to "listen" for specific events. If an event occurs, a callback function will be invoked.

See also the webServiceAsync function.

Error handlers

errorSetHandler(cbFunction, type)

A RAMPScript 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 cbFunction 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

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, RAMPScript provides various timer functions.

timerStartTask(cbFunction, delay)

The timerStartTask(cbFunction, 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,

timerStartTask
@task = timerStartTask("foo", "60000");

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

The function "foo" could be implemented as

function foo(time)
{
  l1.text = time / 60000 ++ " minutes have elapsed";
}

The time passed to the function "foo" is the time (in milliseconds) since the RAMP application started running (not since the timer was started). You don't have to implement your callback function to use the time. For example, the function below would also work

function foo()
{
  webServiceAsync("getSharePrice", "updateShareTickerFunc", "nasdaqCode", "MSFT");
}
timerStopTask(task)

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

function foo(time)
{
    if (time > 36000000) {
         timerStopTask(@task);
    } else {
         l1.text = time / 60000 ++ " minutes have elapsed";
    }
}
timerGetTime()

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

timerGetDeviceTime() (since 4.4.0)

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

Dynamic UXML

RAMPScript allows UXML elements to be accessed simply as UXML variables. However, sometimes it's necessary to perform the same operation on a number of UXML elements (e.g. changing the style name for several related components. Also, sometimes, one needs to create a form where the number of items (labels and text inputs) cannot be specified statically. RAMPScript provides methods for accessing and creating UXML elements dynamically.

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 (i = 1; i <= 30; i=i+1) {
  attr = "label" ++ i ++ ".stylename";
  uxmlSet(attr, "largeFontStyle");
}

could be used to change the styles of 30 labels with far less code than explicit assignments.

uxmlGet(key)

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

uxmlNewNode(type, id, attrs)

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.

attrs is a Map of (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:

attrs = Map("label", "Exit", "click", "exit()");
button = uxmlNewNode("button", "b1", attrs);

uxmlNewNode(type, id, attrs, 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 Map of (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:

attrs = Map("label", "My form heading", "stylename", "headstyle");
formheading = uxmlNewNode("formheading", "fh1", attrs);

attrs = Map("label", "Exit", "click", "exit()");
button = uxmlNewNode("button", "b1", attrs);

childNodes = List(formheading, button);

attrs = Map("stylename", "formstyle");

form = uxmlNewNode("form", "f1", attrs, childNodes);

After creating a UXML element dynamically it can be accessed in the usual ways; e.g. goto("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 map must be created before the node can be instantiated. Convenience methods are provided that create the map 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) (since 3.7.1)

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}) (since 3.7.1)

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

uxmlHorizontalRule(id, stylename) (since 3.7.2)

Creates a Horizontal Rule with the specified id and styling.

uxmlTicker(id, text, stylename) (since 3.7.2)

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

uxmlNodeSupported(type) (since 4.4.0)

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

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

RAMP Platform Functions

funcSupported(functionname) (since 3.7)

Returns "1" if a specific RAMP VM plugin function is supported and "0" if it is not supported. e.g. funcSupported("vmt_takePicture") will return "1" on a VM that includes the VMT camera plugin and "0" on a VM that doesn't.

rampGetVersion()

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

rampDirectInput()

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

rampGetProperty(key)

Returns the property value referenced by the specified key.

A list of useful keys.

rampSetProperty(key, value)

Sets the value of a property that is referenced by the specified key.

A list of useful keys.

rampIsMidp2()

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

rampGetVar(name)

Used to retrieve the value of a RAMP variable. Currently, only persistent variables are supported. Example usage: rampGetVar("#password").

rampSetVar(name, value)

Used to set the value of a RAMP variable. Currently, only persistent variables are supported. Example usage: rampSetVar("#password", "abc123").

List of RAMP properties

Each key listed references a RAMP property. The property value can be retrieved by passing the listed key to the RAMP script function rampGetProperty(key). Some of these properties can also be modified with the RAMP script function rampSetProperty(key).

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.

Device Functions

The device functions are only supported on smart phones.

getDeviceOrientation() (since 4.2.0)

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

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 methods are available as RAMPScript functions and have the canvas prefix, followed by the name of the corresponding method.

Canvas functions available in RAMPScript, but not found in HTML5 do not have the canvas prefix.

Non-HTML5 Functions

setWorkingContext(canvasContextId)

This function needs to be called before any of the canvas prefixed functions are called. It indicates to which CanvasContext component the function calls should apply.

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.

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.

Canvas State Functions

canvasSave()

Pushes the current CanvasContext state onto the stack.

canvasRestore()

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

Transformation Functions

canvasScale(x, y)

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

canvasRotate(angle)

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

canvasTranslate(x, y)

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

canvasTransform(a, b, c, d, e, f)

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

canvasSetTransform(a, b, c, d, e, f)

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

Style Functions

canvasCreateLinearGradient(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.

canvasCreateRadialGradient(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.

canvasCreatePattern(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.

gradientAddColorStop(gradient, offset, color)

This function 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 argument must be one created using either the canvasCreateLinearGradient or the canvasCreateRadialGradient function.

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.

Simple Shape Functions

canvasClearRect(x, y, w, h)

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

canvasFillRect(x, y, w, h)

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

canvasStrokeRect(x, y, w, h)

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

Path Functions

canvasBeginPath()

Resets the current path.

canvasMoveTo(x, y)

Creates a new subpath with the given point.

canvasClosePath()

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.

canvasLineTo(x, y)

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

canvasQuadraticCurveTo(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.

canvasBezierCurveTo(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.

canvasArcTo(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.

canvasArc(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.

canvasRect(x, y, w, h)

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

canvasFill()

Fills the subpaths with the current fill style.

canvasStroke()

Strokes the subpaths with the current stroke style.

canvasClip()

Further constrains the clipping region to the given path.

canvasIsPointInPath(x, y)

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

Text Functions

canvasFillText(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.

canvasStrokeText(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.

canvasMeasureText(text)

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

Image Functions

canvasDrawImage(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.

canvasDrawImage(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.

canvasDrawImage(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.

Pixel Manipulation Functions

canvasCreateImageData(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.

canvasGetImageData(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.

canvasPutImageData(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.

WebView JavaScript Support

Performing RAMP actions from JavaScript

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 RAMPScript action to perform, which is either the name of a UXML component to navigate to, or a RAMPScript function to call. To indicate it is a RAMPScript function it must end with open and close parentheses (e.g. "function1()"). 

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

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

If RAMP actions need to be performed within the 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 JavaScript functions from RAMPScript

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

webViewInvoke(webViewId, functionName {, parameter}*)

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

Example

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

When the WebView has loaded, the rampOnReady() JavaScript function is executed, which calls the RAMPScript appendRandom() function, with the parameter "abc". The appendRandom() function appends a random value to the parameter passed in and returns the result. The appendRandomCallback() 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 func JavaScript function with 2 parameters. The first is the callback function it wishes to be called by the JavaScript and the second is a JSON string. The func() 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 RAMPScript 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 RAMPScript 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 RAMPScript 
			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>
RAMPScript
function main()
{
	goto("form");
}

function appendRandom(value)
{
	return value ++ random(0, 1000000);
}

function buttonClick()
{
	webViewInvoke("webview", "func", "setButtonText()", "{\"key1\":\"value1\", \"key2\":\"value2\"}");
}

function setButtonText(text)
{
	button1.text = text;
	goto("form");
}
form UXML
<SmartForm id="form" stylename="" 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">
		<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