表單¶
FormEngine 依 TOML 檔的定義,透過終端機、zenity 或本機網頁詢問問題,並記住答案。
Warning
web renderer 會在 127.0.0.1 啟動 HTTP 伺服器並開啟瀏覽器;答案存在 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 |
None
|
renderer
|
str or FormRenderer
|
|
'auto'
|
web_port
|
int
|
Port for the WebRenderer (default 9876). |
9876
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If both or neither of |
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 | |
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
|
|
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 | |
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 |
required |
on_cancel
|
callable
|
Optional callable invoked if the user cancels (Ctrl-C / dialog close).
If |
None
|
daemon
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
Thread
|
The background thread (already started).
Call |
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 | |
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 | |
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: |
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 | |
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 |
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 |
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 |
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 | |
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 | |
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 |
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 | |
loads(toml_str)
classmethod
¶
Build a schema from a TOML string.
Source code in src/cjtrade/pkgs/ui/schema.py
230 231 232 233 | |
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 | |
defaults()
¶
Return a dict of resolved default values for every field.
Source code in src/cjtrade/pkgs/ui/schema.py
250 251 252 | |