Overview of JavaScript Modules

JavaScript Modules provide a way to split code into smaller, manageable pieces, making it easier to structure, maintain, and reuse. Before modules were introduced, JavaScript code was often written in a single file, which could become cumbersome and difficult to maintain as projects grew larger. Modules help solve this problem by enabling developers to isolate code into individual files or units of functionality.

Key Features:

  • Encapsulation: Modules allow you to encapsulate variables and functions, exposing only the necessary parts (usually through module.exports) to the outside world. This prevents polluting the global namespace.

  • Reusability: Once a module is created, it can be reused across multiple files, improving code reuse and reducing duplication.

  • Separation of Concerns: JavaScript modules encourage a clean separation of different concerns within an application, making it easier to manage and maintain the codebase.

  • Dependency Management: Modules allow you to load dependencies on demand, making the code more flexible and maintainable.

CommonJS Module Example:

var { getDevice } = require('sigma/device');
print(device.getDevice());  // Output: main device

Benefits of Using Modules:

  • Code Maintenance: With modular code, each part of the application is isolated and can be maintained independently.

  • Separation of Concerns: Different aspects of the application can be handled in separate modules, making the application more organized and understandable.

  • Collaboration: Different team members can work on separate modules independently, improving collaboration and productivity.

JavaScript Modules, especially CommonJS, provide a flexible way to manage dependencies, modularize your code, and keep your application organized.

Modules

aai.js

This module provides a high-level interface for controlling Android device UI through the AAI (Advanced Accessibility Interface),
allowing script-level automation of UI elements like buttons, text fields, checkboxes, sliders, and more.

It is designed to work with Total Control’s FindNode engine and integrates seamlessly with the UI Explorer tool.
Developers can locate and interact with UI components via selectors, perform input and gesture operations,
monitor screen states, and manage multi-device batch actions.

All functions are accessible via UiElement, UiElementArray, UiSelector, or directly from Device.sendAai(...).

Key Features

  • UI Query & Selection**: Use UiSelector or FindNode queries to locate UI elements on screen.
  • Element Interaction**: Click, long-click, input text, get/set properties, take screenshots.
  • Batch Control**: UiElementArray enables simultaneous actions across devices or multiple UI nodes.
  • State Monitoring**: Register listeners with addQueryListener() to watch UI changes in real-time.
  • FindNode Integration**: Supports advanced queries like "T:Settings&&R:.settings" with rich filter support.
  • Custom Automation**: Compatible with TCThreadVirtual, DeviceArray, and async scripts for full test automation.

app.js

Application control module for Android devices in the Total Control scripting system.

This module enables automation and control of Android apps running on connected devices. It provides
functionality to launch, close, install, uninstall, and query apps, as well as manipulate or retrieve
activities on the device. It supports both Java-layer and JS-layer extensions to the Device object,
allowing methods to be invoked via device.runApp() or directly through exports.

Features

  • Launch and restart applications by package name
  • Close apps or check if an app is running in the foreground
  • Retrieve the currently focused app or activity
  • Install or uninstall APK files from a specified path
  • Get a list of all installed packages on the device
  • Dynamically open activities by component name with or without root

color.js

Device screen color analysis and recognition module [Color]

This module provides a collection of methods for pixel color reading, comparison, and matching
on Android device screens. It is designed for use in automated scripts within the Total Control system.

All functions are dynamically attached to Device.prototype, enabling direct calls such as:
device.getColorBits(), device.compareColor(...), device.seekColor(...), etc.

Key Features

  • Pixel Color Reading: Get RGB or hexadecimal color values of specific screen pixels.
  • Color Comparison:
    • Match a pixel with multiple candidate colors or color ranges.
    • Multi-point comparison for UI validation.
  • Color Search:
    • Locate color points or patterns on the screen or in memory screenshots.
    • Support directional search, similarity thresholds, and fast memory-based lookup.
  • Color Count: Count how many distinct colors exist in a given region.
  • Color Wait: Wait for specific colors to appear before proceeding.

common/deviceFns.js

Dynamic Device method injection utilities for the Total Control scripting system.

This module lets you define and attach custom JavaScript functions to the Device and DeviceArray
prototypes at runtime, so they can be called as native methods (e.g., device.myFn() or
devices.myFn() for multiple devices). It supports both synchronous and asynchronous execution
across multiple devices and provides a safe way to remove injected methods.

It is designed to be used from Userlib.js (Total Control 7.0.0+), where custom behaviors are
registered via addDeviceFunction() and, when needed, removed with delDeviceFunction().

Features

  • Register user-defined functions as Device/DeviceArray methods with a chosen alias
  • Execute on a single device or broadcast to multiple devices (multiple: true)
  • Choose execution mode per function:
    • sync: iterate devices one-by-one
    • async: parallel per-device execution using Java threads
  • Automatic argument injection: the target Device instance is prepended to your function’s arguments
  • Safe teardown: remove custom methods from Array, Device, and DeviceArray prototypes
  • Graceful error handling during dynamic binding (eval guarded with try/catch)
  • Backward compatibility defaults for options (sync + single-device if not specified)

common/errors.js

Unified error handling helpers

This module provides a simple wrapper around sigmaDeviceManager’s
error message API. It allows scripts to:

  • Set the current error message
  • Retrieve the last error message
  • Throw an error while recording it in the device manager

common/fileio.js

File I/O helpers for the Total Control scripting system.

This module exposes lightweight, cross-utility helpers to read files from the
host computer where scripts are executed. It wraps Java NIO for reliability
and performance, returning either raw byte arrays (as unsigned 0–255 integers)
or line-oriented text using a caller-specified character set.

Features

  • Read an entire file as unsigned byte values (0–255)
  • Read a text file into an array of lines with a chosen charset (UTF-8 by default)
  • Consistent error reporting via setError(...)/lastError()
  • Small, dependency-free surface built on Java NIO (Paths/Files/Charset)

common/format.js

Formatting utilities for Rhino/RingoJS environments.

The common/format module provides Java-style string formatting via
java.lang.String.format and timestamp helpers based on ringo/utils/dates.
It is designed for legacy or embedded runtimes where Java interop is available,
offering predictable printf semantics and compact, sortable time strings.

Features

  • Java Formatter semantics: %s, %d, %f, %x, %o, %b, %%, %n, %tX
  • Positional arguments and flags: %1$s, %2$d, +, -, 0, ,, (, #, <, $
  • Human-readable local-time timestamps: yyyy-MM-dd HH:mm:ss.SSS
  • Log/filename-friendly timestamps: yyyyMMdd_HHmmss
  • JS→Java numeric interop: integers boxed as java.lang.Integer for %d
  • Clear failure modes: format() returns null and records setError(e); timestamp helpers throw

common/http.js

Provides a simple, synchronous HTTP request interface for legacy JavaScript environments such as RingoJS or Rhino.

The http module exposes a convenient wrapper function TCHttpRequest for performing basic REST API calls and page retrievals.
It simplifies network communication by returning a structured response object containing headers, content, cookies, encoding,
and other HTTP metadata, while handling connection setup, timeouts, and errors internally.

Core Features:

  • Lightweight, synchronous HTTP client built on ringo/httpclient.
  • Supports standard HTTP methods: GET, POST, PUT, and DELETE.
  • Customizable headers, request body, and connection timeout.
  • Returns a detailed response object with connection info, status, headers, and content.
  • Simple error handling with null return and lastError() reporting.

common/output.js

Output buffer utilities for the Total Control scripting environment.

The common/output module implements a lightweight, process-local message pipeline
for collecting ad-hoc results (strings, numbers, JSON-compatible objects) across
user code and custom device functions. Collected messages can be retrieved once
via lastOutput(). The buffer is intended to be transient: when any Total Control
JS/Java API that interacts with devices is executed, the buffer is cleared by the
host to avoid stale data.

Features

  • Append arbitrary messages to a transient buffer with addOutput(message)
  • Retrieve the latest buffered content with lastOutput() (string or array)
  • Programmatic inspection helpers: getOutputLength() and getOutputFunc()
  • Explicit reset hook initOutput() for manual lifecycle control
  • Designed to work with single- or multi-device workflows (e.g., addDeviceFunction)

Behavior & Notes

  • Buffer semantics:
    • Empty buffer �� lastOutput() returns ""
    • One item �� returns that single value
    • Multiple items �� returns an array preserving insertion order
  • Host interaction:
    • The buffer is cleared whenever a Total Control device API is invoked
      (e.g., device.click(...), Device.getMain(), etc.), ensuring output
      reflects only the most recent logical step.
  • Validation & errors:
    • addOutput(message) requires exactly one argument; otherwise calls setError("Invalid parameter input")
      and returns false.

Example Scenarios

  1. Accumulate simple messages across steps, then consume via lastOutput()
  2. Store structured JSON and numbers, preserving order
  3. Use with addDeviceFunction(..., { multiple: true }) to collect values (e.g., SNs) from many devices

common/print.js

Logging and pretty-print utilities for the Sigma RT script runtime.

This module provides lightweight console output helpers that integrate with the
Sigma RT Java bridge (com.sigma_rt.script.ScriptParameter). It offers plain
and color-capable printing, formatted error emission that aborts the running
script, indentation helpers for structured logs, and a recursive pretty-printer
for objects and arrays.

Core Features:

  • Thin wrappers around the engine's print for consistent spacing.
  • ANSI escape sequence awareness (prevents spurious spaces between color codes).
  • Uniform error printing helpers (printErr, printSysErr) that terminate with "csStop".
  • Indentation utility for building multi-line, hierarchical output.
  • printVar for readable, recursive object/array inspection.

common/runtime.js

Provides a thin runtime bridge to the Sigma-RT scripting engine (Total Control),
exposing common script primitives such as metadata definition, blocking delays, execution checks,
and configuration retrieval.

The runtime module wraps engine-bound capabilities via global.sigmaScriptParameter,
offering a small, predictable API you can use across legacy JavaScript hosts
(e.g., Rhino/RingoJS–style environments embedded by the engine).

Core Features:

  • Script metadata (define): Declare script versioning, recording resolution, required engine version,
    log verbosity, script path, and screen orientation.
  • Blocking delay (delay): Pause the script synchronously for a given number of milliseconds.
  • Execution guard (checkScriptExit): Probe engine state to gracefully stop work if the script
    has been requested to exit (useful in long loops/polls).
  • Configuration lookup (getSetting): Read Total Control properties and device-scoped settings
    (e.g., path bundle, build country code) with automatic JSON parsing when appropriate.

common/scripts.js

Scripting control module for the Total Control automation system.

This module provides high-level helpers to run, monitor, and stop automation scripts
across the Total Control environment. It supports executing JavaScript (.js) files
and test scenario files (.tst), passing arguments and device hints, resolving
script paths from multiple locations, and capturing/propagating exit codes in a
consistent way (via exit() or quit() semantics).

It also exposes utilities to list running scripts, kill one or all scripts, and
run inline test functions with argument passing (sigmaRun) to simplify debugging.
Internally it integrates with the Total Control task context (sigmaConstItemId)
so logs, device managers, and utilities are correctly bound to the current run.

Key Features

  • Run JS or TST files with aliasing and argument passing (scriptRun)
  • Poll script status by alias (scriptWait) and terminate runs (scriptKill, scriptKillAll)
  • Enumerate currently running scripts and their metadata (scriptList)
  • Execute an in-memory function with arguments, capturing exit codes (sigmaRun)
  • Load and execute a script file with path fallback and exit-code capture (sigmaLoad, alias tcLoad)
  • Explicit script termination helpers:
    • exit(code): throws a special, catchable signal used by runners to return code
    • quit(code): immediately aborts the script with a ||quit||<code> marker
  • Configure and query script context (setScriptFileName / getScriptFileName,
    setSigmaConstItemId / getSigmaConstItemId, getExitCode)

common/system.js

System utilities module for the Total Control scripting environment.

This module (path: "sigma/common/system") exposes lightweight host-side helpers
that interact with the desktop OS and the Total Control (TC) runtime. Use it to
execute local shell commands, read the system clipboard, and query TC’s language
and API version. It is framework-agnostic: functions are exported directly and are
not attached to Device objects.

Import path: require("sigma/common/system")

Features

  • Run native commands on the host OS and capture stdout/stderr
  • Return command output as a single string or as an array of lines
  • Optionally filter out empty lines from command output
  • Read the desktop clipboard as plain text
  • Query the current TC scripting API version (e.g., "2.1.0.20911")
  • Query the TC UI language (e.g., "zh", "en")

common/ui.js

Provides simple, modal UI primitives for terminal-style scripts running on
Java-based script engines (e.g., Rhino/RingoJS within the Sigma runtime).

The common/ui module exposes blocking input dialogs and button-prompt utilities that
display HTML-capable messages, capture user responses, and gracefully handle cancellation.
It wraps the Sigma runtime’s TerminalInputDialog singleton and global.sigmaScriptParameter
helpers to offer a small, consistent API for user interaction.

Core Features:

  • HTML-capable message titles (e.g., <b>, <br>, \n line breaks).
  • Synchronous, modal prompts that return a value or a clear cancellation signal.
  • Text input with optional length constraint (short text) and unlimited-length input.
  • Multi-button selection dialogs with stable, 1-based index results.
  • Safe fallbacks: invalid parameters set an error and return null/0.

device.js

Provides device management and control utilities for Total Control scripting system.
Allows access to connected Android devices, querying device properties, and performing operations
such as selection, filtering, and batch execution. This module supports both object-oriented
(Device class) and utility-style APIs (getDevice, getDevices, etc.).

Features

  • Get the main or all connected Android devices
  • Filter devices by name, group, serial number, or selection state
  • Access device properties like name, width, height, etc.
  • Handle collections of devices using DeviceArray and output wrappers

excel.js

Excel automation module for Total Control scripting system.

This module allows reading, writing, editing, and navigating Excel files (both .xls and .xlsx)
programmatically without launching Excel. It leverages Apache POI and provides an easy-to-use interface
for accessing and modifying worksheets, individual cells, and data ranges.

Features

  • Supports both .xls and .xlsx formats
  • Access any cell using A1 notation (e.g., "B2", "C3:D5")
  • Update cell values and save files
  • Retrieve workbook and worksheet objects for POI-level control
  • Retrieve metadata such as sheet names and version
  • Export specific ranges or entire worksheets as 2D arrays
  • Switch between sheets dynamically

file.js

Device file management module for Android devices in the Total Control scripting system.

This module provides a high-level file I/O interface for managing files and folders
on connected Android devices, as well as transferring files between the device and
the host computer. All functions are exposed as Java-layer extensions to the
Device object so they can be invoked via device.cpFile(), device.readFile(),
etc.

Features

  • Copy and move files with optional overwrite
  • Rename files or relocate them atomically
  • Check whether a file or directory exists on the device
  • Read text content from a file
  • Write/append text to a file with optional offset and append mode
  • Delete files and remove directories
  • Upload files from PC → device and download files from device → PC with timeout control

image.js

This module provides image processing and screenshot functionality for Android devices controlled via Total Control.
It supports capturing, comparing, and parsing screen images in BMP format, as well as memory-optimized operations and visual element detection.

Key Features:

  • Capture screenshots to file, memory, or device storage.
  • Find images on screen or in memory using exact or fuzzy matching.
  • Wait for target images to appear on screen (waitForImage).
  • Read and parse BMP headers, including custom TC Creator metadata (parseBMP).
  • Use memory slots (@0, @1, @2, @@) for faster repeated image operations.
  • Retrieve raw image data (pixels and metadata) from screen or memory.

input.js

This module provides various input-related operations for simulating user actions on Android devices,
such as taps, swipes, scrolls, key presses, and directional movements. It enables automated UI interactions,
and supports both single and multi-device operations with absolute or relative coordinate systems.

All functions are dynamically attached to Device.prototype, allowing usage like device.click(...), device.scroll(...), etc.

Key Features

  • Touch Events**: Precise taps using click and randomized area taps using click2.
  • Scroll Simulation**: Scroll in any direction with pixel or ratio-based coordinates.
  • Key Event Sending**: Simulate key codes for HOME, BACK, VOLUME, letters, numbers, etc.
  • Directional Movement**: Use shift or move for predefined navigation gestures.
  • Multi-point Swipes**: Create complex gestures with swipe, supporting finger indexing and delay.
  • Multi-device Support**: Execute operations simultaneously on multiple connected devices.

keyboard.js

This module provides global keyboard shortcut functionality for the Total Control environment.
It allows users to bind physical key combinations (e.g., Ctrl+Alt+V) to functions executed on specific Android devices.

Key Features:

  • Register global keyboard shortcuts with custom handler functions.
  • Conditional execution based on foreground app and bound device.
  • Support for retrieving, triggering, logging, and unregistering shortcuts.
  • Automatically manages key uniqueness using app and device identifiers.

map.js

Provides a polyfill-style Map class compatible with legacy JavaScript environments such as Rhino or RingoJS.

The Map module implements an ES6-inspired key-value store with predictable iteration order,
offering modern APIs like set, get, delete, has, forEach, entries, and functional utilities.
It is designed for environments lacking native Map support, such as embedded test runners, script engines, or early JavaScript runtimes.

Core Features:

  • Key-based storage with insertion-order tracking.
  • Chainable and iterable methods including forEach, map, reduce, and filter.
  • Full support for functional transformations and merging/cloning operations.
  • Compatible keys(), values(), entries() for data traversal.
  • Custom sort methods: sortKeys(), sortValues(), and ordering control via reverse().

mte.js

Provides the Multi-threaded Execution (MTE) framework for automated test orchestration in Total Control.

The mte module enables parallel and configurable execution of test scripts across one or more Android devices,
leveraging .tpf configuration files and JavaScript-based test cases. It is ideal for scenarios such as regression testing,
multi-device validation, and scalable automation.

Core Features:

  • Create and manage test runs via the Testrun class.
  • Parallel execution across multiple devices (runDTest) or configuration variants (runCTest).
  • Real-time test state tracking, including messages, status, and device binding.
  • Static control interfaces for external status updates, result queries, and test termination.
  • Dynamic test data injection through .tpf config files or external data payloads.

navKeys.js

Navigation key control module for Android device interaction in the Total Control scripting system.

This module allows scripted directional navigation and screen scrolling actions on a connected device.
All functions are injected into Device.prototype, enabling direct use via device.up(), device.down(), etc.

It includes both basic directional actions (e.g., up, down) and accelerated versions (e.g., shiftUp, shiftPgDn)
for quicker movement. The module is useful for UI traversal, automated page scrolling, and script-driven navigation.

Features

  • Move the screen or focus slightly in all directions: up, down, left, right
  • Move faster or across larger sections with shiftUp, shiftDown, shiftPgUp, etc.
  • Scroll full pages with pgUp, pgDn
  • Uniform return value (0) on success
  • All functions are available as methods on device

notification.js

This module provides notification bar message monitoring functionality for Android devices within the Total Control environment.
It allows scripts to capture, filter, and respond to system or app-level notification messages in real time.

Key Features:

  • Create Notification objects to monitor messages by device, app, and content pattern.
  • Support both batch polling (getNotification()) and real-time listener (setListener()).
  • Support regex pattern matching and wildcard (tcConst.Any) for flexible filtering.
  • Retrieve matched notifications including app name, content, and device source.
  • Fully controllable with reset() and deleteListener() to manage message flow and memory.

ocr.js

This module provides OCR (Optical Character Recognition) functionality using Tesseract engine.
It enables text recognition from screen regions on Android devices, supporting multiple languages and layout modes.

Key Features:

  • Analyze screen content with support for English, Chinese, numbers, and multi-column layouts.
  • Upload .traineddata files for various languages.
  • Multiple recognition modes: single line, multiline, word, character, number, and unordered layout.

sqlite.js

Lightweight SQLite database access module [sqlite]

This module provides a simple, JDBC-based interface for working with SQLite databases
in Rhino/Java environments. It supports basic SQL execution, parameter binding, transactions,
migrations, and optional connection pooling for concurrent read/write access.

Designed for use in scripting environments where the SQLite JDBC driver (org.xerial:sqlite-jdbc)
is available on the classpath.

Key Features

  • Connection Management:
    • Open/close connections using file paths or JDBC/URI formats.
    • Configurable read-only mode, busy timeout, and PRAGMA foreign_keys settings.
  • SQL Execution:
    • run for INSERT/UPDATE/DELETE with affected row count and last insert ID.
    • get for fetching a single row, all for multiple rows.
    • exec for executing one or more SQL statements without parameters.
    • Automatic JDBC-to-JavaScript type coercion (e.g., timestamps to Date).
  • Parameter Binding:
    • Supports positional (?) and named (:name, @name, $name) parameters.
    • Handles Date, boolean, and other JavaScript values safely.
  • Batch Execution:
    • runMany for executing the same SQL statement with multiple parameter sets.
    • Optional transactional wrapping, batch size control, and error handling callbacks.
  • Transactions:
    • transaction helper with deferred, immediate, or exclusive modes.
  • Migrations:
    • migrate applies schema changes only once, tracked in an internal _migrations table.
  • Advanced Configuration:
    • SQLite.uri() helper for building JDBC URIs with query parameters.
    • setJournalMode / enableWAL for journal mode control.
  • Connection Pooling:
    • SQLitePool for managing one writer and multiple reader connections.
    • Thread-safe withWriter / withReader execution helpers.

system.js

This module provides system-level device control functionalities for Total Control environments.
It enables interaction with Android devices via JavaScript, offering APIs for device status querying, system configuration, screen control, and command execution.

Key Features:

  • Retrieve device properties: name, battery, screen orientation, IP, clipboard, brightness, volume, etc.
  • Modify device settings: clipboard content, brightness, input method, volume levels, and Wi-Fi state.
  • Control screen behavior: lock, unlock, sleep, wakeup.
  • Execute shell and ADB commands on connected devices.
  • Support for both single device and multiple device operations (Device and DeviceArray).
  • Utility functions for getting cursor coordinates, SD card path, temp path, and display mode.

task.js

This module provides scheduled and immediate task execution functionality within the Total Control environment.
It enables users to create, manage, and control script-based tasks that can run once or repeatedly based on flexible time schedules.

Key Features:

  • Create script tasks with absolute or relative paths.
  • Support for one-time execution, scheduled execution (date/time), and weekly recurring cycles.
  • Configure execution parameters such as iteration count, start time, target days, and devices.
  • Pause, resume, stop, or delete tasks at runtime.
  • Query task details and list all active or completed tasks.

tcThreadManager.js

Thread management for JavaScript running inside the Total Control (TC) environment.

This module exposes two thread wrappers — TCThread (backed by pooled Java platform threads)
and TCThreadVirtual (backed by JDK 21+ virtual threads) — plus a set of manager utilities
to coordinate thread lifecycle, cooperative pause/resume, interruption on timeout, and global
concurrency policy ("serialized" vs "unsafe-parallel").

Why this module exists
Rhino/RingoJS style engines frequently execute JS on a single-host thread and are not re‑entrant.
Running JS callbacks concurrently from multiple Java threads can corrupt interpreter state or
produce hard‑to‑debug races. This module provides:

  • A global JS lock to serialize entry into JS frames when policy is "serialized"
  • A thread registry with synchronized access to support lookups, counting, and cleanup
  • Cooperative controls (pause/resume/stop) that work with yield points inside user code
  • Stable waiting semantics via TCWait with immediate/finite timeout handling
  • Re‑runnable executor that can be shut down and automatically re‑created as needed

tests.js

This module provides device text control functions, including clipboard text retrieval and automated input capabilities on Android devices.
It allows developers to programmatically simulate text input, including support for multi-field forms using simulated tab and enter keys.

Key Features:

  • Clipboard Access: Get the current content of the device's clipboard.
  • Text Input: Simulate input into the currently focused or specified screen coordinates.
  • Form Input Support: Use \t (tab) and \n (enter) to fill multiple fields, ideal for login or registration forms.

trigger.js

This module provides a unified public interface for creating and managing event-based triggers within the Total Control system.
It allows developers to bind callback functions to system events (e.g. device connect, system start), as well as custom image-based or logic-based conditions.

Key Features:

  • Create triggers for various system events: startup, shutdown, device connection/disconnection, etc.
  • Support for image-based triggers ("Image:SeekImage").
  • Associate multiple callback functions with each trigger.
  • Enable, disable, query, or remove triggers at runtime.
  • Inspect registered triggers and their associated callbacks.