Use native display resolution and adaptive typography

This commit is contained in:
mikecarper committed 2026-09-08 16:02:16 -07:00
1 parent 0058f72192
commit 846282adf4
64 files changed
+5643 -533

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <string>
// Models Adafruit's bounded printf so a long verse sent via printf is caught.
class Stream {
public:
std::string text;
size_t print(const char* value) { text += value; return std::strlen(value); }
size_t printf(const char* format, ...) {
char buf[256];
va_list args;
va_start(args, format);
vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
return print(buf);
}
};
+94
View File
@@ -0,0 +1,94 @@
#include <Arduino.h>
#include <helpers/CompanionJohn.h>
#include <helpers/bible/JohnData.generated.h>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
using namespace mesh::bible;
int main(int argc, char**) {
Reference ref = {};
for (const char* cmd : {"get John 3:16", " GET\tJoHn 3:16 \t", "get john 03:16"}) {
assert(parse(cmd, ref) == ParseResult::Valid && ref.chapter == 3 && ref.verse == 16);
}
for (const char* cmd : {"get John", "get John 0:1", "get John 22:1",
"get John 1:52", "get John 3:0", "get John -3:16", "get John 3:16-18",
"get John 3:16 junk", "get John 9999999999:1", "get John 1:9999999999",
"get John 3:", "get John 3:16\x1b", "get John 3 :16", "get John :16"}) {
assert(parse(cmd, ref) == ParseResult::Invalid);
}
for (const char* cmd : {"get name", "forget John 3:16", "get johnny 3:16",
"get 1 John 3:16", "getJohn 3:16", "", "get J", "get", "g"}) {
assert(parse(cmd, ref) == ParseResult::NoMatch);
Stream output;
assert(!mesh::handleJohnCommand(cmd, output) && output.text.empty());
}
assert(parse(nullptr, ref) == ParseResult::NoMatch);
const Corpus& corpus = generated::johnCorpus;
struct Guarded { uint32_t pre; char scratch[kBlockSize]; uint32_t post; } buf = {};
buf.pre = 0x11223344; buf.post = 0xaabbccdd;
unsigned count = 0;
for (uint8_t chapter = 1; chapter <= 21; ++chapter) {
for (uint8_t verse = 1; verse <= kChapterVerses[chapter - 1]; ++verse) {
const char* text;
assert(lookup(corpus, {chapter, verse}, buf.scratch, kBlockSize, text) == LookupResult::Found);
assert(buf.pre == 0x11223344 && buf.post == 0xaabbccdd);
char cmd[32];
snprintf(cmd, sizeof(cmd), "get John %u:%u", chapter, verse);
Stream output;
assert(mesh::handleJohnCommand(cmd, output));
const std::string expected = "\r\n" + std::string(text) + "\r\n";
assert(output.text.find(expected) != std::string::npos);
for (const unsigned char* c = reinterpret_cast<const unsigned char*>(text); *c; ++c)
assert(*c >= 32 && *c < 127);
// A machine-readable dump lets Python compare every decoded byte to
// the independently ASCII-normalized pinned plaintext source.
if (argc > 1) std::printf("%u:%u\t%s\n", chapter, verse, text);
++count;
}
}
assert(count == 879);
const char* text;
assert(lookup(corpus, {22, 1}, buf.scratch, kBlockSize, text) == LookupResult::Invalid);
assert(lookup(corpus, {1, 1}, buf.scratch, kBlockSize - 1, text) == LookupResult::Corrupt);
Corpus bad = corpus;
bad.data_size = 0;
assert(lookup(bad, {1, 1}, buf.scratch, kBlockSize, text) == LookupResult::Corrupt);
bad = corpus; bad.block_count = 0;
assert(lookup(bad, {1, 1}, buf.scratch, kBlockSize, text) == LookupResult::Corrupt);
bad = corpus; bad.verse_count = 878;
assert(lookup(bad, {1, 1}, buf.scratch, kBlockSize, text) == LookupResult::Corrupt);
assert(lookup(corpus, {1, 1}, nullptr, kBlockSize, text) == LookupResult::Corrupt);
// One-byte stored DEFLATE block: distinguish an absent verse marker from
// damaged text without a terminator, and never return an unsafe pointer.
uint8_t stored[] = {0x01, 0x01, 0x00, 0xfe, 0xff, 0x00};
const BlockIndex stored_index = {0, sizeof(stored), 1, 0};
bad = corpus; bad.data = stored; bad.data_size = sizeof(stored);
bad.blocks = &stored_index; bad.block_count = 1;
assert(lookup(bad, {1, 1}, buf.scratch, kBlockSize, text) == LookupResult::Missing);
assert(text == nullptr);
stored[5] = 'x';
assert(lookup(bad, {1, 1}, buf.scratch, kBlockSize, text) == LookupResult::Corrupt);
assert(text == nullptr);
assert(lookup(bad, {1, 2}, buf.scratch, kBlockSize, text) == LookupResult::Corrupt);
std::vector<BlockIndex> blocks(corpus.blocks, corpus.blocks + corpus.block_count);
bad = corpus; bad.blocks = blocks.data();
for (int mutation = 0; mutation != 5; ++mutation) {
blocks[0] = corpus.blocks[0];
switch (mutation) {
case 0: blocks[0].plain = kBlockSize + 1; break;
case 1: blocks[0].packed--; break;
case 2: blocks[0].packed++; break; // Trailing bytes are rejected.
case 3: blocks[0].offset = UINT32_MAX; break;
case 4: blocks[0].first_verse = 1; break;
}
assert(lookup(bad, {1, 1}, buf.scratch, kBlockSize, text) == LookupResult::Corrupt);
assert(text == nullptr && buf.pre == 0x11223344 && buf.post == 0xaabbccdd);
}
Stream invalid;
assert(mesh::handleJohnCommand("get John 3:99", invalid));
assert(invalid.text.find("ERROR") != std::string::npos);
if (argc == 1) std::puts("All 879 verses, terminal output, parser and corruption checks passed");
}
+336
View File
@@ -0,0 +1,336 @@
#include <helpers/CompanionJohn.h>
#include <helpers/bible/JohnBookmarkFiles.h>
#include <helpers/ui/UIScreen.h>
#include <cassert>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
using namespace mesh::bible;
static uint32_t test_now = 100;
uint32_t millis() { return test_now; }
ColorVal UIColor::window_bkg = 0, UIColor::title_bkg = 0, UIColor::title_txt = 1;
ColorVal UIColor::primary_txt = 1, UIColor::secondary_txt = 1, UIColor::warning_txt = 1;
ColorVal UIColor::popup_bkg = 0, UIColor::popup_txt = 1, UIColor::corp_blue = 1;
struct Files {
std::map<std::string, std::vector<uint8_t>> data;
int calls = 0, fail_at = -1;
bool fail() { return calls++ == fail_at; }
bool exists(const char* p) { return data.count(p); }
bool remove(const char* p) {
if (fail()) return false;
data.erase(p); return true;
}
bool rename(const char* a, const char* b) {
if (fail() || !exists(a) || exists(b)) return false;
data[b] = data[a]; data.erase(a); return true;
}
bool read(const char* p, uint8_t (&out)[kBookmarkBytes]) {
if (fail() || !exists(p)) return false;
if (data[p].size() != sizeof(out)) { memset(out, 0, sizeof(out)); return true; }
memcpy(out, data[p].data(), sizeof(out)); return true;
}
bool write(const char* p, const uint8_t (&in)[kBookmarkBytes]) {
if (fail()) { data[p] = std::vector<uint8_t>(in, in + 3); return false; }
data[p] = std::vector<uint8_t>(in, in + sizeof(in)); return true;
}
};
struct FakeMesh {
Files files;
int saves = 0;
bool loadJohnBookmark(Position& p) { return loadReaderBookmark(files, p); }
bool saveJohnBookmark(Position p) { ++saves; return saveReaderBookmark(files, p); }
} the_mesh;
class UITask {
public:
bool closed = false;
std::string alert;
void closeJohnReader() { closed = true; }
void showAlert(const char* text, int) { alert = text; }
};
#include "../../../examples/companion_radio/ui-new/JohnReaderScreen.h"
class Display : public DisplayDriver {
int x = 0, y = 0;
public:
struct Line { int x, y; std::string text; };
std::vector<Line> lines;
std::vector<uint8_t> pixels;
Display(int w, int h) : DisplayDriver(w, h), pixels(w * h, 0) {}
int bodyY() const { return width() < 64 ? 22 : 12; }
void resize(int w, int h) { setDimensions(w, h); pixels.assign(w * h, 0); clear(); }
bool isOn() override { return true; }
void turnOn() override {}
void turnOff() override {}
void clear() override { lines.clear(); std::fill(pixels.begin(), pixels.end(), 0); }
void startFrame(ColorVal = 0) override { clear(); }
void endFrame() override {}
void setTextSize(int) override {}
void setColor(ColorVal) override {}
void setCursor(int a, int b) override { x = a; y = b; }
uint16_t getTextWidth(const char* str) override { return strlen(str) * 6; }
void print(const char* str) override {
assert(x >= 0 && x + getTextWidth(str) <= width());
assert(y >= 0 && y + 8 <= height());
lines.push_back({x, y, str});
}
void fillRect(int a, int b, int w, int h) override {
assert(a >= 0 && b >= 0 && a + w <= width() && b + h <= height());
for (int row = b; row < b + h; ++row)
for (int col = a; col < a + w; ++col) pixels[row * width() + col] = 1;
}
void drawRect(int a, int b, int w, int h) override {
assert(a >= 0 && b >= 0 && a + w <= width() && b + h <= height());
fillRect(a, b, w, 1); fillRect(a, b + h - 1, w, 1);
fillRect(a, b, 1, h); fillRect(a + w - 1, b, 1, h);
}
void drawXbm(int, int, const uint8_t*, int, int) override {}
std::string body() const {
#if UI_SMALL_MESSAGE_FONT
if (useSmallMessageFont())
return std::string(pixels.begin() + bodyY() * width(), pixels.end());
#endif
std::string result;
for (const auto& line : lines) if (line.y >= bodyY()) result += line.text;
return result;
}
void dump() const {
for (const auto& line : lines)
std::printf("%d\t%d\t%s\n", line.x, line.y, line.text.c_str());
for (int row = 0; row < height(); ++row)
for (int col = 0; col < width(); ++col)
if (pixels[row * width() + col]) std::printf("PIXEL %d %d\n", col, row);
}
};
static std::string noSpaces(std::string text) {
text.erase(std::remove(text.begin(), text.end(), ' '), text.end()); return text;
}
static Position pos(uint16_t verse, uint16_t offset = 0) {
Position p; p.verse = verse; p.offset = offset; return p;
}
int main(int argc, char** argv) {
if (argc > 1) {
if (argc > 2) assert(std::freopen(argv[2], "w", stdout));
Display display(128, 64);
UITask task;
JohnReaderScreen first(&task, &display);
first.open(); first.render(display);
std::puts("FRAME 128 64 John 1:1");
display.dump();
assert(the_mesh.saveJohnBookmark(pos(91))); // John 3:16
JohnReaderScreen verse(&task, &display);
verse.open();
for (int part = 0; part < (UI_SMALL_MESSAGE_FONT ? 1 : 2); ++part) {
display.clear(); verse.render(display);
std::printf("FRAME 128 64 John 3:16 part %d\n", part + 1);
display.dump();
verse.handleInput(KEY_NEXT);
}
#if UI_SMALL_MESSAGE_FONT
Display tiny(72, 40);
assert(the_mesh.saveJohnBookmark(pos(91)));
JohnReaderScreen tiny_verse(&task, &tiny);
tiny_verse.open(); tiny_verse.render(tiny);
std::puts("FRAME 72 40 John 3:16 on a tiny screen (5px)");
tiny.dump();
tiny.resize(40, 72);
tiny_verse.render(tiny);
std::puts("FRAME 40 72 Same reader rotated (5px)");
tiny.dump();
#endif
return 0;
}
// Every verse/part, in both directions, at common small-screen sizes.
const int cases[][3] = {
{128,64,6}, {64,128,6}, {160,80,0}, {80,160,0}, {240,135,0},
{159,80,6}, {80,159,6}, {320,240,0}, {240,320,0}, {250,122,0}, {200,200,0},
{72,40,5}, {40,72,5}, {128,32,5}, {32,128,5}, {64,48,5}, {48,64,5},
};
for (const auto& dimensions : cases) {
Display display(dimensions[0], dimensions[1]);
Display expected(dimensions[0], dimensions[1]);
const int top = expected.bodyY();
#if UI_SMALL_MESSAGE_FONT
mesh::ui::SmallMessageText compact(expected);
const bool small = dimensions[2] != 0;
assert(expected.useSmallMessageFont() == small);
if (small) assert(compact.capitalHeight() == dimensions[2]);
DisplayDriver& expected_text = small ? static_cast<DisplayDriver&>(compact) : expected;
const int line_height = small ? compact.lineHeight() : 10;
const int rows = small ? compact.lineCount(top) : (expected.height() - top) / line_height;
#else
DisplayDriver& expected_text = expected;
const int line_height = 10;
const int rows = (display.height() - top) / line_height;
#endif
auto measure = [&expected_text](const char* line) { return expected_text.getTextWidth(line); };
UITask task;
the_mesh = FakeMesh{};
JohnReaderScreen screen(&task, &display);
screen.open();
assert(screen.flush() && the_mesh.saves == 0); // don't create John 1:1
std::vector<std::string> expected_pages;
char scratch[kBlockSize];
for (uint16_t verse = 0; verse < kVerseCount; ++verse) {
const char* text;
assert(mesh::readJohnVerse(referenceAt(verse), scratch, sizeof(scratch), text) == LookupResult::Found);
memmove(scratch, text, strlen(text) + 1);
std::string rebuilt;
uint16_t offset = 0;
do {
const auto page = readerPage(scratch, offset, display.width(), rows, measure);
assert(page.start == offset && page.next > offset);
expected.clear();
uint16_t next = offset;
for (int row = 0; row < rows && scratch[next]; ++row) {
char line[kReaderLineBytes];
next = readerLine(scratch, next, display.width(), measure, line);
rebuilt += line;
expected_text.setCursor(0, top + row * line_height);
expected_text.print(line);
}
assert(next == page.next);
display.clear(); screen.render(display);
const std::string body = display.body();
assert(!body.empty());
assert(body == expected.body());
assert(display.getTextWidth("ABC") == 18); // header/driver font unchanged
expected_pages.push_back(body);
screen.handleInput(KEY_NEXT);
offset = page.next;
} while (scratch[offset]);
if (noSpaces(rebuilt) != noSpaces(scratch)) {
std::fprintf(stderr, "%dx%d verse index %u\nExpected: %s\nActual: %s\n",
display.width(), display.height(), verse, scratch, rebuilt.c_str());
return 1;
}
}
display.clear(); screen.render(display);
assert(display.body() == expected_pages.back()); // no wrap at end
for (size_t page = expected_pages.size(); page > 0; --page) {
display.clear(); screen.render(display);
assert(display.body() == expected_pages[page - 1]);
screen.handleInput(KEY_PREV);
}
display.clear(); screen.render(display);
assert(display.body() == expected_pages.front()); // no wrap before start
screen.handleInput(KEY_ENTER);
assert(task.closed);
}
// Resume within a split verse; independent screen and store lifecycle.
the_mesh = FakeMesh{};
Display display(64,32);
UITask task;
JohnReaderScreen first(&task, &display);
first.open(); first.handleInput(KEY_NEXT);
display.clear(); first.render(display); const auto body = display.body();
first.poll(); assert(the_mesh.saves == 0);
test_now += 2000; first.poll(); assert(the_mesh.saves == 1);
first.poll(); assert(the_mesh.saves == 1);
Position saved;
assert(the_mesh.loadJohnBookmark(saved) && saved.verse == 0 && saved.offset > 0);
JohnReaderScreen rebooted(&task, &display);
rebooted.open(); display.clear(); rebooted.render(display);
assert(display.body() == body);
rebooted.handleInput(KEY_PREV); assert(rebooted.flush());
assert(!the_mesh.files.exists("/john.pos") && !the_mesh.files.exists("/john.pos.bak"));
assert(!the_mesh.loadJohnBookmark(saved) && saved.atStart());
#if UI_SMALL_MESSAGE_FONT
// A bookmark from the old 6-pixel-wide font resumes on the new page that
// contains those words; it does not advance to another verse or lose them.
char scratch[kBlockSize];
const char* text;
assert(mesh::readJohnVerse({3, 16}, scratch, sizeof(scratch), text) == LookupResult::Found);
const auto legacy_measure = [](const char* line) { return strlen(line) * 6; };
const auto legacy = readerPage(text, 0, 128, 5, legacy_measure);
assert(text[legacy.next]);
the_mesh = FakeMesh{};
assert(the_mesh.saveJohnBookmark(pos(91, legacy.next)));
Display migrated_display(128,64);
mesh::ui::SmallMessageText compact(migrated_display);
const auto compact_measure = [&compact](const char* line) { return compact.getTextWidth(line); };
const auto compact_page = readerPage(text, legacy.next, 128, compact.lineCount(12), compact_measure);
assert(compact_page.start <= legacy.next && compact_page.next > legacy.next);
JohnReaderScreen migrated(&task, &migrated_display);
migrated.open(); migrated.render(migrated_display); assert(migrated.flush());
assert(the_mesh.loadJohnBookmark(saved) && saved == pos(91, compact_page.start));
assert(compact_page.parts == 1); // John 3:16 now fits in one V4 screen
// Reflow an already-open reader when panel geometry crosses the 5px/6px
// threshold, and when a tiny panel rotates into the stacked-header layout.
for (const auto& dimensions : {std::make_pair(72,40), {128,64}, {40,72}, {64,128}, {32,128}, {160,80}, {80,160}, {159,80}}) {
assert(the_mesh.saveJohnBookmark(pos(91, legacy.next)));
Display changed(72,40);
JohnReaderScreen active(&task, &changed);
active.open(); active.render(changed); assert(active.flush());
Position before; assert(the_mesh.loadJohnBookmark(before));
changed.resize(dimensions.first, dimensions.second);
mesh::ui::SmallMessageText small_font(changed);
const bool small = changed.useSmallMessageFont();
DisplayDriver& new_font = small ? static_cast<DisplayDriver&>(small_font) : changed;
auto new_measure = [&new_font](const char* line) { return new_font.getTextWidth(line); };
const auto new_page = readerPage(text, before.offset, changed.width(),
small ? small_font.lineCount(changed.bodyY()) : (changed.height() - changed.bodyY()) / 10,
new_measure);
assert(new_page.start <= before.offset && new_page.next > before.offset);
active.render(changed); assert(active.flush());
Position after; assert(the_mesh.loadJohnBookmark(after));
assert(after == pos(91, new_page.start));
const auto rendered = changed.body();
JohnReaderScreen reopened(&task, &changed);
reopened.open(); changed.clear(); reopened.render(changed);
assert(changed.body() == rendered);
}
#endif
// Checksum/version/bounds checks, including validly checksummed bad values.
uint8_t record[kBookmarkBytes];
for (Position p : {pos(1), pos(878, 2000)}) {
encodeBookmark(p, record); Position decoded;
assert(decodeBookmark(record, decoded) && decoded == p);
for (unsigned i = 0; i < sizeof(record); ++i) {
record[i] ^= 1; assert(!decodeBookmark(record, decoded)); record[i] ^= 1;
}
}
for (Position p : {pos(0), pos(879), pos(1, 2048)}) {
encodeBookmark(p, record); assert(!decodeBookmark(record, saved));
}
// Inject failure at each I/O step; reboot must find either the old or the
// new verified bookmark, never a partially written record or an empty file.
Files original; assert(saveReaderBookmark(original, pos(4, 12)));
for (int failure = 0; failure < 12; ++failure) {
Files files = original; files.calls = 0; files.fail_at = failure;
const bool ok = saveReaderBookmark(files, pos(30, 45));
files.fail_at = -1;
Position recovered; assert(loadReaderBookmark(files, recovered));
assert(recovered == pos(4, 12) || recovered == pos(30, 45));
if (ok) assert(recovered == pos(30, 45));
}
// A reset between renames recovers the previous record, not the .tmp.
Files interrupted = original;
assert(interrupted.rename("/john.pos", "/john.pos.bak"));
assert(loadReaderBookmark(interrupted, saved) && saved == pos(4, 12));
assert(saveReaderBookmark(interrupted, pos(20)));
assert(saveReaderBookmark(interrupted, pos(0)) && interrupted.data.empty());
Files damaged;
damaged.data["/john.pos"] = {1, 2, 3};
assert(!loadReaderBookmark(damaged, saved) && saved.atStart());
assert(saveReaderBookmark(damaged, pos(10)));
assert(loadReaderBookmark(damaged, saved) && saved == pos(10));
ReaderBookmark bookmark;
bookmark.move(pos(1), UINT32_MAX - 1000);
assert(!bookmark.due(998) && bookmark.due(999));
assert(bookmark.dirty()); bookmark.saved(); assert(!bookmark.dirty());
bookmark.move(pos(0), 2000); assert(bookmark.dirty());
std::puts("Reader: all 879 verses paginated forward/back, resume, bounds and save-failure tests passed");
}
+90
View File
@@ -0,0 +1,90 @@
// Host doubles for panel libraries only. The test appends real driver headers
// and real drawing methods; no coordinate or font mapping is reimplemented.
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <vector>
#include <helpers/ui/DisplayDriver.h>
#define pgm_read_byte(p) (*(const uint8_t*)(p))
#define PROGMEM
#define HSPI 1
#define GEOMETRY_RAWMODE 0
#define PIN_TFT_CS 1
#define PIN_TFT_DC 2
#define PIN_TFT_SDA 3
#define PIN_TFT_SCL 4
#define PIN_TFT_RST 5
#define ST7789_RESET 1
#define ST7789_RS 2
#define ST7789_CS 3
#define ST7789_SDA 4
#define ST7789_MISO 5
#define ST7789_SCK 6
#define PIN_DISPLAY_CS 1
#define PIN_DISPLAY_DC 2
#define PIN_DISPLAY_RST 3
#define PIN_DISPLAY_BUSY 4
#define DISP_CS 1
#define DISP_DC 2
#define DISP_RST 3
#define DISP_BUSY 4
#define ST77XX_WHITE 1
#define ST77XX_BLACK 0
struct SPIClass { explicit SPIClass(int = 0) {} } SPI, SPI1;
struct TwoWire {};
struct RefCountedDigitalPin {};
enum OLEDDISPLAY_COLOR { BLACK, WHITE };
const int ArialMT_Plain_16 = 16, ArialMT_Plain_24 = 24;
const int FreeSans9pt7b = 13, FreeSansBold12pt7b = 18, FreeSans18pt7b = 26;
struct CRC32 {
template<class T> void update(T) {}
template<class T> void update(const T*, size_t) {}
};
ColorVal UIColor::window_bkg=0, UIColor::title_bkg=0, UIColor::title_txt=1;
ColorVal UIColor::primary_txt=1, UIColor::secondary_txt=1, UIColor::warning_txt=1;
ColorVal UIColor::popup_bkg=0, UIColor::popup_txt=1, UIColor::corp_blue=1;
struct Canvas {
static Canvas* active;
int w=EXPECTED_WIDTH, h=EXPECTED_HEIGHT, x=0, y=0, size=1, ascent=0;
std::vector<int> pixels = std::vector<int>(w*h);
Canvas() { active=this; }
int width() const { return w; }
int height() const { return h; }
void setCursor(int xx, int yy) { x=xx; y=yy; }
void setTextSize(int s) { size=s; }
void setTextColor(int) {}
void setColor(OLEDDISPLAY_COLOR) {}
void setRGB(int) {}
void setFont(int) {}
void setFont(const int* font) { ascent=*font; }
void print(const char*) {}
void drawString(int xx,int yy,const char*) { x=xx; y=yy; }
void drawStringMaxWidth(int xx,int yy,int ww,const char*) { x=xx; y=yy; assert(ww==w); }
int getStringWidth(const char* s) { return std::strlen(s)*6*size; }
void getTextBounds(const char* s,int,int,int16_t* xx,int16_t* yy,uint16_t* ww,uint16_t* hh) {
*xx=0; *yy=-ascent; *ww=getStringWidth(s); *hh=ascent ? ascent+4 : 8*size;
}
void fillRect(int xx,int yy,int ww,int hh,int=1) {
for(int row=std::max(yy,0); row<std::min(yy+hh,h); ++row)
for(int col=std::max(xx,0); col<std::min(xx+ww,w); ++col) ++pixels[row*w+col];
}
void drawRect(int xx,int yy,int ww,int hh,int c=1) {
if(ww<=0 || hh<=0) return;
fillRect(xx,yy,ww,1,c); fillRect(xx,yy+hh-1,ww,1,c);
fillRect(xx,yy,1,hh,c); fillRect(xx+ww-1,yy,1,hh,c);
}
void drawBitmap(int xx,int yy,const uint8_t* bits,int ww,int hh,int c) {
for(int row=0;row<hh;++row) for(int col=0;col<ww;++col)
if(bits[row*((ww+7)/8)+col/8] & (0x80>>(col&7))) fillRect(xx+col,yy+row,1,1,c);
}
void reset() { std::fill(pixels.begin(),pixels.end(),0); }
};
Canvas* Canvas::active=nullptr;
struct ST7789Spi : Canvas { template<class... T> ST7789Spi(T...) {} };
struct Adafruit_ST7789 : Canvas { template<class... T> Adafruit_ST7789(T...) {} };
struct GxEPD2_150_BN { static const int WIDTH=200,HEIGHT=200; template<class... T> GxEPD2_150_BN(T...) {} };
struct WidePanel { static const int WIDTH=122,HEIGHT=250; template<class... T> WidePanel(T...) {} };
struct TallPanel { static const int WIDTH=192,HEIGHT=256; template<class... T> TallPanel(T...) {} };
template<class T,int H> struct GxEPD2_BW : Canvas { explicit GxEPD2_BW(T) {} };
+6
View File
@@ -0,0 +1,6 @@
#pragma once
#include <cstdint>
#define HIGH 1
#define OUTPUT 1
inline void pinMode(uint8_t, int) {}
inline void digitalWrite(uint8_t, int) {}
+1
View File
@@ -0,0 +1 @@
#pragma once
+2
View File
@@ -0,0 +1,2 @@
#pragma once
class TwoWire {};
+88
View File
@@ -0,0 +1,88 @@
#include <cassert>
#include <cstring>
#include <vector>
#include <helpers/ui/ST7735Display.h>
#include <helpers/ui/SmallMessageText.h>
ColorVal UIColor::window_bkg = 0, UIColor::title_bkg = 0, UIColor::title_txt = 1;
ColorVal UIColor::primary_txt = 1, UIColor::secondary_txt = 1, UIColor::warning_txt = 1;
ColorVal UIColor::popup_bkg = 0, UIColor::popup_txt = 1, UIColor::corp_blue = 1;
struct Canvas {
std::vector<int> pixels = std::vector<int>(160 * 80);
int x = 0, y = 0, size = 1, prints = 0;
void setCursor(int xx, int yy) { x = xx; y = yy; }
void setTextSize(int s) { size = s; }
void setTextColor(int) {}
void print(const char*) { ++prints; }
int textWidth(const char* s) { return std::strlen(s) * 6 * size; }
void fillRect(int xx, int yy, int w, int h, int) {
assert(xx >= 0 && yy >= 0 && xx + w <= 160 && yy + h <= 80);
for (int row = yy; row < yy + h; ++row)
for (int col = xx; col < xx + w; ++col) ++pixels[row * 160 + col];
}
void drawRect(int xx, int yy, int w, int h, int c) { fillRect(xx, yy, w, h, c); }
void drawBitmap(int xx, int yy, const uint8_t*, int w, int h, int c) {
fillRect(xx, yy, w, h, c);
}
} canvas;
static Canvas* sprite = &canvas;
static int curr_color = 1;
static bool spriteReady() { return true; }
// Only hardware initialization and SPI transmission are doubled. The runner
// appends the real driver's coordinate/text drawing methods verbatim below.
bool ST7735Display::begin() { return true; }
void ST7735Display::turnOn() {}
void ST7735Display::turnOff() {}
void ST7735Display::clear() { canvas.pixels.assign(160 * 80, 0); }
void ST7735Display::startFrame(ColorVal) { clear(); }
void ST7735Display::endFrame() {}
int main() {
ST7735Display display;
assert(display.width() == 160 && display.height() == 80);
display.setCursor(159, 79);
assert(canvas.x == 159 && canvas.y == 79);
assert(display.getTextWidth("MMMM") == 24);
assert(!display.useSmallMessageFont());
// Every logical pixel covers its own exact physical cell, without gaps or
// overlap. In native mode each of these cells must be exactly one pixel.
display.clear();
for (int y = 0; y < display.height(); ++y)
for (int x = 0; x < display.width(); ++x) display.fillRect(x, y, 1, 1);
for (int count : canvas.pixels) assert(count == 1);
display.clear();
display.drawRect(0, 0, display.width(), display.height());
for (int count : canvas.pixels) assert(count == 1);
mesh::ui::SmallMessageText body(display);
assert(body.capitalHeight() == 6);
#if defined(HELTEC_T096)
assert(body.lineCount(12) == 8);
// Check all 95 real font glyphs against their native bitmap coordinates.
for (int c = 32; c <= 126; ++c) {
display.clear();
char text[] = {static_cast<char>(c), 0};
body.setCursor(0, 0);
body.print(text);
const auto& g = mesh::ui::squeezed6Glyphs[c - 32];
std::vector<int> expected(160 * 80);
for (int y = 0; y < g.height; ++y) {
for (int x = 0; x < g.width; ++x) {
int bit = y * g.width + x;
if (mesh::ui::squeezed6Bitmaps[g.bitmap_offset + bit / 8] & (0x80 >> (bit % 8)))
expected[(5 + g.y_offset + y) * 160 + g.x_offset + x] = 1;
}
}
assert(canvas.pixels == expected);
}
#endif
// A 160px message must use the panel's normal print path, not the compact
// wrapper's per-pixel 5/6px glyphs, even when the feature is compiled in.
display.clear();
canvas.prints = 0;
mesh::ui::drawSmallMessageBody(display, "Sender", "A normal-font message");
assert(canvas.prints >= 2);
for (int count : canvas.pixels) assert(count == 0);
}
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
"""Compare the real firmware decoder and CLI output against every source verse."""
import copy
import importlib.util
import json
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
import zlib
ROOT = Path(__file__).resolve().parents[1]
FIXTURE = ROOT / "test/fixtures/companion_john"
spec = importlib.util.spec_from_file_location("pack_john", ROOT / "tools/bible/pack_john.py")
packer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packer)
class CompanionJohnTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.document = json.loads(packer.SOURCE.read_text(encoding="utf-8"))
# Independent expected typography, not the packer's conversion helper.
typography = str.maketrans({"\u00a0": " ", "\u2013": "-", "\u2014": "-",
"\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"'})
cls.expected_verses = {ref: text.translate(typography)
for ref, text in cls.document["verses"].items()}
def test_generated_header_is_current(self):
self.assertEqual(packer.HEADER.read_text(encoding="utf-8"), packer.render(self.document))
def test_block_sizes_roundtrip_all_verses(self):
for size in (1024, 2048, 4096):
packed, blocks = packer.pack(self.document, size)
actual = []
for offset, length, plain_length, first in blocks:
self.assertEqual(first, len(actual))
plain = zlib.decompress(packed[offset:offset + length], wbits=-15)
self.assertEqual(len(plain), plain_length)
self.assertLessEqual(len(plain), size)
self.assertEqual(plain[-1], 0)
actual.extend(part.decode("ascii") for part in plain[:-1].split(b"\0"))
self.assertEqual(actual, list(self.expected_verses.values()))
def test_ascii_typography_preserves_words_case_and_pinned_source(self):
original = copy.deepcopy(self.document)
sample = '\u201cJohn\u2019s\u00a0Word\u201d\u2014\u2018Test\u2019\u2013Yes!'
self.assertEqual(packer.ascii_verse(sample, 64), b'"John\'s Word"-\'Test\'-Yes!')
self.assertEqual(packer.ascii_verse('Already ASCII: John 3:16.', 64),
b'Already ASCII: John 3:16.')
# Bounds apply after conversion, not to the original multibyte form.
self.assertEqual(packer.ascii_verse('\u201cHi\u201d', 4), b'"Hi"')
with self.assertRaises(ValueError):
packer.ascii_verse('\u201cHi\u201d', 3)
packer.pack(self.document)
self.assertEqual(self.document, original)
def test_ascii_data_size(self):
packed, blocks = packer.pack(self.document)
self.assertEqual(sum(block[2] for block in blocks), 96568)
self.assertEqual(len(blocks), 49)
self.assertEqual(len(packed) + 12 * len(blocks), 43891)
def test_invalid_sources_are_rejected(self):
for bad_text in ("", "leading\ncommand", "bad\x1b[2J", "bad\0text",
"bad\u202eRTL", " too much space", "a" * 2048,
"caf\u00e9", "unmapped\u2026punctuation", "bad\U0001f600text"):
document = copy.deepcopy(self.document)
document["verses"]["1:1"] = bad_text
with self.assertRaises(ValueError):
packer.pack(document)
for key in ("1:1", "21:25"):
document = copy.deepcopy(self.document)
del document["verses"][key]
with self.assertRaises(ValueError):
packer.pack(document)
def test_firmware_decoder_and_terminal_on_both_platform_profiles(self):
cc, cxx = shutil.which("gcc"), shutil.which("g++")
if not cc or not cxx:
self.skipTest("host GCC and G++ required")
with tempfile.TemporaryDirectory(prefix="meshcore-john-") as directory:
directory = Path(directory)
for platform in ("ESP32_PLATFORM", "NRF52_PLATFORM"):
flags = [f"-D{platform}=1", "-DCOMPANION_RADIO_FULL=1", "-DENABLE_USB_INTERFACE=1"]
obj, binary = directory / "tinf.o", directory / "john.exe"
self.run_checked([cc, "-std=c11", "-Os", *flags, "-c",
str(ROOT / "src/helpers/ota/OtaTinf.c"), "-o", str(obj)])
self.run_checked([cxx, "-std=c++17", "-Os", "-Wall", "-Wextra", "-Werror",
*flags, "-I" + str(ROOT / "src"), "-I" + str(FIXTURE),
str(FIXTURE / "test_john.cpp"),
str(ROOT / "src/helpers/CompanionJohn.cpp"), str(obj), "-o", str(binary)])
result = self.run_checked([str(binary), "--dump"])
actual = dict(line.split("\t", 1) for line in result.splitlines())
self.assertEqual(actual, self.expected_verses)
def test_other_profiles_exclude_corpus(self):
cxx = shutil.which("g++")
if not cxx:
self.skipTest("host G++ required")
for flags in ([], ["-DESP32_PLATFORM=1"], ["-DNRF52_PLATFORM=1"],
["-DESP32_PLATFORM=1", "-DCOMPANION_RADIO_FULL=1"],
["-DESP32_PLATFORM=1", "-DCOMPANION_RADIO_FULL=1",
"-DENABLE_USB_INTERFACE=1", "-DCOMPANION_FEATURE_JOHN=0"]):
result = self.run_checked([cxx, "-E", "-P", *flags,
str(ROOT / "src/helpers/CompanionJohn.cpp")])
self.assertNotIn("johnData", result)
self.assertNotIn("handleJohnCommand", result)
def test_terminal_dispatch_is_separate_from_bounded_api_replies(self):
source = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text(encoding="utf-8")
start = source.index("void MyMesh::handleTerminalCommand(")
end = source.index("\nvoid MyMesh::enterCLIRescue()", start)
terminal = source[start:end]
self.assertEqual(source.count("mesh::handleJohnCommand("), 1)
self.assertLess(terminal.index("mesh::handleJohnCommand("),
terminal.index("char local_reply[160]"))
self.assertIn("get John <chapter>:<verse> (World English Bible, offline)", terminal)
self.assertEqual(terminal.count("#if COMPANION_FEATURE_JOHN"), 2)
def test_reader_navigation_and_bookmark_recovery(self):
cc, cxx = shutil.which("gcc"), shutil.which("g++")
if not cc or not cxx:
self.skipTest("host GCC and G++ required")
with tempfile.TemporaryDirectory(prefix="meshcore-john-reader-") as directory:
directory = Path(directory)
flags = ["-DNRF52_PLATFORM=1", "-DCOMPANION_RADIO_FULL=1", "-DENABLE_USB_INTERFACE=1"]
obj, binary = directory / "tinf.o", directory / "reader.exe"
self.run_checked([cc, "-Os", *flags, "-c", str(ROOT / "src/helpers/ota/OtaTinf.c"),
"-o", str(obj)])
for small_font in (0, 1):
self.run_checked([cxx, "-std=c++11", "-Os", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
*flags, f"-DUI_SMALL_MESSAGE_FONT={small_font}",
"-I" + str(ROOT / "src"), "-I" + str(FIXTURE),
str(FIXTURE / "test_reader.cpp"), str(ROOT / "src/helpers/CompanionJohn.cpp"),
str(obj), "-o", str(binary)])
self.run_checked([str(binary)])
def test_reader_button_routing_and_profile_gate(self):
ui = (ROOT / "examples/companion_radio/ui-new/UITask.cpp").read_text(encoding="utf-8")
long_press = ui[ui.index("char UITask::handleLongPress("):]
self.assertLess(long_press.index("isJohnReaderActive()"), long_press.index("enterCLIRescue()"))
self.assertLess(long_press.index("isRadioPage()"), long_press.index("enterCLIRescue()"))
self.assertIn("#if COMPANION_FEATURE_JOHN\n#include \"JohnReaderScreen.h\"", ui)
self.assertIn("&& !isJohnReaderActive()", ui)
self.assertIn("else if (isJohnReaderActive())", ui)
self.assertIn("c = handleLongPress(KEY_ENTER);", ui)
self.assertIn("handleDoubleClick(KEY_PREV)", ui)
def run_checked(self, command):
result = subprocess.run(command, capture_output=True, encoding="utf-8",
errors="backslashreplace", timeout=60)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
return result.stdout
if __name__ == "__main__":
unittest.main()
@@ -1,6 +1,23 @@
#include <gtest/gtest.h>
#include "helpers/ui/CompanionMessageHistory.h"
#include <helpers/ui/CompanionMessageHistory.h>
TEST(CompanionMessageNativeLayout, NormalFontsFitHeadersFootersAndSummaryRows) {
for (int line_height : {10, 18, 22, 30}) {
const auto chrome = mesh::ui::makeCompanionMessageChromeLayout(false, line_height);
EXPECT_GE(chrome.header_divider_y, line_height);
EXPECT_GE(chrome.origin_y, chrome.header_divider_y + 2);
EXPECT_GE(chrome.message_y, chrome.origin_y + line_height);
EXPECT_GE(chrome.filter_height, chrome.filter_text_offset + line_height);
const auto list = mesh::ui::makeCompanionMessageListLayout(240, line_height);
EXPECT_GE(list.preview_offset, list.title_offset + line_height);
EXPECT_GE(list.divider_offset, list.preview_offset + line_height);
EXPECT_LE(list.top + list.visible_rows * list.row_height, 240);
// Indicator compact chrome is independent of native font metrics.
const auto indicator = mesh::ui::makeCompanionMessageChromeLayout(true, line_height);
EXPECT_EQ(8, indicator.header_divider_y);
EXPECT_EQ(14, indicator.filter_height);
}
}
#include <cstdint>
#include <cstring>
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Exercise actual non-Indicator driver geometry/drawing with recording panels."""
import os
from pathlib import Path
import re
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
UI = ROOT / "src/helpers/ui"
def method(source, cls, name):
start = source.index(f"{cls}::{name}(")
start = source.rfind("\n", 0, start) + 1
end = source.index("\n}", start) + 2
return source[start:end] + "\n"
class NativeDisplaysTest(unittest.TestCase):
def test_real_headers_and_rendering(self):
cases = [
("ST7789Display", 240, 135, []),
("ST7789Display", 320, 170, ["HELTEC_VISION_MASTER_T190"]),
("ST7789Display", 320, 240, ["THINKNODE_M9"]),
("ST7789LCDDisplay", 320, 240, []),
("ST7789LCDDisplay", 320, 240, ["USE_PIN_TFT"]),
("ST7789LCDDisplay", 320, 240, ["LILYGO_TDECK"]),
("ST7789LCDDisplay", 240, 320, ["HELTEC_V4_R8_TFT", "ST7789_PORTRAIT_PROFILE", "DISPLAY_ROTATION=0"]),
("NV3001BDisplay", 220, 128, []),
("GxEPDDisplay", 200, 200, []),
("GxEPDDisplay", 250, 122, ["EINK_DISPLAY_MODEL=WidePanel"]),
("GxEPDDisplay", 250, 122, ["EINK_DISPLAY_MODEL=WidePanel", "DISPLAY_ROTATION=1"]),
("GxEPDDisplay", 192, 256, ["EINK_DISPLAY_MODEL=TallPanel", "DISPLAY_ROTATION=4"]),
]
with tempfile.TemporaryDirectory(prefix="meshcore-native-panels-") as temp:
for cls, width, height, defines in cases:
with self.subTest(driver=cls, defines=defines):
source = (ROOT / "test/fixtures/native_displays/recording.cpp").read_text()
header = (UI / (cls + ".h")).read_text()
source += re.sub(r'^\s*#(?:include|pragma).*$', '', header, flags=re.M)
driver = (UI / (cls + ".cpp")).read_text()
if cls == "NV3001BDisplay":
source += "Canvas nv_canvas;\n"
source += f"bool {cls}::begin() {{ is_on=true; return true; }}\n"
source += f"void {cls}::fillPhysicalRect(int x,int y,int w,int h) {{ Canvas::active->fillRect(x,y,w,h); }}\n"
a = driver.index("static const uint8_t font5x7")
b = driver.index("static void setupOptionalOutput", a)
source += driver[a:b]
source += method(driver, cls, "drawChar")
else:
source += f"bool {cls}::begin() {{ return true; }}\n"
for name in ("turnOn", "turnOff", "clear", "endFrame"):
source += f"void {cls}::{name}() {{}}\n"
source += f"void {cls}::startFrame(ColorVal) {{}}\n"
if cls == "ST7789LCDDisplay":
source += f"void {cls}::setFlipped(bool) {{}}\n"
names = ["setTextSize", "setColor", "setCursor", "print", "fillRect", "drawRect", "drawXbm", "getTextWidth"]
if cls == "ST7789Display":
names += ["printWordWrap"]
source += "\n".join(method(driver, cls, name) for name in names)
source += f"\nusing Driver = {cls};\n"
source += r'''
int main() {
Driver d; d.begin(); d.setColor(1); d.setTextSize(1);
auto& c=*Canvas::active;
assert(d.width()==EXPECTED_WIDTH && d.height()==EXPECTED_HEIGHT);
assert(!d.useSmallMessageFont());
c.reset();
for(int y=0;y<d.height();++y) for(int x=0;x<d.width();++x) d.fillRect(x,y,1,1);
for(int pixel:c.pixels) assert(pixel==1);
c.reset(); d.drawRect(0,0,d.width(),d.height());
for(int y=0;y<d.height();++y) for(int x=0;x<d.width();++x)
assert((c.pixels[y*d.width()+x]>0)==(x==0||y==0||x==d.width()-1||y==d.height()-1));
// Non-byte-aligned bitmap and the bottom/right panel boundary.
const uint8_t bitmap[]={0x81,0x80,0x42,0x00};
c.reset(); d.drawXbm(d.width()-9,d.height()-2,bitmap,9,2);
assert(std::count(c.pixels.begin(),c.pixels.end(),1)==5);
assert(c.pixels.back()==0 && c.pixels[(d.height()-2)*d.width()+d.width()-1]==1);
assert(d.getTextWidth("MMMM") >= 24);
assert(d.getTextWidth("MMMMMMMM") > d.getTextWidth("MMMM"));
assert(d.getTextWidth("")==0);
d.setCursor(7,9); d.print("M");
#ifdef NV_NATIVE_TEST
// Native 5x7 glyph: no historical vertical doubling.
c.reset(); d.setCursor(0,0); d.print("M");
for(int y=7;y<d.height();++y) for(int x=0;x<d.width();++x) assert(c.pixels[y*d.width()+x]==0);
#else
assert(c.x==7 && c.y==9+c.ascent);
#endif
}
'''
flags = [f"-D{x}" for x in defines]
if cls == "NV3001BDisplay":
flags += ["-DNV_NATIVE_TEST"]
if os.name != "nt":
flags += ["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]
binary = Path(temp) / "display.exe"
result = subprocess.run(["c++", "-std=c++11", "-Wall", "-Wextra", "-Werror",
"-Wno-unused-parameter", "-Wno-unused-variable", "-Wno-type-limits", *flags,
f"-DEXPECTED_WIDTH={width}", f"-DEXPECTED_HEIGHT={height}",
"-I", str(ROOT / "src"), "-x", "c++", "-", "-o", str(binary)],
input=source, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
result = subprocess.run([str(binary)], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
def test_no_obsolete_panel_scaling_flags(self):
for driver in ("ST7735Display", "ST7789Display", "ST7789LCDDisplay", "NV3001BDisplay", "GxEPDDisplay"):
for suffix in (".h", ".cpp"):
source = (UI / (driver + suffix)).read_text()
self.assertNotRegex(source, r"DISPLAY_SCALE|EINK_SCALE|SCALE_[XY]|portraitViewport")
if __name__ == "__main__":
unittest.main()
+11 -45
View File
@@ -1,23 +1,12 @@
#pragma once
#include "helpers/ui/DisplayDriver.h"
#include "helpers/ui/DisplayViewport.h"
#include <string>
#include <vector>
// A DisplayDriver that records physical-pixel draw calls instead of pushing
// them at a panel, reproducing the two real ST7789LCDDisplay coordinate and
// text-metric profiles:
//
// portrait (ST7789_PORTRAIT_PROFILE) 240x320, DisplayViewport mapping,
// physical text scale = logical * 2
// landscape (default) 320x240, x * 2.5 / y * 3.75,
// physical text scale = (int)(logical * 2.5)
//
// Text extents are recorded at the size the layout *asked* for, so a row that
// only fits because the driver would silently shrink or clip it still shows up
// as an out-of-bounds op.
// Recording counterpart of the native portrait/landscape ST7789LCD profiles.
// Coordinates and normal font pixels are 1:1; explicit heading sizes remain.
class MockDisplay : public DisplayDriver {
public:
enum Mode { PORTRAIT, LANDSCAPE };
@@ -28,11 +17,11 @@ public:
ColorVal color;
std::string text;
int logical_size;
bool scale_fallback; // portrait driver would have shrunk this string
bool scale_fallback; // native drivers never shrink a string implicitly
};
explicit MockDisplay(Mode mode)
: DisplayDriver(128, 64), _mode(mode), _on(true), _color(0), _size(1), _cx(0), _cy(0) {}
: DisplayDriver(mode == PORTRAIT ? 240 : 320, mode == PORTRAIT ? 320 : 240), _mode(mode), _on(true), _color(0), _size(1), _cx(0), _cy(0) {}
std::vector<Op> ops;
@@ -61,12 +50,6 @@ public:
int scale = physicalScale(_size);
int px = mapX(_cx), py = mapY(_cy);
bool fallback = false;
if (_mode == PORTRAIT) {
int available = panelWidth() - px;
if (n * 6 * scale > available) {
fallback = true; // the real driver drops to the minimum scale here
}
}
ops.push_back(Op{Op::TEXT, px, py, n * 6 * scale, 8 * scale, _color, std::string(str), _size,
fallback});
_cx += (int)((n * 6 * scale) / xScale());
@@ -87,16 +70,7 @@ public:
if (!str) return 0;
int n = (int)strlen(str);
int scale = physicalScale(_size);
if (_mode == PORTRAIT) {
// Mirrors ST7789LCDDisplay::getTextWidth(): measure at the scale the
// driver would pick, clamp to the panel, convert back to logical.
if (n * 6 * scale > panelWidth()) scale = _size;
int w = n * 6 * scale;
if (w > panelWidth()) w = panelWidth();
DisplayViewport::Geometry g{128, 64, 240, 320};
return g.logicalWidthForPhysical((uint16_t)w);
}
return (uint16_t)((n * 6 * scale) / 2.5f);
return (uint16_t)(n * 6 * scale);
}
private:
@@ -105,18 +79,10 @@ private:
ColorVal _color;
int _size, _cx, _cy;
float xScale() const { return _mode == PORTRAIT ? (240.0f / 128.0f) : 2.5f; }
int physicalScale(int logical) const {
return _mode == PORTRAIT ? logical * 2 : (int)(uint8_t)(logical * 2.5f);
}
int mapX(int x) const {
return _mode == PORTRAIT ? (int)((int32_t)x * 240 / 128) : (int)(x * 2.5f);
}
int mapY(int y) const {
return _mode == PORTRAIT ? (int)((int32_t)y * 320 / 64) : (int)(y * 3.75f);
}
int spanX(int x, int w) const { return mapX(x + w) - mapX(x); }
int spanY(int y, int h) const { return mapY(y + h) - mapY(y); }
float xScale() const { return 1; }
int physicalScale(int logical) const { return logical; }
int mapX(int x) const { return x; }
int mapY(int y) const { return y; }
int spanX(int, int w) const { return w; }
int spanY(int, int h) const { return h; }
};
@@ -277,8 +277,8 @@ TEST(ObserverDashboardLayout, AllTextIsPaddedInsideTheMargins) {
}
TEST(ObserverDashboardLayout, NoTextSilentlyShrinksToTheFallbackScale) {
// The portrait driver halves the glyph size rather than clipping. A row that
// only fits because of that would break the grid, so it must never happen.
// Native drivers retain the requested font size. Rows must fit without a
// driver-level fallback that hides layout errors.
for (const RadioActivitySnapshot& s : {makeBusy(), makeEmpty()}) {
MockDisplay d(MockDisplay::PORTRAIT);
drawFull(d, portraitLayout(), makeContext(), s);
@@ -471,6 +471,9 @@ TEST(ObserverDashboardSignature, DataChangesBelowTheGraphResolutionDoNotRepaint)
Context ctx = makeContext();
RadioActivitySnapshot a = makeBusy();
// The taller native graph needs a larger peak for a one-packet change to
// stay below one pixel of vertical resolution.
a.buckets[0] = a.peak_per_min = 1000;
RadioActivitySnapshot b = a;
b.buckets[N - 1] = (uint16_t)(a.buckets[N - 1] + 1);
+78
View File
@@ -0,0 +1,78 @@
"""Real ST7789 SPI flush at native widths >255 and non-eight-row heights."""
from pathlib import Path
import os
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class NativeTransferTest(unittest.TestCase):
def test_flush_covers_only_native_panel_rows(self):
driver = (ROOT / "src/helpers/ui/ST7789Spi.h").read_text()
flush = driver[driver.index(" void display(void)"):driver.index(" virtual void resetOrientation()")]
source = r'''
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <vector>
using std::min; using std::max;
#define LOW 0
#define HIGH 1
#define rtos_malloc std::malloc
#define rtos_free std::free
void yield() {}
struct Bus {
int transfers=0, expected_bytes=0;
template<class T> void beginTransaction(T) {}
void endTransaction() {}
void transfer(void*,void*,int bytes) { assert(bytes==expected_bytes); ++transfers; }
};
class Panel {
public:
int displayWidth,displayHeight,_buffheight;
uint16_t _RGB=0xffff;
int _spiSettings=0;
Bus bus; Bus* _spi=&bus;
std::vector<uint8_t> front,back;
uint8_t* buffer; uint8_t* buffer_back;
std::vector<int> rows;
Panel(int w,int h):displayWidth(w),displayHeight(h),_buffheight((h+7)/8),
front(w*_buffheight,0xff),back(w*_buffheight,0),
buffer(front.data()),buffer_back(back.data()),rows(h,0) {}
void set_CS(int) {}
void setAddrWindow(int x,int y,int w,int h) {
assert(x==0 && w==displayWidth && h==1 && y>=0 && y<displayHeight);
++rows[y]; bus.expected_bytes=w*2;
}
'''
source += flush + r'''
};
int main() {
for(auto size:{std::make_pair(240,135),{320,170},{320,240}}) {
Panel p(size.first,size.second); p.display();
assert(p.bus.transfers==p.displayHeight);
for(int row:p.rows) assert(row==1);
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
p.display(); assert(p.bus.transfers==p.displayHeight);
#endif
}
}
'''
with tempfile.TemporaryDirectory(prefix="meshcore-native-spi-") as temp:
for double in (False, True):
flags = ["-DOLEDDISPLAY_DOUBLE_BUFFER"] if double else []
if os.name != "nt":
flags += ["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]
binary = Path(temp) / "flush.exe"
result = subprocess.run(["c++", "-std=c++11", *flags, "-x", "c++", "-", "-o", str(binary)],
input=source, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Test the real ST7735 header and drawing methods with a recording TFT canvas."""
from pathlib import Path
import os
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
FIXTURE = ROOT / "test/fixtures/st7735_native"
class T096NativeResolutionTest(unittest.TestCase):
def test_all_st7735_boards_are_native(self):
driver = (ROOT / "src/helpers/ui/ST7735Display.cpp").read_text()
source = (FIXTURE / "render.cpp").read_text() + "\n"
source += "\n".join(line for line in driver.splitlines()
if line.startswith("#define SCALE_")) + "\n"
for name in ("setTextSize", "setColor", "setCursor", "print", "fillRect",
"drawRect", "drawXbm", "getTextWidth"):
start = driver.index(f"ST7735Display::{name}(")
start = driver.rfind("\n", 0, start) + 1
end = driver.index("\n}", start) + 2
source += driver[start:end] + "\n"
with tempfile.TemporaryDirectory(prefix="meshcore-t096-native-") as directory:
for native in (False, True):
for tft_pin in (False, True):
with self.subTest(native=native, tft_pin=tft_pin):
binary = Path(directory) / "render.exe"
flags = (["-DHELTEC_T096=1"] if native else [])
flags += ["-DUSE_PIN_TFT=1"] if tft_pin else []
if os.name != "nt":
flags += ["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]
result = subprocess.run([
"c++", "-std=c++11", "-Wall", "-Wextra", "-Werror",
"-Wno-unused-parameter", *flags,
"-I", str(FIXTURE / "mocks"), "-I", str(ROOT / "src"),
"-x", "c++", "-", "-o", str(binary),
], input=source, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
result = subprocess.run([str(binary)], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("sprite->createSprite(160, 80)", driver)
if __name__ == "__main__":
unittest.main()