MIDletPascal Language Reference

Repositories

The open-source compiler and IDEs behind MIDletPascal.


Overview

MIDletPascal is a small Pascal dialect that compiles straight to a runnable J2ME .jar. This page is the complete language — its syntax, its types, and every one of its built-in procedures and functions — checked line-for-line against the mp3cc compiler that actually builds your code.

It turns a familiar-looking Pascal program into a J2ME MIDlet: you write .pas source, the compiler translates it to Java bytecode and packs it into a .jar that runs on any MIDP phone or emulator.

The language is deliberately small. It keeps the shape of Pascal — program, begin/end, procedure, function, the usual control flow — but drops much of the machinery of full Pascal so that the whole compiler and runtime fit on a feature phone. Drawing, forms, sound, storage and networking are exposed as built-in routines rather than library imports, so most programs need no uses clause at all.

A few things to keep in mind before reading on:

  • The language is case-insensitive for keywords and identifiers — Begin, begin and BEGIN are the same.
  • Drawing does not go to the screen directly. Graphics routines paint an off-screen buffer; the buffer reaches the display only when you call Repaint.
  • Strings are a primitive type, not arrays of characters, and the first character is at index 0.
  • Every routine on this page was verified against the mp3cc compiler. Where the original 2005 manual and the compiler disagree, the compiler wins — the unavailable badge marks the 4 documented routines this build does not actually accept.
How a build works. The compiler emits M.class (your program) plus any unit and record classes. Whenever your code calls into forms, real numbers, storage, HTTP, sound or SMS, the compiler notes that a runtime helper class is needed — FS, F/Real, RS, H, P or SM. Those classes, and always FW.class, are added to the JAR. The needs X badge on a routine tells you which class it pulls in.

Program structure

A program is a header, an optional set of declarations, and a main body.

program programName;

  { constant declarations }
  { type declarations }
  { variable declarations }
  { procedure and function declarations }

begin
  { statements }
end.

The program header is optional in practice, but conventional. Declarations may appear in any order and may be repeated. Execution starts at the main begin … end. block — note the trailing period, which marks the end of the program.

Comments

Four comment styles are accepted. The first two are standard Pascal; the last two are extensions of the mp3cc port:

{ curly-brace comment }
(* parenthesis-star comment *)
// line comment, to end of line          (extension)
/* C-style block comment */              (extension)
No compiler directives. Unlike some Pascals, {$R+} /{$V+}-style switches inside braces are ignored here. Real-number mode and canvas type are chosen by the build, not by the source.

Data types

Ten built-in types, split into simple values and complex aggregates.

TypeKindDescription
booleansimpletrue or false. Operators: =, <>, and, or, xor, not.
charsimpleA single character. Comparable, and + concatenates two chars into a string. Use ord/chr to convert to and from the ASCII code.
integersimple32-bit signed, roughly ±2,147,483,647. Operators include div, mod, shl, shr.
realsimpleNon-integer numbers, emulated in software (see Real numbers). Slower and larger than integers.
stringsimpleA sequence of characters — a primitive, not an array. First char is at index 0. + appends a string, integer, char or boolean.
imagesimple*A bitmap, produced by LoadImage and the ImageFrom… functions.
commandsimple*A soft-key button, created with CreateCommand and read via GetClickedCommand.
recordStoresimple*A handle to persistent storage (the RMS). See the Record Store routines.
httpsimple*An HTTP connection handle. See Http Connectivity.
resourcesimple*A read stream over a file bundled in the JAR. See Resource Files.
recordcomplexA user-defined struct of named fields (below).
arraycomplexA fixed, multi-dimensional array with explicit index ranges (below).

* handle types: you receive and pass them around, but never inspect their internals.

record

A record groups several fields under one type. Access fields with .:

type heroType = record
  positionX, positionY: integer;
  health: integer;
end;

var hero: heroType;
begin
  hero.positionX := hero.positionX + 1;
end.
Records cannot be copied whole. a := b; on two record variables is rejected — assign field by field (a.x := b.x;). Arrays inside records are also not supported.

array

Arrays are declared with explicit low/high bounds per dimension, and any number of dimensions:

type chessFieldType = array[1..8, 1..8] of integer;
var chessField: chessFieldType;

// or inline:
var field: array[1..15] of integer;
No bounds checking. Reading or writing outside the declared range (e.g. a[7] in an array[1..5]) crashes the MIDlet at runtime. You also cannot assign a value to a whole array — only to its elements.

Declarations

Constants, types and variables are introduced with const, type and var blocks.

const
  minutesInHour = 60;
  famousQuote   = 'To be or not to be';

type
  number = integer;
  point  = record x, y: integer; end;

var
  index: integer;
  field: array[1..15] of integer;
  p:     point;

A const binds a fixed value to a name. A type block names new types — aliases, records or arrays. A var block declares variables, which may use a named type or an inline type. Variables declared at program level are global and visible inside every procedure and function.


Statements

Assignment, procedure calls, and a compact set of control-flow constructs. Where a construct takes a body, a single statement needs no begin/end; several statements do.

Assignment

variable := expression;

for … to / downto … do

for i := 1 to 10 do
begin
  sum := sum + i;
end;

for i := 10 downto 1 do  drawText(integerToString(i), 0, i*10);

while … do

while (getKeyClicked = KE_NONE) do
  delay(100);

repeat … until (and the forever extension)

repeat
  delay(100);
until (getKeyClicked <> KE_NONE);

repeat
  tick;
forever;                 { mp3cc extension: an intentional infinite loop }

if … then … else

if condition then
begin
  { runs when condition is true }
end
else
begin
  { runs when condition is false }
end;

The else branch is optional.

break

Exits the innermost for, while or repeat loop. Using break outside a loop is a compile error.

repeat
  for i := 1 to 10 do
    if doSomething(i) = -1 then break;   { leaves the for loop }
until getClickedCommand <> emptyCommand;
Not supported. The case … of statement, the with statement, sets, files and enumerated types are all recognised by the parser only so it can reject them with a clear error. There is no case in MIDletPascal — use a chain of if … else if instead.

Procedures & functions

A procedure returns nothing; a function returns a value by assigning to its own name (or to result).

procedure twoArgs(a: integer; b: string);
var len: integer;          { local — re-created on every call }
begin
  len := length(b);
  n := a + len;            { n is a global }
end;

function multiply(a, b: integer): integer;
begin
  multiply := a * b;       { classic Pascal: assign to the function name }
end;

function square(x: integer): integer;
begin
  result := x * x;         { mp3cc extension: the result keyword }
end;

Recursion

Functions and procedures may call themselves.

function factorial(n: integer): integer;
begin
  if n = 1 then
    factorial := 1
  else
    factorial := n * factorial(n - 1);
end;

forward declarations

If two routines call each other, declare one forward so it is visible before its body appears:

procedure b(y: integer); forward;

procedure a(x: integer);
begin  b(x);  end;

procedure b(y: integer);
begin  a(y);  end;
Differences from standard Pascal.
  • Procedures and functions cannot be nested — one may not be declared inside another.
  • No var parameters. Every parameter is passed by value; a var keyword in a parameter list is ignored with a warning.
  • The exit keyword (an extension) returns early from a routine — or acts like Halt in the main block.

Units & libraries

Split a program across files with units, or reach into raw MIDP API that MIDletPascal doesn't wrap by writing a library unit in Java.

Pascal units

A unit is compiled separately and pulled in with uses:

uses mymath, ui;

// resolve a name defined in two units:
mymath.square(5);

A MIDletPascal unit has the familiar unit / interface / implementation shape. The initialization section runs at startup; a finalization section is not supported. Unit names must be at least two characters.

Library units (Java)

When you need a MIDP API call that the language does not expose, write a library unit in Java. It compiles to a Lib_<name>.class that the compiler reads directly, so you can call Java from Pascal.

Rules for a library unit.
  • The class must not be in any package, and the name must be Lib_ followed by an all-lowercase name (Java is case-sensitive — Pascal is not).
  • Every exported member must be public static.
  • Parameters and return values may only be: int String Image Command RecordStore InputStream (and void return). Anything else is rejected.
  • Library units hold functions and procedures only — no types, no variables.
  • The compiled class goes in the global Libs directory (or the project's own library directory, which is searched first).
// Lib_mylib.java  — compiled & preverified with the WTK, then dropped in Libs/
public class Lib_mylib {
  public static int square(int val) {
    return val * val;
  }
}
uses mylib;
var idx: integer;
begin
  showForm;
  idx := formAddString('5 squared is: ' + mylib.square(5));
  delay(5000);
end.

To reach the current Display (for vibrate, backlight, and the like) a library unit can also ship its own FW.java that exposes the live MIDlet object — see the original manual's Advanced features chapter. Always wrap MIDP 2.0-only calls in a try/catch so MIDP 1.0 phones don't crash.


Operators

Arithmetic, comparison, boolean and bitwise operators, plus a couple of mp3cc additions.

GroupOperatorsNotes
Arithmetic+   -   *   /On integers, / is the same as div (integer division).
Integer divisiondiv   modmod is the remainder of integer division.
Comparison=   <>   <   >   <=   >=String comparison with =/<> is case-sensitive.
Booleanand   or   xor   notnot binds tightest; =, <, > bind loosest.
Bitwise shiftshl   shr   ushrAlso written <<, >>, >>>. ushr is an unsigned right shift (extension).
Concatenation+A string + a string / integer / char / boolean yields a string.
String / char index[ ]Index a string with an integer (0-based) — see GetChar.
Literals. Integers may be written in hex with a leading $ ($FF00). Characters can be given by code with # (#65 or #$41). Strings use single quotes; a doubled quote ('') is an embedded quote. The port also accepts C-style double-quoted strings.

Real numbers

Phones have no floating-point unit, so real arithmetic is emulated — it is slow and inflates the JAR. Two implementations are available, chosen by the build, not the source.

Fixed-point  ·  F.class  ·  default
Fast and compact. Low precision (a fixed number of fractional bits). Selected with mp3cc -m1. Pulls in F.class.
Floating-point  ·  Real.class
Much more precise, but slower and adds several KB to the JAR. Selected with mp3cc -m2. Pulls in Real.class and Real$NumberFormat.class.

Roughly twenty math routines (see the Math category) plus the predefined constant pi operate on reals. Any routine that touches a real value is marked needs F / Real.


Compiler extensions

The mp3cc port (MIDletPascal 3.5) adds a handful of features on top of the original 3.x language.

  • Inline bytecode. A bytecode … end block (or the deprecated inline(…)) lets you write raw JVM opcodes, with labels, straight into a routine — an escape hatch for hand-tuned code.
  • exit and result. exit returns early from a routine (or halts in the main block); result is an alias for the function's return value.
  • forever. Terminates a repeat loop as an explicit infinite loop.
  • ushr / >>>. Unsigned right shift.
  • Extra literal & comment syntax. C-style // and /* */ comments, $ hex integers, # character codes, and double-quoted strings.
A silent build failure to know about. If the compiler process is killed (a bad argument, or a binary that doesn't match the device), it can exit without producing M.class. A JAR that contains only FW.class is not a working build — a real toolchain checks that M.class exists and that the exit code is the compiler's own error count.

Built-in routines

Function & procedure reference

Every built-in routine, grouped by area. Each card shows the signature the compiler accepts, which runtime class it needs, and — where the manual provided one — an example. Use the search box to filter by name.

Drawing

31

procedureDrawArc

Drawing
procedure DrawArc(x, y, width, height, startAngle, arcAngle: integer);

Draws the arc covering the specified rectangle. The arc starts at 'startAngle' and extends for 'arcAngle' degrees. The angle of 0° degrees is at 3 o'clock position. The angle of 90° is at 12 o'clock position.

Example
begin
   DrawArc(0, 0, GetWidth, GetHeight, 0, 90);
   Repaint;
   Delay(1000);
end.
See also GetWidth · GetHeight · Repaint

procedureDrawEllipse

Drawing
procedure DrawEllipse(x, y, width, height: integer);

Draws the outline of an ellipse covering the specified rectangle.

Example
begin
   DrawEllipse(0, 0, GetWidth, GetHeight);
   Repaint;
   Delay(1000);
end.

procedureDrawImage

Drawing
procedure DrawImage(img: image; x, y: integer);

Draws the image to the display buffer. The 'x' and 'y' coordinates are the coordinates where the upper left corner of the image will be placed.

Example
begin
   DrawImage(LoadImage('/logo.png'), 0, 0);
   Repaint;
   Delay(1000);
end.
See also LoadImage · Repaint

procedureDrawLine

Drawing
procedure DrawLine(x1, y1, x2, y2: integer);

Draws the line between the point ('x1', 'y1') and the point ('x2', 'y2').

Example
begin
    DrawLine(10, 15, 25, 35);
    Repaint;
    Delay(1000);
end.
See also SetColor · Repaint

procedureDrawRect

Drawing
procedure DrawRect(x, y, width, height: integer);

Draws the outline of the specified rectangle.

Example
begin
    DrawRect(5, 5, 20, 20);
    Repaint;
    Delay(1000);
end.
See also FillRect · SetColor · Repaint

procedureDrawRoundRect

Drawing
procedure DrawRoundRect(x, y, width, height, arcWidth, arcHeight: integer);

Draws the outline of the specified rounded corner rectangle.

Example
begin
    DrawRoundRect(5, 5, 20, 20, 2, 2);
    Repaint;
    Delay(1000);
end.

procedureDrawText

Drawing
procedure DrawText(text: string, xPos, yPos: integer);

Draws the text 'text' to the display buffer. The 'xPos' and 'yPos' are coordinates of the upper left corner of the text-bounding box.

Example
begin
    SetColor(255, 0, 0);
    DrawText('Hello world', 0, 0);
    Repaint;
    Delay(1000);
end.

procedureFillEllipse

Drawing
procedure FillEllipse(x, y, width, height: integer);

Fills the ellipse covering the specified rectangle.

Example
begin
    FillEllipse(0, 0, GetWidth, GetHeight);
    Repaint;
    Delay(1000);
end.

procedureFillRect

Drawing
procedure FillRect(x, y, width, height: integer);

Fills the specified rectangle.

Example
begin
    FillRect(5, 5, 20, 20);
    Repaint;
    Delay(1000);
end.
See also DrawRect · SetColor · Repaint

procedureFillRoundRect

Drawing
procedure FillRoundRect(x, y, width, height, arcWidth, arcHeight: integer);

Fills the specified rounded corner rectangle.

Example
begin
    FillRoundRect(5, 5, 20, 20, 2, 2);
    Repaint;
    Delay(1000);
end.

functionGetColorBlue

Drawing
function GetColorBlue: integer;

Returns the blue component value of the current color. function GetColorBlue: integer;

Example
begin
    SetColor(0, 0, 127);
    if GetColorBlue <> 127 then
    begin
      DrawText('This should never happen', 0, 0);
      Repaint;
    end;
    Delay(1000);
end.

functionGetColorGreen

Drawing
function GetColorGreen: integer;

Returns the green component value of the current color. function GetColorGreen: integer;

Example
begin
    SetColor(0, 127, 0);
    if GetColorGreen <> 0 then
    begin
      DrawText('This should never happen', 0, 0);
      Repaint;
    end;
    Delay(1000);
end.

functionGetColorRed

Drawing
function GetColorRed: integer;

Returns the red component value of the current color. function GetColorRed: integer;

Example
begin
    SetColor(127, 0, 0);
    if GetColorRed <> 127 then
    begin
      DrawText('This should never happen', 0, 0);
      Repaint;
    end;
    Delay(1000);
  end.

functionGetColorsNum

Drawing
function GetColorsNum:integer;

Returns the number of different colors that the device display can show. function GetColorsNum:integer;

functionGetHeight

Drawing
function GetHeight: integer;

Returns the height (in pixels) of the display area. function GetHeight: integer;

Example
begin
    DrawEllipse(0, 0, GetWidth, GetHeight);
    Repaint;
    Delay(1000);
end.
See also GetWidth

functionGetImageHeight

Drawing
function GetImageHeight(img: image): integer;

Returns the height of the given image in pixels.

functionGetImageWidth

Drawing
function getImageWidth(img: image): integer;

Returns the width of the given image in pixels.

Example
begin
   DrawEllipse(0, 0, GetWidth, GetHeight);
   Repaint;
   Delay(1000);
end.

functionGetStringHeight

Drawing
function GetStringHeight(text: string): integer;

Returns the height (in pixels) for showing the 'text' on display in the current font.

Example
var text: string;
    height: integer;
begin
    text   := 'Text to display';
    height := GetStringHeight(text);
    DrawText(text, 0, (GetHeight - height)/2);
    Repaint;
    Delay(1000);
end.

functionGetStringWidth

Drawing
function GetStringWidth(text: string): integer;

Returns the width (in pixels) for showing the 'text' on display in the current font.

Example
var text: string;
     width: integer;
begin
    text  := 'Text to display';
    width := GetStringWidth(text);
    DrawText(text, (GetWidth - width)/2, 0);
    Repaint;
    Delay(1000);
end.

functionGetWidth

Drawing
function GetWidth: integer;

Returns the width (in pixels) of the display area. function GetWidth: integer;

Example
begin
    DrawEllipse(0, 0, GetWidth, GetHeight);
    Repaint;
    Delay(1000);
  end.
See also GetHeight

functionImageFromBuffer

Drawingneeds S
function ImageFromBuffer(buffer: string; length: integer): image;

Decodes an image (PNG/JPEG) held in a string buffer — for example one read from a resource or received over HTTP — into an image value. Undocumented in the original manual but present in the compiler.

functionIsColorDisplay

Drawing
function IsColorDisplay:boolean;

Returns true if the device display can show colors; otherwise returns false. function IsColorDisplay:boolean;

See also GetColorsNum

functionLoadImage

Drawing
function LoadImage(resource: string): image

Loads the image from the resource and returns an 'image' object. To access the file inside the JAR archive (the file added as a resource into the MIDletPascal project), the 'resource' parameter must begin with '/' character. If the resource name is invalid, the application will fail.

Example
begin
    DrawImage(LoadImage('/icon.png'), 0, 0);
    Repaint;
    Delay(1000); { wait 1 second before the MIDlet terminates }
end.

procedurePlot

Drawing
procedure Plot(x, y:integer);

Sets the color of a single pixel to the current color.

Example
begin
    SetColor(255, 0, 0);
    Plot(5, 10);
    Repaint;
    Delay(1000);
end.
See also SetColor · Repaint

procedureRepaint

Drawing
procedure Repaint;

Repaints the device display. All drawing functions (such as drawLine, drawText, fillRect etc.) do not draw directly to the device display. The drawing functions draw to the off-screen buffer, and the procedure 'repaint' copies the off-screen buffer to the device display. The repainting is a time-consuming procedure so it should be called as rarely as possible. procedure Repaint;

Example
begin
    DrawText('Hello world', 0, 0);
    Repaint;
    Delay(1000);
end.

procedureSetClip

Drawing
procedure SetClip(int x, int y, int width, int height);

Sets the clipping area for the subsequent drawing operations. All drawing operations which take place outside of the clipping area rectangle will be ommited.

Example
begin
    // draw the ellipse
    SetColor(0, 0, 0);
    FillEllipse(0, 0, GetWidth, GetHeight);
    Repaint;
    Delay(2000);
    // draw ellipse again with setClip called before
    SetClip(10, 10, 15, 25);
    FillEllipse(0, 0, GetWidth, GetHeight);
    Repaint;
    Delay(2000);
end.

procedureSetColor

Drawing
procedure SetColor(red, green, blue:integer);

Set the color to be used for drawing all the subsequent graphical elements. The 'red', 'green' and 'blue' components can take values between 0 and 255. For example, the black color representation is (0, 0, 0), bright red is (255, 0, 0), and white is (255, 255, 255).

Example
begin
    SetColor(0, 0, 255); { set the color to bright blue }
    DrawText('Hello world', 0, 0);
    Repaint;
    Delay(1000);
end.

procedureSetDefaultFont

Drawing
procedure SetDefaultFont;

Sets the current font to the default font used on the device. Note that some devices use only one font, so calling setDefaultFont will have no effect on those devices. procedure SetDefaultFont;

See also SetFont

procedureSetFont

Drawing
procedure SetFont(fontFace, fontStyle, fontSize);

Sets the font to be used for displaying text. The 'fontFace' can be any of the following predefined constants:

  • FONT_FACE_SYSTEM
  • FONT_FACE_MONOSPACE
  • FONT_FACE_PROPORTIONAL

The 'fontStyle' can be any of the following predefined constants:

  • FONT_STYLE_PLAIN
  • FONT_STYLE_BOLD
  • FONT_STYLE_ITALIC
  • FONT_STYLE_UNDERLINE

These styles may be combined together using the logical operator or. For exaple, to create the font that is bold and underlined, use (FONT_STYLE_BOLD or FONT_STYLE_UNDERLINE) as the value for the font style. The font size can be any of the following predefined constants:

  • FONT_SIZE_SMALL
  • FONT_SIZE_MEDIUM
  • FONT_SIZE_LARGE

Note that some devices use only one font, so calling setFont will have no effect on those devices.

Example
begin
    SetFont(FONT_FACE_SYSTEM,
            FONT_STYLE_BOLD or FONT_STYLE_UNDERLINE,
            FONT_SIZE_LARGE);
    DrawText('Hello world', 0, 0);
    Repaint;
    Delay(1000);
end.

Keypad Access

3

functionGetKeyClicked

Keypad Access
function GetKeyClicked: integer;

Returns the code of the last clicked key on the keypad, or KE_NONE if no key is pressed. The standard key codes have predefined constant values:

  • KE_KEY0
  • KE_KEY1
  • KE_KEY2
  • KE_KEY3
  • KE_KEY4
  • KE_KEY5
  • KE_KEY6
  • KE_KEY7
  • KE_KEY8
  • KE_KEY9
  • KE_STAR
  • KE_POUND

function GetKeyClicked: integer;

Example
begin
    while GetKeyClicked <> KE_STAR do
    begin
      Delay(100);
    end;
end.

functionGetKeyPressed

Keypad Access
function GetKeyPressed: integer;

Returns the code of the key that is currently pressed, or KE_NONE if no key is pressed. The standard key codes have predefined constant values:

  • KE_KEY0
  • KE_KEY1
  • KE_KEY2
  • KE_KEY3
  • KE_KEY4
  • KE_KEY5
  • KE_KEY6
  • KE_KEY7
  • KE_KEY8
  • KE_KEY9
  • KE_STAR
  • KE_POUND

function GetKeyPressed: integer;

Example
begin
  while GetKeyPressed <> KE_STAR do
    begin
      Delay(100);
    end;
end.

functionKeyToAction

Keypad Access
function KeyToAction(keyCode: integer): integer;

getKeyClicked and getKeyPressed functions return the key code of the key pressed. However, different devices have different key mappings. For example, one device may have FIRE key return key code 100, and the other device may have its FIRE key return key code 120. To avoid this problem, you can use the keyToAction function that translates the key code into mapped game actions. keyToAction can return any of the following predefined values:

  • GA_NONE
  • GA_UP
  • GA_DOWN
  • GA_LEFT
  • GA_RIGHT
  • GA_FIRE
  • GA_GAMEA
  • GA_GAMEB
  • GA_GAMEC
  • GA_GAMED
Example
begin
  while KeyToAction(getKeyClicked) <> GA_FIRE do
    begin
      Delay(100);
    end;
end.

Date and Time

11

procedureDelay

Date and Time
procedure Delay(millis: integer);

Suspends the execution of a program for the given time in milliseconds. To display a message on to the screen, wait 2 seconds, and then close MIDlet, use the following code:

Example
begin
    DrawText('Hello world', 0, 0);
    Repaint;
    Delay(2000);
end.

functionGetCurrentTime

Date and Time
function GetCurrentTime: integer;

Returns the current time in seconds since midnight 1.1.1970. The returned value (the number of seconds) can be used as argument to call functions such as GetMonth or GetHour. function GetCurrentTime: integer;

Example
var time: integer;
      text: string;
begin
    time := GetCurrentTime;
    text := 'Current time is ' + GetHour(time);
    text := text + ':'+ GetMinute(time);
    text := text + ':' + GetSecond(time);
    DrawText(text, 0, 0);
    Repaint;
    Delay(1000); { wait 1 second before MIDlet terminates }
end.

functionGetDay

Date and Time
function GetDay(time: integer): integer;

Returns the day in the month for the given time (time is represented in seconds since 1.1.1970. and can be retrieved by calling GetCurrentTime function). The returned value is between 1 and 31.

functionGetHour

Date and Time
function GetHour(time: integer): integer;

Returns the hour for the given time (time is represented in seconds since midnight 1.1.1970 and can be retrieved by calling GetCurrentTime function). The returned value is between 0 and 23.

Example
var time: integer;
      text: string;
begin
    time := GetCurrentTime;
    text := 'Current time is ' + GetHour(time);
    text := text + ':' + GetMinute(time);
    text := text + ':' + GetSecond(time);
    DrawText(text, 0, 0);
    Repaint;
    Delay(1000); { wait 1 second before MIDlet terminates }
end.

functionGetMinute

Date and Time
function GetMinute(time: integer): integer;

Returns the minute for the given time (time is represented in seconds since midnight 1.1.1970 and can be retrieved by calling GetCurrentTime function). The returned value is between 0 and 59.

Example
var time: integer;
      text: string;
begin
    time := GetCurrentTime;
    text := 'Current time is ' + GetHour(time);
    text := text + ':' + GetMinute(time);
    text := text + ':' + GetSecond(time);
    DrawText(text, 0, 0);
    Repaint;
    Delay(1000); { wait 1 second before MIDlet terminates }
end.

functionGetMonth

Date and Time
function GetMonth(time: integer): integer;

Returns the month number for the given time (time is represented in seconds since 1.1.1970. and can be retrieved by calling GetCurrentTime function). The returned value is between 1 and 12.

functionGetRelativeTimeMs

Date and Time
function GetRelativeTimeMs: integer;

Return the current time in milliseconds. Note that the return value is 32-bit integer that can represent only 2^32 milliseconds, which is a little bit over 48 days. So every 48 days, this value is reset and starts counting from 0. Do not use this function to determine the current date, but it can be used for implementing timers in an application. Consider a simple game (such as Tetris, for example) that needs to move the block down each second. Also, the game should move the block left or right when the user presses the left/right key on the keypad. The main program loop could be implemented as follows: function GetRelativeTimeMs: integer;

Example
...
  lastSavedTime := GetRelativeTimeMs; { initialize the timer }
  repeat
    { read and process the keypad input }
    key := GetKeyClicked;
    if KeyToAction(key) = GA_LEFT then moveLeft;
    if KeyToAction(key) = GA_RIGHT then moveRight;
    { check if 1 second has passed }
    if ((GetRelativeTimeMs - lastSavedTime) > 1000)
      or (GetRelativeTimeMs < lastSavedTime)  { check if the timer is reset after 48 days }
      then
      begin
        lastSavedTime := GetRelativeTimeMs;
        moveDown;
      end;
  until gameOver;
...

functionGetSecond

Date and Time
function GetSecond(time: integer): integer;

Returns the second for the given time (time is represented in seconds since midnight 1.1.1970 and can be retrieved by calling GetCurrentTime function). The returned value is between 0 and 59.

Example
var time: integer;
      text: string;
begin
    time := GetCurrentTime;
    text := 'Current time is ' + GetHour(time);
    text := text + ':' + GetMinute(time);
    text := text + ':' + GetSecond(time);
    DrawText(text, 0, 0);
    Repaint;
    Delay(1000); { wait 1 second before MIDlet terminates }
end.

functionGetWeekDay

Date and Time
function GetWeekDay(time: integer): integer;

Returns the day in week for the given time (time is represented in seconds since 1.1.1970. and can be retrieved by calling GetCurrentTime function). Returned value is 1 for Sunday, 2 for Monday, etc (7 is Saturday).

functionGetYear

Date and Time
function GetYear(time: integer): integer;

Returns the year for the given time (time is represented in seconds since 1.1.1970. and can be retrieved by calling GetCurrentTime function).

functionGetYearDay

Date and Time
function GetYearDay(time: integer): integer;

Returns the day in year for the given time (time is represented in seconds since midnight 1.1.1970. and can be retrieved by calling GetCurrentTime function). Returned value is between 1 and 366.

Math

19

functionAbs

Math
function Abs(n: integer): integer;

Returns the absolute value of the given number.

functionAcos

Mathneeds F / Real
function Acos(num: real):real;

Returns the arc cosine of a number, in the range 0 to pi (in radians).

functionAsin

Mathneeds F / Real
function Asin(num: real):real;

Returns the arc sine of a number, in the range -pi/2 to the pi/2 (in radians).

functionAtan

Mathneeds F / Real
function Atan(num: real):real;

Returns the arc tangent, in the range from -pi/2 to pi/2 (represented in radians).

functionAtan2

Mathneeds F / Real
function Atan2(y,x: real):real;

Converts the rectangular coordinates (x,y) into polar coordinates (r, theta). This method computes the phase theta by computing an arc tangent of y/x in the range of -pi to pi.

functionCos

Mathneeds F / Real
function Cos(num: real):real;

Returns the cosine of the given number (represented in radians).

functionExp

Mathneeds F / Real
function Exp(num: real):real;

Returns the Euler's number 'e' raised to the value of 'num'.

functionFrac

Mathneeds F / Real
function Frac(num: real):real;

Returns the fraction of a number (the fraction of 1.234 is 0.234).

functionLog

Mathneeds F / Real
function Log(num: real):real;

Returns the natural logarithm of the given number.

functionLog10

Mathneeds F / Real
function Log10(num: real):real;

Returns the logarithm base 10 of the given number.

functionPow

Mathneeds F / Real
function Pow(a, b: real):real;

Returns the value of 'a' raised to the power of 'b'.

functionRabs

Mathneeds F / Real
function Rabs(num:real):real;

Returns the absolute value of the real number.

functionSin

Mathneeds F / Real
function Sin(num: real):real;

Returns the sine of the given number (represented in radians).

functionSqr

Math
function Sqr(n: integer): integer;

Returns the square of the given number.

functionSqrt

Mathneeds F / Real
function Sqrt(num: real):real;

Returns the square root of the given number.

functionTan

Mathneeds F / Real
function Tan(num: real):real;

Returns the tangent of an angle represented in radians.

functionToDegrees

Mathneeds F / Real
function ToDegrees(num: real):real;

Converts the angle from radians into degrees.

functionToRadians

Mathneeds F / Real
function ToRadians(num: real):real;

Converts the angle from degrees into radians.

functionTrunc

Mathneeds F / Real
function Trunc(num: real):integer;

Truncates the real number and returns only the integer part.

“”

String

10

functionCopy

String
function Copy(str1: string; begin, end: integer): string;

The function returns the substring of the given string which starts at position 'begin' and ends at position 'end'-1. For example, copy('MIDletPascal', 2, 5) returns 'Dle'. Note that this is different from the classic Pascal function copy. Strings in MIDletPascal are slightly different than strings in regular Pascal: the index of the first character in string is 0 in MIDletPascal.

See also Length · Pos

functionGetChar

Stringneeds S
function GetChar(str: string; pos:integer): char;

Returns the character at a given index within the string. The first character in a string is at index 0. If 'pos' is larger than the length of the string, character with ASCII code '0' is returned.

See also SetChar

functionIntegerToString

String
function IntegerToString(val: integer): string;

Converts integer into string representation of the same number.

Example
var i: integer;
  s: string;
begin
    i := 15;
    s := IntegerToString(i);
    s := '' + i; // this has the same effect as the previous statement
end.

functionLength

String
function Length(str: string): integer;

Retuns the length of the given string. Strings in MIDletPascal are slightly different than strings in regular Pascal: the index of the first character in string is 0 in MIDletPascal.

See also Copy · Pos

functionLocase

String
function Locase(str: string): string;

Returns the copy of the 'str' string with all letters in lowercase.

See also Upcase · Copy

functionPos

String
function Pos(str1, str2: string): integer;

Returns the position of the first occurence of 'str2' in 'str1', or -1 if 'str2' does not occur in 'str1'. The comparison is case-sensitive.

See also Copy · Length

functionSetChar

Stringneeds S
function SetChar(str: string; c: char; pos:integer): string;

Returns the string that is identical to 'str' except that it has character 'c' at position 'pos'. Position indexes start with zero. If 'pos' is larger then the length of the 'str', a copy of 'str' is returned.

See also GetChar

functionStringToInteger

Stringneeds S
function StringToInteger(s:string):integer;

Transforms the string into an integer (base 10 is used). If the string 's' is not a valid integer, the function will return 0. The string 's' may contain only digits, except for the first character which may be a '+' or a '-' sign.

functionStringToReal

Stringneeds F / Real
function StringToReal(str:string; base:integer):real;

Transforms the string into the real number. The second parameter is the base for transformation.

functionUpcase

String
function Upcase(str: string): string;

Returns the copy of the 'str' string with all letters capitalized.

See also Locase · Copy

Forms

39

procedureAddCommand

Forms
procedure AddCommand(cmd: command);

Inserts a command on the device display. Some devices (such as Motorola mobile phones) will not draw the command until Repaint is called. So after calling AddCommand be sure to call Repaint.

functionChoiceAppendString

Forms
function ChoiceAppendString(choiceID: integer; itemText:string):integer;

Inserts a string into the choice group element identified by choice group ID. The function returns the index of he newly inserted element within the choice group.

Example
var choiceGroupID: integer;
    NY, LA: integer;
begin
    ShowForm;
    choiceGroupID := FormAddChoice('Where do you live?', CH_EXCLUSIVE);
    NY := ChoiceAppendString(choiceGroupID, 'New York');
    LA := ChoiceAppendString(choiceGroupID, 'Los Angeles');
end.

functionChoiceAppendStringImage

Forms
function ChoiceAppendStringImage(choiceID: integer; itemText:string; img:image):integer;

Inserts a string and an image into the choice group element identified by choice group ID. The function returns the index of he newly inserted element within the choice group.

Example
var choiceGroupID: integer;
    NY, LA: integer;
begin
    ShowForm;
    choiceGroupID := FormAddChoice('Where do you live?', CH_EXCLUSIVE);
    NY := ChoiceAppendStringImage(choiceGroupID,
                                  'New York',
                                  LoadImage('/NY.png'));
    LA := ChoiceAppendStringImage(choiceGroupID,
                                  'Los Angeles',
                                  LoadImage('/LA.png'));
end.

functionChoiceGetSelectedIndex

Forms
function ChoiceGetSelectedIndex(choiceID: integer):integer;

The function returns the index of the selected choice group item, or -1 if no item is selected. For CH_MULTIPLE choice groups, -1 is always returned, and ChoiceIsSelected should be called instead.

functionChoiceIsSelected

Forms
function ChoiceIsSelected(choiceID: integer; itemIndex:integer):boolean;

The function returns true if the item (identified by 'itemIndex') is selected in choice group (identified by 'choiceID').

Example
var choiceGroupID: integer;
    NY, LA: integer;
begin
    ShowForm;
    choiceGroupID := FormAddChoice('Where do you live?', CH_EXCLUSIVE);
    NY := ChoiceAppendStringImage(choiceGroupID,
                                  'New York',
                                  LoadImage('/NY.png'));
    LA := ChoiceAppendStringImage(choiceGroupID,
                                  'Los Angeles',
                                  LoadImage('/LA.png'));
    if choiceIsSelected(choiceGroupID, NY) then
      FormAddString('New York');
    else
      FormAddString('Los Angeles');
end.
See also FormAddChoice

procedureClearForm

Formsneeds FS
procedure ClearForm;

Removes all elements and commands from the form. procedure ClearForm;

Example
var label_id, textField_id: integer;
begin
    label_id := FormAddString('Hello world');
    textField_id := FormAddTextField('Enter your name', 'Mr.Smith', 20, TF_ANY);
    ShowForm;
    Delay(2000);
    ClearForm;
    Delay(2000);
end.
See also ShowForm

functionCreateCommand

Forms
function CreateCommand(label:string; commandType:integer; priority:integer): command;

Creates the command element with the label 'label'. The label should be as short as possible. The priority of the command is set with the 'priority' parameter; the lower value means higher priority. The application uses the 'commandType' to specify the intent of this command. For example, if the application specifies that the command is of type CM_BACK, and if the device has a standard of placing the "back" operation on a certain soft-button, the implementation can follow the style of the device by using the semantic information as a guide. 'commandType' can be any of the following:

  • CM_SCREEN - any command type
  • CM_BACK
  • CM_CANCEL
  • CM_OK
  • CM_HELP
  • CM_STOP
  • CM_EXIT
  • CM_ITEM
Example
var exitCmd, pauseCmd: command;
begin
    exitCmd := CreateCommand('Exit', CM_EXIT, 1);
    pauseCmd := CreateCommand('Pause', CM_SCREEN, 1);
    AddCommand(exitCmd);
    AddCommand(pauseCmd);
end.

functionEmptyCommand

Forms
function EmptyCommand:command;

Returns a nonclicked command. The returned command MAY NOT be added to the screen (otherwise the MIDlet will crash), it can only be used for comparing if somthing has been clicked. function EmptyCommand:command;

Example
var ok, clicked:command;
begin
    ok := CreateCommand('OK', CM_OK, 1);
    AddCommand(ok);
    repeat
      clicked := GetClickedCommand;
    until clicked <> EmptyCommand;
    if clicked = ok then halt else doSomething...
end.

functionFormAddChoice

Formsneeds FS
function FormAddChoice(label:string; choiceType:integer):integer;

Adds the choice group element to the form. The function returns ID of the new choice group element. The 'choiceType' can be any of the following:

  • CH_EXCLUSIVE - exactly one item must be selected at a time
  • CH_MULTIPLE - arbitrary number of elements may be selected

functionFormAddDateField

Formsneeds FS
function FormAddDateField(label: string, type:integer): integer;

Inserts date field element into the form. The second parameter to the function specifies the control type and can be any of the following:

  • DF_DATE - control contains only date
  • DF_TIME - control contains only time
  • DF_DATE_TIME - control contains both date and time

The function returns the index of the inserted control.

functionFormAddGauge

Formsneeds FS
function FormAddGauge(label:string; isInteractive:boolean; maxValue, initialValue:integer ):integer;

Inserts a gauge element to the form. The function returns the ID of the text field. If 'isInteractive' is set to false, the user can not change the value of the gauge.

Example
var gauge_id: integer;
begin
    gauge_id := FormAddGauge('Choose your age', true, 100, 18);
    ShowForm;
    Delay(2000);
end.

functionFormAddImage

Forms
function FormAddImage(i:image):integer;

Inserts an image to the form. Returns the ID of the image element.

Example
var image_id: integer;
begin
    image_id := FormAddImage(LoadImage('/logo.png'));
    ShowForm;
    Delay(2000);
end.
See also ShowForm · FormRemove

functionFormAddSpace

Forms
function FormAddSpace:integer;

Inserts a space on the form. The space is used to separate groups of elements. Returns the ID of the space element. function FormAddSpace:integer;

Example
var label_id, space_id, textField_id: integer;
begin
    label_id := FormAddString('Hello world');
    space_id := FormAddSpace();
    textField_id := FormAddTextField('Enter your name',
                                     'Mr.Smith', 20, TF_ANY);
    ShowForm;
    Delay(2000);
end.
See also ShowForm · FormRemove

functionFormAddString

Forms
function FormAddString(s:string):integer;

Inserts a (uneditable) string label on to the form. The function returns the ID of a newly inserted element.

Example
var label_id: integer;
begin
    label_id := FormAddString('Hello world');
    ShowForm;
    Delay(2000);
end.
See also ShowForm · FormRemove

functionFormAddTextField

Formsneeds FS
function FormAddTextField(prompt, defaultValue: string; maxSize: integer; constraints:integer ):integer;

Inserts a text field to the form. The function returns the ID of the text field. The 'prompt' is the string displayed next to tet field. 'defaultValue' is the text that is initially in the text field. 'maxSize' is the maximum length of the text field in number of characters. 'constraints' can be any of the following:

  • TF_ANY - text field can contain any characters
  • TF_EMAIL - only email can be entered into text field
  • TF_NUMERIC - only number can be entered into text field
  • TF_PHONENUMBER - only phonenumber can be entered into text field
  • TF_URL - only URL can be enetered into the ext field
  • TF_PASSWORD - the text in the field is hidden, '*' character are displayed instead
Example
var textField_id: integer;
begin
    textField_id := FormAddTextField('Enter your name', 'Mr.Smith', 20, TF_ANY);
    ShowForm;
    Delay(2000);
end.

functionFormGetDate

Formsneeds FS
function FormGetDate(index: integer): integer;

Returns the date and time contained in the date field control identified by its index. The returned date and time is an integer value representing the number of seconds since the midnight of January 1., 1970. Date and time functions use the same format for representing time.

functionFormGetText

Formsneeds FS
function FormGetText(textFieldID:integer):string;

Returns the text in the text field identified by its ID. If the 'textFieldID' does not identify a text field element, an empty string is returned.

functionFormGetValue

Formsneeds FS
function FormGetValue(gaugeID:integer):integer;

Returns the value in the gauge identified by its ID. If the 'gaugeID' does not identify a gauge element, -1 is returned.

Example
var gauge_id, value: integer;
begin
    gauge_id := FormAddGauge('Choose your age', true, 100, 18);
    ShowForm;
    value := FormGetValue(gauge_id);
    Delay(2000);
end.
See also FormAddGauge

procedureFormRemove

Forms
procedure FormRemove(item:integer);

Removes an element from the form.

Example
var textField:integer;
begin
    showForm;
    textField := FormAddTextField('Name', '', 20, TF_ANY);
    Delay(1000);
    FormRemove(textField);
end.

procedureFormSetDate

Formsneeds FS
procedure FormSetDate(index: integer; dateTime: integer);

Sets the date and time of the date field control identified by its index. If the date field type is DF_TIME, the date part of the dateTiem must be set to zero.

procedureFormSetText

Formsneeds FS
procedure FormSetText(textFieldID:integer; text:string);

Sets the text of the text field indetified by the text field ID.

procedureFormSetValue

Formsneeds FS
procedure FormSetValue(gaugeID:integer; value:integer);

Sets the value in the gauge identified by gauge ID.

See also FormAddGauge

functionGetClickedCommand

Forms
function GetClickedCommand: command;

Returns the last command that has been clicked. function GetClickedCommand: command;

Example
var exitCmd, clicked: command;
begin
    exitCmd := CreateCommand('Exit', CM_EXIT, 1);
    AddCommand(exitCmd);
    repeat
      clicked := GetClickedCommand;
    until clicked <> EmptyCommand;
end.

functionGetFormTitle

Formsneeds FS
function GetFormTitle: string;

Returns the current form title, or an empty string if the form has no title. function GetFormTitle: string;

functionGetTextBoxString

Forms
function GetTextBoxString:string;

Returns the text entered into the text box. function GetTextBoxString:string;

Example
var cont : command;
    quote : string;
begin
    ShowTextBox('Enter your favorite quote', 'To be or not to be', 200, TF_ANY);
    cont := CreateCommand('Continue', CM_SCREEN, 1);
    AddCommand(cont);
    repeat
      delay(100);
    until GetClickedCommand <> EmptyCommand;
    quote := GetTextBoxString;
    ...
end.
See also ShowTextBox

functionMenuAppendString

Forms
function MenuAppendString(text: string): integer;

Appends a string entry to current menu. The function returns the index of the new entry within the menu.

Example
var tetris, minesweeper, snake : integer;
      play, clicked : command;
begin
    ShowMenu('Select a game', CH_IMPLICIT);
    tetris      := MenuAppendString('Tetris');
    minesweeper := MenuAppendString('Minesweeper');
    snake       := MenuAppendString('Snake');
    play := CreateCommand('Play', CM_SCREEN, 1);
    AddCommand(play);
    repeat
      delay(100);
      clicked := GetClickedCommand;
    until clicked = play;
    ShowCanvas; // show canvas and remove menu from the screen
    if MenuGetSelectedIndex = tetris then PlayTetris;
    if MenuGetSelectedIndex = minesweeper then PlayMinesweeper;
    if MenuGetSelectedIndex = snake then PlaySnake;
    ...
end.

functionMenuAppendStringImage

Forms
function MenuAppendStringImage(text: string; img:image): integer;

Appends a string entry to current menu. The entry contains an image next to the text. The function returns the index of the new entry within the menu.

Example
var tetris, minesweeper, snake : integer;
      play, clicked : command;
begin
    ShowMenu('Select a game', CH_IMPLICIT);
    tetris      := MenuAppendStringImage('Tetris', LoadImage('/tetris.png'));
    minesweeper := MenuAppendStringImage('Minesweeper', LoadImage('/mine.png'));
    snake       := MenuAppendStringImage('Snake', LoadImage('/snake.png'));
    play := CreateCommand('Play', CM_SCREEN, 1);
    AddCommand(play);
    repeat
      Delay(100);
      clicked := GetClickedCommand;
    until clicked = play;
    ShowCanvas; // show canvas and remove menu from the screen
    if MenuGetSelectedIndex = tetris then PlayTetris;
    if MenuGetSelectedIndex = minesweeper then PlayMinesweeper;
    if MenuGetSelectedIndex = snake then PlaySnake;
    ...
end.

functionMenuGetSelectedIndex

Forms
function MenuGetSelectedIndex: integer;

Returns the index of the currently selected entry in the menu. Returns -1 if no entry is selected. function MenuGetSelectedIndex: integer;

Example
var tetris, minesweeper, snake : integer;
      play, clicked : command;
begin
    ShowMenu('Select a game', CH_IMPLICIT);
    tetris      := MenuAppendStringImage('Tetris', LoadImage('/tetris.png'));
    minesweeper := MenuAppendStringImage('Minesweeper', LoadImage('/mine.png'));
    snake       := MenuAppendStringImage('Snake', LoadImage('/snake.png'));
    play := CreateCommand('Play', CM_SCREEN, 1);
    AddCommand(play);
    repeat
      Delay(100);
      clicked := GetClickedCommand;
    until clicked = play;
    ShowCanvas; // show canvas and remove menu from the screen
    if MenuGetSelectedIndex = tetris then PlayTetris;
    if MenuGetSelectedIndex = minesweeper then PlayMinesweeper;
    if MenuGetSelectedIndex = snake then PlaySnake;
    ...
end.

functionMenuIsSelected

Forms
function MenuIsSelected(index: integer): boolean;

Returns true if the entry at 'index' within the menu is selected.

Example
var tetris, minesweeper, snake : integer;
      play, clicked : command;
begin
    ShowMenu('Select a game', CH_IMPLICIT);
    tetris      := MenuAppendStringImage('Tetris', LoadImage('/tetris.png'));
    minesweeper := MenuAppendStringImage('Minesweeper', LoadImage('/mine.png'));
    snake       := MenuAppendStringImage('Snake', LoadImage('/snake.png'));
    play := CreateCommand('Play', CM_SCREEN, 1);
    AddCommand(play);
    repeat
      Delay(100);
      clicked := GetClickedCommand;
    until clicked = play;
    ShowCanvas; // show canvas and remove menu from the screen
    if MenuIsSelected(tetris) then PlayTetris;
    if MenuIsSelected(minesweeper) then PlayMinesweeper;
    if MenuIsSelected(snake) then PlaySnake;
    ...
end.

procedurePlayAlertSound

Forms
procedure PlayAlertSound;

Plays a sound associated with the current alert. procedure PlayAlertSound;

Example
var cm : command;
begin
    ShowAlert('Message',
              'New message arrived',
              LoadImage('/img1.png'),
              ALERT_INFO);
    PlayAlertSound;
    cm := CreateCommand('OK', CM_OK, 1);
    AddCommand(cm);
    repeat
      Delay(100);
    until GetClickedCommand <> EmptyCommand;
    ShowForm; // this will clear alert from the screen
    ...
end.
See also ShowAlert

procedureRemoveFormTitle

Forms
procedure RemoveFormTitle;

Removes the form title from the form. procedure RemoveFormTitle;

procedureSetTicker

Forms
procedure SetTicker(s:string);

Adds a ticker-tape effect to the form.

Example
begin
    ShowForm;
    SetTicker('MIDlet created with MIDletPascal');
    Delay(5000);
end.

procedureShowAlert

Forms
procedure ShowAlert(title: string; message:string; img:image; alertType:alert);

Displays an alert on the screen. The screen cannot contain any other form elements (except commands) when an alert is displayed. An alert can play the sound when it is displayed. Alert type can be any of the following:

  • ALERT_INFO
  • ALERT_WARNING
  • ALERT_ERROR
  • ALERT_ALARM
  • ALERT_CONFIRMATION
Example
var cm : command;
begin
    showAlert('New message',
              'You have just received a message from MrSmith',
              loadImage('/img1.png'),
              ALERT_INFO);
    playAlertSound;
    cm := createCommand('Read', CM_OK, 1);
    addCommand(cm);
    repeat
        delay(100);
    until getClickedCommand <> emptyCommand;
    showForm; // this will clear alert from the screen
    ...
end.

procedureShowCanvas

Forms
procedure ShowCanvas;

Displays the canvas on the device screen. The device screen can show either form or canvas. The form contains labels, images, text fields and other user interface elements. The canvas, on the other hand, does not contain user interface elements; it is an area that is painted by the program. When the MIDlet is started, the canvas is shown on the screen. procedure ShowCanvas;

Example
var label_id, textField_id: integer;
begin
    label_id := FormAddString('Hello world');
    textField_id := FormAddTextField('Enter your name', 'Mr.Smith', 20, TF_ANY);
    ShowForm;
    Delay(2000);
    ShowCanvas;
    DrawText('Hello world', 0, 0);
    Repaint;
    Delay(2000);
end.
See also ShowForm

procedureShowForm

Forms
procedure ShowForm;

Displays the form on the device screen. The device screen can show either form or canvas. The form contains labels, images, text fields and other user interface elements. The canvas, on the other hand, does not contain user interface elements; it is an area that is painted by the program. procedure ShowForm;

Example
var label_id, textField_id: integer;
begin
    label_id := formAddString('Hello world');
    textField_id := formAddTextField('Enter your name',
                                     'Mr.Smith', 20, TF_ANY);
    showForm;
    delay(2000);
end.

procedureShowMenu

Forms
procedure ShowMenu(title:string; menuType:integer);

Shows a menu on the device display. No other form elements (excepts commands) can be added to the screen when a menu is displayed. 'menuType' can be any of the following:

  • CH_IMPLICIT - this is what you probably want
  • CH_EXCLUSIVE - a small radio button is displayed next to each menu entry
  • CH_MULTIPLE - you can select multiple entries
Example
var tetris, minesweeper, snake : integer;
    play, clicked : command;
begin
    showMenu('Select a game', CH_IMPLICIT);
    tetris := menuAppendString('Tetris');
    minesweeper := menuAppendString('Minesweeper');
    snake := menuAppendString('Snake');
    play := createCommand('Play', CM_SCREEN, 1);
    addCommand(play);
    repeat
        delay(100);
        clicked := getClickedCommand;
    until clicked = play;
    showCanvas; // show canvas and remove menu from the screen
    if menuGetSelectedIndex = tetris then playTetris;
    if menuGetSelectedIndex = minesweeper then playMinesweeper;
    if menuGetSelectedIndex = snake then playSnake;
    ...
end.

procedureShowTextBox

Forms
procedure showTextBox(title: string; initialContents: string; maxSize: integer; constraints: integer);

Shows the text box on the screen. Text box occupies the whole device display and no other form elements except commands can be added to the screen. The 'constraints' can be any of the following:

  • TF_ANY - text field can contain any characters
  • TF_EMAIL - only email can be entered into text field
  • TF_NUMERIC - only number can be entered into text field
  • TF_PHONENUMBER - only phonenumber can be entered into text field
  • TF_URL - only URL can be enetered into the text field
Example
var cont : command;
      quote : string;
begin
    showTextBox('Enter message, '', 200, TF_ANY);
    cont := createCommand('Send', CM_SCREEN, 1);
    addCommand(cont);
    repeat
      delay(100);
    until getClickedCommand <> emptyCommand;
    quote := getTextBoxString;
    ...
end.

Record Store

13

functionAddRecordStoreEntry

Record Storeneeds RS
function AddRecordStoreEntry(rs: recordStore; data: string): integer;

The function adds 'data' into the record store 'rs'. The function returns the index inside record store at which 'data' is stored, or -1 if an error occured.

procedureCloseRecordStore

Record Storeneeds RS
procedure CloseRecordStore(rs: recordStore);

Closes an open record store.

procedureCloseRSEnumeration

unavailableRecord Store
procedure CloseRSEnumeration(rsEnumIdx: integer);
Not in this compiler build. Documented for MIDletPascal 3.5 but NOT compiled into this mp3cc build — the record-store enumeration API is absent from the parser. Iterate records by index with GetRecordStoreSize / ReadRecordStoreEntry instead.

Closes the record store enumeration created internally by calling EnumerateRecords. This procedure MUST be called when record store enumeration is no longer needeed; otherwise all phone resources will be reserved and record store will not be able to create enumerations any more.

procedureDeleteRecordStore

Record Storeneeds RS
procedure DeleteRecordStore(name: string);

Deletes the record store identified by its name. All data stored inside the record store will be lost. If the record store with the given name does not exist, nothing is deleted.

procedureDeleteRecordStoreEntry

Record Storeneeds RS
procedure DeleteRecordStoreEntry(rs: recordStore; index: integer);

Deletes the entry located at index 'index' inside the 'rs' recordStore. The procedure will do nothing if nothing exists at the given index.

procedureEnumerateRecords

unavailableRecord Store
function EnumerateRecords(rs: recordStore): integer;
Not in this compiler build. Documented for MIDletPascal 3.5 but NOT compiled into this mp3cc build — the record-store enumeration API is absent from the parser. Iterate records by index with GetRecordStoreSize / ReadRecordStoreEntry instead.

The function enumerates all nonempty records in the record store so that they can be iterated without reading the empty records. The function returns the index of the internal record store enumeration object that is used to access the enumerated data. The function will return -1 if enumeration failed.

Example
uses RSEnum;
var rs: recordStore;
    entryIdx: integer;
    rsEnumIdx: integer;
    data: string;
begin
  rs := OpenRecordStore('Test record store');
  entryIdx := AddRecordStoreEntry(rs, 'First Entry');
  entryIdx := AddRecordStoreEntry(rs, 'Second Entry');
  entryIdx := AddRecordStoreEntry(rs, 'Third entry');
  rsEnumIdx := EnumerateRecords(rs);
  repeat
    data := NextRecord(rsEnumIdx);
    debug(data);
  until data = '';
  DeleteRecordStoreEntry(rs, 2);
  UpdateRSEnumeration(rsEnumIdx);
  repeat
    data := NextRecord(rsEnumIdx);
    debug(data);
  until data = '';
  CloseRSEnumeration(rsEnumIdx);
end.

functionGetRecordStoreNextId

Record Storeneeds RS
function GetRecordStoreNextId(rs: recordStore): integer;

Returns the entry index that will be given to the next record store entry created with 'AddRecordStoreEntry' function.

functionGetRecordStoreSize

Record Storeneeds RS
function GetRecordStoreSize(rs: recordStore): integer;

Returns the number of records in the record store.

procedureModifyRecordStoreEntry

Record Storeneeds RS
procedure GetRecordStoreSize(rs: recordStore; newData: string; index: integer);

Modifies existing record store entry identified by 'index'. The value of the record store entry is set to 'newData'.

procedureNextRecord

unavailableRecord Store
function NextRecord(rsEnumIdx: integer): string;
Not in this compiler build. Documented for MIDletPascal 3.5 but NOT compiled into this mp3cc build — the record-store enumeration API is absent from the parser. Iterate records by index with GetRecordStoreSize / ReadRecordStoreEntry instead.

Returns the next record from the record store enumeration. If there are no more records in the enumeration, returns an empty string.

functionOpenRecordStore

Record Storeneeds RS
function OpenRecordStore(name: string): recordStore;

Open the record store with the name 'name'. If the record store does not exist, an empty record store is created.

functionReadRecordStoreEntry

Record Storeneeds RS
function ReadRecordStoreEntry(rs: recordStore; index: integer): string;

Returns the data stored at index 'index' inside record store 'rs', or an empty string if nothing exists at the given index.

procedureUpdateRSEumeration

unavailableRecord Store
procedure UpdateRSEnumeration(rsEnumIdx: integer);
Not in this compiler build. Documented for MIDletPascal 3.5 but NOT compiled into this mp3cc build — the record-store enumeration API is absent from the parser. Iterate records by index with GetRecordStoreSize / ReadRecordStoreEntry instead.

Updates the record store enumeration so that it reflects the most recent state of the record store.

Http Connectivity

9

procedureAddHttpBody

Http Connectivityneeds H
procedure AddHttpBody(httpConn: http; data: string);

Appends 'data' to the http request message body. Only POST request may contain a non-empty body.

procedureAddHttpHeader

Http Connectivityneeds H
procedure AddHttpHeader(httpConn: http; name, value:string);

Inserts a http header into http request. For example, to add the header "Accept-encoding: gzip, none", call 'addHttpHeader' with 'name' set to "Accept-encoding", and 'value' set to "gzip, none".

procedureCloseHttp

Http Connectivityneeds H
procedure CloseHttp(httpConn: http);

Closes an open http connection.

functionGetHttpHeader

Http Connectivityneeds H
function GetHttpHeader(httpConn: http; name: string): string;

Returns the value of the header 'name' from the http response. For example, if the http response contains the header "Content-type: text/plain", calling 'getHttpHeader' with 'name' set to "Content-type" will return "text/plain".

functionGetHttpResponse

Http Connectivityneeds H
function GetHttpResponse(httpConn: http):string;

Returns the data that has been sent by the server in a response to http request.

functionIsHttpOpen

Http Connectivity
function IsHttpOpen(httpConn: http):boolean;

Returns true if the 'httpConn' connection is already open.

functionOpenHttp

Http Connectivityneeds H
function OpenHttp(httpConn: http; url: string):boolean;

Opens the 'httpConn' connection to the 'url'. The 'url' must be in form 'http://servername[:port][/file]'. Returns true on success, or false if fails.

functionSendHttpMessage

Http Connectivityneeds H
function SendHttpMessage(httpConn: http): integer;

This function send the http request, waits for the response and returns http response code or -1 if an internal error occured. The complete list of HTTP response codes can be found on the Internet (generally, 200 means OK, codes between 400-499 denote client-side errors, and codes between 500-599 denote server-side errors).

procedureSetHttpMethod

Http Connectivityneeds H
procedure SetHttpMethod(httpConn: http; method:string);

Sets the method for the http request. The method can be any of the following:

  • GET
  • POST
  • HEAD

SMS Messaging

3

functionSmsIsSending

SMS Messagingneeds SM
function SmsIsSending: boolean;

Returns true if SMS subsystem is busy sending an SMS message, or false otherwise. function SmsIsSending: boolean;

functionSmsStartSend

SMS Messagingneeds SM
function SmsStartSend(destination: string; message:string): boolean;

Starts sending an SMS message. Returns true if SMS message has been sent to the SMS subsystem and if the subsystem is not sending another message. Returns false if the message was not sent to the SMS subsystem. 'destination' address must have the form: sms://<phone-number> SMS sending from J2ME is not supported on all devices. MIDletPascal tries to send SMS messages using Wireless Messaging API and Siemens API. The following example illustrates simple use of SMS functions:

Example
begin
  if not SmsStartSend('sms://+5550000', 'Hello!') then Halt;
    while SmsIsSending do // wait for the message to be sent
      Delay(100);
      if not SmsWasSuccessfull then Halt; // check if the message was sent                       //successfully
end.

functionSmsWasSuccessfull

SMS Messagingneeds SM
function SmsWasSuccessfull: boolean;

Returns true if the last SMS message was sent successfully. This function returning false can mean any of the following:

  • the mobile phone does not support sending SMS messages from J2ME MIDlet
  • the SMS destination address is invalid
  • the operator refused to relay an SMS message

function SmsWasSuccessfull: boolean;

Sound and Music

6

functionGetPlayerDuration

Sound and Musicneeds PMMAPI or MIDP2.0
function GetPlayerDuration:integer;

Returns the total duration (in milliseconds) of the music that was loaded into player. function GetPlayerDuration:integer;

See also OpenPlayer

functionOpenPlayer

Sound and Musicneeds PMMAPI or MIDP2.0
function OpenPlayer(resource:string; mimetype:string):boolean;

Opens a given resource file in the audio player. The resource is not played before 'startPlayer' is called. The function will return false if it did not succedd. 'mimetype' can be any of the following:

  • wave files: audio/x-wav
  • au files: audio/basic
  • MP3 files: audio/mpeg
  • MIDI files: audio/midi

Note that devices usually do not support all sound formats. Compatibility: the music functions will work only on MIDP-2.0 compatible mobile phones. MIDlets with sound support will CRASH on MIDP-1.0 phones!

Example
begin
    if not OpenPlayer('/explosion.mid', 'audio/midi') then Halt;
    if not SetPlayerCount(-1) then Halt;
    if not StartPlayer then Halt;
    Delay(5000);
end.

procedurePlayTone

Sound and MusicMMAPI or MIDP2.0
procedure PlayTone(note, duration, volume: integer);

Plays a single tone through the Mobile Media API. 'note' is the MIDI note number (0..127, 69 = A4 = 440 Hz), 'duration' is the length in milliseconds and 'volume' is 0..100. Undocumented in the original manual but present in the compiler.

functionSetPlayerCount

Sound and Musicneeds PMMAPI or MIDP2.0
function SetPlayerCount(loopCount:integer):boolean;

Sets the loop count for the player - the 'loopCount' is the number of times that the music should be played. This function should be called after 'openPlayer' and before 'startPlayer' is called. If 'loopCount' is set to -1, then the music will play forever.

See also OpenPlayer

functionStartPlayer

Sound and Musicneeds PMMAPI or MIDP2.0
function StartPlayer:boolean;

Starts playing the audio previously loaded by 'openPlayer'. Returns false if the player cannot be started. function StartPlayer:boolean;

Example
begin
    if not OpenPlayer('/explosion.mid', 'audio/midi') then Halt;
    if not SetPlayerCount(-1) then Halt;
    if not StartPlayer then Halt;
    Delay(5000);
end.
See also OpenPlayer

procedureStopPlayer

Sound and Musicneeds PMMAPI or MIDP2.0
procedure StopPlayer;

Stops the music that is currently played. procedure StopPlayer;

Resource Files

5

functionOpenResource

Resource Filesneeds S
function OpenResource(name: string):resource;

The function opens the resource file located within the application's JAR file. To add the resource file into the JAR file, select the Project->Insert resource menu.

Example
var res   : resource;
    byte  : integer;
    line  : string;
    index : integer;
begin
      res := OpenResource('/data.txt');
      if (resourceAvailable(res)) then
      begin
          byte := ReadByte(res);
          line := ReadLine(res);
          CloseResource(res);
      end;
      ShowForm;
      index := FormAddString('Byte is: ' + chr(byte));
      index := FormAddString('Line is: ' + line);
      Delay(1000);
end.

functionReadByte

Resource Files
function ReadByte(res: resource):integer;

Reads the next byte from the given resource, or returns EOF if there is nothing to read or there was an error reading from the resource.

functionReadLine

Resource Files
function ReadLine(res: resource):string;

Reads the next line from the given resource, returns an empty string if there were no more lines to read or if there was an error reading from the stream. If there are empty lines in the resource, they will be skipped.

functionResourceAvailable

Resource Files
function ResourceAvailable(res: resource):boolean;

The function returns true if the given resource is available (e.g. if it was open correctly).

Misc

10

procedureAssert

Misc
procedure Assert(cond: boolean);

This procedure test if the given condition is true. If the given condition fails (it is not true), then an assertion message is written to the standard debug output. More information about debug output can be found with the definition of debug procedure. The sample assetion message looks like this: Assertion failed at: Tetris.mpsrc:162

See also Debug

functionChr

Misc
function Chr(n: integer): char;

Returns the character with the given ASCII code. Behavior is undefined if 'n' is larger than 127.

procedureDebug

Misc
procedure Debug(s: string);

This procedure writes the given string to the simulator's standard output. It has no effect on the mobile device (except that the generated MIDlet is slightly larger).

See also Assert

functionGetProperty

Misc
function GetProperty(propertyName: string): string;

This procedure is used to get the information about the Java system. Consult the Java documentation for the list of available properties.

Example
begin
    Debug(GetProperty('microedition.locale'));
end.
See also Debug · GetWidth · GetHeight

procedureHalt

Misc
procedure Halt;

Terminates the MIDlet execution. procedure Halt;

functionIsMidletPaused

Misc
function IsMidletPaused: boolean;

Returns true if the MIDlet is in the paused state, otherwise false. When the MIDlet is started, it is not in the paused state. The MIDlet can enter paused state when, for example, the phone receives incoming call. Then the MIDlet enters paused state, the call is answered, and after the phone call the user may resume the MIDlet - after resuming the MIDlet is not in the paused state any more. Determining if the MIDlet is in the paused state may be useful in different applications. Consider, for example, a game that must be paused when the MIDlet is paused. The following code would do the trick: function IsMidletPaused: boolean;

Example
...
  repeat
    { process keypad inputs and read the timer }
    { if the MIDlet is paused, wait until it is resumed }
    while IsMidletPaused do
    begin
      Delay(100);
    end;
  until gameOver;
...

functionOdd

Misc
function Odd(n: integer): boolean;

Returns true if the given number 'n' is odd, false otherwise.

functionOrd

Misc
function Ord(c: char): integer;

Returns the ASCII character code for the given character.

functionRandom

Misc
function Random(n: integer): integer;

Returns the pseudorandom number between 0 and (n-1). The following function will return random boolean value; the probability that the returned value is true is 75 %.

Example
function randomBoolean: boolean;
  begin
    if Random(4) = 3 then
      randomBoolean := false;
    else
      randomBoolean := true;
end;
See also Randomize

procedureRandomize

Misc
procedure Randomize;

Reinitialize the random number generator. The MIDlet does this initialization when it is run; however, you may wish to reinitialize the random number generator at some time. procedure Randomize;


Lookup tables

Appendices

Predefined constants and key scan codes, for quick reference.

Predefined constants

Constants the compiler defines for every program — no declaration needed.

Game actions — returned by KeyToAction

ConstantValueConstantValue
GA_NONE0GA_FIRE8
GA_UP1GA_GAMEA9
GA_DOWN6GA_GAMEB10
GA_LEFT2GA_GAMEC11
GA_RIGHT5GA_GAMED12

Key codes — standard on all phones

ConstantValueConstantValueConstantValue
KE_NONE0KE_KEY452KE_KEY957
KE_KEY048KE_KEY553KE_STAR42
KE_KEY149KE_KEY654KE_POUND35
KE_KEY250KE_KEY755
KE_KEY351KE_KEY856

Fonts — for SetFont

FaceValueStyleValueSizeValue
FONT_FACE_SYSTEM0FONT_STYLE_PLAIN0FONT_SIZE_MEDIUM0
FONT_FACE_MONOSPACE32FONT_STYLE_BOLD1FONT_SIZE_SMALL8
FONT_FACE_PROPORTIONAL64FONT_STYLE_ITALIC2FONT_SIZE_LARGE16
FONT_STYLE_UNDERLINED4

Font style values combine as a bitmask (e.g. bold + italic = 3).

Commands, text fields, choices, alerts, date fields

Command type#Text field#Choice#
CM_SCREEN1TF_ANY0CH_EXCLUSIVE1
CM_BACK2TF_EMAIL1CH_MULTIPLE2
CM_CANCEL3TF_NUMERIC2CH_IMPLICIT3
CM_OK4TF_PHONENUMBER3DF_DATE1
CM_HELP5TF_URL4DF_TIME2
CM_STOP6TF_PASSWORD0x10000DF_DATE_TIME3
CM_EXIT7GET / POST / HEADstrEOF1000
CM_ITEM8pi3.14159…alert types →

Alert types (passed to ShowAlert): ALERT_INFO, ALERT_WARNING, ALERT_ERROR, ALERT_ALARM, ALERT_CONFIRMATION. HTTP methods GET, POST and HEAD are predefined string constants.


Key scan codes

The number keys, * and # report the same codes on every phone. Navigation and soft keys do not — this is why KeyToAction exists. Raw values from GetKeyPressed / GetKeyClicked by manufacturer:

KeySiemensSony EricssonNokiaMotorola
0 – 948–5748–5748–5748–57
*   /   #42 / 3542 / 3542 / 3542 / 35
Up−59−1−11 (−1)
Down−60−2−26 (−2)
Left−61−3−32 (−3)
Right−62−4−45 (−4)
Fire−26−5−520 (−5)
Left soft-key−1−621
Right soft-key−4−722
Clear−8−80