From 49fee337d7d3bb7a787f56106ca51d11d3f3d082 Mon Sep 17 00:00:00 2001 From: MangaValk Date: Mon, 16 Nov 2026 00:26:27 +0100 Subject: [PATCH] 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 --- .claude/skills/nextion-hmi/SKILL.md | 2 +- README.md | 2 +- docs/COVERAGE.md | 5 +- docs/FORMAT.md | 11 +- docs/RENDER.md | 29 ++++ src/nxhmi/fonts.py | 40 +++--- src/nxhmi/project.py | 3 + src/nxhmi/render.py | 210 ++++++++++++++++++++++++++-- tests/test_media.py | 17 +++ tests/test_render.py | 47 +++++++ 10 files changed, 334 insertions(+), 32 deletions(-) diff --git a/.claude/skills/nextion-hmi/SKILL.md b/.claude/skills/nextion-hmi/SKILL.md index c5f5f66..38e1599 100644 --- a/.claude/skills/nextion-hmi/SKILL.md +++ b/.claude/skills/nextion-hmi/SKILL.md @@ -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 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 compile ("not enough memory ... QR code"). Keep QR texts short there and compile to check. diff --git a/README.md b/README.md index bf13adc..9aa1f4d 100644 --- a/README.md +++ b/README.md @@ -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 | | 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, 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 | ## Compatibility diff --git a/docs/COVERAGE.md b/docs/COVERAGE.md index 143f6a7..183ddba 100644 --- a/docs/COVERAGE.md +++ b/docs/COVERAGE.md @@ -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 | | 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** | -| 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 | | 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 | 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) | Item | Status | diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 0ff22a3..653dd28 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -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) -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, 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. 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 -column-by-column, bottom-to-top order as pictures (runs continue across columns): +Glyph: mode byte (0x01 = black/white), then run-length codes over the pixels in the same order +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 | |---|---| diff --git a/docs/RENDER.md b/docs/RENDER.md index 3fba936..e004d10 100644 --- a/docs/RENDER.md +++ b/docs/RENDER.md @@ -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 | | 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 - 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 (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), 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 diff --git a/src/nxhmi/fonts.py b/src/nxhmi/fonts.py index 28b6888..d5a5648 100644 --- a/src/nxhmi/fonts.py +++ b/src/nxhmi/fonts.py @@ -24,9 +24,10 @@ Character map: ``count`` entries of 10 bytes:: 5 3 glyph data offset (relative to the start of the map) 8 2 glyph data length -Glyph data: one mode byte (0x01 = black/white), then run-length codes. Pixels are scanned -column by column (x = 0..w-1), each column from the bottom row up -- the same 90-degree panel -rotation as pictures. Codes (top two bits = op):: +Glyph data: one mode byte (0x01 = black/white), then run-length codes. Pixels are scanned in +the project's display direction, exactly like pictures (header byte 3 = 0x0A + direction): at +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 01 0xxxxx x transparent + 1 ink 01 1xxxxx x transparent + 2 ink @@ -63,6 +64,8 @@ class Font: last: int glyphs: list = field(default_factory=list) 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 @classmethod @@ -77,29 +80,35 @@ class Font: start, = struct.unpack_from(" bytes: 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() off = MAP_ENTRY * len(self.glyphs) + pad = -off % 4 if self.align else 0 + off += pad for g, b in zip(self.glyphs, bodies): mp += struct.pack("> 8) & 0xFF, off >> 16]) + struct.pack(" list: +def decode_glyph(data: bytes, w: int, h: int, direction: int = 1) -> list: stream = [] for b in data[1:]: 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: stream += [0] * x + [1] * (op * 2 - 1 + bit) 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 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.""" - 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() i, n = 0, len(s) while i < n: diff --git a/src/nxhmi/project.py b/src/nxhmi/project.py index cff2720..2c45648 100644 --- a/src/nxhmi/project.py +++ b/src/nxhmi/project.py @@ -257,6 +257,9 @@ def add_font(h: HMIFile, font) -> int: n = 0 while h.find("%d.zi" % n): 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("main.HMI", main_insert_resource(h.read("main.HMI"), "zi", "%d.zi" % n)) return n diff --git a/src/nxhmi/render.py b/src/nxhmi/render.py index e3cd8ba..ffd7aaf 100644 --- a/src/nxhmi/render.py +++ b/src/nxhmi/render.py @@ -186,7 +186,11 @@ class Renderer: t = c.get("type") 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, - 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: fn(img, c) @@ -232,16 +236,25 @@ class Renderer: light, dark = (230, 226, 230), (65, 68, 65) # measured in Editor 1.68 if style == 2: light, dark = dark, light - d.line((x, y, x + w - 1, y), fill=light); d.line((x, y, x, y + h - 1), fill=light) - 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) + top, left = (x, y, x + w - 1, y), (x, y, x, y + h - 1) + 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) if font is None or not s: return spax, spay = c.get("spax") or 0, c.get("spay") or 0 - xcen, ycen = c.get("xcen"), c.get("ycen") - wrap = c.get("isbr") + xcen = c.get("xcen") if xcen is None else xcen + 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} def gw(ch): @@ -258,6 +271,7 @@ class Renderer: lines.append(cur) line_h = font.height + spay total_h = len(lines) * line_h - spay + cy0, cy1 = clip or (y, y + h) # rows drawn (TextSelect: the component) if ycen == 1: ty = y + max(0, (h - total_h) // 2) # never starts above the box elif ycen == 2: @@ -281,12 +295,13 @@ class Renderer: if g: for gy, row in enumerate(g.pixels): 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 + col = shade(yy) if shade else color for gx, v in enumerate(row): xx = tx + gx 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) ty += line_h @@ -491,3 +506,182 @@ class Renderer: src = self.pic(c.get("pic")) if src: 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)) diff --git a/tests/test_media.py b/tests/test_media.py index 9c136f4..f34b78d 100644 --- a/tests/test_media.py +++ b/tests/test_media.py @@ -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((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") def test_image_roundtrip(self): from PIL import Image diff --git a/tests/test_render.py b/tests/test_render.py index 4addfed..5478698 100644 --- a/tests/test_render.py +++ b/tests/test_render.py @@ -126,6 +126,53 @@ class Render(unittest.TestCase): self.assertEqual(img.getpixel((0, 0)), (194, 0, 92)) 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): from nxhmi.render import Renderer r = Renderer(HMIFile.load(FIXTURE))