General Automation Platform

API reference · GAP 4.6

Everything a script
can call.

Every function is a global: a script calls tap(…), not gap.tap(…). Scripts are modern JavaScript (ES2023) running in GAP's engine on the device.

Conventions

  • Images are integer handles, and 0 means “no image”. openImage() returns 0 for a missing file. Every handle you get must be passed to releaseImage() — they are native memory, not garbage-collected.
  • Some image functions change the image you pass in instead of returning a new one. They are marked in place below.
  • Coordinates are screen pixels, the same space for screenshots and touches. Fractions are rounded.
  • during is a wait after the action, giving the app time to react — not how long a finger is held.
  • Calls marked newer are not in GAP 3.3, the current stable release, so check first: if (typeof gapPerf === 'function') …
  • Calls marked opt-in do nothing until the user switches them on for that script.

start() and stop()

A script defines two globals. The floating bar's Play calls start(settings) through the settings page, and Stop calls stop(). start() usually loops; stop() runs on another thread while it does, so it only needs to clear a flag the loop checks.

index.js
var running = false;

function start(settings = {}) {
  running = true;
  while (running) {
    // look, decide, act
    sleep(500);
  }
}

function stop() {
  running = false;
}

Pause needs nothing from the script: GAP freezes it inside sleep() and inside every touch call (not keycode() or typing()), and it continues from the same spot on resume. After a Stop, new touches from that run are dropped; a drag already in progress can still finish its moveTo() and tapUp().

Optional hooks: define onPause() and onResume() to be called around a pause, and reportIssue(reason, arg) to be called when the user holds the bar's Log button to report a problem. A script can also name itself with const GAP_SCRIPT_ID = '…'.

Screen

CallReturnsWhat it does
getScreenSize(){width, height}The screen size right now, following rotation.
getVirtualButtonHeight()numberHeight of the navigation bar, 0 when there is none.
getScreenshot()imageThe whole screen, in BGRA. About a millisecond on the fast capture path.
getScreenshotModify(cropX, cropY, cropW, cropH, resizeW, resizeH, quality)imageA region of the screen, optionally resized. Crop first, then resize (0 = no resize); a quality of 1–99 adds a JPEG round-trip, 100 leaves it out.
getColor(x, y){r, g, b, a}The colour of one pixel, from a fresh capture. Nothing to release.
getColors(points)[{r, g, b, a}]Several pixels from one capture. points is [{x, y}].

Touch and keys

CallReturnsWhat it does
tap(x, y, during, holdMs)—Press, hold holdMs (default 40, up to 5000), release, then wait during ms. holdMs is newer.
tapDown(x, y, during)—Put a finger down.
moveTo(x, y, during, wait)—Move the finger that is down. With wait true it returns only once the app has taken the move, so a long drag on a busy app loses nothing.
tapUp(x, y, during)—Lift the finger.
swipe(x1, y1, x2, y2, during)—A swipe: down, ten moves, up.
keycode(label, during)—Press a key: 'HOME', 'BACK', 'KEYCODE_ENTER', or a number.
typing(words, during)—Type text into whatever has focus. Characters the keyboard map can't produce are skipped.
readTouch(timeoutMs){x, y, down} | nullWait for the user's next touch, in screen pixels. Up to 120 s; null on timeout.
touchDevices()[{path, xMax, yMax}]The touchscreens the device reports.

Apps and device

Always available, with no shell needed.

CallReturnsWhat it does
launchApp(package, activity)booleanOpen an app, by its launcher entry unless you name an activity. Opening one that is already open doesn't stack a second copy.
stopApp(package)booleanForce-stop an app.
isInstalled(package)booleanWhether an app is installed.
foregroundApp(){package, activity} | nullThe app in front.
deviceInfo()object | null{model, manufacturer, device, androidRelease, fingerprint, emulator, density, rooted}. density and rooted are newer.
dumpUi()stringThe window hierarchy as XML, "" when it can't be read. Handy for reading text and finding views by id.
getDeviceId()stringTwelve hex digits naming this device, stable across reboots, different per emulator instance.
getDeviceName()stringThe device's name, as set in GAP's Settings; if unset, its model and the start of its id.

Image processing

OpenCV underneath. Colour bounds are per channel in B, G, R, A order.

CallReturnsWhat it does
clone(img)imageA copy.
cropImage(img, x, y, width, height)imageA rectangle of it. Clamped to the image; entirely outside returns 0.
resizeImage(img, width, height)imageScaled.
bgrToGray(img)imageGreyscale.
absDiff(a, b)imagePer-pixel difference — what changed between two frames.
inRange(img, minB, minG, minR, minA, maxB, maxG, maxR, maxA)image (mask)White where a pixel's colour is inside the bounds.
outRange(img, minB, minG, minR, minA, maxB, maxG, maxR, maxA)image (mask)White where it is outside.
cloneWithMask(img, mask)imageOnly the masked pixels.
canny(img, t1, t2, apertureSize)imageEdges.
findContours(edges, minArea, maxArea)[{x, y, width, height, area}]Outlines found in an edge image, as boxes. maxArea 0 = no upper limit.
houghCircles(img, method, dp, minDist, p1, p2, minR, maxR)[{x, y, radius}]Circles.
smooth(img, type, size)in place—Blur: 1 box, 2 Gaussian, 3 median, 4 bilateral.
convertColor(img, code)in place—Convert colour space with an OpenCV code.
threshold(img, thr, maxThr, code)in place—Threshold.
eroid(img, width, height, x, y)in place—Erode (the name is the original API's).
dilate(img, width, height, x, y)in place—Dilate.
drawCircle(img, x, y, radius, r, g, b, a)in place—Draw a circle, for debug pictures.

Matching

CallReturnsWhat it does
findImage(img, template){x, y, score}Where the template best matches, with a score from 0 to 1. x, y is the top-left corner. A template bigger than the image gives {x: -1, y: -1, score: -1}.
findImages(img, template, scoreLimit, resultCountLimit, withoutOverlap)[{x, y, score}]Every match above a score.
getIdentityScore(a, b)numberHow alike two pictures are, resizing b to a first — “is this the same screen?”.

Single-colour templates are handled: they are matched a different way so a score of 1.0 still means a perfect match.

Image files

CallReturnsWhat it does
openImage(path)imageLoad a PNG or JPEG. 0 when the file is missing.
saveImage(img, path)—Save, creating folders. .jpg drops transparency.
getImageSize(img){width, height}
getImageColor(img, x, y){r, g, b, a}A pixel of an image you hold. Outside the image gives zeros.
getImageColors(img, points)[{r, g, b, a}]Several at once.
releaseImage(img)—Free it. Using it afterwards throws.
getImageFromBase64(text)imageDecode, data: prefix allowed.
getBase64FromImage(img)stringPNG as base64.
getImageFromURL("env:KEY")opt-inimageDownload an image from a URL the user configured; 0 if that fails or is not allowed. See network.

Timing and paths

CallReturnsWhat it does
sleep(ms)—Wait. Stop, Close and Pause all take effect during it. There is no setTimeout: scripts are loops around sleep().
getScriptPath()stringThis script's own folder — use it for images/ and anything shipped with the script.
getStoragePath()stringGAP's folder, …/Download/GeneralAutomationPlatform.
getDevicePath()stringA folder for this device alone, for output. Use it when several emulators share storage.

Files

CallReturnsWhat it does
readFile(path)string"" when it can't be read.
writeFile(path, text)—Creates folders as needed.
makeDirs(path)booleanLike mkdir -p.
listDir(path)[string]Names, sorted. A missing folder lists empty.
copyFile(from, to)booleanOverwrites.
removeFile(path, recursive)booleanFolders only with recursive.

Shell: execute()

When no named call does what you need, execute() runs any shell command with the same access adb shell has — am, pm, settings, input, and the rest.

CallReturnsWhat it does
execute(command)opt-instringRuns command and returns its output (stdout and stderr together). "" while the switch is off.

Off until the user allows it: tap the script's card in the Library, tap Settings to open its Script env screen, and turn on Allow shell commands (GAP asks to confirm). On GAP 4.4 and earlier, Script env is the sliders button on the card instead. Scripts signed for GAP Companion always have it. The switch applies at once. Write scripts to carry on without it, and prefer the named calls above — they are faster and always available. The Playground example uses it this way to open a web page.

example
// Open a web page — something no named call does.
var out = execute('am start -a android.intent.action.VIEW -d "https://example.com"');
if (out === '') {
  console.log('Shell is off: open the page yourself, or allow shell commands');
}

Overlay, log and events

CallReturnsWhat it does
console.log / info / warn / error / debug—To the log panel, the settings page's onLog(), logcat (gap.script) and the log file in logs/. Objects are printed as JSON.
showBanner(message, duration, plays)—A line on the banner beside the floating bar. plays 0 = for the whole run. Also takes {message, duration, plays}.
setReadTop(y)—The top-most screen row the script reads, so GAP keeps its status line above it. Negative withdraws it.
pauseScript()—Pause this run, as if Pause were pressed. The user resumes it.
emitEvent(name, data)—Broadcast one of your own events to tools on a computer — to start a screen recording, say. Up to 50 a second, 16 KB each.
emitTrace(kind, data)—Live debug data for a developer tool.
traceAttached()booleanWhether such a tool is connected; check before building anything expensive.
traceWantFrame() · traceFrameId()— · numberSend the next capture to the tool; the id sent for the latest capture, or 0 if it was not sent.

Settings and network

A script never names a URL. It ships gap-env.json listing the values it wants; the user fills them in from a button on its Library card, and must switch on Use environment variables and, for requests, Allow network requests. Requests then say "env:KEY", and GAP sends them to the URL the user typed.

CallReturnsWhat it does
getEnv(key)opt-instring | number | boolean | undefinedThe user's value, else the default. undefined while variables are off.
httpClient(method, "env:KEY", body, headers)opt-instringA request that waits for the answer. Error bodies are returned too; "" when refused or failed.
httpRequest(method, "env:KEY", body, headers)opt-innumberA request that returns at once with an id; the answer arrives as a network event.
addNetworkListener(fn) · removeNetworkListener(fn)—fn({id, type, status, body, error, …}) for each step: queued, sent, then done, failed or refused.

Limits: one request at a time, at least a second apart, 30 a minute per key, bodies up to 1 MiB. Settings pages can't use the network at all.

Script control

CallReturnsWhat it does
importJS(library)—Load another file: an absolute path, or a name from libs/ or scripts/.
runScript(code)—Evaluate code in the script's global scope.
encrypt(code) · runEncryptedScript(text)string · —Ship closed-source code: encrypt once, run the result.

Restarts and speed

For long runs that slow down over hours. Both take and return JSON text.

CallReturnsWhat it does
gapPerf(options)newerJSONThe run's capture rate and capture time against how fast the device was just after it started, and whether that counts as slow.
gapRestartDevice(options)neweropt-inJSONRestart the device. Needs shell access, and GAP Companion linked to start the run again afterwards.

Settings page bridge

A script's index.html runs in GAP's floating window, offline. It talks to the script through JavaScriptInterface, and GAP calls back into it.

In index.htmlKindWhat it does
onEvent(type)you defineA floating-bar button was pressed: OnPlayClick, OnPauseClick (the Stop button), OnCloseClick, OnSettingClick, OnLogClick, OnMenuClick.
onLog(message)you defineEvery console line from the script.
onGapState(json)you defineQuick Bar page only: the run's state, {active, paused, visible, stripHeight}.
onGapMessage(topic)you defineA nudge from the script's other page (settings ↔ Quick Bar).
JavaScriptInterface.runScript(code)callRun code in index.js, e.g. 'start(' + JSON.stringify(settings) + ');'.
JavaScriptInterface.runScriptCallback(code, fnName)callRun it and call the page's fnName(result) with the answer.
JavaScriptInterface.showMenu() · hideMenu()callShow or hide the floating bar. showMenu() also closes the settings panel, so an OnPlayClick handler calls it to get out of the way.
JavaScriptInterface.setClipboard(text) · getClipboard()callThe system clipboard.
JavaScriptInterface.broadcast(topic)callNudge the script's other page.
JavaScriptInterface.setVersion(version)callThe version on the bar's first chip (or define a VERSION global).
JavaScriptInterface.setQuickBarExpanded(on) · setQuickBarHotspot(l, t, w, h)callQuick Bar layout.
JavaScriptInterface.stopScript() · interruptScript()callStop the run: politely, through the script's stop(), or at once, even mid-loop.
JavaScriptInterface.log(message)callWrite a line to the script's log.
JavaScriptInterface.getScriptId() · isServiceConnected()callThis script's id; whether GAP's engine is reachable.
JavaScriptInterface.close()callClose the floating window.
localStorageweb APIWhere settings are kept between runs.

Files in a script folder

FileNeededWhat it does
index.jsyesThe script.
index.htmlyesIts settings page, which also connects Play and Stop.
images/noTemplates for findImage().
quickbar.htmlnoA strip of the script's own buttons beside the floating bar.
floating-bar.jsonnoSizes, colours and icons for the floating bar.
gap-env.jsonnoThe values the script asks the user for (URLs, keys) — see network.
gap-backup.jsonno{"v": 1, "keys": [...]}: which localStorage keys get Back up / Restore settings on the card.

The language

QuickJS-ng with ES2023: class with private fields, async/await, generators, optional chaining, ??, destructuring, template literals, BigInt, Proxy. Files are classic scripts, so function start(){} lands on the global object; name a file .mjs for module semantics. There is no setTimeout or setInterval.

Nothing matches that filter.