forked from crosspoint-reader/crosspoint-reader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGfxRenderer.cpp
More file actions
2350 lines (2080 loc) · 89.4 KB
/
Copy pathGfxRenderer.cpp
File metadata and controls
2350 lines (2080 loc) · 89.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "GfxRenderer.h"
#include <BidiUtils.h>
#include <BoardConfig.h>
#include <BuildScratch.h>
#include <FontDecompressor.h>
#include <HalGPIO.h>
#include <Logging.h>
#include <SdCardFont.h>
#include <Utf8.h>
#include <algorithm>
#include "FontCacheManager.h"
namespace {
/**
* Resolves the requested style to the best available style in the given SD card font.
* Falls back gracefully when the font lacks the requested variant.
*/
uint8_t resolveSdCardStyle(const SdCardFont& font, const EpdFontFamily::Style style) {
return font.resolveStyle(static_cast<uint8_t>(style));
}
} // namespace
namespace {
const char* resolveVisualText(const char* text, std::string& visualBuffer, BidiUtils::BidiBaseDir baseDir);
// Appends the shaped visual form of every RTL token in `text` to `shapedOut`.
// getTextAdvanceX() measures the bidi-reordered, Arabic-shaped codepoint stream,
// so the SD advance table must be warmed with the presentation forms as well as
// the logical codepoints — otherwise every RTL word measurement misses the fast
// path and falls through to onGlyphMiss(), which opens the .cpfont and reads
// glyph metadata + bitmap into the 8-slot overflow ring, once per glyph.
// Tokens without RTL lead bytes (0xD6-0xDB) are skipped with a byte scan, so
// pure-LTR text pays almost nothing.
void appendShapedRtlTokens(const char* text, std::string& shapedOut) {
const auto isBreak = [](const char c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; };
std::string token;
std::string visual;
const char* p = text;
while (*p) {
while (*p && isBreak(*p)) ++p;
const char* start = p;
bool hasRtlBytes = false;
while (*p && !isBreak(*p)) {
const auto b = static_cast<unsigned char>(*p);
hasRtlBytes = hasRtlBytes || (b >= 0xD6 && b <= 0xDB);
++p;
}
if (!hasRtlBytes) continue;
token.assign(start, p - start);
if (BidiUtils::applyBidiVisual(token.c_str(), visual, static_cast<int>(BidiUtils::BidiBaseDir::AUTO))) {
shapedOut += visual;
}
}
}
} // namespace
const uint8_t* GfxRenderer::getGlyphBitmap(const EpdFontData* fontData, const EpdGlyph* glyph) const {
if (fontData->groups != nullptr) {
auto* fd = fontCacheManager_ ? fontCacheManager_->getDecompressor() : nullptr;
if (!fd) {
LOG_ERR("GFX", "Compressed font but no FontDecompressor set");
return nullptr;
}
uint32_t glyphIndex = static_cast<uint32_t>(glyph - fontData->glyph);
// For page-buffer hits the pointer is stable for the page lifetime.
// For hot-group hits it is valid only until the next getBitmap() call — callers
// must consume it (draw the glyph) before requesting another bitmap.
return fd->getBitmap(fontData, glyph, glyphIndex);
}
// For SD card fonts, check if the glyph was loaded on demand into the overflow
// buffer. getOverflowBitmap() returns:
// - bitmap pointer for overflow glyphs with bitmap data
// - nullptr for overflow glyphs without bitmap data (e.g. space: width=0, height=0)
// - nullptr for non-overflow glyphs (normal prewarmed path)
// We distinguish overflow-with-no-bitmap from non-overflow by checking isOverflowGlyph().
if (fontData->glyphMissCtx) {
auto* sdFont = SdCardFont::fromMissCtx(fontData->glyphMissCtx);
if (sdFont->isOverflowGlyph(glyph)) {
return sdFont->getOverflowBitmap(glyph); // may be nullptr for zero-width glyphs
}
}
return &fontData->bitmap[glyph->dataOffset];
}
void GfxRenderer::ensureSdCardFontReady(int fontId, const char* utf8Text, uint8_t styleMask) const {
auto it = sdCardFonts_.find(fontId);
if (it != sdCardFonts_.end()) {
std::string shaped;
appendShapedRtlTokens(utf8Text, shaped);
int missed = it->second->buildAdvanceTable(utf8Text, styleMask, shaped.empty() ? nullptr : shaped.c_str());
if (missed > 0) {
LOG_DBG("GFX", "ensureSdCardFontReady: %d glyph(s) not found", missed);
}
}
}
void GfxRenderer::ensureSdCardFontReady(int fontId, const std::deque<std::string>& words, bool includeHyphen,
uint8_t styleMask) const {
auto it = sdCardFonts_.find(fontId);
if (it != sdCardFonts_.end()) {
// Augment the persistent advance-only table for layout measurement.
// The table survives across paragraphs/sections (capped per font), so
// repeated indexing of the same SD font amortizes glyph-metric SD reads.
std::string shaped;
for (const auto& w : words) {
appendShapedRtlTokens(w.c_str(), shaped);
}
int missed =
it->second->buildAdvanceTable(words, includeHyphen, styleMask, shaped.empty() ? nullptr : shaped.c_str());
if (missed > 0) {
LOG_DBG("GFX", "ensureSdCardFontReady: %d glyph(s) not found", missed);
}
}
}
void GfxRenderer::begin() {
frameBuffer = display.getFrameBuffer();
if (!frameBuffer) {
LOG_ERR("GFX", "!! No framebuffer");
assert(false);
}
panelWidth = display.getDisplayWidth();
panelHeight = display.getDisplayHeight();
panelWidthBytes = display.getDisplayWidthBytes();
frameBufferSize = display.getBufferSize();
bwBufferChunks.assign((frameBufferSize + BW_BUFFER_CHUNK_SIZE - 1) / BW_BUFFER_CHUNK_SIZE, nullptr);
}
void GfxRenderer::releaseFrameBufferForBuild() {
// Lend the framebuffer's bytes IN PLACE: the allocation is never freed, so
// it cannot move and repeated loans cannot fragment the heap (the previous
// free+realloc model measurably decayed the max contiguous block over a
// session). The bytes are deposited in the build-scratch registry so
// memory-hungry build phases (e.g. InflateStream's tinfl state + window)
// can claim them instead of allocating.
uint32_t size = 0;
uint8_t* scratch = display.lendFrameBufferStorage(&size);
frameBuffer = nullptr;
if (scratch) {
buildscratch::lend(scratch, size);
}
}
bool GfxRenderer::restoreFrameBufferAfterBuild() {
buildscratch::reclaim();
display.returnFrameBufferStorage(); // cannot fail: the allocation was never freed
frameBuffer = display.getFrameBuffer();
return frameBuffer != nullptr;
}
GfxRenderer::FrameBufferLoan::FrameBufferLoan(GfxRenderer& renderer) : renderer_(renderer) {
// Nesting guard: if the framebuffer is already lent out (an outer loan),
// stay inert so this end() cannot return storage the outer loan still owns.
if (!renderer_.hasFrameBuffer()) return;
renderer_.releaseFrameBufferForBuild();
active_ = true;
}
void GfxRenderer::FrameBufferLoan::end() {
if (!active_) return;
active_ = false;
if (!renderer_.restoreFrameBufferAfterBuild()) {
// Only reachable if the framebuffer never existed, which begin() already
// asserts against; kept as a backstop since running blind helps nobody.
LOG_ERR("GFX", "Framebuffer restore failed - restarting");
ESP.restart();
}
}
bool GfxRenderer::isFontCacheScanning() const { return fontCacheManager_ && fontCacheManager_->isScanning(); }
void GfxRenderer::insertFont(const int fontId, EpdFontFamily font) {
auto result = fontMap.insert({fontId, font});
if (!result.second) {
LOG_ERR("GFX", "Font ID %d already registered, ignoring duplicate", fontId);
}
}
int GfxRenderer::resolveTextFontId(const int fontId, const char* text, const EpdFontFamily::Style style) const {
if (fallbackFontMap_.empty() || text == nullptr || *text == '\0') {
return fontId;
}
const auto fbIt = fallbackFontMap_.find(fontId);
if (fbIt == fallbackFontMap_.end()) {
return fontId; // no fallback registered for this font
}
const int fallbackFontId = fbIt->second;
const auto fontIt = fontMap.find(fontId);
const auto fallbackIt = fontMap.find(fallbackFontId);
if (fontIt == fontMap.end() || fallbackIt == fontMap.end()) {
return fontId; // unknown primary or fallback not loaded — let the caller handle it
}
const EpdFontFamily& primary = fontIt->second;
const EpdFontFamily& fallback = fallbackIt->second;
const char* cursor = text;
uint32_t cp;
while ((cp = utf8NextCodepoint(reinterpret_cast<const uint8_t**>(&cursor)))) {
// Only redirect for CJK the primary font cannot draw but the fallback can.
// Latin/symbol strings the built-in UI fonts already cover are left
// untouched, and a partial-coverage fallback (e.g. kana-only) is not worth
// dragging the whole string into for glyphs it would also miss.
if (utf8IsCjkCodepoint(cp) && !primary.hasCodepoint(cp, style) && fallback.hasCodepoint(cp, style)) {
return fallbackFontId;
}
}
return fontId;
}
void GfxRenderer::prewarmFallbackText(const int fontId, const TextGetter getter, const void* ctx,
const uint32_t textCount, const EpdFontFamily::Style style) const {
if (getter == nullptr || textCount == 0) {
return;
}
// Resolve the fallback id from the first string that actually redirects; a
// screen with no CJK strings resolves nothing and this is a no-op.
int fallbackFontId = fontId;
for (uint32_t i = 0; i < textCount && fallbackFontId == fontId; i++) {
const char* text = getter(ctx, i);
if (text == nullptr || *text == '\0') continue;
fallbackFontId = resolveTextFontId(fontId, text, style);
}
if (fallbackFontId == fontId) {
return;
}
const auto sdIt = sdCardFonts_.find(fallbackFontId);
if (sdIt == sdCardFonts_.end()) {
return;
}
const uint8_t styleMask = static_cast<uint8_t>(1u << (static_cast<uint8_t>(style) & 0x03));
// Append one virtual index for U+2026: truncation measures every long row
// as "label…", so an ellipsis missing from the batch forces a union rebuild
// on the first repaint.
struct WrapCtx {
TextGetter getter;
const void* ctx;
uint32_t count;
} wrap{getter, ctx, textCount};
const auto withEllipsis = [](const void* wc, uint32_t i) -> const char* {
const auto* w = static_cast<const WrapCtx*>(wc);
return i < w->count ? w->getter(w->ctx, i) : "\xe2\x80\xa6";
};
// loadKernLig=false: see ensureSdGlyphsResident below.
sdIt->second->prewarm(withEllipsis, &wrap, textCount + 1, styleMask, /*metadataOnly=*/false,
/*loadKernLig=*/false);
}
void GfxRenderer::prewarmFallbackText(const int fontId, const char* text, const EpdFontFamily::Style style) const {
if (text == nullptr || *text == '\0') {
return;
}
const int resolvedFontId = resolveTextFontId(fontId, text, style);
if (resolvedFontId != fontId) {
ensureSdGlyphsResident(resolvedFontId, text, style, false);
}
}
void GfxRenderer::ensureSdGlyphsResident(const int fontId, const char* text, const EpdFontFamily::Style style,
const bool metadataOnly) const {
const auto sdIt = sdCardFonts_.find(fontId);
if (sdIt == sdCardFonts_.end()) {
return;
}
// SUP/SUB bits don't select a distinct .cpfont style bitstream — mask to the
// base style. resolveStyleMask() inside prewarm folds absent styles.
// loadKernLig=false: redirected fallback strings (CJK titles, filenames)
// have no useful kern pairs, and the ~3KB class-table load plus per-rebuild
// mini-matrix build cost heap and SD time exactly where these strings live
// (heap-tight UI screens). The reader's PrewarmScope path keeps kern; a
// kern-wanting request that subset-hits a kern-free mini tops the matrix up
// in prewarmStyle without re-reading glyphs.
const uint8_t styleMask = static_cast<uint8_t>(1u << (static_cast<uint8_t>(style) & 0x03));
sdIt->second->prewarm(text, styleMask, metadataOnly, /*loadKernLig=*/false);
}
// Translate logical (x,y) coordinates to physical panel coordinates based on current orientation
// This should always be inlined for better performance
static inline void rotateCoordinates(const GfxRenderer::Orientation orientation, const int x, const int y, int* phyX,
int* phyY, const uint16_t panelWidth, const uint16_t panelHeight) {
switch (orientation) {
case GfxRenderer::Portrait: {
// Logical portrait (480x800) → panel (800x480)
// Rotation: 90 degrees clockwise
*phyX = y;
*phyY = panelHeight - 1 - x;
break;
}
case GfxRenderer::LandscapeClockwise: {
// Logical landscape (800x480) rotated 180 degrees (swap top/bottom and left/right)
*phyX = panelWidth - 1 - x;
*phyY = panelHeight - 1 - y;
break;
}
case GfxRenderer::PortraitInverted: {
// Logical portrait (480x800) → panel (800x480)
// Rotation: 90 degrees counter-clockwise
*phyX = panelWidth - 1 - y;
*phyY = x;
break;
}
case GfxRenderer::LandscapeCounterClockwise: {
// Logical landscape (800x480) aligned with panel orientation
*phyX = x;
*phyY = y;
break;
}
}
}
// Output of screenRectToAlignedMemRect: a rectangle in panel-memory
// coordinates whose x and width are guaranteed to be multiples of 8 (the
// SDK's EInkDisplay::displayWindow alignment requirement). `valid == false`
// means the input was empty or fully outside the panel.
struct AlignedMemRect {
uint16_t x = 0;
uint16_t y = 0;
uint16_t w = 0;
uint16_t h = 0;
bool valid = false;
};
// Translate a screen-coordinate rectangle (the coordinate system used by
// fillRect / drawText / the rest of the renderer's public API) into a
// panel-memory rectangle suitable for direct framebuffer indexing. Rotates
// the rectangle's two opposite corners with rotateCoordinates(), takes the
// bounding box (which naturally swaps width/height in Portrait /
// PortraitInverted), then snaps the x extent outward to multiples of 8 and
// clamps to panel bounds. Precondition: panel dims are multiples of 8 (true
// for the 800x480 panel), so clamping cannot re-break alignment.
static AlignedMemRect screenRectToAlignedMemRect(GfxRenderer::Orientation orientation, int sx, int sy, int sw, int sh,
uint16_t panelWidth, uint16_t panelHeight) {
AlignedMemRect out;
if (sw <= 0 || sh <= 0) return out;
int x0, y0, x1, y1;
rotateCoordinates(orientation, sx, sy, &x0, &y0, panelWidth, panelHeight);
rotateCoordinates(orientation, sx + sw - 1, sy + sh - 1, &x1, &y1, panelWidth, panelHeight);
const int memXLo = std::min(x0, x1);
const int memYLo = std::min(y0, y1);
const int memXHi = std::max(x0, x1) + 1; // exclusive upper bound
const int memYHi = std::max(y0, y1) + 1;
// Snap x outward to multiples of 8.
int alignedXLo = memXLo & ~0x7; // round down
int alignedXHi = (memXHi + 7) & ~0x7; // round up
if (alignedXLo < 0) alignedXLo = 0;
if (alignedXHi > panelWidth) alignedXHi = panelWidth;
int clampedYLo = memYLo;
int clampedYHi = memYHi;
if (clampedYLo < 0) clampedYLo = 0;
if (clampedYHi > panelHeight) clampedYHi = panelHeight;
if (alignedXHi <= alignedXLo || clampedYHi <= clampedYLo) return out;
out.x = static_cast<uint16_t>(alignedXLo);
out.y = static_cast<uint16_t>(clampedYLo);
out.w = static_cast<uint16_t>(alignedXHi - alignedXLo);
out.h = static_cast<uint16_t>(clampedYHi - clampedYLo);
out.valid = true;
return out;
}
enum class TextRotation { None, Rotated90CW };
// Shared glyph rendering logic for normal and rotated text.
// Coordinate mapping and cursor advance direction are selected at compile time via the template parameter.
// Render a glyph at 50% scale. Used for SUP/SUB style bits.
//
// Each destination pixel represents a 2x2 source block. Drawing when that block
// contains ink preserves thin strokes that nearest-neighbor sampling can skip.
//
// The advance width is also halved in drawText() so layout reserves exactly the right
// horizontal space for the scaled glyph.
static void renderCharScaled(const GfxRenderer& renderer, GfxRenderer::RenderMode renderMode,
const EpdFontFamily& fontFamily, const uint32_t cp, int cursorX, int cursorY,
const bool pixelState, const EpdFontFamily::Style style) {
const EpdGlyph* glyph = fontFamily.getGlyph(cp, style);
if (!glyph) return;
const EpdFontData* fontData = fontFamily.getData(style);
const uint8_t* bitmap = renderer.getGlyphBitmap(fontData, glyph);
if (!bitmap) return;
const int srcW = glyph->width;
const int srcH = glyph->height;
const int dstW = (srcW + 1) / 2; // ceil so odd-width glyphs aren't clipped
const int dstH = (srcH + 1) / 2;
// Scale the glyph bearing by the same factor so the scaled glyph sits at the correct
// pixel offset from the (already-shifted) cursor position.
const int baseX = cursorX + glyph->left / 2;
const int baseY = cursorY - glyph->top / 2;
if (fontData->is2Bit) {
// 2-bit packed format: 4 pixels per byte, MSB first, 2 bits per pixel.
// raw value: 0=white, 1=light-gray, 2=dark-gray, 3=black.
for (int dstY = 0; dstY < dstH; dstY++) {
const int srcY = dstY * 2;
for (int dstX = 0; dstX < dstW; dstX++) {
const int srcX = dstX * 2;
uint8_t coverage = 0;
uint8_t maxRaw = 0;
for (int sampleY = 0; sampleY < 2 && srcY + sampleY < srcH; sampleY++) {
for (int sampleX = 0; sampleX < 2 && srcX + sampleX < srcW; sampleX++) {
const int pos = (srcY + sampleY) * srcW + srcX + sampleX;
const uint8_t byte = bitmap[pos >> 2];
const uint8_t raw = (byte >> ((3 - (pos & 3)) * 2)) & 0x3;
coverage += raw;
if (raw > maxRaw) maxRaw = raw;
}
}
if (maxRaw >= 2 || coverage >= 2) {
renderer.drawPixel(baseX + dstX, baseY + dstY, pixelState);
}
}
}
} else {
// 1-bit packed format: 8 pixels per byte, MSB first.
for (int dstY = 0; dstY < dstH; dstY++) {
const int srcY = dstY * 2;
for (int dstX = 0; dstX < dstW; dstX++) {
const int srcX = dstX * 2;
bool hasInk = false;
for (int sampleY = 0; sampleY < 2 && srcY + sampleY < srcH; sampleY++) {
for (int sampleX = 0; sampleX < 2 && srcX + sampleX < srcW; sampleX++) {
const int pos = (srcY + sampleY) * srcW + srcX + sampleX;
const uint8_t byte = bitmap[pos >> 3];
const uint8_t bit = 7 - (pos & 7);
if ((byte >> bit) & 1) {
hasInk = true;
}
}
}
if (hasInk) {
renderer.drawPixel(baseX + dstX, baseY + dstY, pixelState);
}
}
}
}
}
template <TextRotation rotation = TextRotation::None>
static void renderCharImpl(const GfxRenderer& renderer, GfxRenderer::RenderMode renderMode,
const EpdFontFamily& fontFamily, const uint32_t cp, int cursorX, int cursorY,
const bool pixelState, const EpdFontFamily::Style style) {
const EpdGlyph* glyph = fontFamily.getGlyph(cp, style);
if (!glyph) {
LOG_ERR("GFX", "No glyph for codepoint %d", cp);
return;
}
const EpdFontData* fontData = fontFamily.getData(style);
const bool is2Bit = fontData->is2Bit;
const uint8_t width = glyph->width;
const uint8_t height = glyph->height;
const int left = glyph->left;
const int top = glyph->top;
// Tiled-grayscale band culling: if this glyph's physical y-extent is entirely
// outside the active strip, skip it before the expensive bitmap decode. This
// is what makes per-band re-rendering cheap. No-op outside strip mode.
if constexpr (rotation == TextRotation::Rotated90CW) {
const int ob = cursorX + fontData->ascender - top;
const int ib = cursorY - left;
if (!renderer.glyphIntersectsStrip(ob, ib - (width - 1), ob + height - 1, ib)) {
return;
}
} else {
const int gx0 = cursorX + left;
const int gy0 = cursorY - top;
if (!renderer.glyphIntersectsStrip(gx0, gy0, gx0 + width - 1, gy0 + height - 1)) {
return;
}
}
const uint8_t* bitmap = renderer.getGlyphBitmap(fontData, glyph);
if (bitmap != nullptr) {
// For Normal: outer loop advances screenY, inner loop advances screenX
// For Rotated: outer loop advances screenX, inner loop advances screenY (in reverse)
int outerBase, innerBase;
if constexpr (rotation == TextRotation::Rotated90CW) {
outerBase = cursorX + fontData->ascender - top; // screenX = outerBase + glyphY
innerBase = cursorY - left; // screenY = innerBase - glyphX
} else {
outerBase = cursorY - top; // screenY = outerBase + glyphY
innerBase = cursorX + left; // screenX = innerBase + glyphX
}
if (is2Bit) {
int pixelPosition = 0;
for (int glyphY = 0; glyphY < height; glyphY++) {
const int outerCoord = outerBase + glyphY;
for (int glyphX = 0; glyphX < width; glyphX++, pixelPosition++) {
int screenX, screenY;
if constexpr (rotation == TextRotation::Rotated90CW) {
screenX = outerCoord;
screenY = innerBase - glyphX;
} else {
screenX = innerBase + glyphX;
screenY = outerCoord;
}
const uint8_t byte = bitmap[pixelPosition >> 2];
const uint8_t bit_index = (3 - (pixelPosition & 3)) * 2;
// the direct bit from the font is 0 -> white, 1 -> light gray, 2 -> dark gray, 3 -> black
// we swap this to better match the way images and screen think about colors:
// 0 -> black, 1 -> dark grey, 2 -> light grey, 3 -> white
const uint8_t bmpVal = 3 - ((byte >> bit_index) & 0x3);
if (renderMode == GfxRenderer::BW && bmpVal < 3) {
// Black (also paints over the grays in BW mode)
renderer.drawPixel(screenX, screenY, pixelState);
} else if (renderMode == GfxRenderer::GRAYSCALE_MSB && (bmpVal == 1 || bmpVal == 2)) {
// Light gray (also mark the MSB if it's going to be a dark gray too)
// Dedicated X3 gray LUTs now provide proper 4-level gray on both devices
// We have to flag pixels in reverse for the gray buffers, as 0 leave alone, 1 update
renderer.drawPixel(screenX, screenY, false);
} else if (renderMode == GfxRenderer::GRAYSCALE_LSB && bmpVal == 1) {
// Dark gray
renderer.drawPixel(screenX, screenY, false);
}
}
}
} else {
int pixelPosition = 0;
for (int glyphY = 0; glyphY < height; glyphY++) {
const int outerCoord = outerBase + glyphY;
for (int glyphX = 0; glyphX < width; glyphX++, pixelPosition++) {
int screenX, screenY;
if constexpr (rotation == TextRotation::Rotated90CW) {
screenX = outerCoord;
screenY = innerBase - glyphX;
} else {
screenX = innerBase + glyphX;
screenY = outerCoord;
}
const uint8_t byte = bitmap[pixelPosition >> 3];
const uint8_t bit_index = 7 - (pixelPosition & 7);
if ((byte >> bit_index) & 1) {
renderer.drawPixel(screenX, screenY, pixelState);
}
}
}
}
}
}
// IMPORTANT: This function is in critical rendering path and is called for every pixel. Please keep it as simple and
// efficient as possible.
void GfxRenderer::drawPixel(const int x, const int y, const bool state) const {
int phyX = 0;
int phyY = 0;
// Note: this call should be inlined for better performance
rotateCoordinates(orientation, x, y, &phyX, &phyY, panelWidth, panelHeight);
// Bounds checking against runtime panel dimensions
if (phyX < 0 || phyX >= panelWidth || phyY < 0 || phyY >= panelHeight) {
LOG_ERR("GFX", "!! Outside range (%d, %d) -> (%d, %d)", x, y, phyX, phyY);
return;
}
// Tiled grayscale: redirect writes to the strip scratch and clip to the
// current band. Single predictable branch on the hot per-pixel path.
uint8_t* target = frameBuffer;
uint32_t rowY = static_cast<uint32_t>(phyY);
if (_stripActive) {
if (phyY < _stripY0 || phyY >= _stripY0 + _stripRows) {
return; // pixel outside the band currently being rendered
}
target = _stripBuf;
rowY = static_cast<uint32_t>(phyY - _stripY0);
}
// Calculate byte position and bit position
const uint32_t byteIndex = rowY * panelWidthBytes + (phyX / 8);
const uint8_t bitPosition = 7 - (phyX % 8); // MSB first
if (state) {
target[byteIndex] &= ~(1 << bitPosition); // Clear bit
} else {
target[byteIndex] |= 1 << bitPosition; // Set bit
}
}
int GfxRenderer::getTextWidth(const int fontId, const char* text, const EpdFontFamily::Style style,
const BidiUtils::BidiBaseDir baseDir) const {
if (text == nullptr || *text == '\0') {
return 0;
}
// Measure with the same font drawText would render with (see resolveTextFontId)
// so wrapping, truncation and centering of CJK strings stay consistent.
const int resolvedFontId = resolveTextFontId(fontId, text, style);
const auto fontIt = fontMap.find(resolvedFontId);
if (fontIt == fontMap.end()) {
LOG_ERR("GFX", "Font %d not found", resolvedFontId);
return 0;
}
std::string visual;
const char* renderedText = resolveVisualText(text, visual, baseDir);
// Redirected to the SD fallback: batch-load the string's glyphs so the
// per-codepoint measurement loop below doesn't fault them in one SD read
// at a time (#2725).
if (resolvedFontId != fontId) {
ensureSdGlyphsResident(resolvedFontId, renderedText, style, true);
}
int w = 0, h = 0;
fontIt->second.getTextDimensions(renderedText, &w, &h, style);
return w;
}
void GfxRenderer::drawCenteredText(const int fontId, const int y, const char* text, const bool black,
const EpdFontFamily::Style style, const BidiUtils::BidiBaseDir baseDir) const {
const int x = (getScreenWidth() - getTextWidth(fontId, text, style, baseDir)) / 2;
drawText(fontId, x, y, text, black, style, baseDir);
}
void GfxRenderer::drawText(const int fontId, const int x, const int y, const char* text, const bool black,
const EpdFontFamily::Style style, const BidiUtils::BidiBaseDir baseDir) const {
// cannot draw a NULL / empty string
if (text == nullptr || *text == '\0') {
return;
}
// Route CJK-bearing strings to the fallback font when the requested font
// lacks the glyphs (e.g. Chinese book titles drawn with a Latin UI font).
const int resolvedFontId = resolveTextFontId(fontId, text, style);
std::string visual;
const char* renderedText = resolveVisualText(text, visual, baseDir);
// Baseline from the resolved font; when the string was redirected to the
// fallback, the caller positioned this line with the REQUESTED font's
// metrics (row bands, icon centering), so center the fallback's line box
// inside the requested font's line box instead of letting a taller/shorter
// fallback hang below or float above the row's visual center.
int yPos = y + getFontAscenderSize(resolvedFontId);
if (resolvedFontId != fontId) {
yPos += (getLineHeight(fontId) - getLineHeight(resolvedFontId)) / 2;
}
int lastBaseX = x;
int lastBaseLeft = 0;
int lastBaseWidth = 0;
int lastBaseTop = 0;
int32_t prevAdvanceFP = 0; // 12.4 fixed-point: prev glyph's advance + next kern for snap
if (fontCacheManager_ && fontCacheManager_->isScanning()) {
fontCacheManager_->recordText(renderedText, resolvedFontId, style);
return;
}
// Redirected to the SD fallback: batch-load the string's glyphs so the draw
// loop below doesn't fault them in one SD read at a time (#2725).
if (resolvedFontId != fontId) {
ensureSdGlyphsResident(resolvedFontId, renderedText, style, false);
}
const auto fontIt = fontMap.find(resolvedFontId);
if (fontIt == fontMap.end()) {
LOG_ERR("GFX", "Font %d not found", resolvedFontId);
return;
}
const auto& font = fontIt->second;
const char* textCursor = renderedText;
uint32_t cp;
uint32_t prevCp = 0;
while ((cp = utf8NextCodepoint(reinterpret_cast<const uint8_t**>(&textCursor)))) {
// RTL vowel marks (Hebrew niqqud, Arabic harakat) ride the combining-mark
// path: zero-advance overlays on the preceding base glyph (applyBidiVisual
// emits base-then-marks per UAX#9 L3). anchorFor pins position-sensitive
// niqqud (dagesh, shin/sin dots, holam) to their spot on the base; other
// marks stay centered, raised above the base or (kasra) at their
// font-native position. Fonts without their glyphs — the built-ins — miss
// the getGlyph lookup and skip them, as before.
if (utf8IsCombiningMark(cp) || BidiUtils::isTransparentMark(cp)) {
const EpdGlyph* combiningGlyph = font.getGlyph(cp, style);
if (!combiningGlyph) continue;
const auto anchor = combiningMark::anchorFor(cp);
const int raiseBy =
combiningMark::raiseAboveBase(anchor, combiningGlyph->top, combiningGlyph->height, lastBaseTop);
const int combiningX = combiningMark::anchorOver(anchor, lastBaseX, lastBaseLeft, lastBaseWidth,
combiningGlyph->left, combiningGlyph->width);
renderCharImpl<TextRotation::None>(*this, renderMode, font, cp, combiningX, yPos - raiseBy, black, style);
continue;
}
cp = font.applyLigatures(cp, textCursor, style);
// Differential rounding: snap (previous advance + current kern) as one unit so
// identical character pairs always produce the same pixel step regardless of
// where they fall on the line.
if (prevCp != 0) {
const auto kernFP = font.getKerning(prevCp, cp, style); // 4.4 fixed-point kern
lastBaseX += fp4::toPixel(prevAdvanceFP + kernFP); // snap 12.4 fixed-point to nearest pixel
}
const EpdGlyph* glyph = font.getGlyph(cp, style);
lastBaseLeft = glyph ? glyph->left : 0;
lastBaseWidth = glyph ? glyph->width : 0;
lastBaseTop = glyph ? glyph->top : 0;
prevAdvanceFP = glyph ? glyph->advanceX : 0; // 12.4 fixed-point
const bool isSupSub = (style & (EpdFontFamily::SUP | EpdFontFamily::SUB)) != 0;
if (isSupSub) {
// Halve the advance so the cursor advances by the same amount the scaled glyph
// actually occupies, keeping spacing correct without needing a separate smaller font.
prevAdvanceFP = (prevAdvanceFP + 1) / 2;
}
if (isSupSub) {
// yPos already carries the vertical offset applied by TextBlock::render().
renderCharScaled(*this, renderMode, font, cp, lastBaseX, yPos, black, style);
} else {
renderCharImpl<TextRotation::None>(*this, renderMode, font, cp, lastBaseX, yPos, black, style);
}
prevCp = cp;
}
}
namespace {
const char* resolveVisualText(const char* text, std::string& visualBuffer, const BidiUtils::BidiBaseDir baseDir) {
if (!text || *text == '\0') return text;
if (baseDir != BidiUtils::BidiBaseDir::RTL) {
// Byte-level scan: skip BiDi when no RTL script lead bytes are present.
// Hebrew UTF-8 lead bytes: 0xD6-0xD7; Arabic/Syriac: 0xD8-0xDB.
// This covers all RTL content without false negatives and avoids triggering
// the full UAX#9 algorithm for Latin-extended, em-dashes, accented text, etc.
bool hasRtlBytes = false;
for (const unsigned char* q = reinterpret_cast<const unsigned char*>(text); *q; ++q) {
if (*q >= 0xD6 && *q <= 0xDB) {
hasRtlBytes = true;
break;
}
}
if (!hasRtlBytes) return text;
}
if (BidiUtils::applyBidiVisual(text, visualBuffer, static_cast<int>(baseDir)) && !visualBuffer.empty()) {
return visualBuffer.c_str();
}
return text;
}
} // namespace
void GfxRenderer::drawLine(int x1, int y1, int x2, int y2, const bool state) const {
if (fontCacheManager_ && fontCacheManager_->isScanning()) return;
if (x1 == x2) {
if (y2 < y1) {
std::swap(y1, y2);
}
for (int y = y1; y <= y2; y++) {
drawPixel(x1, y, state);
}
} else if (y1 == y2) {
if (x2 < x1) {
std::swap(x1, x2);
}
for (int x = x1; x <= x2; x++) {
drawPixel(x, y1, state);
}
} else {
// Bresenham's line algorithm — integer arithmetic only
int dx = x2 - x1;
int dy = y2 - y1;
int sx = (dx > 0) ? 1 : -1;
int sy = (dy > 0) ? 1 : -1;
dx = sx * dx; // abs
dy = sy * dy; // abs
int err = dx - dy;
while (true) {
drawPixel(x1, y1, state);
if (x1 == x2 && y1 == y2) break;
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x1 += sx;
}
if (e2 < dx) {
err += dx;
y1 += sy;
}
}
}
}
void GfxRenderer::drawLine(int x1, int y1, int x2, int y2, const int lineWidth, const bool state) const {
for (int i = 0; i < lineWidth; i++) {
drawLine(x1, y1 + i, x2, y2 + i, state);
}
}
void GfxRenderer::drawRect(const int x, const int y, const int width, const int height, const bool state) const {
drawLine(x, y, x + width - 1, y, state);
drawLine(x + width - 1, y, x + width - 1, y + height - 1, state);
drawLine(x + width - 1, y + height - 1, x, y + height - 1, state);
drawLine(x, y, x, y + height - 1, state);
}
// Border is inside the rectangle
void GfxRenderer::drawRect(const int x, const int y, const int width, const int height, const int lineWidth,
const bool state) const {
// Keep the border inside [x, x+width) like the thin overload: the previous
// right/bottom edges at x+width / y+height sat one pixel outside the rect,
// so stroked boxes looked shifted against fills computed from the rect.
for (int i = 0; i < lineWidth; i++) {
drawLine(x + i, y + i, x + width - 1 - i, y + i, state);
drawLine(x + width - 1 - i, y + i, x + width - 1 - i, y + height - 1 - i, state);
drawLine(x + width - 1 - i, y + height - 1 - i, x + i, y + height - 1 - i, state);
drawLine(x + i, y + height - 1 - i, x + i, y + i, state);
}
}
void GfxRenderer::drawArc(const int maxRadius, const int cx, const int cy, const int xDir, const int yDir,
const int lineWidth, const bool state) const {
const int stroke = std::min(lineWidth, maxRadius);
const int innerRadius = std::max(maxRadius - stroke, 0);
const int outerRadius = maxRadius;
if (outerRadius <= 0) {
return;
}
const int outerRadiusSq = outerRadius * outerRadius;
const int innerRadiusSq = innerRadius * innerRadius;
int xOuter = outerRadius;
int xInner = innerRadius;
for (int dy = 0; dy <= outerRadius; ++dy) {
while (xOuter > 0 && (xOuter * xOuter + dy * dy) > outerRadiusSq) {
--xOuter;
}
// Keep the smallest x that still lies outside/at the inner radius,
// i.e. (x^2 + y^2) >= innerRadiusSq.
while (xInner > 0 && ((xInner - 1) * (xInner - 1) + dy * dy) >= innerRadiusSq) {
--xInner;
}
if (xOuter < xInner) {
continue;
}
const int x0 = cx + xDir * xInner;
const int x1 = cx + xDir * xOuter;
const int left = std::min(x0, x1);
const int width = std::abs(x1 - x0) + 1;
const int py = cy + yDir * dy;
if (width > 0) {
fillRect(left, py, width, 1, state);
}
}
};
// Border is inside the rectangle, rounded corners
void GfxRenderer::drawRoundedRect(const int x, const int y, const int width, const int height, const int lineWidth,
const int cornerRadius, bool state) const {
drawRoundedRect(x, y, width, height, lineWidth, cornerRadius, true, true, true, true, state);
}
// Border is inside the rectangle, rounded corners
void GfxRenderer::drawRoundedRect(const int x, const int y, const int width, const int height, const int lineWidth,
const int cornerRadius, bool roundTopLeft, bool roundTopRight, bool roundBottomLeft,
bool roundBottomRight, bool state) const {
if (lineWidth <= 0 || width <= 0 || height <= 0) {
return;
}
const int maxRadius = std::min({cornerRadius, width / 2, height / 2});
if (maxRadius <= 0) {
drawRect(x, y, width, height, lineWidth, state);
return;
}
const int stroke = std::min(lineWidth, maxRadius);
const int right = x + width - 1;
const int bottom = y + height - 1;
const int horizontalWidth = width - 2 * maxRadius;
if (horizontalWidth > 0) {
if (roundTopLeft || roundTopRight) {
fillRect(x + maxRadius, y, horizontalWidth, stroke, state);
}
if (roundBottomLeft || roundBottomRight) {
fillRect(x + maxRadius, bottom - stroke + 1, horizontalWidth, stroke, state);
}
}
const int verticalHeight = height - 2 * maxRadius;
if (verticalHeight > 0) {
if (roundTopLeft || roundBottomLeft) {
fillRect(x, y + maxRadius, stroke, verticalHeight, state);
}
if (roundTopRight || roundBottomRight) {
fillRect(right - stroke + 1, y + maxRadius, stroke, verticalHeight, state);
}
}
if (roundTopLeft) {
drawArc(maxRadius, x + maxRadius, y + maxRadius, -1, -1, lineWidth, state);
}
if (roundTopRight) {
drawArc(maxRadius, right - maxRadius, y + maxRadius, 1, -1, lineWidth, state);
}
if (roundBottomRight) {
drawArc(maxRadius, right - maxRadius, bottom - maxRadius, 1, 1, lineWidth, state);
}
if (roundBottomLeft) {
drawArc(maxRadius, x + maxRadius, bottom - maxRadius, -1, 1, lineWidth, state);
}
}
void GfxRenderer::fillRect(const int x, const int y, const int width, const int height, const bool state) const {
if (state) {
fillRectImpl<Color::Black>(x, y, width, height);
} else {
fillRectImpl<Color::White>(x, y, width, height);
}
}
// NOTE: Those are in critical path, and need to be templated to avoid runtime checks for every pixel.
// Any branching must be done outside the loops to avoid performance degradation.
template <>
void GfxRenderer::drawPixelDither<Color::Clear>(const int x, const int y) const {
// Do nothing
}
template <>
void GfxRenderer::drawPixelDither<Color::Black>(const int x, const int y) const {
drawPixel(x, y, true);
}
template <>
void GfxRenderer::drawPixelDither<Color::White>(const int x, const int y) const {
drawPixel(x, y, false);
}
template <>
void GfxRenderer::drawPixelDither<Color::LightGray>(const int x, const int y) const {
drawPixel(x, y, x % 2 == 0 && y % 2 == 0);
}
template <>
void GfxRenderer::drawPixelDither<Color::DarkGray>(const int x, const int y) const {
drawPixel(x, y, (x + y) % 2 == 0); // TODO: maybe find a better pattern?
}
void GfxRenderer::fillRectDither(const int x, const int y, const int width, const int height, Color color) const {
switch (color) {
case Color::Clear:
break;
case Color::Black:
fillRectImpl<Color::Black>(x, y, width, height);
break;
case Color::White:
fillRectImpl<Color::White>(x, y, width, height);
break;
case Color::LightGray:
fillRectImpl<Color::LightGray>(x, y, width, height);
break;
case Color::DarkGray:
fillRectImpl<Color::DarkGray>(x, y, width, height);
break;
}
}
template <Color C>
void GfxRenderer::fillRectImpl(const int x, const int y, const int width, const int height) const {
if constexpr (C == Color::Clear) return;
if (width <= 0 || height <= 0) return;
if (fontCacheManager_ && fontCacheManager_->isScanning()) return;
// Clip in logical space.
const int screenW = getScreenWidth();
const int screenH = getScreenHeight();
const int lx0 = std::max(0, x);
const int ly0 = std::max(0, y);
const int lx1 = std::min(screenW, x + width);
const int ly1 = std::min(screenH, y + height);
if (lx0 >= lx1 || ly0 >= ly1) return;
// Rotate the two opposing logical corners into physical-framebuffer space.
// The bounding rect in physical space is the rect we need to fill — rotation
// is rigid (no shear/stretch) so the bbox of the two corners IS the rect.
int paX, paY, pbX, pbY;