tft: generic type engine (tft_types), number and button; notes on the Editor inspection

Record slots follow the Editor's visible attribute list; generated scripts are
templates compiled by the normal script compiler. Number (all backgrounds and
border styles) and button (solid background, all five styles) are byte-identical.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
mangavalkandClaude Fable 5.2 committed 2026-11-16 19:16:21 +01:00
1 parent b5eaa68298
commit a8622e7462
4 files changed
+351 -153

No files matched your search

+28
View File
@@ -193,3 +193,31 @@ Starting points for the next component types (from those samples, not yet in the
filled and the empty part. Gauge: one `09 0A 08` line. QR code: one `09 08 08` line. filled and the empty part. Gauge: one `09 0A 08` line. QR code: one `09 08 08` line.
- Slider and touch cap add the init line `09 16 04 1`; slider has a `slide` event label. - Slider and touch cap add the init line `09 16 04 1`; slider has a `slide` event label.
- Object flag byte: 0x37 types with a rectangle, 0x27 timer and touch cap, 0x07 variable. - Object flag byte: 0x37 types with a rectangle, 0x27 timer and touch cap, 0x07 variable.
### Look inside the Editor (2026-11-17, allowed by the owner, read-only)
Result: almost nothing, and nothing from it is in the repo.
- `Nextion Editor.exe` is a small .NET loader; the real program (and with it the compiler and
the per-component script templates) is `ACTR.dll`, which is encrypted and was left alone.
- `en0_com.bin` / `en0_va.bin` are the Editor's help texts for commands and system variables
(plain text behind a one-byte XOR). They give the complete list of names (64 commands, 75
variables and constants) but not the token numbers: the order in the file is not the token
order. **Fact from the inspection:** only this list of names, used to decide what to put in
sample projects. Every token number in `tft_code.py` was read from compiled samples.
### Slot rule and the generic builder (2026-11-17)
Found by comparing samples, not from the Editor: a component's record slots follow the
attributes the Editor *shows* for it, in order. Components with a rectangle: 19 common slots
(type, id, objname, vscope, drag, sendkey, aph, movex, movey, x, y, w, h, endx, endy, effect,
first, time, lockobj), then one slot per visible attribute, then 8 empty ones. Components
without (variable, timer, touch cap): 7, the visible attributes, 2 empty. Hidden attributes
get no slot -- e.g. `style` disappears when `sta` is not "solid color", `borderc`/`borderw`
exist only for style "border" -- so every later slot moves.
The generated scripts are ordinary Nextion script compiled by the same compiler as event code
(`if(val==1) {...} else {...}` in a button becomes the usual test/jump chunks), with constant
attributes written as literals and RAM attributes as record references. `nxhmi.tft_types`
therefore describes a type as: visible attributes, record kinds, RAM order, script templates.
The RAM order and the unnamed drawing commands still have to be read from samples per type.
+156 -152
View File
@@ -2,8 +2,9 @@
What is reproduced byte for byte (Nextion Editor 1.68.2, model NX4832T035): header, resource What is reproduced byte for byte (Nextion Editor 1.68.2, model NX4832T035): header, resource
area (the firmware files are read from the user's own Editor installation; pictures, fonts), page area (the firmware files are read from the user's own Editor installation; pictures, fonts), page
section for the component types in ``TYPES`` and the script subset in :mod:`nxhmi.tft_code`, section for the component types in :mod:`nxhmi.tft_types` and the script subset in
layout table and all checksums. Anything else raises :class:`Unsupported` -- never a guess. :mod:`nxhmi.tft_code`, layout table and all checksums. Anything else raises
:class:`Unsupported` -- never a guess.
""" """
from __future__ import annotations from __future__ import annotations
@@ -11,72 +12,26 @@ import os
import re import re
import struct import struct
from . import tft, tft_code from . import tft, tft_code, tft_types
from .checksum import word_per_byte_crc
from .container import HMIFile from .container import HMIFile
from .page import Page from .page import Page
from .checksum import word_per_byte_crc
from .tft_code import Unsupported from .tft_code import Unsupported
FIRMWARE_FILES = ("input.bin", "asp0.dll", "cd0.dll", "qr0.bin", "syscom.bin", "h0-0.dll", "h1-0.dll") FIRMWARE_FILES = ("input.bin", "asp0.dll", "cd0.dll", "qr0.bin", "syscom.bin", "h0-0.dll", "h1-0.dll")
DEFAULT_EDITOR_DIR = r"C:\Program Files (x86)\Nextion Editor" DEFAULT_EDITOR_DIR = r"C:\Program Files (x86)\Nextion Editor"
SUPPORTED_MODEL = 0xB23BC018 # NX4832T035_011, the only model measured SUPPORTED_MODEL = 0xB23BC018 # NX4832T035_011, the only model measured
BLOCK = 0x10000 BLOCK = 0x10000
_RECT = ("x", "y", "w", "h", "endx", "endy")
# attribute map positions in the object record (u16 table at +0x38) _RECT_REC = {"x": (9, 0x0B, 6000, -6000), "y": (10, 0x0C, 6000, -6000), "w": (11, 0x0D, 2000, -2000),
MAP = {"vscope": 1, "sta": 2, "bco": 4, "pco": 16, "val": 20, "font": 25, "xcen": 26, "ycen": 27, "txt": 28, "h": (12, 0x0E, 2000, -2000), "endx": (13, 0x08, 32767, -32768), "endy": (14, 0x08, 32767, -32768)}
"txt_maxl": 29, "tim": 33, "en": 34, "isbr": 54, "spax": 56, "spay": 57, "pw": 58, "style": 59, "x": 42, "y": 43, "endx": 44, "endy": 45, "w": 46, "h": 47, _CONST_KINDS = (0x01, 0x02)
"id": 49, "type": 62}
# attribute record templates: name -> (slot, kind, size, max, min)
_COMMON = {"type": (0, 0x01, 1, 255, 0), "id": (1, 0x01, 1, 255, 0), "vscope": (3, 0x01, 1, 1, 0)}
_RECT = {"x": (9, 0x0B, 2, 6000, -6000), "y": (10, 0x0C, 2, 6000, -6000), "w": (11, 0x0D, 2, 2000, -2000),
"h": (12, 0x0E, 2, 2000, -2000), "endx": (13, 0x08, 2, 32767, -32768), "endy": (14, 0x08, 2, 32767, -32768)}
def _text_draw(rect, ref):
"""Draw section of a text component (solid background, no border)."""
line = (b"\x09\x1c\x08" + ("%d,%d,%d,%d," % tuple(rect[:4])).encode() + ref("font") + b"," + ref("pco") + b","
+ ref("bco") + b"," + ref("xcen") + b"," + ref("ycen") + b",1," + ref("isbr") + b",0,0," + ref("pw") + b",0")
return [line, b"\x09\x13\x04" + b"\x03\xff\x7f\x00\x00," * 4 + ref("txt")]
# type id -> description. ``ram`` attributes live in the page's RAM image (in this order);
# ``owner``: whether records name the component to refresh when the attribute changes.
TYPES = {
121: dict(name="page", slots=33, flag=0x37, group=8, const={**_COMMON, **_RECT},
ram={"sta": (23, 0x21, 1, 2, 0), "bco": (24, 0x32, 2, 65535, 0)}, owner=True),
109: dict(name="hotspot", slots=27, flag=0x37, group=16, const={**_COMMON, **_RECT}, ram={}, owner=True),
52: dict(name="variable", slots=11, flag=0x07, group=16,
const={**_COMMON, "sta": (7, 0x01, 1, 1, 0)},
ram={"val": (8, 0x39, 4, 2147483647, -2147483648)}, owner=False),
51: dict(name="timer", slots=11, flag=0x27, group=16, const=dict(_COMMON),
ram={"tim": (7, 0x32, 2, 65534, 50), "en": (8, 0x31, 1, 1, 0)}, owner=True, action={"tim": 1, "en": 2}),
# text: only the plain form (sta = solid colour, style = flat, no extra spacing) was measured
116: dict(name="text", slots=41, flag=0x37, group=16,
const={**_COMMON, **_RECT, "sta": (19, 0x01, 1, 2, 0), "style": (20, 0x01, 1, 3, 0),
"txt_maxl": (29, 0x02, 2, 65534, 0), "spax": (31, 0x01, 1, 255, 0), "spay": (32, 0x01, 1, 255, 0)},
ram={"font": (22, 0x31, 1, "fonts", 0), "isbr": (30, 0x31, 1, 1, 0), "pco": (24, 0x32, 2, 65535, 0),
"bco": (23, 0x32, 2, 65535, 0), "xcen": (25, 0x31, 1, 2, 0), "ycen": (26, 0x31, 1, 2, 0),
"pw": (27, 0x31, 1, 1, 0), "txt": (28, 0x3F, 0, 0, 0)},
owner=True, need={"sta": 1, "style": 0, "spax": 0, "spay": 0}, draw=_text_draw),
# touch cap: down/up events without a rectangle; one init line (only one per page was measured)
5: dict(name="touch_cap", slots=10, flag=0x27, group=16, const=dict(_COMMON),
ram={"val": (7, 0x21, 1, 65535, 0)}, owner=True, events=True, init=b"\x09\x16\x041"),
}
def _chunk(b: bytes) -> bytes: def _chunk(b: bytes) -> bytes:
return struct.pack("<I", len(b)) + b return struct.pack("<I", len(b)) + b
def _u(attr) -> int:
return int.from_bytes(attr.value, "little")
def _s(attr, signed) -> int:
v, bits = _u(attr), 8 * len(attr.value)
return v - (1 << bits) if signed and v >> (bits - 1) else v
def resource_area(hmi: HMIFile, editor_dir: str) -> tuple[bytes, dict]: def resource_area(hmi: HMIFile, editor_dir: str) -> tuple[bytes, dict]:
"""Directory + firmware files + pictures + fonts, zero-padded to a 64 KB multiple.""" """Directory + firmware files + pictures + fonts, zero-padded to a 64 KB multiple."""
def numbered(ext): def numbered(ext):
@@ -116,9 +71,45 @@ def resource_area(hmi: HMIFile, editor_dir: str) -> tuple[bytes, dict]:
return area, info return area, info
def compile_pages(pages: list[Page], program: str, nfonts: int = 0): class _Comp:
"""One component with its compiled description (see tft_types)."""
def __init__(self, c, page_index, env):
self.c = c
self.name = c.get("objname")
self.v = {a.name: int.from_bytes(a.value, "little") for a in c.attrs() if not a.string}
self.s = {a.name: a.value for a in c.attrs() if a.string}
self.tid = self.v["type"]
if self.tid not in tft_types.TYPES:
raise Unsupported("component type %d (%s) on page %d" % (self.tid, self.name, page_index))
self.kind, self.visible, describe = tft_types.TYPES[self.tid]
if self.v["vscope"] != 0:
raise Unsupported("global components (%s)" % self.name)
if self.visible and (self.v["drag"], self.v["sendkey"], self.v["aph"], self.v["effect"]) != (0, 0, 127, 0):
raise Unsupported("drag, sendkey, aph or effect on %s" % self.name)
self.d = describe(self.v, self.s, env)
base = 19 if self.visible else 7
self.slot = {"type": 0, "id": 1, "vscope": 3}
if self.visible:
self.slot.update({k: r[0] for k, r in _RECT_REC.items()})
for i, name in enumerate(self.d["vis"]):
if name in self.d["rec"]:
self.slot[name] = base + i
self.nslots = base + len(self.d["vis"]) + (8 if self.visible else 2)
self.first = 0 # global number of the first record (set later)
def is_const(self, name):
return name not in self.d["rec"] or self.d["rec"][name][0] in _CONST_KINDS
def signed(self, name, lo):
v, bits = self.v[name], 8 * len(self.c.attr(name).value)
return v - (1 << bits) if lo < 0 and v >> (bits - 1) else v
def compile_pages(pages: list[Page], program: str, nfonts: int = 0, npics: int = 0):
"""-> (code blob, global variable descriptors, attribute records, page table, object records, """-> (code blob, global variable descriptors, attribute records, page table, object records,
program offset).""" program offset)."""
env = {"fonts": nfonts, "pics": npics}
names = sorted((tft.name_hash(p.components[0].get("objname")), i) for i, p in enumerate(pages)) names = sorted((tft.name_hash(p.components[0].get("objname")), i) for i, p in enumerate(pages))
n = len(pages) n = len(pages)
decl, program_lines = tft_code.declarations(tft_code.statements(program.splitlines())) decl, program_lines = tft_code.declarations(tft_code.statements(program.splitlines()))
@@ -133,17 +124,19 @@ def compile_pages(pages: list[Page], program: str, nfonts: int = 0):
offsets = {name: 4 * i for i, name in enumerate(decl)} offsets = {name: 4 * i for i, name in enumerate(decl)}
descriptors = b"".join(struct.pack("<III", h, o, 9) for h, o in descriptors = b"".join(struct.pack("<III", h, o, 9) for h, o in
sorted((word_per_byte_crc(name.encode("latin-1")), o) for name, o in offsets.items())) sorted((word_per_byte_crc(name.encode("latin-1")), o) for name, o in offsets.items()))
# record numbers are needed before any script is compiled: number them first # record numbers are needed before any script is compiled: describe and number everything first
where, base_rec = {}, 0 # (page name, component name) -> (first record, type) comps, where, rec_no = [], {}, 0
for page in pages: for pi, page in enumerate(pages):
pname = page.components[0].get("objname") row = []
for c in page.components: for ci, c in enumerate(page.components):
tid = _u(c.attr("type")) k = _Comp(c, pi, env)
if tid not in TYPES: if (ci == 0) != (k.tid == 121):
raise Unsupported("component type %d (%s)" % (tid, c.get("objname"))) raise Unsupported("page component in the wrong place")
where[(pname, c.get("objname"))] = (base_rec, TYPES[tid]) k.first, rec_no = rec_no, rec_no + k.nslots
base_rec += TYPES[tid]["slots"] where[(row[0].name if row else k.name, k.name)] = k
current = [None] row.append(k)
comps.append(row)
current = [None, None] # page name, component being compiled (templates)
def attr(path): def attr(path):
if len(path) == 3: if len(path) == 3:
@@ -152,129 +145,139 @@ def compile_pages(pages: list[Page], program: str, nfonts: int = 0):
key, name = (current[0], path[0]), path[1] key, name = (current[0], path[0]), path[1]
else: else:
return None return None
if key not in where: k = where.get(key)
if k is None or name not in k.slot:
return None return None
first, t = where[key] if name in k.d["rec"] and k.d["rec"][name][0] == 0x3F: # string attributes: not measured
slot = {**t["const"], **t["ram"]}.get(name)
if slot is None or slot[1] == 0x3F: # string attributes in script: not measured
return None return None
return first + slot[0] return k.first + k.slot[name]
ctx = tft_code.Context(offsets, {k[1] for k in where}, attr) def local(name):
k = current[1]
if k is None:
raise Unsupported("@ in script")
if name == "pagebco":
page = where[(current[0], current[0])]
return b"\x01" + struct.pack("<I", page.first + page.slot["bco"])
if name in k.slot and not (name in _RECT or k.is_const(name)):
return b"\x01" + struct.pack("<I", k.first + k.slot[name])
if name not in k.v:
raise Unsupported("literal %s of %s" % (name, k.name))
if k.v[name] > 999: # like any number of four or more digits
return b"\x03" + struct.pack("<I", k.v[name])
return b"%d" % k.v[name]
def section(lines, label=None): ctx = tft_code.Context(offsets, {key[1] for key in where}, attr)
ctx.local = local
def section(lines, label=None, template=()):
if label: if label:
blob.extend(_chunk(label)) blob.extend(_chunk(label))
for c in tft_code.compile_lines(list(template), ctx):
blob.extend(_chunk(c))
keep, current[1] = current[1], None # user code: no template names
for c in tft_code.compile_lines(lines, ctx): for c in tft_code.compile_lines(lines, ctx):
blob.extend(_chunk(c)) blob.extend(_chunk(c))
current[1] = keep
blob.extend(_chunk(b"")) blob.extend(_chunk(b""))
section(program_lines + ["page 0"]) section(program_lines + ["page 0"])
records, objects, table, rec_base = bytearray(), bytearray(), [], 0 records, objects, table = bytearray(), bytearray(), []
for pi, page in enumerate(pages): for pi, row in enumerate(comps):
ram = bytearray(b"\xff" * 8) ram = bytearray(b"\xff" * 8)
prec, first_obj, comp_names, init = bytearray(), len(objects) // tft.OBJ_SIZE, [], [] prec, first_obj, comp_names, init = bytearray(), len(objects) // tft.OBJ_SIZE, [], []
page_bco = 0
pre, post = [], [] pre, post = [], []
current[0] = page.components[0].get("objname") current[0] = row[0].name
for ci, c in enumerate(page.components): for k in row:
a = {x.name: x for x in c.attrs()} d, tid, cid = k.d, k.tid, k.v["id"]
tid = _u(a["type"]) current[1] = k
if tid not in TYPES or (ci == 0) != (tid == 121): owner = struct.pack("<BB", pi, cid) if d.get("owner", True) else b"\xff\xff"
raise Unsupported("component type %d (%s) on page %d" % (tid, c.get("objname"), pi))
t = TYPES[tid]
if tid == 121 and _u(a["sta"]) != 1:
raise Unsupported("page background other than a solid colour")
if tid == 52 and _u(a["sta"]) != 0:
raise Unsupported("string variables")
if _u(a["vscope"]) != 0:
raise Unsupported("global components")
for name, value in t.get("need", {}).items():
if _u(a[name]) != value:
raise Unsupported("%s with %s=%d" % (t["name"], name, _u(a[name])))
cid = _u(a["id"])
owner = struct.pack("<BB", pi, cid) if t["owner"] else b"\xff\xff"
slot0 = len(prec) // tft.REC_SIZE
group = g + 4 + (4 if tid == 121 else len(ram)) # RAM address of the component's data group = g + 4 + (4 if tid == 121 else len(ram)) # RAM address of the component's data
recs = [bytes(tft.REC_SIZE)] * t["slots"] recs = [bytes(tft.REC_SIZE)] * k.nslots
amap = [0xFFFF] * 88 amap = [0xFFFF] * 88
for name, (slot, kind, size, hi, lo) in t["const"].items():
recs[slot] = struct.pack("<Iiii2sBBBBH", group, _s(a[name], lo < 0), hi, lo, owner, 0, 0, kind, size, 0) def put(name, value, hi, lo, kind, size, action=0):
amap[MAP[name]] = slot0 + slot recs[k.slot[name]] = struct.pack("<Iiii2sBBBBH", group, value, hi, lo, owner, 0, action, kind, size, 0)
for name, (slot, kind, size, hi, lo) in t["ram"].items(): if name not in tft_types.MAP:
raise Unsupported("attribute %s (no map position measured)" % name)
amap[tft_types.MAP[name]] = k.first - row[0].first + k.slot[name]
put("type", tid, 255, 0, 1, 1)
put("id", cid, 255, 0, 1, 1)
put("vscope", 0, 1, 0, 1, 1)
if k.visible:
for name, (_, kind, hi, lo) in _RECT_REC.items():
put(name, k.signed(name, lo), hi, lo, kind, 2)
for name, spec in d["rec"].items():
if spec[0] in _CONST_KINDS and name in k.slot:
kind, size, hi, lo = spec[:4]
put(name, k.signed(name, lo), hi, lo, kind, size)
for item in d["ram"]:
if isinstance(item, int):
ram += bytes(item)
continue
kind, size, hi, lo = d["rec"][item][:4]
action = d["rec"][item][4] if len(d["rec"][item]) > 4 else 0
if kind == 0x3F: # string: txt_maxl + 1 bytes, not aligned if kind == 0x3F: # string: txt_maxl + 1 bytes, not aligned
size = _u(a["txt_maxl"]) + 1 size = k.v["txt_maxl"] + 1
if size > 255 or len(a[name].value) >= size: data = k.s[item]
raise Unsupported("text longer than txt_maxl, or txt_maxl > 254") if size > 255 or len(data) >= size:
raise Unsupported("text longer than txt_maxl, or txt_maxl > 254 (%s)" % k.name)
else: else:
ram += bytes(-len(ram) % min(size, 4)) ram += bytes(-len(ram) % min(size, 4))
if hi == "fonts": data = (k.v[item] & ((1 << 8 * size) - 1)).to_bytes(size, "little")
hi = nfonts - 1 if isinstance(hi, str):
if _u(a[name]) > hi: hi = env[hi] - 1
raise Unsupported("font %d does not exist" % _u(a[name])) if k.v[item] > hi and k.v[item] != 0xFFFF:
recs[slot] = struct.pack("<Iiii2sBBBBH", group, g + 4 + len(ram), hi, lo, owner, 0, raise Unsupported("%s %d of %s does not exist" % (item, k.v[item], k.name))
t.get("action", {}).get(name, 0), kind, size, 0) put(item, g + 4 + len(ram), hi, lo, kind, size, action)
amap[MAP[name]] = slot0 + slot ram += data.ljust(size, b"\0")
if name == "bco" and tid == 121:
page_bco = rec_base + slot0 + slot
ram += a[name].value[:size].ljust(size, b"\0")
ram += bytes(-len(ram) % 4) ram += bytes(-len(ram) % 4)
prec += b"".join(recs) prec += b"".join(recs)
# code block: draw section, erase section (visible types), event sections # code block: draw section, erase section (visible types), event sections
start = len(blob) start = len(blob)
ev = {g.name: tft_code.statements(tft_code.group_lines(g)) for g in c.groups if g.name != "att"} ev = {grp.name: tft_code.group_lines(grp) for grp in k.c.groups if grp.name != "att"}
rect = [_u(a[k]) if k in a else v for k, v in (("x", 0), ("y", 0), ("w", 1), ("h", 1), ("endx", 0), ("endy", 0))] rect = [k.v.get(name, default) for name, default in zip(_RECT, (0, 0, 1, 1, 0, 0))]
fill = b"\x09\x0d\x04" + ("%d,%d,%d,%d," % tuple(rect[:4])).encode() + b"\x01" + struct.pack("<I", page_bco)
draw = erase = 0xFFFFFFFF draw = erase = 0xFFFFFFFF
if d.get("draw"):
draw = len(blob)
section([], template=d.get("draw", ()))
if tid == 121: if tid == 121:
draw = len(blob)
blob += _chunk(fill)
section([]) section([])
section([]) elif k.visible:
else:
if "draw" in t:
draw = len(blob)
table_ = {**t["const"], **t["ram"]}
for raw in t["draw"](rect, lambda name: b"\x01" + struct.pack(
"<I", rec_base + slot0 + table_[name][0])):
blob += _chunk(raw)
section([])
if t["flag"] & 0x10:
erase = len(blob) erase = len(blob)
blob += _chunk(fill) section([], template=["fill @x,@y,@w,@h,@pagebco"])
section([])
code_at = [0xFFFFFFFF] * 4 # down, up, timer, unload (object +0x0C..) code_at = [0xFFFFFFFF] * 4 # down, up, timer, unload (object +0x0C..)
touch = t["flag"] & 0x10 or t.get("events") for label, group_name, prefix in d.get("events", ()):
if "init" in t: where_ = {"down": 0, "up": 1, "unload": 3}.get(label)
if t["init"] in init: if where_ is None and tft_code.statements(ev.get(group_name, [])):
raise Unsupported("two %s components on one page" % t["name"]) raise Unsupported("code in the %s event" % label)
init.append(t["init"]) if where_ is not None and (prefix or tft_code.statements(ev.get(group_name, []))):
for i, (label, group_name, wanted) in enumerate(( code_at[where_] = len(blob) + 4 + len(label)
(b"down", "codesdown", touch), (b"up", "codesup", touch), section(ev.get(group_name, []), label.encode(), prefix)
(None, None, False), (b"unload", "codesunload", tid == 121))):
if wanted:
if ev.get(group_name):
code_at[i] = len(blob) + 4 + len(label)
section(ev.get(group_name, []), label)
if tid == 121: if tid == 121:
pre, post = ev.get("codesload", []), ev.get("codesloadend", []) pre, post = ev.get("codesload", []), ev.get("codesloadend", [])
if tid == 51: if d.get("timer"):
# event: label, "S <1>", the event lines; registered by two init lines # event: label, "S <1>", the event lines; registered by two init lines
blob += _chunk(b"timer") blob += _chunk(b"timer")
code_at[2] = len(blob) code_at[2] = len(blob)
blob += _chunk(b"S \x03" + struct.pack("<I", 1)) blob += _chunk(b"S \x03" + struct.pack("<I", 1))
first = rec_base + slot0 init.append(b"\x09\x22\x08\x01" + struct.pack("<I", k.first + k.slot["en"]) + (",%d," % cid).encode()
init.append(b"\x09\x22\x08\x01" + struct.pack("<I", first + 8) + (",%d," % cid).encode() + b"\x01" + struct.pack("<I", k.first + k.slot["tim"]) + b",0")
+ b"\x01" + struct.pack("<I", first + 7) + b",0")
init.append(b"L \x03" + struct.pack("<I", len(blob))) init.append(b"L \x03" + struct.pack("<I", len(blob)))
section(ev.get("codestimer", [])) section(ev.get("codestimer", []))
for raw in tft_code.compile_lines(list(d.get("init", ())), ctx):
if raw in init:
raise Unsupported("two %s components on one page" % k.kind)
init.append(raw)
obj = bytearray(b"\xff" * tft.OBJ_SIZE) obj = bytearray(b"\xff" * tft.OBJ_SIZE)
struct.pack_into("<BBBBII", obj, 0, tid, cid, 0, t["flag"], draw, erase) struct.pack_into("<BBBBII", obj, 0, tid, cid, 0, d["flag"], draw, erase)
struct.pack_into("<4I", obj, 0x0C, *code_at) struct.pack_into("<4I", obj, 0x0C, *code_at)
struct.pack_into("<IHBBI6HI", obj, 0x1C, group, 0, 0x7F, 0, 0, *rect, start) struct.pack_into("<IHBBI6HI", obj, 0x1C, group, 0, 0x7F, 0, 0, *rect, start)
struct.pack_into("<88H", obj, 0x38, *amap) struct.pack_into("<88H", obj, 0x38, *amap)
objects += obj objects += obj
comp_names.append((tft.name_hash(c.get("objname")), cid)) comp_names.append((tft.name_hash(k.name), cid))
current[1] = None
names_off = len(blob) names_off = len(blob)
blob += _chunk(b"".join(struct.pack("<IH", h, i) for h, i in sorted(comp_names))) blob += _chunk(b"".join(struct.pack("<IH", h, i) for h, i in sorted(comp_names)))
blob += _chunk(bytes(ram) + bytes(8)) blob += _chunk(bytes(ram) + bytes(8))
@@ -284,9 +287,8 @@ def compile_pages(pages: list[Page], program: str, nfonts: int = 0):
blob += _chunk(c) blob += _chunk(c)
blob += _chunk(b"\x09\x21\x08") blob += _chunk(b"\x09\x21\x08")
section(post) section(post)
table.append((first_obj, len(page.components), names_off, rec_base, len(ram))) table.append((first_obj, len(row), names_off, row[0].first, len(ram)))
records += prec records += prec
rec_base += len(prec) // tft.REC_SIZE
rec_off = len(blob) + len(descriptors) rec_off = len(blob) + len(descriptors)
ptable = b"".join(struct.pack("<HHIII", f, cnt, no, rec_off + rb * tft.REC_SIZE, rs) for f, cnt, no, rb, rs in table) ptable = b"".join(struct.pack("<HHIII", f, cnt, no, rec_off + rb * tft.REC_SIZE, rs) for f, cnt, no, rb, rs in table)
return bytes(blob), descriptors, bytes(records), ptable, bytes(objects), program_off return bytes(blob), descriptors, bytes(records), ptable, bytes(objects), program_off
@@ -303,8 +305,9 @@ def build_tft(hmi: HMIFile, editor_dir: str = DEFAULT_EDITOR_DIR) -> bytes:
raise Unsupported("display direction %d" % pm["direction"]) raise Unsupported("display direction %d" % pm["direction"])
w, h = project_size(hmi) w, h = project_size(hmi)
pages = [Page.parse(hmi.read(name)) for rtype, name in pm["resources"] if rtype == "pa"] pages = [Page.parse(hmi.read(name)) for rtype, name in pm["resources"] if rtype == "pa"]
count = lambda ext: sum(1 for x in hmi.names() if re.fullmatch(r"\d+\." + ext, x)) # noqa: E731
blob, descriptors, records, ptable, objects, program_off = compile_pages( blob, descriptors, records, ptable, objects, program_off = compile_pages(
pages, hmi.read("Program.s").decode("latin-1"), sum(1 for x in hmi.names() if re.fullmatch(r"\d+\.zi", x))) pages, hmi.read("Program.s").decode("latin-1"), count("zi"), count("i"))
area, info = resource_area(hmi, editor_dir) area, info = resource_area(hmi, editor_dir)
base = tft.RES_START + len(area) base = tft.RES_START + len(area)
body = blob + descriptors + records + ptable + objects body = blob + descriptors + records + ptable + objects
@@ -322,7 +325,8 @@ def build_tft(hmi: HMIFile, editor_dir: str = DEFAULT_EDITOR_DIR) -> bytes:
head[0x4C:0x54] = b"\xff" * 8 head[0x4C:0x54] = b"\xff" * 8
struct.pack_into("<I", head, 0x58, len(blob) + len(descriptors) + len(records)) struct.pack_into("<I", head, 0x58, len(blob) + len(descriptors) + len(records))
pt = base + len(blob) + len(descriptors) + len(records) pt = base + len(blob) + len(descriptors) + len(records)
layout = [len(blob), len(blob), len(descriptors) // 12, len(blob) + len(descriptors), tft.RES_START, base, pt, pt + len(ptable), layout = [len(blob), len(blob), len(descriptors) // 12, len(blob) + len(descriptors), tft.RES_START,
base, pt, pt + len(ptable),
tft.RES_START + info["pictures"], 0, 0, 0, tft.RES_START + info["fonts"], program_off, tft.RES_START + info["pictures"], 0, 0, 0, tft.RES_START + info["fonts"], program_off,
len(pages) | (len(objects) // tft.OBJ_SIZE) << 16, info["npics"], 0, info["nfonts"], 3] len(pages) | (len(objects) // tft.OBJ_SIZE) << 16, info["npics"], 0, info["nfonts"], 3]
for i, v in enumerate(layout): for i, v in enumerate(layout):
+11 -1
View File
@@ -33,7 +33,7 @@ SYSTEM = {
} }
RAW_ARGS = {"printh"} # arguments copied as text RAW_ARGS = {"printh"} # arguments copied as text
_KEYWORDS = {"if", "else", "while", "for"} _KEYWORDS = {"if", "else", "while", "for"}
_TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|(?:p\[\d+\]\.)?b\[\d+\]\.\w+|0x[0-9A-Fa-f]+|\d+|[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*|.', re.S) _TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|@\w+|(?:p\[\d+\]\.)?b\[\d+\]\.\w+|0x[0-9A-Fa-f]+|\d+|[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*|.', re.S)
class Context: class Context:
@@ -112,6 +112,13 @@ def _expr(text: str, ctx: Context) -> bytes:
raise Unsupported("number after a binary minus in %r" % text) raise Unsupported("number after a binary minus in %r" % text)
del out[-1] del out[-1]
out += b out += b
elif t[0] == "@" and len(t) > 1: # component templates (tft_types)
local = getattr(ctx, "local", None)
if local is None:
raise Unsupported("%r in %r" % (t, text))
out += local(t[1:])
elif re.fullmatch(r"sys[0-9A-F]{2}_[48]", t): # unnamed system variable in a template
out += struct.pack("<BBHB", 4, int(t[6]), int(t[3:5], 16), 0)
elif "[" in t and len(t) > 1: # b[1].val, p[0].b[2].val stay text elif "[" in t and len(t) > 1: # b[1].val, p[0].b[2].val stay text
out += t.encode() out += t.encode()
elif t[0].isalpha() or t[0] == "_": elif t[0].isalpha() or t[0] == "_":
@@ -141,6 +148,9 @@ def _expr(text: str, ctx: Context) -> bytes:
def compile_line(line: str, ctx: Context) -> bytes: def compile_line(line: str, ctx: Context) -> bytes:
word = re.match(r"[A-Za-z_][A-Za-z0-9_]*", line) word = re.match(r"[A-Za-z_][A-Za-z0-9_]*", line)
raw = re.match(r"cmd([0-9A-F]{2})_([48])( |$)", line) # unnamed command in a template
if raw:
return bytes([9, int(raw.group(1), 16), int(raw.group(2))]) + _expr(line[raw.end():], ctx)
if word and word.group(0) in COMMANDS and line[word.end():word.end() + 1] in ("", " "): if word and word.group(0) in COMMANDS and line[word.end():word.end() + 1] in ("", " "):
table, idx = COMMANDS[word.group(0)] table, idx = COMMANDS[word.group(0)]
args = line[word.end() + 1:] args = line[word.end() + 1:]
+156
View File
@@ -0,0 +1,156 @@
"""Compiled form of each component type in a .tft (see docs/FORMAT.md 7.7).
Every entry was measured on Nextion Editor 1.68.2 output; combinations that were not measured
raise :class:`Unsupported`. A type is ``(name, visible, describe)``; ``describe(v, s, env)``
gets the numeric attributes ``v``, the string attributes ``s`` and ``env`` (font and picture
counts) and returns:
``vis`` attribute names in the Editor's order -- they get the record slots after the common ones
``rec`` name -> (kind, size, max, min[, change action]); kinds 0x01/0x02 are constants, the
others live in RAM; max "fonts"/"pics" = number of fonts/pictures - 1
``ram`` names in RAM order; an int = that many bytes whose meaning is unknown (always zero)
``draw`` script of the draw section; ``@name`` = the attribute (a record reference when it is
in RAM, its value otherwise), ``cmdXX_N`` / ``sysXX_N`` = command / system variable
tokens that have no public name
``events`` (label, event group, script put before the user's lines)
``init`` script added to the page's init code
``flag`` object flag byte
"""
from __future__ import annotations
from .tft_code import Unsupported
# attribute -> position in the object record's map (u16 table at +0x38)
MAP = {"vscope": 1, "sta": 2, "bco": 4, "picc": 5, "pic": 6, "pco2": 12, "pco": 16, "val": 20, "bco2": 24,
"font": 25, "xcen": 26, "ycen": 27, "txt": 28, "txt_maxl": 29, "tim": 33, "en": 34, "lenth": 41, "x": 42,
"y": 43, "endx": 44, "endy": 45, "w": 46, "h": 47, "id": 49, "isbr": 54, "spax": 56, "spay": 57, "pw": 58,
"style": 59, "borderc": 60, "borderw": 61, "type": 62, "format": 64}
U8, U16, COLOR = (0x31, 1, 255, 0), (0x32, 2, 65535, 0), (0x32, 2, 65535, 0)
TOUCH = (("down", "codesdown", ()), ("up", "codesup", ()))
def _need(kind, v, **values):
for name, value in values.items():
if v[name] != value:
raise Unsupported("%s with %s=%d" % (kind, name, v[name]))
def _page(v, s, env):
_need("page", v, sta=1)
return dict(vis=["up", "down", "left", "right", "sta", "bco"],
rec={"sta": (0x21, 1, 2, 0), "bco": COLOR}, ram=["sta", "bco"], flag=0x37,
draw=["fill @x,@y,@w,@h,@bco"], events=TOUCH + (("unload", "codesunload", ()),))
def _hotspot(v, s, env):
return dict(vis=[], rec={}, ram=[], flag=0x37, events=TOUCH)
def _variable(v, s, env):
_need("variable", v, sta=0)
return dict(vis=["sta", "val"], rec={"sta": (0x01, 1, 1, 0), "val": (0x39, 4, 2147483647, -2147483648)},
ram=["val"], flag=0x07, owner=False)
def _timer(v, s, env):
return dict(vis=["tim", "en"], rec={"tim": (0x32, 2, 65534, 50, 1), "en": (0x31, 1, 1, 0, 2)},
ram=["tim", "en"], flag=0x27, timer=True)
def _touch_cap(v, s, env):
return dict(vis=["val"], rec={"val": (0x21, 1, 65535, 0)}, ram=["val"], flag=0x27, events=TOUCH,
init=["cmd16_4 1"])
def _text(v, s, env):
_need("text", v, sta=1, style=0, spax=0, spay=0)
return dict(
vis=["sta", "style", "key", "font", "bco", "pco", "xcen", "ycen", "pw", "txt", "txt_maxl", "isbr", "spax", "spay"],
rec={"sta": (0x01, 1, 2, 0), "style": (0x01, 1, 3, 0), "font": (0x31, 1, "fonts", 0), "bco": COLOR, "pco": COLOR,
"xcen": (0x31, 1, 2, 0), "ycen": (0x31, 1, 2, 0), "pw": (0x31, 1, 1, 0), "txt": (0x3F, 0, 0, 0),
"txt_maxl": (0x02, 2, 65534, 0), "isbr": (0x31, 1, 1, 0), "spax": (0x01, 1, 255, 0), "spay": (0x01, 1, 255, 0)},
ram=["font", "isbr", "pco", "bco", "xcen", "ycen", "pw", "txt"], flag=0x37, events=TOUCH,
draw=["cmd1C_8 @x,@y,@w,@h,@font,@pco,@bco,@xcen,@ycen,@sta,@isbr,@spax,@spay,@pw,0",
"cmd13_4 32767,32767,32767,32767,@txt"])
def _back(v):
"""Background attribute for sta = crop image / solid colour / image, and its record."""
name = ("picc", "bco", "pic")[v["sta"]]
return name, (COLOR if name == "bco" else (0x32, 2, "pics", 0))
def _border(v):
"""Border of the text family: (visible border attributes, last argument of the text command,
script drawing the border). Styles exist only on a solid background."""
style = v["style"] if v["sta"] == 1 else 0
if style == 1:
return ["borderc", "borderw"], v["borderw"], ["cmd07_8 @x,@y,@w,@h,@borderc,@borderc,@borderw"]
if style == 2:
return [], 1, ["cmd07_8 @x,@y,@w,@h,16936,59164,1"]
if style == 3:
return [], 1, ["cmd07_8 @x,@y,@w,@h,59164,16936,1"]
return [], 0, []
def _number(v, s, env):
back, back_rec = _back(v)
border, inset, frame = _border(v)
solid = v["sta"] == 1
return dict(
vis=["sta"] + (["style"] if solid else []) + ["key"] + border
+ ["font", back, "pco", "xcen", "ycen", "val", "lenth", "format", "isbr", "spax", "spay"],
rec={"sta": (0x21, 1, 2, 0), "style": (0x21, 1, 3, 0), "borderc": COLOR, "borderw": U8,
"font": (0x31, 1, "fonts", 0), back: back_rec, "pco": COLOR, "xcen": (0x31, 1, 2, 0),
"ycen": (0x31, 1, 2, 0), "val": (0x39, 4, 2147483647, -2147483648), "lenth": (0x31, 1, 15, 0),
"format": (0x31, 1, 2, 0), "isbr": (0x31, 1, 1, 0), "spax": U8, "spay": U8},
ram=["sta", "style" if solid else 1] + (border or [3])
+ ["font", back, "pco", "xcen", "ycen", "val", "lenth", "format", 2, "isbr", "spax", "spay"],
flag=0x37, events=TOUCH,
draw=["cmd1C_8 @x,@y,@w,@h,@font,@pco,@%s,@xcen,@ycen,%d,@isbr,@spax,@spay,0,%d" % (back, v["sta"], inset),
"cmd11_4 @val,@lenth,@format"] + frame)
def _button(v, s, env):
_need("button", v, sta=1)
style = v["style"]
border = ["borderc", "borderw"] if style == 1 else []
inset = (0, v["borderw"], 1, 1, 1)[style]
text = ["cmd1C_8 @x,@y,@w,@h,@font,@%s,@%s,@xcen,@ycen,@sta,@isbr,@spax,@spay,0,%d",
"cmd13_4 32767,32767,32767,32767,@txt"]
edge = {2: ("16936,59164", "16936,59164"), 3: ("59164,16936", "59164,16936"),
4: ("16936,59164", "59164,16936")}.get(style) # (pressed, released) for 3D_auto
pressed = [text[0] % ("pco2", "bco2", inset), text[1]]
released = [text[0] % ("pco", "bco", inset), text[1]]
after = []
if style == 4:
pressed.append("cmd07_8 @x,@y,@w,@h,%s,1" % edge[0])
released.append("cmd07_8 @x,@y,@w,@h,%s,1" % edge[1])
elif style in (2, 3):
after = ["cmd07_8 @x,@y,@w,@h,%s,1" % edge[0]]
elif style == 1:
after = ["cmd07_8 @x,@y,@w,@h,@borderc,@borderc,@borderw"]
refresh = "ref @id+65535"
return dict(
vis=["sta", "style"] + border + ["font", "bco", "bco2", "pco", "pco2", "xcen", "ycen", "val", "txt", "txt_maxl",
"isbr", "spax", "spay"],
rec={"sta": (0x01, 1, 2, 0), "style": (0x01, 1, 4, 0), "borderc": (0x02, 2, 65535, 0), "borderw": (0x01, 1, 255, 0),
"font": (0x31, 1, "fonts", 0), "bco": COLOR, "bco2": COLOR, "pco": COLOR, "pco2": COLOR,
"xcen": (0x31, 1, 2, 0), "ycen": (0x31, 1, 2, 0), "val": (0x31, 1, 1, 0), "txt": (0x3F, 0, 0, 0),
"txt_maxl": (0x02, 2, 65534, 0), "isbr": (0x31, 1, 1, 0), "spax": (0x01, 1, 255, 0), "spay": (0x01, 1, 255, 0)},
ram=["font", "val", "bco", "bco2", "pco", "pco2", "xcen", "ycen", "isbr", "txt"], flag=0x37,
draw=["if(@val==1)", "{"] + pressed + ["}else", "{"] + released + ["}"] + after,
events=(("down", "codesdown", ("@val=1", refresh)), ("up", "codesup", ("@val=0", refresh))))
# type id -> (name, has a rectangle and the 19 common attributes, describe)
TYPES = {
121: ("page", True, _page),
109: ("hotspot", True, _hotspot),
52: ("variable", False, _variable),
51: ("timer", False, _timer),
5: ("touch_cap", False, _touch_cap),
116: ("text", True, _text),
54: ("number", True, _number),
98: ("button", True, _button),
}