Skip to content

Forms

FormEngine asks the questions declared in a TOML file, through a terminal, zenity or a local web page, and remembers the answers.

Warning

The web renderer starts an HTTP server on 127.0.0.1 and opens a browser; answers are saved under paths.form_state_dir().

cjtrade.pkgs.ui.engine

FormEngine — ties schema loading, renderer selection, and result handling.

Quick usage
from cjtrade.pkgs.ui.engine import FormEngine

result = FormEngine("my_form.toml", renderer="cli").run()
# result = {"watch_list": "2330", "fund": 500000, ...}
Renderer strings

"cli" — interactive terminal prompts "zenity" — GTK dialogs via the zenity binary "web" — local HTML form opened in the browser "auto" — zenity if available, else cli

FormEngine(schema_path=None, toml_str=None, renderer='auto', web_port=9876)

High-level facade: load schema → pick renderer → collect input → return results.

Parameters:

Name Type Description Default
schema_path str or Path

Path to the TOML schema file. Its stem names the state file.

None
toml_str str

TOML schema as a string; its state file is named "inline". Give exactly one of schema_path and toml_str.

None
renderer str or FormRenderer

"cli" | "zenity" | "web" | "auto" | a :class:FormRenderer instance.

'auto'
web_port int

Port for the WebRenderer (default 9876).

9876

Raises:

Type Description
ValueError

If both or neither of schema_path / toml_str are given, or the renderer name is unknown.

Source code in src/cjtrade/pkgs/ui/engine.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def __init__(
    self,
    schema_path: str | Path | None = None,
    toml_str: str | None = None,
    renderer: str | FormRenderer = "auto",
    web_port: int = 9876,
) -> None:
   # 必須提供其中一個,而且只能提供一個
    if (schema_path is None) == (toml_str is None):
        raise ValueError(
            "Provide exactly one of schema_path or toml_str."
        )

    if schema_path is not None:
        self.schema = FormSchema.load(schema_path)
        state_name = Path(schema_path).stem
    else:
        self.schema = FormSchema.loads(toml_str)
        state_name = "inline"

    self._renderer = self._resolve(renderer, web_port)
    self._state = UserState(state_name)

    # Build persist_map: {field_name → persist_key} for fields that opt in
    self._persist_map: dict[str, str] = {
        f.name: f.persist_key
        for f in self.schema.fields
        if f.persist_key
    }

run()

Present the form and block until it is submitted.

Persists relevant values and returns the result dict. Fields whose cli_arg flag was found in sys.argv are skipped entirely — the renderer never sees them.

Returns:

Type Description
dict

{field_name: value}, without display-only fields.

Warnings

Writes fields with persist_key to the user state file. On KeyboardInterrupt it calls sys.exit(0) instead of raising.

Source code in src/cjtrade/pkgs/ui/engine.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def run(self) -> dict[str, Any]:
    """Present the form and **block** until it is submitted.

    Persists relevant values and returns the result dict.
    Fields whose ``cli_arg`` flag was found in ``sys.argv`` are skipped
    entirely — the renderer never sees them.

    Returns
    -------
    dict
        ``{field_name: value}``, without display-only fields.

    Warnings
    --------
    Writes fields with ``persist_key`` to the user state file. On
    KeyboardInterrupt it calls ``sys.exit(0)`` instead of raising.
    """
    import dataclasses

    self._inject_persisted_defaults()

    cli_overrides = self._parse_cli_args()

    # Build a schema containing only the fields that still need prompting
    if cli_overrides:
        remaining = [f for f in self.schema.fields if f.name not in cli_overrides]
        prompt_schema = dataclasses.replace(self.schema, fields=remaining)
    else:
        prompt_schema = self.schema

    try:
        if prompt_schema.fields:
            result = self._renderer.render(prompt_schema)
        else:
            result = {}
    except KeyboardInterrupt:
        form_console().info("\n\n  Cancelled.")
        sys.exit(0)

    # Merge: CLI-provided values win; renderer fills the rest
    merged = {**result, **cli_overrides}

    # Strip display-only fields — they carry no user input
    display_names = {f.name for f in self.schema.fields if f.type == "display"}
    merged = {k: v for k, v in merged.items() if k not in display_names}

    if self._persist_map:
        self._state.save(merged, self._persist_map)
    #print(merged, file=sys.stderr)
    return merged

run_async(callback, *, on_cancel=None, daemon=True)

Show the form in a background thread and call callback when done.

The calling thread is never blocked — it can keep doing work (e.g. running a live strategy) while the user fills the form.

Parameters:

Name Type Description Default
callback callable

Called with the result dict once the user submits. Runs on the background thread, so keep it thread-safe (use a threading.Lock if you mutate shared state).

required
on_cancel callable

Optional callable invoked if the user cancels (Ctrl-C / dialog close). If None, cancellation is silently ignored.

None
daemon bool

When True (default) the thread won't prevent the program from exiting if the main thread finishes first.

True

Returns:

Type Description
Thread

The background thread (already started). Call .join() if you later want to wait for it.

Warnings

Unlike :meth:run, this renders the full schema directly; it does not apply CLI-flag overrides, inject persisted defaults or save state.

Example

::

engine = FormEngine("modify_strategy.toml", renderer="web")

def apply_changes(result):
    strategy.update_params(result)  # runs on bg thread

t = engine.run_async(callback=apply_changes)
# main thread keeps running…
strategy.run()         # ← not blocked
t.join()               # ← optionally wait at the end
Source code in src/cjtrade/pkgs/ui/engine.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
def run_async(
    self,
    callback: Callable[[dict[str, Any]], None],
    *,
    on_cancel: Callable[[], None] | None = None,
    daemon: bool = True,
) -> threading.Thread:
    """Show the form in a **background thread** and call *callback* when done.

    The calling thread is **never blocked** — it can keep doing work
    (e.g. running a live strategy) while the user fills the form.

    Parameters
    ----------
    callback : callable
        Called with the result dict once the user submits.
        Runs on the background thread, so keep it thread-safe
        (use a ``threading.Lock`` if you mutate shared state).
    on_cancel : callable, optional
        Optional callable invoked if the user cancels (Ctrl-C / dialog close).
        If ``None``, cancellation is silently ignored.
    daemon : bool, optional
        When ``True`` (default) the thread won't prevent the program from
        exiting if the main thread finishes first.

    Returns
    -------
    threading.Thread
        The background thread (already started).
        Call ``.join()`` if you later want to wait for it.

    Warnings
    --------
    Unlike :meth:`run`, this renders the full schema directly; it does not
    apply CLI-flag overrides, inject persisted defaults or save state.

    Example
    -------
    ::

        engine = FormEngine("modify_strategy.toml", renderer="web")

        def apply_changes(result):
            strategy.update_params(result)  # runs on bg thread

        t = engine.run_async(callback=apply_changes)
        # main thread keeps running…
        strategy.run()         # ← not blocked
        t.join()               # ← optionally wait at the end
    """
    def _worker():
        try:
            result = self._renderer.render(self.schema)
        except KeyboardInterrupt:
            if on_cancel:
                on_cancel()
            return
        callback(result)

    t = threading.Thread(target=_worker, daemon=daemon, name="FormEngine-async")
    t.start()
    return t

run_and_export()

Like :meth:run, but also export results into os.environ.

Writes each field's result into the env var named by field.env_out (if set). Useful when the form feeds a shell script.

Warnings

Mutates this process's environment, in addition to everything :meth:run does.

Source code in src/cjtrade/pkgs/ui/engine.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def run_and_export(self) -> dict[str, Any]:
    """Like :meth:`run`, but also export results into ``os.environ``.

    Writes each field's result into the env var named by
    ``field.env_out`` (if set). Useful when the form feeds a shell script.

    Warnings
    --------
    Mutates this process's environment, in addition to everything
    :meth:`run` does.
    """
    results = self.run()
    for f in self.schema.fields:
        if f.env_out and f.name in results and results[f.name] is not None:
            os.environ[f.env_out] = str(results[f.name])
    return results

print_exports(results)

Print export VAR=value lines for all fields that have an env_out key.

Pipe this into a shell eval to inject values into the calling process. List values (multiselect) are serialised as comma-separated strings.

Parameters:

Name Type Description Default
results dict

Result dict from :meth:run.

required
Source code in src/cjtrade/pkgs/ui/engine.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def print_exports(self, results: dict[str, Any]) -> None:
    """Print ``export VAR=value`` lines for all fields that have an ``env_out`` key.

    Pipe this into a shell ``eval`` to inject values into the calling process.
    List values (multiselect) are serialised as comma-separated strings.

    Parameters
    ----------
    results : dict
        Result dict from :meth:`run`.
    """
    for f in self.schema.fields:
        if f.env_out and f.name in results:
            val = results[f.name]
            if val is None:
                continue
            # Serialise lists (multiselect) as comma-separated strings
            if isinstance(val, list):
                raw = ",".join(str(v) for v in val)
            else:
                raw = str(val)
            escaped = raw.replace("'", "'\\''")
            get_console().info(f"export {f.env_out}='{escaped}'")

cjtrade.pkgs.ui.schema

FormField dataclass and FormSchema TOML loader.

TOML DSL spec

Each [[field]] block maps directly to a FormField. Type-specific options live in a [field.config] sub-table:

[[field]]
name        = "fund"          # required – result dict key (optional for type="display")
label       = "Initial Fund"  # required – display label
type        = "number"        # text | number | select | multiselect | checkbox | date | file | display
default     = 500000          # hardcoded default
env_in      = "MY_ENV_VAR"    # env var read as default (beats `default`)
env_out     = "INITIAL_FUND"  # env var the result is exported into
placeholder = "500000"        # hint shown in prompt
optional    = true            # if true, empty input is accepted
[field.config]
min      = 1000               # number: lower bound
max      = 9999               # number: upper bound
step     = 1000               # number: increment hint
options  = ["a","b","c"]      # select / multiselect: choices
filter   = "*.toml"           # file: extension filter hint
multiple = false              # file: allow selecting multiple files
heading  = "Title"            # display: heading text
body     = "Body paragraph"   # display: body / description text

FormField(name, label, type, default=None, env_in=None, env_out=None, placeholder=None, optional=False, persist_key=None, cli_arg=None, config=dict()) dataclass

One field of a form, as declared by a [[field]] TOML block.

Parameters:

Name Type Description Default
name str

Result dict key.

required
label str

Display label.

required
type str

text | number | select | multiselect | checkbox | date | file | display.

required
default Any

Hardcoded default.

None
env_in str

Env var read as default (beats default).

None
env_out str

Env var the result is exported into.

None
placeholder str

Hint shown in the prompt.

None
optional bool

If true, empty input is accepted.

False
persist_key str

Key used in the per-schema state file.

None
cli_arg str

CLI flag, e.g. "--watch-list"; the prompt is skipped if it is given.

None
config dict

Type-specific options from [field.config].

dict()

eff_min property

config["min"] as a float, or None.

eff_max property

config["max"] as a float, or None.

eff_step property

config["step"] as a float, or None.

eff_options property

config["options"] for select / multiselect, or None.

eff_filter property

File filter / glob pattern hint (e.g. *.toml).

eff_multiple property

Whether a file picker allows multiple selection.

resolved_default(persisted=None)

Effective default — priority: env-var > state-file > TOML default > None.

Parameters:

Name Type Description Default
persisted dict

State-file values, keyed by persist_key.

None

Returns:

Type Description
Any

For multiselect, a list (comma-separated strings are split).

Source code in src/cjtrade/pkgs/ui/schema.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def resolved_default(self, persisted: dict | None = None) -> Any:
    """Effective default — priority: env-var > state-file > TOML default > None.

    Parameters
    ----------
    persisted : dict, optional
        State-file values, keyed by ``persist_key``.

    Returns
    -------
    Any
        For multiselect, a list (comma-separated strings are split).
    """
    if self.env_in:
        env_val = os.environ.get(self.env_in)
        if env_val is not None:
            if self.type == "multiselect":
                return [x.strip() for x in env_val.split(",") if x.strip()]
            return env_val
    if persisted and self.persist_key and self.persist_key in persisted:
        return persisted[self.persist_key]
    # Normalise multiselect: TOML arrays are returned as-is;
    # plain strings are treated as comma-separated.
    if self.type == "multiselect" and isinstance(self.default, str):
        return [x.strip() for x in self.default.split(",") if x.strip()]
    return self.default

coerce(raw)

Convert a raw value from the renderer into the correct Python type.

Raises:

Type Description
ValueError

If a number field's value does not parse.

Source code in src/cjtrade/pkgs/ui/schema.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def coerce(self, raw: Any) -> Any:
    """Convert a raw value from the renderer into the correct Python type.

    Raises
    ------
    ValueError
        If a number field's value does not parse.
    """
    if self.type == "checkbox":
        if isinstance(raw, bool):
            return raw
        return str(raw).strip().lower() in ("y", "yes", "true", "1")
    if self.type == "multiselect":
        if isinstance(raw, list):
            return raw
        # Accept "2330,0050" or "2330 0050"
        return [x.strip() for x in str(raw).replace(",", " ").split() if x.strip()]
    if self.type in ("date", "file"):
        return str(raw)
    if self.type == "number":
        raw = str(raw).strip()
        try:
            return int(raw) if "." not in raw else float(raw)
        except ValueError:
            raise ValueError(f"'{raw}' is not a valid number for field '{self.name}'")
    return str(raw)

FormSchema(title, fields) dataclass

A whole form: a title and its fields.

Parameters:

Name Type Description Default
title str

Form title.

required
fields list of FormField

Fields in declaration order.

required

from_dict(data) classmethod

Build a schema from parsed TOML data.

Fields without a name are named _display_<index>; title defaults to "Form".

Raises:

Type Description
KeyError

If a field has no type.

Source code in src/cjtrade/pkgs/ui/schema.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "FormSchema":
    """Build a schema from parsed TOML data.

    Fields without a ``name`` are named ``_display_<index>``; ``title``
    defaults to "Form".

    Raises
    ------
    KeyError
        If a field has no ``type``.
    """
    title = data.get("title", "Form")

    fields = [
        FormField(
            name=fd.get("name", f"_display_{i}"),
            label=fd.get("label", ""),
            type=fd["type"],
            default=fd.get("default"),
            env_in=fd.get("env_in"),
            env_out=fd.get("env_out"),
            placeholder=fd.get("placeholder"),
            optional=fd.get("optional", False),
            persist_key=fd.get("persist_key"),
            cli_arg=fd.get("cli_arg"),
            config=fd.get("config", {}),
        )
        for i, fd in enumerate(data.get("field", []))
    ]

    return cls(title=title, fields=fields)

loads(toml_str) classmethod

Build a schema from a TOML string.

Source code in src/cjtrade/pkgs/ui/schema.py
230
231
232
233
@classmethod
def loads(cls, toml_str: str) -> "FormSchema":
    """Build a schema from a TOML string."""
    return cls.from_dict(tomllib.loads(toml_str))

load(path) classmethod

Build a schema from a TOML file; the title defaults to the file stem.

Source code in src/cjtrade/pkgs/ui/schema.py
235
236
237
238
239
240
241
242
243
244
245
246
247
@classmethod
def load(cls, path: str | Path) -> "FormSchema":
    """Build a schema from a TOML file; the title defaults to the file stem."""
    path = Path(path)
    with open(path, "rb") as fh:
        data = tomllib.load(fh)

    schema = cls.from_dict(data)

    if "title" not in data:
        schema.title = path.stem

    return schema

defaults()

Return a dict of resolved default values for every field.

Source code in src/cjtrade/pkgs/ui/schema.py
250
251
252
def defaults(self) -> dict[str, Any]:
    """Return a dict of resolved default values for every field."""
    return {f.name: f.resolved_default() for f in self.fields}