API Reference

This section documents the Python API for ggblab, automatically generated from docstrings.

Main Interface

ggblab: Interactive geometric scene construction with Python and GeoGebra.

This package provides a JupyterLab extension that opens a GeoGebra applet and enables bidirectional communication between Python and GeoGebra through a dual-channel architecture (IPython Comm + Unix socket/TCP WebSocket).

Main Components:
  • GeoGebra: Primary interface for controlling GeoGebra applets

  • ggb_comm: Communication layer (IPython Comm + out-of-band socket)

  • ggb_construction: GeoGebra file (.ggb) loader and saver

  • ggb_parser: Dependency graph parser for GeoGebra constructions

Example

>>> from ggblab import GeoGebra
>>> ggb = await GeoGebra().init()
>>> await ggb.command("A=(0,0)")
>>> value = await ggb.function("getValue", ["A"])

GeoGebra Control

class ggblab.ggbapplet.GeoGebra[source]

Bases: object

Main interface for controlling GeoGebra applets from Python.

This class implements a singleton pattern to ensure only one GeoGebra instance per kernel session. It provides async methods for sending commands and calling GeoGebra API functions.

The communication uses a dual-channel architecture: - IPython Comm: Primary control channel - Unix socket/TCP WebSocket: Out-of-band response delivery during cell execution

Semantic Validation: - check_syntax: Validates command strings can be tokenized - check_semantics: Validates referenced objects exist in applet - Future: Type checking, scope/visibility validation

file

GeoGebra file (.ggb) loader and saver

Type:

ggb_file

construction

Backward compatibility alias for file attribute

parser

Dependency graph parser with command learning (lazy-loaded from ggblab_extra)

comm

Communication layer (initialized after init())

Type:

ggb_comm

kernel_id

Current Jupyter kernel ID

Type:

str

app

ipylab frontend interface

Type:

JupyterFrontEnd

check_syntax

Enable syntax validation (default: False)

Type:

bool

check_semantics

Enable semantic validation (default: False)

Type:

bool

_applet_objects

Cached object names from applet (updated by command/function)

Type:

set

Note

The parser attribute is deprecated and will be removed in ggblab 1.0.0. Use ‘from ggblab_extra import ggb_parser’ instead.

Example

>>> ggb = GeoGebra()
>>> await ggb.init()
>>> await ggb.command("A=(0,0)")
>>> result = await ggb.function("getValue", ["A"])
>>> # With validation
>>> ggb.check_syntax = True
>>> ggb.check_semantics = True
>>> await ggb.command("Circle(A, B)")
async command(c)[source]

Execute a GeoGebra command with optional validation.

Parameters:

c (str) – GeoGebra command string (e.g., “A=(0,0)”, “Circle(A, 2)”).

Returns:

Response from GeoGebra (typically includes object label).

Return type:

dict

Raises:
  • GeoGebraSyntaxError – If syntax check is enabled and command has syntax errors.

  • GeoGebraSemanticsError – If semantics check is enabled and validation fails.

  • GeoGebraAppletError – If GeoGebra applet produces error events during execution.

Example

>>> await ggb.command("A=(0,0)")
>>> await ggb.command("B=(3,4)")
>>> await ggb.command("Circle(A, Distance(A, B))")
>>> # With validation
>>> ggb.check_syntax = True
>>> ggb.check_semantics = True
>>> await ggb.command("Circle(A, B)")  # Validates syntax and references
>>> # Error handling
>>> try:
...     await ggb.command("Unbalanced(")
... except GeoGebraAppletError as e:
...     print(f"Applet error: {e.error_message}")
async function(f, args=None)[source]

Call a GeoGebra API function.

Parameters:
  • f (str) – GeoGebra API function name (e.g., “getValue”, “getXML”).

  • args (list, optional) – Function arguments. Defaults to None.

Returns:

Function return value from GeoGebra.

Return type:

Any

Example

>>> value = await ggb.function("getValue", ["A"])
>>> xml = await ggb.function("getXML", ["A"])
>>> all_objs = await ggb.function("getAllObjectNames")
async init()[source]

Initialize the GeoGebra widget and communication channels.

This method: 1. Starts the out-of-band socket server (Unix socket on POSIX, TCP WebSocket on Windows) 2. Registers the IPython Comm target (‘ggblab-comm’) 3. Opens the GeoGebra widget panel via ipylab with communication settings 4. Initializes the object cache

The widget is launched programmatically to pass kernel-specific settings (Comm target, socket path) before initialization, avoiding the limitations of fixed arguments from Launcher/Command Palette.

Returns:

Self reference for method chaining.

Return type:

GeoGebra

Example

>>> ggb = await GeoGebra().init()
>>> # GeoGebra panel opens in split-right position
async refresh_object_cache()[source]

Refresh the cached set of known objects from the applet.

Called automatically during init() and can be called manually to synchronize the object cache with current applet state.

Communication Layer

class ggblab.comm.ggb_comm[source]

Bases: object

Dual-channel communication layer for kernel↔widget messaging.

Implements a combination of IPython Comm (primary) and out-of-band socket (Unix domain socket on POSIX, TCP WebSocket on Windows) to enable message delivery during cell execution when IPython Comm is blocked.

IPython Comm cannot receive messages while a notebook cell is executing, which breaks interactive workflows. The out-of-band socket solves this by providing a secondary channel for GeoGebra responses.

Architecture:
  • IPython Comm: Command dispatch, event notifications, heartbeat

  • Out-of-band socket: Response delivery during cell execution

Comm target is fixed at ‘ggblab-comm’ because multiplexing via multiple targets would not solve the IPython Comm receive limitation.

target_comm

IPython Comm object

target_name

Comm target name (‘ggblab-comm’)

Type:

str

server_handle

WebSocket server handle

server_thread

Background thread running the socket server

clients

Currently connected WebSocket clients

Type:

set

socketPath

Unix domain socket path (POSIX)

Type:

str

wsPort

TCP port number (Windows)

Type:

int

recv_logs

Response storage keyed by message ID

Type:

dict

recv_events

Event queue for frontend notifications

Type:

queue.Queue

See:

docs/architecture.md for detailed communication architecture.

async client_handle(client_id)[source]
handle_recv(msg)[source]
logs = []
mid = None
recv_events = <queue.Queue object>
recv_logs = {}
recv_msgs = {}
register_target()[source]
register_target_cb(comm, msg)[source]
send(msg)[source]
async send_recv(msg)[source]

Send a message via IPython Comm and wait for response via out-of-band socket.

This method: 1. Generates a unique message ID (UUID) 2. Sends the message via IPython Comm to the frontend 3. Waits for the response to arrive via the out-of-band socket 4. Raises GeoGebraAppletError if error events are received 5. Returns the response payload

The 3-second timeout is sufficient for interactive operations. For long-running operations, decompose into smaller steps.

Parameters:

msg (dict or str) – Message to send (will be JSON-serialized).

Returns:

Response payload from GeoGebra.

Return type:

dict

Raises:
  • asyncio.TimeoutError – If no response arrives within 3 seconds.

  • GeoGebraAppletError – If the applet produces error events.

Example

>>> response = await comm.send_recv({
...     "type": "command",
...     "payload": "A=(0,0)"
... })
async server()[source]
start()[source]

Start the out-of-band socket server in a background thread.

Creates a Unix domain socket (POSIX) or TCP WebSocket server (Windows) and runs it in a daemon thread. The server listens for GeoGebra responses.

stop()[source]

Stop the out-of-band socket server.

thread = None
unregister_target_cb(comm, msg)[source]

Construction File Handler

Dependency Parser

Parser Utilities

Schema Loader

class ggblab.schema.ggb_schema[source]

Bases: object

GeoGebra XML schema loader and validator.

Manages the GeoGebra XML schema (XSD) for validating and parsing .ggb construction files. The schema is automatically downloaded from the official GeoGebra site and cached locally for offline use.

The schema enables: - XML validation of GeoGebra constructions - Conversion between XML and Python dictionaries - Type-safe parsing of construction elements

url

URL of the GeoGebra common.xsd schema file

Type:

str

local_path

Local cache path for the downloaded schema

Type:

str

schema_content

Raw XSD content as string

Type:

str

schema

Compiled schema object for validation

Type:

xmlschema.XMLSchema

Example

>>> schema = ggb_schema()
>>> # Schema is loaded and ready for use
>>> data_dict = schema.schema.to_dict(xml_string)

Note

The schema is downloaded once and cached in xsd/common.xsd. Delete the cache to force re-download on next instantiation.

local_path = 'xsd/common.xsd'
url = 'http://www.geogebra.org/apps/xsd/common.xsd'
ggblab.schema.cache_schema_locally(schema_url, local_file_path)[source]

Download and cache a schema file from URL.

Downloads an XML schema from the specified URL and saves it to a local file for offline use. If the file already exists, uses the cached version instead of re-downloading.

Parameters:
  • schema_url (str) – URL of the schema file to download.

  • local_file_path (str) – Path where the schema should be cached.

Returns:

Content of the schema file, or None if download fails.

Return type:

str

Examples

>>> content = cache_schema_locally(
...     'http://example.com/schema.xsd',
...     'cache/schema.xsd'
... )
Using local cached file: cache/schema.xsd

Note

Future enhancement: Add logic to check file age or Last-Modified header to refresh stale cached schemas.