### Connection Setup (Bash) Source: https://context7.com/termux/termux-gui/llms.txt Establishes the two-socket IPC channel with the Termux:GUI plugin by creating abstract Unix domain sockets and broadcasting connection details. ```APIDOC ## Connection Setup (Bash) Establishing the two-socket IPC channel with the plugin. A program opens two server sockets, then fires an Android broadcast to hand the socket names to the plugin. ```bash # Bash: establish a connection to Termux:GUI MAIN_SOCK="myapp_main_$$" EVENT_SOCK="myapp_event_$$" # Create the two abstract Unix domain sockets and listen # (shown conceptually; real implementation uses socat or a language binding) # socat ABSTRACT-LISTEN:${MAIN_SOCK},fork ... & # socat ABSTRACT-LISTEN:${EVENT_SOCK},fork ... & # Deliver the broadcast so the plugin connects back am broadcast --user 0 \ -n com.termux.gui/.GUIReceiver \ --es mainSocket "$MAIN_SOCK" \ --es eventSocket "$EVENT_SOCK" # Optional: verify the peer UID matches your own UID for security # (supported in C bindings via getsockopt SO_PEERCRED) ``` ``` -------------------------------- ### Create New Activity with Termux:GUI (Python) Source: https://context7.com/termux/termux-gui/llms.txt Launches a new Android Activity using the 'newActivity' method. This example demonstrates creating a normal, full-screen activity within a new Task. The response contains the Activity ID and Task ID. ```python # JSON protocol example — create a normal full-screen activity in a new Task send_method(sock, "newActivity", { # omit "tid" to start a new Task "intercept": False # do NOT intercept back button }) response = recv_response(sock) # [aid, tid] or -1 on error aid, tid = response[0], response[1] print(f"Activity id={aid}, Task id={tid}") ``` -------------------------------- ### Manage Activity Configuration in Termux:GUI Source: https://context7.com/termux/termux-gui/llms.txt This code shows how to query device configuration, control orientation, and set themes using Termux:GUI. It includes examples for checking dark mode and preventing screenshots. ```python # Query current configuration send_method(sock, "getConfiguration", {"aid": aid}) cfg = recv_response(sock) # Returns: {"dark_mode": True, "orientation": "portrait", "screenwidth": 393, # "screenheight": 851, "language": "en", "country": "US", # "fontscale": 1.0, "density": 2.75, "keyboardHidden": True} ``` -------------------------------- ### Binary Protocol Method Invocation with Protobuf Source: https://context7.com/termux/termux-gui/llms.txt Send delimited protobuf Method messages and receive corresponding *Response messages. This example shows creating a new activity using the binary protocol. ```python # Python pseudo-example using the generated protobuf stubs import socket, struct from tgui.proto0 import GUIProt0_pb2 as proto # After connecting and negotiating with byte 0x00 (binary protocol): def send_proto(sock, method_msg): data = method_msg.SerializeToString() # Write as varint-delimited (protobuf standard delimited encoding) size_varint = encode_varint(len(data)) sock.sendall(size_varint + data) def recv_proto(sock, response_class): size = decode_varint_from_socket(sock) data = _recv_exact(sock, size) return response_class.FromString(data) # Create an Activity req = proto.Method() req.newActivity.tid = -1 # new Task req.newActivity.type = proto.NewActivityRequest.normal req.newActivity.interceptBackButton = False send_proto(sock, req) resp = recv_proto(sock, proto.NewActivityResponse) if resp.aid == -1: raise RuntimeError("Failed to create activity") print(f"aid={resp.aid}, tid={resp.tid}") ``` -------------------------------- ### newActivity Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Launches a new Android Activity. It can be started in a new task, as a dialog, in Picture-in-Picture mode, on the lockscreen, or as an overlay. It also supports intercepting back button presses and configuring dialog dismissal. ```APIDOC ## newActivity ### Description Launches a new Activity and returns the activity id. In case of an error, -1 is returned. ### Parameters - **tid** (integer) - Optional - The task in which the Activity should be started. If not specified, a new Task is created and the id is returned after the Activity id. - **dialog** (boolean) - Optional - If true, the Activity will be launched as a dialog. - **pip** (boolean) - Optional - Whether or not to start the Activity in Picture-in-Picture mode. Default is false. This should only be used to create Activities in a new Task. - **lockscreen** (boolean) - Optional - Displays this Activity on the lockscreen. - **overlay** (boolean) - Optional - Uses a system overlay window to display above everything else. Overlays are never in a Task and creating one doesn't return a Task id. Overlays don't get Activity lifecycle events. - **intercept** (boolean) - Optional - Whether to intercept back button presses and send an event or to use the default action of finishing the Activity. Default value is false. - **canceloutside** (boolean) - Optional - Sets whether the Activity is destroyed when it is displayed as a dialog and the user clicks outside. Default is true. ``` -------------------------------- ### getText Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Gets the text of the View. Applicable to TextView, Button, or EditText. ```APIDOC ## getText ### Description Gets the text of the View. Applicable to TextView, Button, or EditText. ### Parameters #### Path Parameters - **id** (integer) - Required - The View id. - **aid** (integer) - Required - The id of the Activity the View is in. ``` -------------------------------- ### getScrollPosition Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Gets the x and y scroll position of an NestedScrollView or HorizontalScrollView. ```APIDOC ## getScrollPosition ### Description Gets the x and y scroll position of an NestedScrollView or HorizontalScrollView. ### Parameters #### Path Parameters - **id** (integer) - Required - The View id. - **aid** (integer) - Required - The id of the Activity the View is in. ``` -------------------------------- ### getDimensions Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Gets the current width and height of a View in pixels. ```APIDOC ## getDimensions ### Description Gets the current width and height of a View in pixels. ### Parameters #### Path Parameters - **id** (string) - Required - The id of the View. - **aid** (string) - Required - The id of the Activity the View is in. ``` -------------------------------- ### Establish Connection to Termux:GUI (Bash) Source: https://context7.com/termux/termux-gui/llms.txt Sets up the necessary environment variables for socket names and broadcasts to the Termux:GUI plugin to establish the IPC channel. Ensure socat or a language binding is used to create the actual sockets. ```bash # Bash: establish a connection to Termux:GUI MAIN_SOCK="myapp_main_$$" EVENT_SOCK="myapp_event_$$" # Create the two abstract Unix domain sockets and listen # (shown conceptually; real implementation uses socat or a language binding) # socat ABSTRACT-LISTEN:${MAIN_SOCK},fork ... & # socat ABSTRACT-LISTEN:${EVENT_SOCK},fork ... & # Deliver the broadcast so the plugin connects back am broadcast --user 0 \ -n com.termux.gui/.GUIReceiver \ --es mainSocket "$MAIN_SOCK" \ --es eventSocket "$EVENT_SOCK" # Optional: verify the peer UID matches your own UID for security # (supported in C bindings via getsockopt SO_PEERCRED) ``` -------------------------------- ### Send Method with Configuration and Toast Source: https://context7.com/termux/termux-gui/llms.txt This snippet demonstrates sending a method with specific configuration parameters, including aid, orientation, and secure flags, and displaying a toast message. ```python send_method(sock, "setOrientation", {"aid": aid, "orientation": "landscape"}) # Prevent screenshots and task-switcher preview send_method(sock, "setSecure", {"aid": aid, "secure": True}) # Toast message (no activity needed) send_method(sock, "toast", {"text": "Settings saved!", "long": False}) ``` -------------------------------- ### Receive Response with Configuration Details Source: https://context7.com/termux/termux-gui/llms.txt This code receives a response from the Termux:GUI server, including details about dark mode, orientation, screen dimensions, language, country, font scale, and keyboard hidden status. ```python cfg = recv_response(sock) # Returns: {"dark_mode": True, "orientation": "portrait", "screenwidth": 393, # "screenheight": 851, "language": "en", "country": "US", # "fontscale": 1.0, "density": 2.75, "keyboardHidden": True} ``` -------------------------------- ### Create a Button in Termux:GUI Source: https://context7.com/termux/termux-gui/llms.txt This snippet demonstrates how to create a button with specific text and properties using the Termux:GUI protocol. Ensure the 'proto' and 'sock' objects are properly initialized. ```python req2 = proto.Method() req2.createButton.data.aid = resp.aid req2.createButton.data.parent = -1 req2.createButton.data.v = proto.visible req2.createButton.text = "Click Me" req2.createButton.allcaps = False send_proto(sock, req2) btn_resp = recv_proto(sock, proto.CreateButtonResponse) print(f"Button id={btn_resp.id}") ``` -------------------------------- ### Create Button Source: https://context7.com/termux/termux-gui/llms.txt This snippet demonstrates how to create a button with specified text and properties using the Protobuf protocol. ```APIDOC ## createButton ### Description Creates a button element within the Termux:GUI interface. ### Method Uses Protobuf protocol via `send_proto` and `recv_proto`. ### Parameters - `req2.createButton.data.aid`: The application ID. - `req2.createButton.data.parent`: The parent element ID (-1 for root). - `req2.createButton.data.v`: Visibility status. - `req2.createButton.text`: The text displayed on the button. - `req2.createButton.allcaps`: Boolean indicating if the text should be all caps. ### Response - `btn_resp.id`: The unique identifier of the created button. ``` -------------------------------- ### Binary Protocol (Protobuf) Source: https://context7.com/termux/termux-gui/llms.txt Interact with the Termux GUI service using a binary protocol based on Protocol Buffers. ```APIDOC ## Method Invocation (Binary Protocol) ### Description Sends delimited protobuf `Method` messages and receives corresponding `*Response` messages over a socket connection. ### Protocol Details - Negotiation starts with byte `0x00` for binary protocol. - Messages are varint-delimited. ### send_proto Function #### Description Serializes a protobuf method message and sends it over the socket. #### Parameters - **sock** (socket) - The socket connection. - **method_msg** (proto.Method) - The protobuf message to send. ### recv_proto Function #### Description Receives a varint-delimited protobuf message from the socket and deserializes it. #### Parameters - **sock** (socket) - The socket connection. - **response_class** (class) - The expected response protobuf class. #### Returns - Deserialized protobuf response message. ### Example: Create Activity #### Request ```python req = proto.Method() req.newActivity.tid = -1 req.newActivity.type = proto.NewActivityRequest.normal req.newActivity.interceptBackButton = False send_proto(sock, req) ``` #### Response ```python resp = recv_proto(sock, proto.NewActivityResponse) # Check resp.aid and resp.tid ``` ``` -------------------------------- ### Python: Create and Select Tabs in TabLayout Source: https://context7.com/termux/termux-gui/llms.txt Creates a tab layout and populates it with tab names. Allows programmatic switching to a specific tab using its index. ```python send_method(sock, "createTabLayout", {"aid": aid, "parent": root_layout}) tabs_id = recv_response(sock) send_method(sock, "setList", { "aid": aid, "id": tabs_id, "list": ["Home", "Search", "Profile"] }) # Switch to the "Search" tab (index 1) programmatically send_method(sock, "selectTab", {"aid": aid, "id": tabs_id, "tab": 1}) ``` -------------------------------- ### Control Activity Configuration and UI Elements Source: https://context7.com/termux/termux-gui/llms.txt This snippet demonstrates controlling activity configuration, such as forcing landscape orientation and preventing screenshots, using Termux:GUI. It also shows how to display a toast message. ```python # Force landscape orientation send_method(sock, "setOrientation", {"aid": aid, "orientation": "landscape"}) # Prevent screenshots and task-switcher preview send_method(sock, "setSecure", {"aid": aid, "secure": True}) # Toast message (no activity needed) send_method(sock, "toast", {"text": "Settings saved!", "long": False}) ``` -------------------------------- ### Create Dialog and Overlay Activities Source: https://context7.com/termux/termux-gui/llms.txt Use 'newActivity' to create dialogs or system overlays. Dialogs are modal and disappear on outside tap. Overlays appear above all other applications. ```python send_method(sock, "newActivity", { "tid": tid, "dialog": True, "canceloutside": True # destroyed when user taps outside }) dialog_aid = recv_response(sock) # single int (no new task) send_method(sock, "newActivity", {"overlay": True}) overlay_aid = recv_response(sock) ``` -------------------------------- ### Python: Create and Select Spinner Items Source: https://context7.com/termux/termux-gui/llms.txt Creates a dropdown menu (Spinner) and populates it with a list of options. Allows programmatic selection of an item by its index. ```python send_method(sock, "createSpinner", {"aid": aid, "parent": root_layout}) spinner_id = recv_response(sock) send_method(sock, "setList", { "aid": aid, "id": spinner_id, "list": ["Option A", "Option B", "Option C", "Option D"] }) # Programmatically select "Option B" (index 1) send_method(sock, "selectItem", {"aid": aid, "id": spinner_id, "item": 1}) # itemselected event arrives on event socket when user or code changes selection: # {"type": "itemselected", "value": {"id": spinner_id, "aid": aid, "selected": "Option B"}} ``` -------------------------------- ### Activity Creation Source: https://context7.com/termux/termux-gui/llms.txt Methods for creating new activities, including dialogs and system overlays. ```APIDOC ## newActivity - Create a new Activity ### Description Creates a new activity within an existing task. This can be a standard activity, a dialog, or a system overlay. ### Method `send_method(sock, "newActivity", params)` ### Parameters - **tid** (int) - Optional - The task ID to create the activity in. If not provided, a new task is created. - **dialog** (bool) - Optional - If true, creates a dialog activity. - **canceloutside** (bool) - Optional - If true, the dialog is destroyed when the user taps outside of it. - **overlay** (bool) - Optional - If true, creates a system overlay activity that shows above all other apps. ### Response - **aid** (int) - The activity ID of the newly created activity. ``` -------------------------------- ### Send Method to Set Orientation and Secure Flags Source: https://context7.com/termux/termux-gui/llms.txt This snippet demonstrates sending a method to set the orientation and secure flags for an activity, ensuring proper security and display settings. ```python send_method(sock, "setOrientation", {"aid": aid, "orientation": "landscape"}) # Prevent screenshots and task-switcher preview send_method(sock, "setSecure", {"aid": aid, "secure": True}) ``` -------------------------------- ### Create LinearLayout and Child Views Source: https://context7.com/termux/termux-gui/llms.txt Build UI hierarchies by creating views with specified parents. Use `parent=-1` for the root view. Each creation returns a View ID. ```python # Build a vertical form: LinearLayout → [TextView label, EditText, Button] # Root vertical linear layout (no parent = replaces root) send_method(sock, "createLinearLayout", { "aid": aid, "parent": -1, "vertical": True, "visibility": 2 # 2 = visible }) root_layout = recv_response(sock) # e.g. 1 # Label send_method(sock, "createTextView", { "aid": aid, "parent": root_layout, "text": "Enter your name:", "selectableText": False }) label_id = recv_response(sock) # Text input send_method(sock, "createEditText", { "aid": aid, "parent": root_layout, "type": "text", "singleline": True, "line": True }) edit_id = recv_response(sock) # Submit button send_method(sock, "createButton", { "aid": aid, "parent": root_layout, "text": "Submit", "allcaps": False }) btn_id = recv_response(sock) print(f"Layout={root_layout}, Label={label_id}, Edit={edit_id}, Btn={btn_id}") ``` -------------------------------- ### Activity Configuration Source: https://context7.com/termux/termux-gui/llms.txt This section covers methods for querying and setting activity configurations, including theme, orientation, and secure flags. ```APIDOC ## getConfiguration ### Description Queries the current device configuration such as screen size, dark mode, and locale. ### Method `send_method(sock, "getConfiguration", {"aid": aid})` ### Response (Success) - `dark_mode` (boolean): Indicates if dark mode is enabled. - `orientation` (string): Current screen orientation ('portrait' or 'landscape'). - `screenwidth` (integer): Width of the screen in pixels. - `screenheight` (integer): Height of the screen in pixels. - `language` (string): Device language code. - `country` (string): Device country code. - `fontscale` (float): Font scaling factor. - `density` (float): Screen density. - `keyboardHidden` (boolean): Indicates if the keyboard is hidden. ``` ```APIDOC ## setTheme ### Description Sets the theme colors for the activity. ### Method `send_method(sock, "setTheme", { ... })` ### Parameters - `aid` (integer): The application ID. - `statusBarColor` (integer): Color of the status bar. - `colorPrimary` (integer): Primary color of the activity. - `windowBackground` (integer): Background color of the window. - `textColor` (integer): Default text color. - `colorAccent` (integer): Accent color. ``` ```APIDOC ## setOrientation ### Description Forces a specific screen orientation. ### Method `send_method(sock, "setOrientation", { ... })` ### Parameters - `aid` (integer): The application ID. - `orientation` (string): The desired orientation ('portrait' or 'landscape'). ``` ```APIDOC ## setSecure ### Description Enables or disables secure flags for the activity, preventing screenshots and task-switcher previews. ### Method `send_method(sock, "setSecure", { ... })` ### Parameters - `aid` (integer): The application ID. - `secure` (boolean): `True` to enable secure flags, `False` otherwise. ``` ```APIDOC ## toast ### Description Displays a short toast message to the user. ### Method `send_method(sock, "toast", { ... })` ### Parameters - `text` (string): The message to display. - `long` (boolean): `True` for a long duration toast, `False` for a short duration. ``` -------------------------------- ### Dropdown Menus (Spinner) Source: https://context7.com/termux/termux-gui/llms.txt Creates a spinner (dropdown menu), populates it with a list of options, and programmatically selects an item. ```APIDOC ## createSpinner / setList / selectItem — Dropdown Menus A Spinner provides a drop-down selection widget; setList populates it and selectItem chooses a value programmatically. ```python send_method(sock, "createSpinner", {"aid": aid, "parent": root_layout}) spinner_id = recv_response(sock) send_method(sock, "setList", { "aid": aid, "id": spinner_id, "list": ["Option A", "Option B", "Option C", "Option D"] }) # Programmatically select "Option B" (index 1) send_method(sock, "selectItem", {"aid": aid, "id": spinner_id, "item": 1}) # itemselected event arrives on event socket when user or code changes selection: # {"type": "itemselected", "value": {"id": spinner_id, "aid": aid, "selected": "Option B"}} ``` ``` -------------------------------- ### Negotiate Protocol with Termux:GUI (Python) Source: https://context7.com/termux/termux-gui/llms.txt Sends a negotiation byte to the Termux:GUI plugin to select the communication protocol (JSON or Protobuf). The plugin responds with an error code if the negotiation fails. ```python import socket, struct # Bit layout of negotiation byte: # bits 3-0 = protocol type: 0 = binary/protobuf, 1 = JSON # bits 7-4 = protocol version (currently 0) PROTO_JSON = 0x01 # JSON protocol PROTO_BINARY = 0x00 # Protobuf (binary) protocol def negotiate(sock: socket.socket, proto: int = PROTO_JSON) -> bool: sock.sendall(bytes([proto])) response = sock.recv(1) if response[0] != 0: raise RuntimeError(f"Plugin rejected protocol (error code {response[0]})") return True # Example: negotiate JSON protocol with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: s.connect('\x00myapp_main_1234') # abstract namespace: leading null byte negotiate(s, PROTO_JSON) print("JSON protocol ready") ``` -------------------------------- ### Input and Event Handling Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Methods for managing soft keyboard and back button events. ```APIDOC ## hideSoftKeyboard ### Description Forces the soft keyboard to hide. ### Parameters - **aid** (integer) - The Activity id of the Activity that wants to hide the soft keyboard. ``` ```APIDOC ## interceptBackButton ### Description Sets whether the back button press should close the activity or be intercepted and sent as an event. ### Parameters - **aid** (integer) - The Activity id of the Activity that wants to intercept back button presses. - **intercept** (boolean) - Whether to intercept back button presses and send an event, or to use the default action of finishing the Activity. ``` -------------------------------- ### Display Images and Use Shared Buffers Source: https://context7.com/termux/termux-gui/llms.txt Show PNG/JPEG images in an ImageView or use high-performance shared-memory buffers for real-time updates. Shared buffers require native bindings for direct memory access. ```python import base64 # --- Simple image from file --- send_method(sock, "createImageView", {"aid": aid, "parent": root_layout}) img_view = recv_response(sock) with open("/sdcard/photo.png", "rb") as f: img_data = base64.b64encode(f.read()).decode() send_method(sock, "setImage", {"aid": aid, "id": img_view, "img": img_data}) # --- Shared memory buffer (for real-time updates) --- send_method(sock, "addBuffer", {"format": "ARGB8888", "w": 320, "h": 240}) # The binary response carries: int32 buffer_id + SCM_RIGHTS file descriptor # (Handled natively by C/C++ bindings via AHardwareBuffer) buffer_id = recv_int32_with_fd(sock) # language-binding specific send_method(sock, "setBuffer", {"aid": aid, "id": img_view, "bid": buffer_id}) # Write pixels directly into the shared fd, then blit and refresh: ``` -------------------------------- ### Information Methods Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Methods to retrieve information about the current screen and device state. ```APIDOC ## keyboardHidden ### Description Checks if a keyboard is currently available on the screen. ### Returns - **keyboardHidden** (boolean) - true if a keyboard is not available, false otherwise. ``` ```APIDOC ## screenwidth ### Description Gets the current window width in density-independent pixels (dp). ### Returns - **screenwidth** (integer) - The current screen width in dp. ``` ```APIDOC ## screenheight ### Description Gets the current window height in density-independent pixels (dp). ### Returns - **screenheight** (integer) - The current screen height in dp. ``` ```APIDOC ## fontscale ### Description Retrieves the current font scaling factor. ### Returns - **fontscale** (float) - The current font scale value. ``` ```APIDOC ## density ### Description Gets the display density of the screen. ### Returns - **density** (float) - The display density, where screenwidth * density = screenwidth_in_px. ``` -------------------------------- ### Set Activity Theme and Colors Source: https://context7.com/termux/termux-gui/llms.txt This snippet shows how to set activity theme properties, including status bar color, primary color, window background, text color, accent color, and font scale, using Termux:GUI. ```python send_method(sock, "setTheme", { "aid": aid, "statusBarColor": 0xFF000000, "colorPrimary": 0xFF1F1F1F, "windowBackground": 0xFF121212, "textColor": 0xFFFFFFFF, "colorAccent": 0xFF03DAC6 }) ``` -------------------------------- ### Tab Navigation (TabLayout) Source: https://context7.com/termux/termux-gui/llms.txt Creates a tab layout, sets the list of tabs, and programmatically selects a tab. ```APIDOC ## createTabLayout / selectTab — Tab Navigation TabLayout provides a horizontal row of named tabs for switching between content areas. ```python send_method(sock, "createTabLayout", {"aid": aid, "parent": root_layout}) tabs_id = recv_response(sock) send_method(sock, "setList", { "aid": aid, "id": tabs_id, "list": ["Home", "Search", "Profile"] }) # Switch to the "Search" tab (index 1) programmatically send_method(sock, "selectTab", {"aid": aid, "id": tabs_id, "tab": 1}) ``` ``` -------------------------------- ### Create and Populate Remote Layout for Widgets Source: https://context7.com/termux/termux-gui/llms.txt Create a remote layout, add text and button views, set their properties, and assign the layout to a widget. The 'remoteclick' event fires when a button is tapped. ```python # Create a remote layout for a widget send_method(sock, "createRemoteLayout") rid = recv_response(sock) # Populate it send_method(sock, "addRemoteTextView", {"rid": rid}) tv_id = recv_response(sock) send_method(sock, "addRemoteButton", {"rid": rid, "parent": -1}) # top-level btn_rid = recv_response(sock) send_method(sock, "setRemoteText", {"rid": rid, "id": tv_id, "text": "Widget Text"}) send_method(sock, "setRemoteText", {"rid": rid, "id": btn_rid,"text": "Tap Me"}) send_method(sock, "setRemoteTextColor", {"rid": rid, "id": tv_id, "color": 0xFF03DAC6}) # Assign the layout to a widget (wid comes from the widget intent) send_method(sock, "setWidgetLayout", {"rid": rid, "wid": "some_widget_id"}) ``` -------------------------------- ### View Creation Source: https://context7.com/termux/termux-gui/llms.txt Methods for creating various UI elements like layouts, text views, buttons, and edit texts. ```APIDOC ## View Creation (createLinearLayout / createTextView / createButton / createEditText) ### Description Creates UI Views and places them in a hierarchy. Pass `parent=-1` to set the root View. Each `create*` call returns a View ID or -1 on error. ### Methods - `send_method(sock, "createLinearLayout", params)` - `send_method(sock, "createTextView", params)` - `send_method(sock, "createButton", params)` - `send_method(sock, "createEditText", params)` ### Parameters for createLinearLayout - **aid** (int) - Required - The activity ID. - **parent** (int) - Required - The parent View ID. Use -1 for the root. - **vertical** (bool) - Optional - If true, the layout is vertical. - **visibility** (int) - Optional - View visibility state (0=gone, 1=hidden, 2=visible). ### Parameters for createTextView - **aid** (int) - Required - The activity ID. - **parent** (int) - Required - The parent View ID. - **text** (string) - Optional - The text to display. - **selectableText** (bool) - Optional - If true, the text can be selected. ### Parameters for createButton - **aid** (int) - Required - The activity ID. - **parent** (int) - Required - The parent View ID. - **text** (string) - Optional - The button text. - **allcaps** (bool) - Optional - If true, the text is displayed in all caps. ### Parameters for createEditText - **aid** (int) - Required - The activity ID. - **parent** (int) - Required - The parent View ID. - **type** (string) - Optional - The input type (e.g., "text"). - **singleline** (bool) - Optional - If true, the edit text is single line. - **line** (bool) - Optional - If true, a line is drawn below the edit text. ### Response - **view_id** (int) - The ID of the created View, or -1 on error. ``` -------------------------------- ### requestFocus Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Focuses a View and opens the soft keyboard if the View has Keyboard input. ```APIDOC ## requestFocus ### Description Focuses a View and opens the soft keyboard if the View has Keyboard input. ### Parameters #### Path Parameters - **id** (integer) - Required - The View id. - **aid** (integer) - Required - The id of the Activity the View is in. - **forcesoft** (boolean) - Optional - Forces the soft keyboard to show. ``` -------------------------------- ### Set Activity Theme Source: https://context7.com/termux/termux-gui/llms.txt Apply activity-wide colors using RGBA8888 format. Colors are packed as a 32-bit integer (0xAABBGGRR). No response is returned; changes are queued if the activity is not visible. ```python # Dark theme: black background, white text, blue accent send_method(sock, "setTheme", { "aid": aid, "statusBarColor": 0xFF1A1A1A, # near-black "colorPrimary": 0xFF1A1A1A, "windowBackground":0xFF121212, "textColor": 0xFFFFFFFF, # white "colorAccent": 0xFFBB86FC # purple accent }) ``` -------------------------------- ### Find NDK Library Source: https://github.com/termux/termux-gui/blob/main/hbuffers/src/main/cpp/CMakeLists.txt Searches for a specified prebuilt library (like 'log') and stores its path in a variable. CMake verifies the library's existence. ```cmake find_library( log-lib log) ``` -------------------------------- ### Protocol Negotiation (Python) Source: https://context7.com/termux/termux-gui/llms.txt Negotiates the communication protocol (JSON or Protobuf) with the Termux:GUI plugin after establishing a connection. ```APIDOC ## Protocol Negotiation (Python) After the plugin connects, the client sends one negotiation byte specifying the protocol type and version before any other message. ```python import socket, struct # Bit layout of negotiation byte: # bits 3-0 = protocol type: 0 = binary/protobuf, 1 = JSON # bits 7-4 = protocol version (currently 0) PROTO_JSON = 0x01 # JSON protocol PROTO_BINARY = 0x00 # Protobuf (binary) protocol def negotiate(sock: socket.socket, proto: int = PROTO_JSON) -> bool: sock.sendall(bytes([proto])) response = sock.recv(1) if response[0] != 0: raise RuntimeError(f"Plugin rejected protocol (error code {response[0]})") return True # Example: negotiate JSON protocol with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: s.connect('\x00myapp_main_1234') # abstract namespace: leading null byte negotiate(s, PROTO_JSON) print("JSON protocol ready") ``` ``` -------------------------------- ### Send Proto Message with Button Creation Data Source: https://context7.com/termux/termux-gui/llms.txt This snippet shows how to send a protobuf message to create a button with specified attributes like aid, parent, and visibility. ```python req2 = proto.Method() req2.createButton.data.aid = resp.aid req2.createButton.data.parent = -1 req2.createButton.data.v = proto.visible req2.createButton.text = "Click Me" req2.createButton.allcaps = False send_proto(sock, req2) ``` -------------------------------- ### setList Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Set the list of a Spinner or TabLayout. ```APIDOC ## setList ### Description Set the list of a Spinner or TabLayout. ### Parameters #### Path Parameters - **id** (integer) - Required - The View id of a Spinner or TabLayout. - **aid** (integer) - Required - The id of the Activity the View is in. - **list** (array of strings) - Required - An array containing the available Spinner options / TabLayout tab titles as strings. ``` -------------------------------- ### RemoteViews for Widgets Source: https://context7.com/termux/termux-gui/llms.txt Create and populate remote layouts for home screen widgets. ```APIDOC ## createRemoteLayout ### Description Creates a new remote layout that can be populated with views. ### Method `send_method(sock, "createRemoteLayout")` ### Response Example `rid = recv_response(sock)` ## addRemoteTextView ### Description Adds a text view to the current remote layout. ### Method `send_method(sock, "addRemoteTextView", { ... })` ### Parameters - **rid** (int) - Required - The ID of the remote layout. ### Response Example `tv_id = recv_response(sock)` ## addRemoteButton ### Description Adds a button to the current remote layout. ### Method `send_method(sock, "addRemoteButton", { ... })` ### Parameters - **rid** (int) - Required - The ID of the remote layout. - **parent** (int) - Optional - The ID of the parent view. Defaults to top-level. ### Response Example `btn_rid = recv_response(sock)` ## setRemoteText ### Description Sets the text for a specific view within a remote layout. ### Method `send_method(sock, "setRemoteText", { ... })` ### Parameters - **rid** (int) - Required - The ID of the remote layout. - **id** (int) - Required - The ID of the view to update. - **text** (string) - Required - The text to set. ## setRemoteTextColor ### Description Sets the text color for a specific text view within a remote layout. ### Method `send_method(sock, "setRemoteTextColor", { ... })` ### Parameters - **rid** (int) - Required - The ID of the remote layout. - **id** (int) - Required - The ID of the text view. - **color** (int) - Required - The color value (e.g., 0xFF03DAC6). ## setWidgetLayout ### Description Assigns a remote layout to a specific widget. ### Method `send_method(sock, "setWidgetLayout", { ... })` ### Parameters - **rid** (int) - Required - The ID of the remote layout. - **wid** (string) - Required - The ID of the widget. ### Response Example `recv_response(sock)` ``` -------------------------------- ### Plugin and Security Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Methods for retrieving plugin version and managing activity security flags. ```APIDOC ## getVersion ### Description Gets the version code of the plugin app. This can be used for feature detection or to prompt the user to update. ### Returns - **version** (integer) - The version code of the plugin app. ``` ```APIDOC ## setSecure ### Description Sets the FLAG_SECURE of the Activity. ### Parameters - **aid** (integer) - The Activity id of the Activity. - **secure** (boolean) - Whether FLAG_SECURE should be set or not. ``` -------------------------------- ### set(Width/Height) Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Sets the width or height of a View. ```APIDOC ## set(Width/Height) ### Description Sets the width or height of a View. ### Parameters #### Path Parameters - **width/height** (string) - Required - The desired dimension. Can be a value in dp, "MATCH_PARENT", or "WRAP_CONTENT". - **id** (string) - Required - The id of the View. - **aid** (string) - Required - The id of the Activity the View is in. - **px** (boolean) - Optional - If true, the measurement is in pixels instead of dp. Default is false. ``` -------------------------------- ### TabLayout and Spinner Methods Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Methods for interacting with TabLayouts and Spinners, allowing selection of tabs and items respectively. ```APIDOC ## selectTab TabLayout ### Description Selects a Tab in a TabLayout. The corresponding itemselected event is also send. ### Parameters - **id** (int) - Required - The View id of a TabLayout. - **aid** (int) - Required - The id of the Activity the View is in. - **tab** (int) - Required - The index of the tab to select, starting at 0. ## selectItem Spinner ### Description Selects a item in a Spinner. The corresponding itemselected event is also send. ### Parameters - **id** (int) - Required - The View id of a Spinner. - **aid** (int) - Required - The id of the Activity the View is in. - **item** (int) - Required - The index of the item to select, starting at 0. ``` -------------------------------- ### WebView Control Methods Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Methods for controlling and interacting with WebViews, including JavaScript execution, content loading, and navigation. ```APIDOC ## allowJavascript WebView ### Description Asks the user for permission to run Javascript in the WebView, if it isn't enabled globally in the options. Returns whether Javascript is enabled after the call. ### Parameters - **aid** (int) - Required - The id of the Activity the View is in. - **id** (int) - Required - The id of the WebView. - **allow** (boolean) - Required - Whether to allow or disallow Javascript. ## allowContentURI WebView ### Description Sets whether loading content:// URIs is allowed in the WebView. This can be used to open data from other apps in the WebView. ### Parameters - **aid** (int) - Required - The id of the Activity the View is in. - **id** (int) - Required - The id of the WebView. - **allow** (boolean) - Required - Whether to allow or disallow content:// URIs. ## setData WebView ### Description Sets the document displayed in the WebView. ### Parameters - **aid** (int) - Required - The id of the Activity the View is in. - **id** (int) - Required - The id of the WebView. - **doc** (string) - Required - A string containing the HTML document. - **mime** (string) - Optional - The mime type. Default is text/html. - **base64** (boolean) - Optional - Whether the data is base64-encoded or not. Default is false. [If false non-ASCII characters have to be escaped](https://developer.android.com/reference/android/webkit/WebView#loadData(java.lang.String,%20java.lang.String,%20java.lang.String)). ## loadURI WebView ### Description Loads a document from the provided URI. ### Parameters - **aid** (int) - Required - The id of the Activity the View is in. - **id** (int) - Required - The id of the WebView. - **uri** (string) - Required - A URI string ## allowNavigation WebView ### Description Allows Javascript and the user to navigate. The recommended solution is to catch the navigation events, check the URL and call loadURI, but this needs more work from the client. Currently only works on Android 8.0 and higher. ### Parameters - **aid** (int) - Required - The id of the Activity the View is in. - **id** (int) - Required - The id of the WebView. - **allow** (boolean) - Required - Whether to allow or disallow navigation in the WebView. ## goBack WebView ### Description Navigates back in the history. ### Parameters - **aid** (int) - Required - The id of the Activity the View is in. - **id** (int) - Required - The id of the WebView. ## goForward WebView ### Description Navigates forward in the history. ### Parameters - **aid** (int) - Required - The id of the Activity the View is in. - **id** (int) - Required - The id of the WebView. ## evaluateJS WebView ### Description Runs Javascript code in the WebView. ### Parameters - **aid** (int) - Required - The id of the Activity the View is in. - **id** (int) - Required - The id of the WebView. - **code** (string) - Required - The Javascript code. ``` -------------------------------- ### ImageView Methods Source: https://github.com/termux/termux-gui/blob/main/Protocol.md Methods for managing ImageViews, including setting buffer sources and refreshing their content. ```APIDOC ## setBuffer ImageView ### Description Sets the ImageView to have a buffer as a source. ### Parameters - **id** (int) - Required - The View id of a ImageView. - **aid** (int) - Required - The id of the Activity the View is in. - **bid** (int) - Required - id of the buffer. ## refreshImageView ImageView ### Description This should be called after blitting an ImageView's buffer to show the new contents. ### Parameters - **id** (int) - Required - The View id of a ImageView. - **aid** (int) - Required - The id of the Activity the View is in. ``` -------------------------------- ### newActivity (JSON Protocol) Source: https://context7.com/termux/termux-gui/llms.txt Launches a new Android Activity (screen) using the JSON protocol. Activities can be of various types like normal, dialog, PiP, lockscreen, or overlay windows. ```APIDOC ## newActivity — Create an Activity Launches a new Android Activity (screen) and returns its ID and the Task ID. Activities can be normal, dialogs, PiP, lockscreen, or overlay windows. ```python # JSON protocol example — create a normal full-screen activity in a new Task send_method(sock, "newActivity", { # omit "tid" to start a new Task "intercept": False # do NOT intercept back button }) response = recv_response(sock) # [aid, tid] or -1 on error aid, tid = response[0], response[1] print(f"Activity id={aid}, Task id={tid}") ``` ``` -------------------------------- ### Control View Visibility and Layout Source: https://context7.com/termux/termux-gui/llms.txt Adjust view sizing, spacing, and visibility. Views can be hidden (occupying space) or gone (not occupying space). Supports explicit sizing and margin/padding settings. ```python # Hide a view without removing it from the layout (still occupies space) send_method(sock, "setVisibility", {"aid": aid, "id": btn_id, "vis": 1}) # 1=hidden # Make it gone (no space consumed) send_method(sock, "setVisibility", {"aid": aid, "id": btn_id, "vis": 0}) # 0=gone # Restore send_method(sock, "setVisibility", {"aid": aid, "id": btn_id, "vis": 2}) # 2=visible # Explicit sizing send_method(sock, "setWidth", {"aid": aid, "id": edit_id, "width": "MATCH_PARENT"}) send_method(sock, "setHeight", {"aid": aid, "id": edit_id, "height": "WRAP_CONTENT"}) # Set 16dp margin on all sides send_method(sock, "setMargin", {"aid": aid, "id": root_layout, "margin": 16}) # 8dp padding on left and right only send_method(sock, "setPadding", {"aid": aid, "id": edit_id, "padding": 8, "dir": "left"}) send_method(sock, "setPadding", {"aid": aid, "id": edit_id, "padding": 8, "dir": "right"}) ``` -------------------------------- ### setTheme Source: https://context7.com/termux/termux-gui/llms.txt Styles an Activity by setting theme colors for various UI elements. ```APIDOC ## setTheme - Style an Activity ### Description Sets Activity-wide colors applied to all subsequently created Views. Colors are RGBA8888 packed as a 32-bit integer (0xAABBGGRR). ### Method `send_method(sock, "setTheme", params)` ### Parameters - **aid** (int) - Required - The activity ID. - **statusBarColor** (int) - Optional - Color for the status bar. - **colorPrimary** (int) - Optional - Primary color for the theme. - **windowBackground** (int) - Optional - Background color for the window. - **textColor** (int) - Optional - Default text color. - **colorAccent** (int) - Optional - Accent color for the theme. ### Response No response value. The theme is queued if the activity is not visible. ```