Render Intelligent-only components; fonts follow the display direction

- SLText, TextSelect, DataRecord, FileBrowser pixel-exact against the Intelligent simulator;
  ComboBox and Switch with approximate anti-aliased edges; media/file components draw nothing
- fonts: header byte 3 = 0x0A + direction, glyphs in the direction's pixel order, Intelligent
  glyph data 4-byte aligned -- reproduces the Editor's own font conversion byte for byte
- Intelligent 3D frames: left edge drawn over the bottom edge

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mangavalkandClaude Opus 5.5 committed 2026-11-16 00:26:27 +01:00
1 parent 56062e1a3e
commit 49fee337d7
10 files changed
+334 -32

No files matched your search

+1 -1
View File
@@ -44,6 +44,6 @@ Back up the user's file first (copy it) unless they said not to; edits write in
- Writes projects for Nextion Editor 1.68.2; the user still compiles/uploads the `.tft` with the - Writes projects for Nextion Editor 1.68.2; the user still compiles/uploads the `.tft` with the
Editor (or Nexus for uploading). nxhmi cannot compile `.tft` files yet. Editor (or Nexus for uploading). nxhmi cannot compile `.tft` files yet.
- Rendering: Intelligent-only components are not drawn yet. - Rendering: Intelligent-only components are drawn as in the simulator (ComboBox and Switch edges are approximate). Run-time content (files, records, video) is not drawn. Fonts and pictures are stored in the project's display direction; `add_font`/`add_picture` handle it.
- QR codes on Basic displays: long texts can exceed the display RAM; the Editor then refuses to - QR codes on Basic displays: long texts can exceed the display RAM; the Editor then refuses to
compile ("not enough memory ... QR code"). Keep QR texts short there and compile to check. compile ("not enough memory ... QR code"). Keep QR texts short there and compile to check.
+1 -1
View File
@@ -31,7 +31,7 @@ Every percentage is a count with a stated basis, so it can be checked (details i
| Font modes | **50 %** (1/2) | black/white done (incl. TrueType import); anti-aliased not yet | | Font modes | **50 %** (1/2) | black/white done (incl. TrueType import); anti-aliased not yet |
| Readable attribute names in JSON | **65 %** (20/31 types) | value lists taken from the Editor for all Basic types; Intelligent-only types still raw numbers | | Readable attribute names in JSON | **65 %** (20/31 types) | value lists taken from the Editor for all Basic types; Intelligent-only types still raw numbers |
| Rendering, Basic components | **100 %** (20/20 pixel-exact) | incl. gauges and QR codes (own encoder, no dependencies) | | Rendering, Basic components | **100 %** (20/20 pixel-exact) | incl. gauges and QR codes (own encoder, no dependencies) |
| Rendering, all components | **65 %** (20/31 pixel-exact) | Intelligent-only components not rendered yet | | Rendering, all components | **94 %** (29/31 pixel-exact) | Intelligent ComboBox and Switch are drawn, but their anti-aliased edges are approximate (~99 % / ~92 % of pixels exact) |
| `.tft` compilation | **31 %** (2.5/8 milestones) | layout mapped, layout table decoded, trailer checksum (same-length edits only); not usable yet | | `.tft` compilation | **31 %** (2.5/8 milestones) | layout mapped, layout table decoded, trailer checksum (same-length edits only); not usable yet |
## Compatibility ## Compatibility
+3 -2
View File
@@ -15,7 +15,7 @@ byte for byte, or a file written by nxhmi was opened in the Editor and showed th
| Readable JSON (enum names, colours) | done for every value list the Editor documents | | Readable JSON (enum names, colours) | done for every value list the Editor documents |
| Pictures | **complete**: format 0 (Basic) and format 4 (Intelligent, with alpha), all display directions | | Pictures | **complete**: format 0 (Basic) and format 4 (Intelligent, with alpha), all display directions |
| Fonts | black/white **complete** incl. generation from TrueType; anti-aliased **missing** | | Fonts | black/white **complete** incl. generation from TrueType; anti-aliased **missing** |
| Rendering pages like the Editor | **pixel-identical** for every Basic component incl. picture skins, radios, gauges and QR codes | | Rendering pages like the Editor | **pixel-identical** for every Basic component and 9 of 11 Intelligent-only ones; ComboBox and Switch approximate at anti-aliased edges |
| New projects from scratch | `project.new_project(model)` for 12 Basic/Intelligent models; the generated demo is byte-identical to the Editor's re-save | | New projects from scratch | `project.new_project(model)` for 12 Basic/Intelligent models; the generated demo is byte-identical to the Editor's re-save |
| Compiling `.tft` firmware | **research only** -- not possible yet | | Compiling `.tft` firmware | **research only** -- not possible yet |
@@ -100,7 +100,8 @@ byte for byte, or a file written by nxhmi was opened in the Editor and showed th
### Rendering ### Rendering
| Item | Notes | | Item | Notes |
|---|---| |---|---|
| Pressed / runtime states, Intelligent-only components | not drawn | | Pressed / runtime states | not drawn |
| Anti-aliased edges (Switch, ComboBox) | approximate: the simulator's coverage routine is unknown (the knob looks like a scaled pre-drawn image) |
### `.tft` compilation (firmware for the display) ### `.tft` compilation (firmware for the display)
| Item | Status | | Item | Status |
+7 -4
View File
@@ -242,16 +242,19 @@ Adding a picture = `N.is` + `N.i` + a `i`/`N.i` resource-list entry (kept groupe
## 5. Fonts (`N.zi`, format version 6) ## 5. Fonts (`N.zi`, format version 6)
Header 44 bytes: magic `04 FF 00 0B`, u16 encoding (3 = iso-8859-1), u8 width, u8 height, Header 44 bytes: magic `04 FF 00` + `0x0A + display direction` (like pictures), u16 encoding (3 = iso-8859-1), u8 width, u8 height,
multi-byte range (2 bytes), code range first/last, u32 character count, u8 version = 6, multi-byte range (2 bytes), code range first/last, u32 character count, u8 version = 6,
u8 name length (twice) + 0, u32 length of name+map+glyphs, u32 name offset = 0x2C, 16 unknown u8 name length (twice) + 0, u32 length of name+map+glyphs, u32 name offset = 0x2C, 16 unknown
bytes. Then the name, the character map, the glyph data. bytes. Then the name, the character map, the glyph data.
Character map: 10 bytes per character: u16 code, u8 glyph width, 2 unknown bytes, Character map: 10 bytes per character: u16 code, u8 glyph width, 2 unknown bytes,
u24 glyph offset (relative to the map start), u16 glyph length. u24 glyph offset (relative to the map start), u16 glyph length. In Intelligent projects the glyph
data starts 4-byte aligned (zero padding after the map); Basic fonts have no padding.
Glyph: mode byte (0x01 = black/white), then run-length codes over the pixels in the same Glyph: mode byte (0x01 = black/white), then run-length codes over the pixels in the same order
column-by-column, bottom-to-top order as pictures (runs continue across columns): as pictures for the project's display direction (runs continue across rows/columns): at 90° column
by column, bottom to top; at 0° row by row. When an Intelligent project is compiled, the Editor
converts a 90° font to the project direction; our encoder reproduces that conversion byte for byte.
| Code | Meaning | | Code | Meaning |
|---|---| |---|---|
+29
View File
@@ -36,11 +36,40 @@ Per component (dedicated test pages):
| QR code (byte/alphanumeric/numeric text, versions 1-8, margins, colours, logo, Latin-1) | 100 % | own encoder (`nxhmi.qr`), see below | | QR code (byte/alphanumeric/numeric text, versions 1-8, margins, colours, logo, Latin-1) | 100 % | own encoder (`nxhmi.qr`), see below |
| hotspot, touch cap, timer, variable | nothing drawn (same as the Editor) | | | hotspot, touch cap, timer, variable | nothing drawn (same as the Editor) | |
Intelligent-only components, checked against the **Intelligent simulator** (5 test pages, 23
TextSelects, several of each other type):
| Component | Match | Notes |
|---|---|---|
| SLText | 100 % | text from the top-left inside the frame |
| TextSelect (hig, val, borders, fonts, cut cells) | 100 % | see rules below |
| DataRecord (header, 1-5 columns, styles) | 100 % | records only exist at run time |
| FileBrowser | 100 % | frame and fill; the file list only exists at run time |
| ExPicture, video, audio, Gmov, FileStream | nothing drawn (same as the simulator) | they show content only once a file is loaded |
| ComboBox | ~99 % | structure exact; anti-aliased corners and arrow approximate |
| Switch | ~88-97 % | structure exact; anti-aliased knob and track edges approximate |
## Rules learned from the Editor ## Rules learned from the Editor
- Colours: RGB565 is expanded differently per series. Basic replicates the top bits - Colours: RGB565 is expanded differently per series. Basic replicates the top bits
(`r<<3 | r>>2`); Intelligent scales (`r*255//31`, `g*255//63`), so `0xC618` shows as (`r<<3 | r>>2`); Intelligent scales (`r*255//31`, `g*255//63`), so `0xC618` shows as
(198,195,198) on Basic and (197,194,197) on Intelligent. (198,195,198) on Basic and (197,194,197) on Intelligent.
- Intelligent 3D frames draw the left edge after the bottom one (dark bottom-left corner on
3D down); Basic draws it the other way round.
- TextSelect: items (`path`, CR LF separated) in cells of `hig` rows inside the frame; the
selected cell starts at `iy + (ih - hig) // 2` and its two `pco1` lines are mirrored
(`top` and `iy + ih - 1 - (ih - hig) // 2`); selected text `pco2`, others `pco`; `val` out
of range selects item 0; the list wraps around. Text is centred in its full cell and clipped
to the frame; a cell cut by the *screen* bottom centres in the part on screen. Rows within
`hig` of the top/bottom edge fade into `bco`: 7-bit alpha `(127 // hig) * d`, blended
`(fg*a + bg*(127-a)) // 127`.
- DataRecord: `dez` columns named by `dir` (`^`-separated); column lines in `gdc` every
`(iw - 1) // dez` px, the last `(iw - 1) % dez` columns one px wider; header `hig` rows in
`bco1`, names in `pco1` placed by `xcen`, vertically centred.
- Switch: track `bco`/`bco2` (on), knob `pco`/`pco2`, text `txt` = "off/on" in `pco1` centred in
`[h, w)` (off) or `[0, w-h)` (on). ComboBox: text placed by `xcen`/`ycen` over the whole box,
`pco3` arrow `wid` px wide 4.5 px from the right edge. Corner radius for both: `dis * h // 200`,
square below 3 px; rounded shapes are inset half a pixel (outer ring 50 %, blended linearly).
- Intelligent pictures with alpha (format 4, 7-bit alpha `a`): 8-bit alpha is `2*a` (127 = 255), - Intelligent pictures with alpha (format 4, 7-bit alpha `a`): 8-bit alpha is `2*a` (127 = 255),
blended as `bg + round((src - bg) * alpha / 255)` per channel. Exact against the Intelligent blended as `bg + round((src - bg) * alpha / 255)` per channel. Exact against the Intelligent
simulator (342 samples). The Editor *canvas* blends slightly differently (up to 3 levels off at simulator (342 samples). The Editor *canvas* blends slightly differently (up to 3 levels off at
+24 -16
View File
@@ -24,9 +24,10 @@ Character map: ``count`` entries of 10 bytes::
5 3 glyph data offset (relative to the start of the map) 5 3 glyph data offset (relative to the start of the map)
8 2 glyph data length 8 2 glyph data length
Glyph data: one mode byte (0x01 = black/white), then run-length codes. Pixels are scanned Glyph data: one mode byte (0x01 = black/white), then run-length codes. Pixels are scanned in
column by column (x = 0..w-1), each column from the bottom row up -- the same 90-degree panel the project's display direction, exactly like pictures (header byte 3 = 0x0A + direction): at
rotation as pictures. Codes (top two bits = op):: 90 degrees column by column (x = 0..w-1), each column from the bottom row up; at 0 degrees row by
row; see ``pictures.stored_order``. Codes (top two bits = op)::
00 0xxxxx x transparent 00 1xxxxx x ink 00 0xxxxx x transparent 00 1xxxxx x ink
01 0xxxxx x transparent + 1 ink 01 1xxxxx x transparent + 2 ink 01 0xxxxx x transparent + 1 ink 01 1xxxxx x transparent + 2 ink
@@ -63,6 +64,8 @@ class Font:
last: int last: int
glyphs: list = field(default_factory=list) glyphs: list = field(default_factory=list)
header: bytes = b"" # original 44-byte header, for fields not modelled header: bytes = b"" # original 44-byte header, for fields not modelled
direction: int = 1 # display direction the glyphs are stored for (header byte 3 = 0x0A + d)
align: bool = False # Intelligent: glyph data starts 4-byte aligned (zero padding after the map)
# ------------------------------------------------------------------ decode # ------------------------------------------------------------------ decode
@classmethod @classmethod
@@ -77,29 +80,35 @@ class Font:
start, = struct.unpack_from("<I", blob, 24) start, = struct.unpack_from("<I", blob, 24)
name = blob[start:start + nlen].decode("latin-1") name = blob[start:start + nlen].decode("latin-1")
m = start + nlen m = start + nlen
f = cls(name, w, h, struct.unpack_from("<H", blob, 4)[0], blob[10], blob[11], [], bytes(blob[:HEADER_SIZE])) d = (blob[3] - 0x0A) % 4
f = cls(name, w, h, struct.unpack_from("<H", blob, 4)[0], blob[10], blob[11], [], bytes(blob[:HEADER_SIZE]), d)
if count:
f.align = (blob[m + 5] | blob[m + 6] << 8 | blob[m + 7] << 16) != MAP_ENTRY * count
for i in range(count): for i in range(count):
e = blob[m + MAP_ENTRY * i: m + MAP_ENTRY * (i + 1)] e = blob[m + MAP_ENTRY * i: m + MAP_ENTRY * (i + 1)]
code, gw = struct.unpack_from("<HB", e, 0) code, gw = struct.unpack_from("<HB", e, 0)
off = e[5] | e[6] << 8 | e[7] << 16 off = e[5] | e[6] << 8 | e[7] << 16
ln, = struct.unpack_from("<H", e, 8) ln, = struct.unpack_from("<H", e, 8)
data = blob[m + off: m + off + ln] data = blob[m + off: m + off + ln]
f.glyphs.append(Glyph(code, gw, decode_glyph(data, gw, h), bytes(e[3:5]), data[0])) f.glyphs.append(Glyph(code, gw, decode_glyph(data, gw, h, d), bytes(e[3:5]), data[0]))
return f return f
# ------------------------------------------------------------------ encode # ------------------------------------------------------------------ encode
def pack(self) -> bytes: def pack(self) -> bytes:
name = self.name.encode("latin-1") name = self.name.encode("latin-1")
bodies = [bytes([g.mode]) + encode_glyph(g.pixels, g.width, self.height) for g in self.glyphs] bodies = [bytes([g.mode]) + encode_glyph(g.pixels, g.width, self.height, self.direction)
for g in self.glyphs]
mp = bytearray() mp = bytearray()
off = MAP_ENTRY * len(self.glyphs) off = MAP_ENTRY * len(self.glyphs)
pad = -off % 4 if self.align else 0
off += pad
for g, b in zip(self.glyphs, bodies): for g, b in zip(self.glyphs, bodies):
mp += struct.pack("<HB", g.code, g.width) + g.map_extra[:2].ljust(2, b"\0") mp += struct.pack("<HB", g.code, g.width) + g.map_extra[:2].ljust(2, b"\0")
mp += bytes([off & 0xFF, (off >> 8) & 0xFF, off >> 16]) + struct.pack("<H", len(b)) mp += bytes([off & 0xFF, (off >> 8) & 0xFF, off >> 16]) + struct.pack("<H", len(b))
off += len(b) off += len(b)
payload = name + bytes(mp) + b"".join(bodies) payload = name + bytes(mp) + bytes(pad) + b"".join(bodies)
hdr = bytearray(self.header or bytes(HEADER_SIZE)) hdr = bytearray(self.header or bytes(HEADER_SIZE))
hdr[0:4] = hdr[0:4] if self.header else b"\x04\xff\x00\x0b" hdr[0:4] = bytes([4, 0xFF, 0, 0x0A + self.direction % 4])
struct.pack_into("<H", hdr, 4, self.encoding) struct.pack_into("<H", hdr, 4, self.encoding)
hdr[6], hdr[7], hdr[10], hdr[11] = self.width, self.height, self.first, self.last hdr[6], hdr[7], hdr[10], hdr[11] = self.width, self.height, self.first, self.last
struct.pack_into("<I", hdr, 12, len(self.glyphs)) struct.pack_into("<I", hdr, 12, len(self.glyphs))
@@ -115,13 +124,12 @@ class Font:
return None return None
def _scan_order(w: int, h: int): def _scan_order(w: int, h: int, direction: int = 1):
for x in range(w): from .pictures import stored_order
for y in range(h - 1, -1, -1): return stored_order(w, h, direction)
yield x, y
def decode_glyph(data: bytes, w: int, h: int) -> list: def decode_glyph(data: bytes, w: int, h: int, direction: int = 1) -> list:
stream = [] stream = []
for b in data[1:]: for b in data[1:]:
op, bit, x = b >> 6, (b >> 5) & 1, b & 0x1F op, bit, x = b >> 6, (b >> 5) & 1, b & 0x1F
@@ -132,14 +140,14 @@ def decode_glyph(data: bytes, w: int, h: int) -> list:
else: else:
stream += [0] * x + [1] * (op * 2 - 1 + bit) stream += [0] * x + [1] * (op * 2 - 1 + bit)
rows = [[0] * w for _ in range(h)] rows = [[0] * w for _ in range(h)]
for v, (x, y) in zip(stream, _scan_order(w, h)): for v, (x, y) in zip(stream, _scan_order(w, h, direction)):
rows[y][x] = v rows[y][x] = v
return rows return rows
def encode_glyph(rows: list, w: int, h: int) -> bytes: def encode_glyph(rows: list, w: int, h: int, direction: int = 1) -> bytes:
"""Run-length encode a glyph (rows top->bottom). Greedy, see docs for the code table.""" """Run-length encode a glyph (rows top->bottom). Greedy, see docs for the code table."""
s = [rows[y][x] for x, y in _scan_order(w, h)] s = [rows[y][x] for x, y in _scan_order(w, h, direction)]
out = bytearray() out = bytearray()
i, n = 0, len(s) i, n = 0, len(s)
while i < n: while i < n:
+3
View File
@@ -257,6 +257,9 @@ def add_font(h: HMIFile, font) -> int:
n = 0 n = 0
while h.find("%d.zi" % n): while h.find("%d.zi" % n):
n += 1 n += 1
main = h.read("main.HMI")
font.direction = main[12] % 4 # glyphs are stored rotated like pictures
font.align = main[11] == 3 # Intelligent: glyph data 4-byte aligned
h.write("%d.zi" % n, font.pack()) h.write("%d.zi" % n, font.pack())
h.write("main.HMI", main_insert_resource(h.read("main.HMI"), "zi", "%d.zi" % n)) h.write("main.HMI", main_insert_resource(h.read("main.HMI"), "zi", "%d.zi" % n))
return n return n
+202 -8
View File
@@ -186,7 +186,11 @@ class Renderer:
t = c.get("type") t = c.get("type")
fn = {116: self.text, 55: self.text, 98: self.text, 53: self.dual, 54: self.number, 59: self.xfloat, fn = {116: self.text, 55: self.text, 98: self.text, 53: self.dual, 54: self.number, 59: self.xfloat,
112: self.picture, 113: self.crop, 1: self.slider, 106: self.progress, 56: self.checkbox, 112: self.picture, 113: self.crop, 1: self.slider, 106: self.progress, 56: self.checkbox,
57: self.radio, 122: self.gauge, 0: self.waveform, 58: self.qrcode}.get(t) 57: self.radio, 122: self.gauge, 0: self.waveform, 58: self.qrcode,
62: self.sl_text, 65: self.file_browser, 66: self.data_record, 68: self.text_select,
67: self.switch, 61: self.combobox}.get(t)
# Intelligent video (3), audio (4), Gmov (2), ExPicture (60) and FileStream (63) show nothing
# until they have a file loaded at run time (same as the simulator)
if fn: if fn:
fn(img, c) fn(img, c)
@@ -232,16 +236,25 @@ class Renderer:
light, dark = (230, 226, 230), (65, 68, 65) # measured in Editor 1.68 light, dark = (230, 226, 230), (65, 68, 65) # measured in Editor 1.68
if style == 2: if style == 2:
light, dark = dark, light light, dark = dark, light
d.line((x, y, x + w - 1, y), fill=light); d.line((x, y, x, y + h - 1), fill=light) top, left = (x, y, x + w - 1, y), (x, y, x, y + h - 1)
d.line((x, y + h - 1, x + w - 1, y + h - 1), fill=dark); d.line((x + w - 1, y, x + w - 1, y + h - 1), fill=dark) bottom, right = (x, y + h - 1, x + w - 1, y + h - 1), (x + w - 1, y, x + w - 1, y + h - 1)
if self.series == 3: # Intelligent: left edge over the bottom one
order = ((top, light), (bottom, dark), (left, light), (right, dark))
else:
order = ((top, light), (left, light), (bottom, dark), (right, dark))
for line, col in order:
d.line(line, fill=col)
def _text(self, img, c, s, x, y, w, h, color): def _text(self, img, c, s, x, y, w, h, color, xcen=None, ycen=None, wrap=None, shade=None, clip=None):
"""Draw text in the box. xcen/ycen/wrap override the component's attributes; ``shade(yy)``,
if given, returns the colour for page row yy (TextSelect fades its outer rows)."""
font = self.font(c.get("font") or 0) font = self.font(c.get("font") or 0)
if font is None or not s: if font is None or not s:
return return
spax, spay = c.get("spax") or 0, c.get("spay") or 0 spax, spay = c.get("spax") or 0, c.get("spay") or 0
xcen, ycen = c.get("xcen"), c.get("ycen") xcen = c.get("xcen") if xcen is None else xcen
wrap = c.get("isbr") ycen = c.get("ycen") if ycen is None else ycen
wrap = c.get("isbr") if wrap is None else wrap
glyphs = {g.code: g for g in font.glyphs} glyphs = {g.code: g for g in font.glyphs}
def gw(ch): def gw(ch):
@@ -258,6 +271,7 @@ class Renderer:
lines.append(cur) lines.append(cur)
line_h = font.height + spay line_h = font.height + spay
total_h = len(lines) * line_h - spay total_h = len(lines) * line_h - spay
cy0, cy1 = clip or (y, y + h) # rows drawn (TextSelect: the component)
if ycen == 1: if ycen == 1:
ty = y + max(0, (h - total_h) // 2) # never starts above the box ty = y + max(0, (h - total_h) // 2) # never starts above the box
elif ycen == 2: elif ycen == 2:
@@ -281,12 +295,13 @@ class Renderer:
if g: if g:
for gy, row in enumerate(g.pixels): for gy, row in enumerate(g.pixels):
yy = ty + gy yy = ty + gy
if yy < y or yy >= y + h or yy >= H: if yy < max(y, cy0) or yy >= min(y + h, cy1) or yy >= H:
continue continue
col = shade(yy) if shade else color
for gx, v in enumerate(row): for gx, v in enumerate(row):
xx = tx + gx xx = tx + gx
if v and x <= xx < x + w and 0 <= xx < W and yy >= 0: if v and x <= xx < x + w and 0 <= xx < W and yy >= 0:
px[xx, yy] = color px[xx, yy] = col
tx += gw(ch) tx += gw(ch)
ty += line_h ty += line_h
@@ -491,3 +506,182 @@ class Renderer:
src = self.pic(c.get("pic")) src = self.pic(c.get("pic"))
if src: if src:
self._paste(img, src, 0, 0, src.width, src.height, x + (w - src.width) // 2, y + (h - src.height) // 2) self._paste(img, src, 0, 0, src.width, src.height, x + (w - src.width) // 2, y + (h - src.height) // 2)
# ------------------------------------------------------------------ Intelligent-only
def sl_text(self, img, c):
"""SLText: background, frame, then the text from the top-left (lines split at CR LF)."""
x, y, w, h = self._box(c)
self._background(img, c, x, y, w, h)
self._border(img, c, x, y, w, h)
self._text(img, c, c.get("txt") or "", *self._inner(c, x, y, w, h), self.rgb(c.get("pco") or 0),
ycen=0)
def file_browser(self, img, c):
"""FileBrowser: background and frame; the file list only exists at run time (SD card)."""
x, y, w, h = self._box(c)
self._background(img, c, x, y, w, h)
self._border(img, c, x, y, w, h)
def data_record(self, img, c):
"""DataRecord: frame, header row in bco1 with dez columns named by the '^'-separated dir,
grid lines in gdc (records are added at run time)."""
x, y, w, h = self._box(c)
self._background(img, c, x, y, w, h)
self._border(img, c, x, y, w, h)
ix, iy, iw, ih = self._inner(c, x, y, w, h)
n = max(1, c.get("dez") or 0) # dez = number of columns
heads = ((c.get("dir") or "").split("^") + [""] * n)[:n]
hig = c.get("hig") or 0
base, extra = divmod(iw - 1, n) # the last `extra` columns are 1 px wider
lines = [ix]
for k in range(n):
lines.append(lines[-1] + base + (1 if k >= n - extra else 0))
gc, hc = self.rgb(c.get("gdc") or 0), self.rgb(c.get("bco1") or 0)
right = lines[-1]
img.paste(gc, (ix, iy, right + 1, iy + 1))
img.paste(gc, (ix, iy + hig, right + 1, iy + hig + 1))
for lx in lines:
img.paste(gc, (lx, iy, lx + 1, iy + hig + 1))
for k, name in enumerate(heads):
cx, cw = lines[k] + 1, lines[k + 1] - lines[k] - 1
img.paste(hc, (cx, iy + 1, cx + cw, iy + hig))
self._text(img, c, name, cx, iy + 1, cw, hig - 1, self.rgb(c.get("pco1") or 0), ycen=1)
def text_select(self, img, c):
"""TextSelect: items (path, one per line) in rows of hig px centred on the selected item
(val, first item if out of range), drawn in pco2 between two pco1 lines; the list wraps around. Text near the
top/bottom edge fades into bco: 7-bit alpha (127 // hig) * d for d < hig rows from the edge
(inside the border), blended as (fg*a + bg*(127-a)) // 127."""
x, y, w, h = self._box(c)
self._background(img, c, x, y, w, h)
self._border(img, c, x, y, w, h)
items = (c.get("path") or "").replace("\r\n", "\n").split("\n")
hig = c.get("hig") or 1
x, y, w, h = self._inner(c, x, y, w, h) # items, lines and fade inside the border
top = y + (h - hig) // 2
lc = self.rgb(c.get("pco1") or 0)
img.paste(lc, (x, top, x + w, top + 1))
bot = y + h - 1 - (h - hig) // 2 # mirrors the top line
img.paste(lc, (x, bot, x + w, bot + 1))
bg = self.rgb(c.get("bco") or 0)
val = c.get("val") or 0
if val >= len(items):
val = 0 # out of range: first item
k0 = -((top - y) // hig + 1)
for k in range(k0, (y + h - top) // hig + 1):
cy = top + k * hig
fg = self.rgb((c.get("pco2") if k == 0 else c.get("pco")) or 0)
def shade(yy, fg=fg):
d = min(yy - y, y + h - 1 - yy)
a = 127 if d >= hig else (127 // hig) * d
return tuple((f * a + b * (127 - a)) // 127 for f, b in zip(fg, bg))
text = items[(val + k) % len(items)] if items else ""
# centred in its cell; a cell cut by the screen bottom centres in the part on screen
c0, c1 = cy, min(cy + hig, img.height) # (only the bottom edge, measured)
self._text(img, c, text, x, c0, w, c1 - c0, fg, xcen=1, ycen=1, wrap=0, shade=shade,
clip=(y, y + h))
# ------------------------------------------------------------------ anti-aliased shapes (Intelligent)
def _aa_fill(self, img, box, col, sdf, gamma=False):
"""Fill the pixels of box (x0, y0, x1, y1) with col, weighted by coverage of the shape whose
signed distance (negative inside) at a pixel centre is sdf(px, py). The Intelligent simulator
blends rounded boxes linearly (their outer ring is exactly 50 %) and the switch knob in
linear light (``gamma``). Its own coverage routine is not known, so edge pixels are
approximate; interiors, colours and positions are exact."""
px = img.load()
W, H = img.size
x0, y0, x1, y1 = box
for yy in range(max(0, y0), min(H, y1)):
for xx in range(max(0, x0), min(W, x1)):
cov = min(1.0, max(0.0, 0.5 - sdf(xx + 0.5, yy + 0.5)))
if cov >= 1.0:
px[xx, yy] = col
elif cov > 0.0:
k = round(cov * 32) / 32
if gamma:
px[xx, yy] = tuple(_enc(_lin(f) * k + _lin(b) * (1 - k)) for f, b in zip(col, px[xx, yy][:3]))
else:
px[xx, yy] = tuple(int(f * k + b * (1 - k)) for f, b in zip(col, px[xx, yy][:3]))
def _round_rect(self, img, x, y, w, h, r, col):
r = min(r, w / 2, h / 2)
if r > 0: # rounded shapes: edge pixels half covered
x, y, w, h = x + 0.5, y + 0.5, w - 1, h - 1
r = min(r, w / 2, h / 2)
def sdf(px, py):
qx = abs(px - (x + w / 2)) - (w / 2 - r)
qy = abs(py - (y + h / 2)) - (h / 2 - r)
return math.hypot(max(qx, 0), max(qy, 0)) + min(max(qx, qy), 0) - r
self._aa_fill(img, (int(x), int(y), int(math.ceil(x + w)), int(math.ceil(y + h))), col, sdf)
def _disc(self, img, cx, cy, r, col):
self._aa_fill(img, (int(cx - r) - 1, int(cy - r) - 1, int(cx + r) + 2, int(cy + r) + 2), col,
lambda px, py: math.hypot(px - cx, py - cy) - r, gamma=True)
def switch(self, img, c):
"""Switch: rounded track (corner radius dis % of h/2) in bco / bco2 (on), knob pco / pco2
on the left (off) or right (on), text (txt "off/on") in pco1 centred on the free side."""
x, y, w, h = self._box(c)
on = bool(c.get("val"))
r = _radius(c, h)
self._round_rect(img, x, y, w, h, r, self.rgb((c.get("bco2") if on else c.get("bco")) or 0))
kx = x + (w - h / 2 + 0.5625 if on else h / 2 - 0.4375)
self._disc(img, kx, y + h / 2 - 0.8125, h / 2 - 1.3125, self.rgb((c.get("pco2") if on else c.get("pco")) or 0))
parts = (c.get("txt") or "").split("/")
label = (parts[1] if len(parts) > 1 else "") if on else parts[0]
tx, tw = (x, w - h) if on else (x + h, w - h)
self._text(img, c, label, tx, y, tw, h, self.rgb(c.get("pco1") or 0), xcen=1, ycen=1, wrap=0)
def combobox(self, img, c):
"""ComboBox (closed): box with corners rounded by dis % of h/2 (flat / border styles; the 3D
styles are square), text placed by xcen/ycen, and a pco3 down arrow wid px wide near the
right edge (none when up = 0). The drop-down list only exists at run time."""
x, y, w, h = self._box(c)
style, sta = c.get("style"), c.get("sta")
r = _radius(c, h)
if sta != 1 or style in (2, 3):
self._background(img, c, x, y, w, h)
self._border(img, c, x, y, w, h)
elif style == 1:
bw = c.get("borderw") or 0
self._round_rect(img, x, y, w, h, r, self.rgb(c.get("borderc") or 0))
self._round_rect(img, x + bw, y + bw, w - 2 * bw, h - 2 * bw, max(0, r - bw), self.rgb(c.get("bco") or 0))
else:
self._round_rect(img, x, y, w, h, r, self.rgb(c.get("bco") or 0))
self._text(img, c, c.get("txt") or "", *self._inner(c, x, y, w, h), self.rgb(c.get("pco") or 0))
if c.get("up"):
wid = c.get("wid") or 0
x1 = x + w - 4.5
x0, top = x1 - wid, y + h / 2 - 2.5
apex = (x1 + x0) / 2, top + wid / 2
edges = ((x0, top, x1, top), (x1, top) + apex, apex + (x0, top))
def sdf(px, py):
d = []
for ax, ay, bx, by in edges: # distance to each edge line, outward positive
nx, ny = by - ay, ax - bx
ln = math.hypot(nx, ny) or 1
d.append(((px - ax) * nx + (py - ay) * ny) / ln)
return max(d)
self._aa_fill(img, (int(x0) - 1, int(top) - 1, int(x1) + 2, int(apex[1]) + 2),
self.rgb(c.get("pco3") or 0), sdf)
def _radius(c, h):
"""Corner radius of switch / combobox: dis % of h/2, whole pixels; below 3 px the simulator
draws square corners (no anti-aliased edge either)."""
r = (c.get("dis") or 0) * h // 200
return r if r >= 3 else 0
def _lin(v):
v /= 255
return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4
def _enc(l):
v = 12.92 * l if l <= 0.0031308 else 1.055 * l ** (1 / 2.4) - 0.055
return int(round(v * 255))
+17
View File
@@ -95,6 +95,23 @@ class Format4(unittest.TestCase):
self.assertEqual(img.getpixel((1, 0))[3], 226) # 227 * 127 // 255 = 113 -> 226 self.assertEqual(img.getpixel((1, 0))[3], 226) # 227 * 127 // 255 = 113 -> 226
self.assertEqual(img.getpixel((2, 0))[3], 2) self.assertEqual(img.getpixel((2, 0))[3], 2)
@unittest.skipUnless(HAVE_PIL, "needs Pillow")
def test_font_follows_project_direction(self):
# an Intelligent landscape project (0 degrees): glyphs row by row, header byte 3 = 0x0A,
# glyph data 4-byte aligned -- what the Editor converts a 90-degree font to
from nxhmi import project
h = project.new_project("NX8048P050_011")
f = fonts.from_ttf(None, 16)
n = project.add_font(h, f)
blob = h.read("%d.zi" % n)
self.assertEqual(blob[3], 0x0A)
back = fonts.Font.parse(blob)
self.assertEqual((back.direction, back.align), (0, True))
self.assertEqual(back.glyph("0").pixels, fonts.from_ttf(None, 16).glyph("0").pixels)
self.assertEqual(back.pack(), blob)
m = 0x2C + blob[17]
self.assertEqual((blob[m + 5] | blob[m + 6] << 8) % 4, 0)
@unittest.skipUnless(HAVE_PIL, "needs Pillow") @unittest.skipUnless(HAVE_PIL, "needs Pillow")
def test_image_roundtrip(self): def test_image_roundtrip(self):
from PIL import Image from PIL import Image
+47
View File
@@ -126,6 +126,53 @@ class Render(unittest.TestCase):
self.assertEqual(img.getpixel((0, 0)), (194, 0, 92)) self.assertEqual(img.getpixel((0, 0)), (194, 0, 92))
self.assertEqual(img.getpixel((1, 0)), (255, 0, 41)) self.assertEqual(img.getpixel((1, 0)), (255, 0, 41))
def _intelligent(self, font_px=16):
from nxhmi import fonts, project
from nxhmi.page import Page
h = project.new_project("NX8048P050_011")
fid = project.add_font(h, fonts.from_ttf(None, font_px))
p = Page.parse(h.read("0.pa"))
p.components[0].set("bco", 0x001F)
return h, p, fid
def test_text_select(self):
# measured in the Intelligent simulator (see RENDER.md)
from nxhmi.render import Renderer
h, p, fid = self._intelligent()
C.add(p, "text_select", x=0, y=0, w=90, h=200, font=fid, hig=42, pco1=0x07E0)
C.add(p, "text_select", x=100, y=0, w=100, h=230, font=fid, hig=55, style=1, borderw=3)
h.write("0.pa", p.pack())
img = Renderer(h).render("page0")
self.assertEqual(img.getpixel((5, 79)), (0, 255, 0)) # lines at (h-hig)//2 ...
self.assertEqual(img.getpixel((5, 120)), (0, 255, 0)) # ... and mirrored at the bottom
self.assertEqual(img.getpixel((105, 87)), (0, 0, 255)) # inside the border, odd gap
self.assertEqual(img.getpixel((105, 142)), (0, 0, 255))
top_row = {img.getpixel((x, 12)) for x in range(90)} - {(255, 255, 255)}
self.assertEqual(top_row, {(182, 182, 182)}) # faded: alpha (127 // 42) * 12
def test_data_record_columns(self):
from nxhmi.render import Renderer
h, p, fid = self._intelligent()
C.add(p, "data_record", x=0, y=0, w=187, h=150, font=fid, dir="h0^h1", dez=4, hig=20, style=0)
h.write("0.pa", p.pack())
img = Renderer(h).render("page0")
grid = [x for x in range(187) if img.getpixel((x, 5)) == (197, 194, 197)]
self.assertEqual(grid, [0, 46, 92, 139, 186]) # last columns take the remainder
def test_switch_and_combobox_structure(self):
from nxhmi.render import Renderer
h, p, fid = self._intelligent()
C.add(p, "switch", x=0, y=0, w=120, h=40, val=1, dis=0, font=fid, txt="Off/On",
bco=0xF800, pco=0x07E0, bco2=0xFFE0, pco2=0xF81F, pco1=0)
C.add(p, "combobox", x=200, y=0, w=60, h=30, dis=5, font=fid)
h.write("0.pa", p.pack())
img = Renderer(h).render("page0")
self.assertEqual(img.getpixel((0, 0)), (255, 255, 0)) # on: bco2 track, square corners
self.assertEqual(img.getpixel((100, 19)), (255, 0, 255)) # knob on the right in pco2
ink = [x for x in range(80) if img.getpixel((x, 20)) == (0, 0, 0)]
self.assertEqual(min(ink), 32) # "On" centred in [0, w-h)
self.assertEqual(img.getpixel((200, 0)), (255, 255, 255)) # radius 30*5//200 < 3: square
def test_demo_pages_render(self): def test_demo_pages_render(self):
from nxhmi.render import Renderer from nxhmi.render import Renderer
r = Renderer(HMIFile.load(FIXTURE)) r = Renderer(HMIFile.load(FIXTURE))