Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1026 lines (919 loc) · 43.8 KB
/
Copy pathmain.cpp
File metadata and controls
1026 lines (919 loc) · 43.8 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 <Arduino.h>
#include <BlePageTurner.h>
#include <BoardConfig.h>
#include <Epub.h>
#include <FontCacheManager.h>
#include <FontDecompressor.h>
#include <GfxRenderer.h>
#include <HalClock.h>
#include <HalDisplay.h>
#include <HalFrontlight.h>
#include <HalGPIO.h>
#include <HalMemory.h>
#include <HalPowerManager.h>
#include <HalStorage.h>
#include <HalSystem.h>
#include <HalTiltSensor.h>
#include <I18n.h>
#include <Logging.h>
#include <SPI.h>
#include <TrustedTime.h>
#include <VectorFontSupport.h>
#include <WiFi.h>
#include <XteinkDetect.h>
#include <builtinFonts/all.h>
#include <esp_wifi.h>
#include <time.h>
#include <atomic>
#include <cstdarg>
#include <cstring>
#include "CrossPointSettings.h"
#include "CrossPointState.h"
#include "KOReaderCredentialStore.h"
#include "LcpPassphraseStore.h"
#include "MappedInputManager.h"
#include "OpdsServerStore.h"
#include "OpdsTokenStore.h"
#include "RecentBooksStore.h"
#include "SdCardFontSystem.h"
#include "WifiCredentialStore.h"
#include "activities/Activity.h"
#include "activities/ActivityManager.h"
#include "activities/settings/SdFirmwareUpdateActivity.h"
#include "components/UITheme.h"
#include "fontIds.h"
#include "platform/UsbSerialJtagHandoff.h"
#include "util/ButtonNavigator.h"
#include "util/PluginEvents.h"
#include "util/ScreenshotUtil.h"
#include "util/Timezones.h"
#if CROSSPOINT_VECTOR_FONTS
// Rendering (incl. FreeType TTF rasterization) runs on the Arduino loop task.
// The default 8 KB stack overflows inside FreeType's FT_Open_Face / variable-font
// parsing. This runtime override applies even with the prebuilt (dio_opi) core,
// where CONFIG_ARDUINO_LOOP_STACK_SIZE from sdkconfig is baked in and ignored.
// Vector-font boards only: without TTF the stock loop stack has always sufficed,
// and non-PSRAM boards need the 16KB back in DRAM.
SET_LOOP_TASK_STACK_SIZE(24 * 1024)
#endif
GfxRenderer renderer(display);
MappedInputManager mappedInputManager(gpio, renderer);
ActivityManager activityManager(renderer, mappedInputManager);
FontDecompressor fontDecompressor;
SdCardFontSystem sdFontSystem;
FontCacheManager fontCacheManager(renderer.getFontMap(), renderer.getSdCardFonts(), renderer.getTtfFonts());
static unsigned long allowSleepAt = 0;
static unsigned long lastX4ProPowerClickAt = 0;
namespace {
constexpr unsigned long X4PRO_POWER_DOUBLE_CLICK_MS = 500;
constexpr unsigned long X4PRO_POWER_CLICK_MAX_HOLD_MS = 300;
} // namespace
// A wake hold must never become an in-app power-button action. Boot may continue
// while the button is held; swallow the one release that ends that wake gesture.
static bool wakePowerReleasePending = false;
// Fonts
EpdFont notosans14RegularFont(¬osans_14_regular);
EpdFont notosans14BoldFont(¬osans_14_bold);
EpdFont notosans14ItalicFont(¬osans_14_italic);
EpdFont notosans14BoldItalicFont(¬osans_14_bolditalic);
EpdFontFamily notosans14FontFamily(¬osans14RegularFont, ¬osans14BoldFont, ¬osans14ItalicFont,
¬osans14BoldItalicFont);
#ifndef OMIT_FONTS
EpdFont notosans12RegularFont(¬osans_12_regular);
EpdFont notosans12BoldFont(¬osans_12_bold);
EpdFont notosans12ItalicFont(¬osans_12_italic);
EpdFont notosans12BoldItalicFont(¬osans_12_bolditalic);
EpdFontFamily notosans12FontFamily(¬osans12RegularFont, ¬osans12BoldFont, ¬osans12ItalicFont,
¬osans12BoldItalicFont);
EpdFont notosans16RegularFont(¬osans_16_regular);
EpdFont notosans16BoldFont(¬osans_16_bold);
EpdFont notosans16ItalicFont(¬osans_16_italic);
EpdFont notosans16BoldItalicFont(¬osans_16_bolditalic);
EpdFontFamily notosans16FontFamily(¬osans16RegularFont, ¬osans16BoldFont, ¬osans16ItalicFont,
¬osans16BoldItalicFont);
EpdFont notosans18RegularFont(¬osans_18_regular);
EpdFont notosans18BoldFont(¬osans_18_bold);
EpdFont notosans18ItalicFont(¬osans_18_italic);
EpdFont notosans18BoldItalicFont(¬osans_18_bolditalic);
EpdFontFamily notosans18FontFamily(¬osans18RegularFont, ¬osans18BoldFont, ¬osans18ItalicFont,
¬osans18BoldItalicFont);
#endif // OMIT_FONTS
EpdFont smallFont(¬osans_8_regular);
EpdFontFamily smallFontFamily(&smallFont);
EpdFont ui10RegularFont(&ubuntu_10_regular);
EpdFont ui10BoldFont(&ubuntu_10_bold);
EpdFontFamily ui10FontFamily(&ui10RegularFont, &ui10BoldFont);
EpdFont ui12RegularFont(&ubuntu_12_regular);
EpdFont ui12BoldFont(&ubuntu_12_bold);
EpdFontFamily ui12FontFamily(&ui12RegularFont, &ui12BoldFont);
// Definitions for SilentRestart.h. RTC_NOINIT survives ESP.restart() but not power loss.
RTC_NOINIT_ATTR uint32_t silentRebootMagic;
RTC_NOINIT_ATTR uint32_t silentRebootTarget;
RTC_NOINIT_ATTR uint32_t silentRebootPayload;
constexpr uint32_t SILENT_REBOOT_MAGIC = 0xC1EAB007;
constexpr uint32_t SILENT_REBOOT_TARGET_HOME = 0;
constexpr uint32_t SILENT_REBOOT_TARGET_READER = 1;
constexpr uint32_t SILENT_REBOOT_TARGET_SETTINGS = 2;
constexpr uint32_t SILENT_REBOOT_TARGET_JOIN_NETWORK = 3;
constexpr uint32_t SILENT_REBOOT_TARGET_MAX = SILENT_REBOOT_TARGET_JOIN_NETWORK;
constexpr uint32_t SILENT_REBOOT_LIGHT_ON = 1U << 0;
// How the device is coming back to life, resolved once at boot. Both resume
// flows suppress the splash and leave the panel holding its pre-boot frame; a
// plain boot shows the splash. See setup() for the resolution.
enum class BootResume : uint8_t {
Splash, // cold boot, flash, panic, or plain reboot
Silent, // heap-defrag ESP.restart() (RTC flag; lost on power loss)
SplashlessWake, // wake from deep sleep with the splash suppressed by the SD flag
};
// Latched true once enterDeepSleep() commits to sleeping, before it tears down
// the current activity. WiFi activities call silentRestart() in onExit() to
// clear heap fragmentation on the way out, but deep sleep is a full chip reset
// on wake and already clears the heap, so rebooting here would just power the
// device back up against the user's sleep gesture. Never cleared:
// startDeepSleep() does not return, so a set latch only ends at the wakeup reset.
static bool deepSleepInProgress = false;
// A silent restart is internal maintenance, so the light must come back exactly
// as the user left it. SETTINGS.frontlightOn is the saved preference and
// legitimately diverges from the live state (a wake with Restore Light on Wake
// off leaves the light off while the saved "was on" preference is kept), so
// carry the live state across the reboot instead of re-deriving it from
// settings. Cleared with the magic in setup().
static void armSilentReboot(const uint32_t target) {
silentRebootTarget = target;
silentRebootPayload = Frontlight.isOn() ? SILENT_REBOOT_LIGHT_ON : 0;
silentRebootMagic = SILENT_REBOOT_MAGIC;
}
// Returns instead of rebooting when sleep supersedes the reboot; callers keep
// running in that case.
static void silentRestartTo(const uint32_t target, const char* targetName) {
if (deepSleepInProgress) return; // sleeping supersedes the heap-defrag reboot
armSilentReboot(target);
LOG_DBG("MAIN", "Silent restart (target=%s)", targetName);
// E-ink retains the previous frame until the target's first paint lands
// (~2-3s). Without an overlay, users don't see the reboot and fire input
// through to the new activity. On Home, Select on the default
// selectorIndex=0 opens the most-recent book, looking like a trampoline back
// to the reader they just exited.
GUI.drawPopup(renderer, tr(STR_LOADING_POPUP));
delay(50);
ESP.restart();
}
void silentRestart() { silentRestartTo(SILENT_REBOOT_TARGET_HOME, "home"); }
void silentRestartToReader() { silentRestartTo(SILENT_REBOOT_TARGET_READER, "reader"); }
void silentRestartToSettings() { silentRestartTo(SILENT_REBOOT_TARGET_SETTINGS, "settings"); }
void silentRestartToJoinNetwork() {
if (deepSleepInProgress) return;
#if FREEINK_CAP_TOUCH
// A software reset would cycle touch/frontlight rails; those boards proceed
// into Join Network without the fresh-heap reboot (return, don't stop WiFi —
// this runs on the way *in*, unlike the exit-time silentRestart()).
if (BoardConfig::hasTouch()) return;
#endif
armSilentReboot(SILENT_REBOOT_TARGET_JOIN_NETWORK);
LOG_DBG("MAIN", "Silent restart (target=join-network)");
GUI.drawPopup(renderer, tr(STR_LOADING_POPUP));
delay(50);
ESP.restart();
}
void restartToHomeAfterStorageHandoff() {
if (deepSleepInProgress) return; // sleeping supersedes the storage handoff reboot
armSilentReboot(SILENT_REBOOT_TARGET_HOME);
LOG_DBG("MAIN", "Restart after storage handoff (target=home)");
GUI.drawPopup(renderer, tr(STR_LOADING_POPUP));
delay(50);
handoffUsbOtgToSerialJtag();
ESP.restart();
}
void toggleFrontlight() {
if (!Frontlight.present()) return;
const bool lightOn = !Frontlight.isOn();
Frontlight.setOn(lightOn);
SETTINGS.frontlightOn = lightOn ? 1 : 0;
SETTINGS.saveToFile();
LOG_INF("LIGHT", "Frontlight toggled %s", lightOn ? "on" : "off");
}
bool handleX4ProFrontlightDoubleClick() {
if (!BoardConfig::isX4Pro() || !SETTINGS.doubleClickPwrLight || !gpio.wasReleased(HalGPIO::BTN_POWER)) {
return false;
}
const unsigned long now = millis();
if (gpio.getPowerButtonHeldTime() > X4PRO_POWER_CLICK_MAX_HOLD_MS) {
lastX4ProPowerClickAt = 0;
return false;
}
if (lastX4ProPowerClickAt == 0 || now - lastX4ProPowerClickAt > X4PRO_POWER_DOUBLE_CLICK_MS) {
lastX4ProPowerClickAt = now;
return false;
}
lastX4ProPowerClickAt = 0;
toggleFrontlight();
return true;
}
// Bluetooth page turner (lib/BlePageTurner): what the module may ask of this firmware. The module
// owns the radio; loop() tells it what is on screen, and the screen changes and sleep ask it to stop.
namespace pageturner {
std::atomic<bool> holdsCpu{false};
bleturner::Heap heap() {
const auto h = HalMemory::getInternalHeap();
return {h.freeBytes, h.largestBlockBytes};
}
// Runs on the radio's start task. Only TRIES the render lock: the render task can hold it through a
// chapter build that is waiting for this very radio.
bool releaseCaches() {
RenderLock lock(RenderLock::Mode::Try);
if (!lock.ownsLock()) return false;
fontCacheManager.releaseSdFontCaches();
return true;
}
bool deliver(const bleturner::Action action) {
switch (action) {
case bleturner::Action::NextPage:
return activityManager.remoteTurn(true, false);
case bleturner::Action::PrevPage:
return activityManager.remoteTurn(false, false);
case bleturner::Action::NextChapter:
return activityManager.remoteTurn(true, true);
case bleturner::Action::PrevChapter:
return activityManager.remoteTurn(false, true);
case bleturner::Action::Confirm:
return activityManager.remoteClick(RemoteButton::Confirm);
case bleturner::Action::Back:
return activityManager.remoteClick(RemoteButton::Back);
case bleturner::Action::ReaderMenu:
return activityManager.remoteShortcut(true);
case bleturner::Action::SaveQuote:
return activityManager.remoteShortcut(false);
case bleturner::Action::None:
return false;
}
return false;
}
bool yieldForRadio() { return true; } // the reader keeps no parser alive between pages
bool fileTransferActive() { return false; } // file transfer is a screen of its own: the radio is off there
void restartIntoBook() { silentRestartToReader(); }
// The radio needs a steady clock while it is up or changing state.
void holdFullSpeed(const bool hold) {
holdsCpu.store(hold);
if (hold) powerManager.setPowerSaving(false);
}
void log(const bool error, const char* format, va_list args) {
#ifdef ENABLE_SERIAL_LOG
if (!error && LOG_LEVEL < 1) return;
char line[160];
vsnprintf(line, sizeof(line), format, args);
logPrintf(error ? "ERR" : "INF", "BLE", "%s", line);
#else
(void)error;
(void)format;
(void)args;
#endif
}
const bleturner::Host host{heap, releaseCaches, deliver, yieldForRadio, fileTransferActive, restartIntoBook,
holdFullSpeed, log, nullptr};
} // namespace pageturner
constexpr char SLEEP_FRAME_FILE[] = "/.crosspoint/sleep_frame.bin";
static void saveSleepFrameBuffer() {
HalFile file;
if (!Storage.openFileForWrite("SLP", SLEEP_FRAME_FILE, file)) return;
file.write(renderer.getFrameBuffer(), renderer.getBufferSize());
file.close();
}
static bool loadSleepFrameBuffer() {
HalFile file;
if (!Storage.openFileForRead("SLP", SLEEP_FRAME_FILE, file)) return false;
const size_t bufferSize = display.getBufferSize();
const size_t bytesRead = file.read(display.getFrameBuffer(), bufferSize);
file.close();
if (bytesRead != bufferSize) {
Storage.remove(SLEEP_FRAME_FILE);
return false;
}
Storage.remove(SLEEP_FRAME_FILE);
return true;
}
// Plugin-event delivery on the way into deep sleep. sleep.enter is delivered
// now — over the live connection, or by bringing WiFi up when a plugin
// subscribes (e.g. fetching a fresh /sleep.bmp so THIS sleep shows it — the
// drain runs before goToSleep() renders the sleep screen). The connect path
// is bounded (join deadline + drain event budget), skipped on low battery,
// and sleep is never blocked on the network: a failed join or delivery just
// sleeps with the previous image and the queued events retry on the next
// drain (at-least-once). The caller's WiFi shutdown tears the radio down
// either way. Deferrable events already queued (reader.exit) ride along in
// the same drain.
static void deliverSleepPluginEvents(const bool allowNetwork) {
// Activity-owned state must be queued before sleep.enter and before this
// same-sleep drain. The hook is idempotent with ordinary activity teardown.
activityManager.prepareForSleep();
// Sleeping straight out of a book is the common flow, but the reader's own
// reader.exit only fires later, inside goToSleep() — after this drain. Carry
// the book and progress on sleep.enter itself so a sync handler bound to it
// pushes current progress on THIS connection, not the next one.
pluginevents::Var vars[2];
size_t varCount = 0;
char percent[8];
const ScreenshotInfo info = activityManager.getScreenshotInfo();
if (info.readerType != ScreenshotInfo::ReaderType::None && !APP_STATE.openEpubPath.empty()) {
snprintf(percent, sizeof(percent), "%d", info.progressPercent);
vars[varCount++] = {"book", APP_STATE.openEpubPath.c_str()};
vars[varCount++] = {"percent", percent};
}
pluginevents::emit(pluginevents::Event::SleepEnter, vars, varCount);
if (!allowNetwork) return;
if (WiFi.status() == WL_CONNECTED) {
pluginevents::drain(&renderer);
return;
}
// Any connect-flagged queued event justifies the join, not only
// sleep.enter: reader.session is queued while reading and delivered on this
// same sleep, and a progress-sync plugin usually subscribes to it alone.
if (!pluginevents::wantsConnectAny()) return;
if (powerManager.getBatteryPercentage() < 20) return;
const auto cred = WIFI_STORE.findCredential(WIFI_STORE.getLastConnectedSsid());
if (!cred) return;
GUI.drawPopup(renderer, tr(STR_LOADING_POPUP));
WiFi.mode(WIFI_STA);
WiFi.begin(cred->ssid.c_str(), cred->password.c_str());
const unsigned long joinDeadline = millis() + 10000;
while (WiFi.status() != WL_CONNECTED && millis() < joinDeadline) {
delay(100);
}
if (WiFi.status() == WL_CONNECTED) {
trustedtime::startSync(); // snap the clock floor while the network is up
pluginevents::drain(&renderer);
} else {
LOG_DBG("MAIN", "Sleep-event WiFi join timed out; deferring delivery");
}
}
// Enter deep sleep mode
void enterDeepSleep(bool fromTimeout = false) {
HalPowerManager::Lock powerLock; // Ensure we are at normal CPU frequency for sleep preparation
APP_STATE.lastSleepFromReader = activityManager.isReaderActivity();
// Sleep may end in a power-off (battery death, latch); persist the clock
// floor now so a later cold boot resumes from it.
trustedtime::note();
// Stop Bluetooth before plugin delivery can start WiFi; a timeout defers delivery.
deepSleepInProgress = true;
const bool bluetoothStopped = bleturner::beforeSleep(2000);
if (!bluetoothStopped) LOG_ERR("SLP", "Bluetooth did not stop; deferring sleep-event delivery");
deliverSleepPluginEvents(bluetoothStopped);
const bool isQuickResumeSleep =
SETTINGS.sleepScreen == CrossPointSettings::SLEEP_SCREEN_MODE::QUICK_RESUME ||
(fromTimeout &&
SETTINGS.quickResumeSleepScreen == CrossPointSettings::QUICK_RESUME_SLEEP_SCREEN::QUICK_RESUME_AFTER_TIMEOUT);
// Every sleep mode leaves a complete retained frame on the e-ink panel. Keep
// it visible until the first useful reader or home paint replaces it.
APP_STATE.showBootScreen = false;
APP_STATE.saveToFile();
activityManager.goToSleep(fromTimeout);
if (isQuickResumeSleep) {
saveSleepFrameBuffer();
} else if (Storage.exists(SLEEP_FRAME_FILE)) {
// A stale Quick Resume frame must not replace the selected sleep screen during wake.
Storage.remove(SLEEP_FRAME_FILE);
}
// Tear down WiFi so the modem power domain isn't held alive across deep sleep.
// Wake from deep sleep is effectively a chip reset, so no state needs to survive.
if (WiFi.getMode() != WIFI_MODE_NULL) {
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
halTiltSensor.deepSleep();
display.deepSleep();
Storage.prepareForDeepSleep();
LOG_DBG("MAIN", "Entering deep sleep");
powerManager.startDeepSleep(gpio);
}
void setupDisplayAndFonts(bool seamless = false) {
#if !FREEINK_MCU_C3
// C3 resolves its controller in HalGPIO::begin() before SPI claims the
// display pins. X4 Pro skips that C3-only path, so probe here before
// display.begin() selects and initializes its panel driver.
static bool controllerResolved = false;
if (!controllerResolved) {
controllerResolved = true;
if (freeink::applyXteinkDisplayController()) {
LOG_DBG("MAIN", "Panel controller: UltraChip UC81xx variant detected");
}
}
#endif
display.begin(seamless);
renderer.begin();
activityManager.begin();
LOG_DBG("MAIN", "Display initialized");
// Initialize font decompressor for compressed reader fonts
if (!fontDecompressor.init()) {
LOG_ERR("MAIN", "Font decompressor init failed");
}
fontCacheManager.setFontDecompressor(&fontDecompressor);
renderer.setFontCacheManager(&fontCacheManager);
renderer.insertFont(NOTOSANS_14_FONT_ID, notosans14FontFamily);
#ifndef OMIT_FONTS
renderer.insertFont(NOTOSANS_12_FONT_ID, notosans12FontFamily);
renderer.insertFont(NOTOSANS_16_FONT_ID, notosans16FontFamily);
renderer.insertFont(NOTOSANS_18_FONT_ID, notosans18FontFamily);
#endif // OMIT_FONTS
renderer.insertFont(UI_10_FONT_ID, ui10FontFamily);
renderer.insertFont(UI_12_FONT_ID, ui12FontFamily);
renderer.insertFont(SMALL_FONT_ID, smallFontFamily);
// Discover and load SD card fonts
sdFontSystem.begin(renderer);
LOG_DBG("MAIN", "Fonts setup");
}
void setup() {
BoardConfig::holdPowerRails();
#ifdef ENABLE_SERIAL_LOG
#ifdef CROSSPOINT_WAIT_FOR_USB_SERIAL
// Development builds preserve reliable early CDC logs; release builds let
// enumeration proceed asynchronously so users do not pay this startup cost.
delay(250);
#endif
Serial.begin(115200);
#if LOG_SERIAL_HAS_TX_TIMEOUT
logSerial.setTxTimeoutMs(1); // This is a load-bearing 1. Do not modify.
#endif
#endif
HalSystem::begin();
// checkPanic() clears the watchdog capture marker after a successful SD
// dump, so retain the boot classification for the later activity route.
const bool rebootedFromPanic = HalSystem::isRebootFromPanic();
// Read-and-clear so a panic later in setup() doesn't loop into silent reboot.
// Bound the target range too — RTC_NOINIT memory is uninitialized on cold boot.
const bool isSilentReboot = (silentRebootMagic == SILENT_REBOOT_MAGIC);
const uint32_t snapshotTarget =
(isSilentReboot && silentRebootTarget <= SILENT_REBOOT_TARGET_MAX) ? silentRebootTarget : 0;
const bool silentRebootLightOn = isSilentReboot && (silentRebootPayload & SILENT_REBOOT_LIGHT_ON) != 0;
silentRebootMagic = 0;
silentRebootTarget = 0;
silentRebootPayload = 0;
gpio.begin();
powerManager.begin();
// Board TX-power ceiling. It can only be set once WiFi has started, so it is
// applied on every STA/AP start rather than at each place that brings WiFi up.
if (BoardConfig::ACTIVE.wifiMaxTxPower != 0) {
const auto applyTxCap = [](arduino_event_id_t, arduino_event_info_t) {
const esp_err_t err = esp_wifi_set_max_tx_power(static_cast<int8_t>(BoardConfig::ACTIVE.wifiMaxTxPower));
if (err != ESP_OK) LOG_ERR("WIFI", "TX power cap failed: %d", err);
};
WiFi.onEvent(applyTxCap, ARDUINO_EVENT_WIFI_STA_START);
WiFi.onEvent(applyTxCap, ARDUINO_EVENT_WIFI_AP_START);
}
const auto wakeupReason = gpio.getWakeupReason();
// Sample the wake hold now — a click wake is released within milliseconds of
// boot — but defer the sleep-or-boot decision until SETTINGS is loaded below:
// click-to-wake is a setting, and an X4 battery power-off cuts all power, so
// only SD state survives to the next boot.
// The Metalio boots after the button is released, so it skips the check.
const bool wakeHoldVerified = wakeupReason != HalGPIO::WakeupReason::PowerButton || BoardConfig::isMetalioEInk4() ||
gpio.verifyPowerButtonWakeup();
// X4 Pro and X4 Classic both map BTN_UP to GPIO0 — an ESP32-S3 boot strap — so
// gate recovery on the non-strap Down key (GPIO7) to avoid a stuck-in-recovery loop.
const auto recoveryButton = (BoardConfig::isX4Pro() || BoardConfig::isX4Classic()) ? MappedInputManager::Button::Down
: MappedInputManager::Button::Up;
const bool recoveryFirmwareMode = wakeupReason == HalGPIO::WakeupReason::PowerButton && !BoardConfig::isPaperMono() &&
mappedInputManager.isPressed(recoveryButton);
halTiltSensor.begin();
halClock.begin();
#if FREEINK_DEVICE_X4 || FREEINK_DEVICE_X3
LOG_INF("MAIN", "Hardware detect: %s", gpio.deviceIsX3() ? "X3" : "X4");
#else
LOG_INF("MAIN", "Device: %s", BoardConfig::ACTIVE.name);
#endif
// SD Card Initialization
// We need 6 open files concurrently when parsing a new chapter
if (!Storage.begin()) {
LOG_ERR("MAIN", "SD card initialization failed");
setupDisplayAndFonts(isSilentReboot);
activityManager.goToFullScreenMessage("SD card error", EpdFontFamily::BOLD);
return;
}
HalSystem::checkPanic();
APP_STATE.loadFromFile();
const bool isSleepWake = wakeupReason == HalGPIO::WakeupReason::PowerButton;
const bool isPersistedSleepWake = isSleepWake && !APP_STATE.showBootScreen;
if (recoveryFirmwareMode) {
LOG_INF("MAIN", "Recovery firmware mode (%s + POWER held at boot)",
(BoardConfig::isX4Pro() || BoardConfig::isX4Classic()) ? "DOWN" : "UP");
}
// Touch boards default the reader menu to the toolbar overlay instead of the
// full-screen list. Seeded before the load: fromJson() falls back to the
// in-memory value only when the file carries no readerMenuStyle key, so a
// user's saved choice (either style) still wins.
if (gpio.hasTouch()) {
SETTINGS.readerMenuStyle = CrossPointSettings::READER_MENU_TOOLBAR;
}
SETTINGS.loadFromFile();
// Push the saved timezone's POSIX rule into the clock (migrating the legacy
// UTC-offset setting on first boot after the update).
timezones::applyToClock();
RECENT_BOOKS.loadFromFile();
I18N.setLanguage(static_cast<Language>(SETTINGS.language));
KOREADER_STORE.loadFromFile();
OPDS_STORE.loadFromFile();
OPDS_TOKENS.loadFromFile();
LCP_PASSPHRASES.loadFromFile();
UITheme::getInstance().reload();
ButtonNavigator::setMappedInputManager(mappedInputManager);
pluginevents::refreshSubscriptions();
// Seed the system clock from the battery-backed RTC: on RTC boards it is the
// only real clock across power-off, and time() is what plugin event
// timestamps, TLS and file dates read. Placed before trustedtime::init(),
// whose floor restore vetoes a lagging RTC and restores the floor instead.
struct tm rtcLocal;
if (halClock.localTime(rtcLocal)) {
// localTime() renders the RTC's UTC epoch under the TZ rule applied above,
// so mktime() inverts it exactly (tm_isdst included).
trustedtime::adopt(static_cast<int64_t>(mktime(&rtcLocal)));
LOG_INF("CLK", "RTC clock read: %04d-%02d-%02d %02d:%02d", rtcLocal.tm_year + 1900, rtcLocal.tm_mon + 1,
rtcLocal.tm_mday, rtcLocal.tm_hour, rtcLocal.tm_min);
}
// Restore the monotonic clock floor before anything reads time() (event
// timestamps, loan-expiry checks).
trustedtime::init();
bleturner::begin(pageturner::host, SETTINGS.ble);
// Brightness and warmth are always restored. A normal wake starts with the
// light off unless Restore Light on Wake is enabled; silent maintenance
// reboots replay the live state captured at restart, so they neither go dark
// nor light up against the user's wake preference.
const bool restoreLightOn =
isSilentReboot ? silentRebootLightOn : (SETTINGS.frontlightOn != 0 && SETTINGS.frontlightRestoreOnWake != 0);
Frontlight.begin(SETTINGS.frontlightBrightness, SETTINGS.frontlightWarmth, restoreLightOn);
switch (wakeupReason) {
case HalGPIO::WakeupReason::PowerButton:
// With Short Power Button Press = Sleep, a single click wakes on any
// device; otherwise the button must still be held (ghost-wake debounce).
if (!wakeHoldVerified && SETTINGS.shortPwrBtn != CrossPointSettings::SHORT_PWRBTN::SLEEP) {
LOG_DBG("MAIN", "Power-button wake not held through verification, sleeping");
Storage.prepareForDeepSleep();
powerManager.startDeepSleep(gpio);
}
wakePowerReleasePending = true;
break;
case HalGPIO::WakeupReason::AfterUSBPower:
// Most devices return to sleep after a USB-powered cold boot.
LOG_DBG("MAIN", "Wakeup reason: After USB Power");
#if FREEINK_DEVICE_X4PRO || FREEINK_DEVICE_X4CLASSIC || FREEINK_DEVICE_PAPERMONO || FREEINK_DEVICE_EEGO_A4 || \
FREEINK_DEVICE_METALIO_EINK4
// X4 Pro must stay awake so USB Serial/JTAG remains available after leaving
// USB Drive and reconnecting the cable. Paper Mono has no armable GPIO wake
// (its button is behind the PMIC). Metalio also needs native USB available
// after a USB-powered boot. EEGO A4's post-flash reset reads as
// POWERON (native-USB), so a flash would otherwise be misclassified as a
// USB-power cold boot and sleep. Sleeping any of these here would strand
// the device in a USB-replug boot loop (or sleep right after a flash).
break;
#else
Storage.prepareForDeepSleep();
powerManager.startDeepSleep(gpio);
break;
#endif
case HalGPIO::WakeupReason::AfterFlash:
// After flashing, just proceed to boot
case HalGPIO::WakeupReason::Other:
default:
break;
}
LOG_DBG("MAIN", "Starting CrossPoint version " CROSSPOINT_VERSION);
// Resolve the single boot-presentation decision. Skipping the splash also
// skips the panel-clearing pass and the X3 initial-full-sync arming (see
// HalDisplay::begin), so the first paint is FAST_REFRESH (~500ms) over the
// retained frame and input dispatches against a visible UI.
// Only a verified deep-sleep wake may use the one-shot persisted flag.
// Otherwise a stale flag could suppress the splash on a cold boot.
const BootResume resume = isSilentReboot ? BootResume::Silent
: isPersistedSleepWake ? BootResume::SplashlessWake
: BootResume::Splash;
bool allowFastInitialReaderRefresh = false;
bool needsWakeRefresh = false;
setupDisplayAndFonts(resume != BootResume::Splash);
switch (resume) {
case BootResume::Silent:
// Splash skipped: the routing block below picks the target activity; the
// panel keeps showing the pre-reboot popup until that first paint lands.
break;
case BootResume::SplashlessWake:
// One-shot flag: re-arm the splash for the next ordinary boot. Save
// before any painting so a hang in the blocking paint path can't strand
// us in a splashless-with-no-frame loop on the next boot.
APP_STATE.showBootScreen = true;
APP_STATE.saveToFile();
if (Storage.exists(SLEEP_FRAME_FILE) && loadSleepFrameBuffer()) {
if (gpio.deviceIsX3()) {
// begin() clears the X3 controller RAM, so restore the saved frame as
// the baseline for the first reader paint without refreshing the panel.
renderer.cleanupGrayscaleWithFrameBuffer();
allowFastInitialReaderRefresh = true;
}
} else {
// Clean the retained sleep image as part of the first Home paint.
needsWakeRefresh = true;
}
break;
case BootResume::Splash:
activityManager.goToBoot();
break;
}
// Output polarity is resolved per render by ActivityManager (night mode
// inverts only the reading surfaces), so nothing to restore here.
if (recoveryFirmwareMode) {
// Skip normal home/reader routing: jump straight into the SD firmware picker.
activityManager.replaceActivity(
std::make_unique<SdFirmwareUpdateActivity>(renderer, mappedInputManager, /*recoveryMode=*/true));
} else if (rebootedFromPanic) {
// If we rebooted from a panic, go to crash report screen to show the panic info
activityManager.goToCrashReport();
} else if (resume == BootResume::Silent && snapshotTarget == SILENT_REBOOT_TARGET_READER &&
!APP_STATE.openEpubPath.empty()) {
activityManager.goToReader(APP_STATE.openEpubPath);
} else if (resume == BootResume::Silent && snapshotTarget == SILENT_REBOOT_TARGET_JOIN_NETWORK) {
// Rebooted on the way *into* File Transfer > Join Network for a fresh heap;
// resume that flow directly instead of landing on home.
activityManager.goToJoinNetwork();
} else if (resume == BootResume::Silent && snapshotTarget == SILENT_REBOOT_TARGET_SETTINGS) {
// Back out of the WiFi rows and the user is where they left off, not on Home.
activityManager.goToSettings(SettingsSection::Network);
} else if (resume == BootResume::Silent) {
// target == home (or reader with no open book): land on home — don't fall
// through to the sleep-wake "resume reader" logic, which fires on stale
// openEpubPath + lastSleepFromReader from a prior session.
activityManager.goHome();
} else if (APP_STATE.openEpubPath.empty() || !APP_STATE.lastSleepFromReader ||
mappedInputManager.isPressed(MappedInputManager::Button::Back) || APP_STATE.readerActivityLoadCount > 0) {
// Boot to home screen if no book is open, last sleep was not from reader, back button is held, or reader activity
// crashed (indicated by readerActivityLoadCount > 0)
activityManager.goHome(HomeMenuItem::NONE, needsWakeRefresh);
} else {
// Clear app state to avoid getting into a boot loop if the epub doesn't load
const auto path = APP_STATE.openEpubPath;
APP_STATE.openEpubPath = "";
APP_STATE.readerActivityLoadCount++;
APP_STATE.saveToFile();
activityManager.goToReader(path, allowFastInitialReaderRefresh);
}
if (resume == BootResume::Silent) {
// Block until the first paint physically completes. refreshDisplay()
// waits on the panel BUSY pin so when this returns the user can see the
// new activity. Without the wait, an edge captured by gpio.update()
// during boot dispatches against an invisible Home and the default
// selectorIndex=0 opens the most-recent book.
activityManager.requestUpdateAndWait();
// Absorb any button held at this point into currentState as a non-edge:
// two gpio.update() calls separated by > InputManager's 5ms debounce
// transition the held bit through lastDebounceTime into currentState
// without setting pressedEvents, so the first loop()'s own gpio.update()
// sees state == currentState and emits nothing.
gpio.update();
delay(10);
gpio.update();
}
allowSleepAt = millis() + 2000;
}
void loop() {
static unsigned long maxLoopDuration = 0;
const unsigned long loopStartTime = millis();
static unsigned long lastMemPrint = 0;
gpio.setSharedConfirmPowerShortPressEmitsPower(SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::SLEEP);
mappedInputManager.update();
// Bluetooth page turner, before the USB drive's early return: a card handed to USB stops the radio
// before anything else.
bleturner::Scene scene{};
// Home counts only for builds whose radio may start there (the S3 profile, RadioPolicy.h).
const bool homeShown = activityManager.isForegroundHomeShown();
const bool remoteContext = activityManager.isRemoteReaderContext();
scene.where = remoteContext ? bleturner::Where::Reader
: homeShown ? bleturner::Where::Home
: bleturner::Where::Elsewhere;
scene.visit = activityManager.visit();
scene.pageShown = homeShown || remoteContext;
scene.storageBusy = activityManager.requiresExclusiveStorageLoop();
scene.wifiOn = WiFi.getMode() != WIFI_MODE_NULL;
const bool remoteActed = bleturner::tick(scene);
if (activityManager.requiresExclusiveStorageLoop()) {
// USB Drive handed the raw SD card to the host. Do not run screenshots,
// sleep, shortcuts, or normal navigation while its filesystem is detached.
activityManager.loop();
if (activityManager.preventAutoSleep()) {
powerManager.setPowerSaving(false);
delay(10);
} else {
// No host is active, so a slower loop is safe. The activity itself times
// out the raw-storage handoff rather than entering deep sleep detached.
powerManager.setPowerSaving(true);
delay(50);
}
return;
}
halTiltSensor.update(SETTINGS.tiltPageTurn, SETTINGS.orientation, activityManager.isReaderActivity());
// Under the render lock, so a step never overlaps the themes' gauge reads.
static bool gaugeCapacityPending = true;
if (gaugeCapacityPending) {
RenderLock lock(RenderLock::Mode::Try);
if (lock.ownsLock()) gaugeCapacityPending = BatteryMonitor::loadDesignCapacity();
}
renderer.setFadingFix(SETTINGS.fadingFix);
// The ROM console does not depend on Arduino USB CDC's connection state.
if ((Serial || FREEINK_LOG_TRANSPORT == FREEINK_LOG_TRANSPORT_ROM_PRINTF) && millis() - lastMemPrint >= 10000) {
const auto heap = HalMemory::getInternalHeap();
LOG_INF("MEM", "Free: %zu bytes, Total: %zu bytes, Min Free: %zu bytes, MaxAlloc: %zu bytes", heap.freeBytes,
heap.totalBytes, heap.minFreeBytes, heap.largestBlockBytes);
#ifdef BOARD_HAS_PSRAM
const auto psram = HalMemory::getPsramHeap();
LOG_INF("MEM", "PSRAM: Free: %zu bytes, Total: %zu bytes, Min Free: %zu bytes, MaxAlloc: %zu bytes",
psram.freeBytes, psram.totalBytes, psram.minFreeBytes, psram.largestBlockBytes);
#endif
lastMemPrint = millis();
}
// Handle incoming serial commands,
// nb: we use logSerial from logging to avoid deprecation warnings
if (logSerial.available() > 0) {
String line = logSerial.readStringUntil('\n');
if (line.startsWith("CMD:")) {
String cmd = line.substring(4);
cmd.trim();
if (cmd == "SCREENSHOT") {
const uint32_t bufferSize = display.getBufferSize();
logSerial.printf("SCREENSHOT_START:%d\n", bufferSize);
uint8_t* buf = display.getFrameBuffer();
logSerial.write(buf, bufferSize);
logSerial.printf("SCREENSHOT_END\n");
}
}
}
// Check for any user activity (button press or release) or active background work
static unsigned long lastActivityTime = millis();
if (gpio.wasAnyPressed() || gpio.wasAnyReleased() || gpio.wasTouchActivity() || halTiltSensor.hadActivity() ||
remoteActed || activityManager.preventAutoSleep()) {
lastActivityTime = millis(); // Reset inactivity timer
powerManager.setPowerSaving(false); // Restore normal CPU frequency on user activity
}
// Let wake continue as soon as its hold has been verified. The release can
// arrive after setup, so consume that one input frame rather than making it
// a page turn, refresh, or other short power-button action.
if (wakePowerReleasePending && !gpio.isPressed(HalGPIO::BTN_POWER)) {
wakePowerReleasePending = false;
return;
}
static bool screenshotButtonsReleased = true;
static bool screenshotComboActive = false;
if (gpio.isPressed(HalGPIO::BTN_POWER) && gpio.isPressed(HalGPIO::BTN_DOWN)) {
screenshotComboActive = true;
if (screenshotButtonsReleased) {
screenshotButtonsReleased = false;
{
RenderLock lock;
ScreenshotUtil::takeScreenshot(renderer);
}
}
return;
}
if (screenshotComboActive) {
if (gpio.isPressed(HalGPIO::BTN_POWER)) return;
if (gpio.wasReleased(HalGPIO::BTN_POWER)) {
screenshotButtonsReleased = true;
screenshotComboActive = false;
return;
}
screenshotButtonsReleased = true;
screenshotComboActive = false;
}
// Consume the second X4 Pro power-button release so it does not also run a
// configured short-power action after toggling the frontlight.
if (handleX4ProFrontlightDoubleClick()) {
return;
}
const bool x4ProDoubleClickPwrLight = BoardConfig::isX4Pro() && SETTINGS.doubleClickPwrLight;
#if FREEINK_CAP_TOUCH
// A single X4 Pro power click becomes Confirm only after the frontlight
// double-click window expires without a second click.
mappedInputManager.setPowerConfirmClickFrame(false);
if (SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::PWR_CONFIRM && x4ProDoubleClickPwrLight) {
if (lastX4ProPowerClickAt != 0 && millis() - lastX4ProPowerClickAt > X4PRO_POWER_DOUBLE_CLICK_MS) {
lastX4ProPowerClickAt = 0;
mappedInputManager.setPowerConfirmClickFrame(true);
}
// A release held too long to be a double-click candidate (but still within
// the normal Confirm press duration) never reaches handleX4ProFrontlightDoubleClick's
// click tracking above, so it needs its own Confirm check here.
if (mappedInputManager.wasReleased(MappedInputManager::Button::Power) &&
gpio.getPowerButtonHeldTime() > X4PRO_POWER_CLICK_MAX_HOLD_MS &&
gpio.getPowerButtonHeldTime() <= SETTINGS.getPowerButtonDuration()) {
mappedInputManager.setPowerConfirmClickFrame(true);
}
}
#endif
// Same deferral for SLEEP: getPowerButtonDuration() drops to 10ms so a quick
// tap sleeps the device, which otherwise fires on button-down and never lets
// a second click land. Sleep only once the double-click window has passed.
if (SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::SLEEP && x4ProDoubleClickPwrLight &&
lastX4ProPowerClickAt != 0 && millis() - lastX4ProPowerClickAt > X4PRO_POWER_DOUBLE_CLICK_MS) {
lastX4ProPowerClickAt = 0;
enterDeepSleep();
// This should never be hit as `enterDeepSleep` calls esp_deep_sleep_start
return;
}
const unsigned long sleepTimeoutMs = SETTINGS.getSleepTimeoutMs();
if (sleepTimeoutMs > 0 && millis() - lastActivityTime >= sleepTimeoutMs) {
LOG_DBG("SLP", "Auto-sleep triggered after %lu ms of inactivity", sleepTimeoutMs);
enterDeepSleep(true);
// This should never be hit as `enterDeepSleep` calls esp_deep_sleep_start
return;
}
// A hold that woke the device must be released before it can count as a new
// in-app long press. Otherwise a user who keeps holding after wake would put
// the device straight back to sleep once allowSleepAt expires.
static bool powerReleasedSinceWake = false;
if (!gpio.isPressed(HalGPIO::BTN_POWER)) powerReleasedSinceWake = true;
// On X4 Pro with SLEEP, a press still within the click window is a
// double-click candidate — let it be released and evaluated above instead
// of sleeping on button-down.
const bool x4ProAwaitingClickWindow = x4ProDoubleClickPwrLight &&
SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::SLEEP &&
gpio.getPowerButtonHeldTime() <= X4PRO_POWER_CLICK_MAX_HOLD_MS;
if (!x4ProAwaitingClickWindow && powerReleasedSinceWake && millis() >= allowSleepAt &&
gpio.isPressed(HalGPIO::BTN_POWER) && gpio.getPowerButtonHeldTime() > SETTINGS.getPowerButtonDuration()) {
// If the screenshot combination is potentially being pressed, don't sleep
if (gpio.isPressed(HalGPIO::BTN_DOWN)) {
return;
}
LOG_DBG("MAIN", "Power button held %lums, sleeping", gpio.getPowerButtonHeldTime());
enterDeepSleep();
// This should never be hit as `enterDeepSleep` calls esp_deep_sleep_start
return;
}
#if FREEINK_DEVICE_PAPERMONO
// Paper Mono reports the PMIC power button as a one-tick click, so the held
// path above cannot fire. With the default Ignore action, retain the normal
// power-button meaning and shut down; explicit alternate bindings still win.
if ((SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::SLEEP ||
SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::IGNORE) &&
millis() >= allowSleepAt && mappedInputManager.wasReleased(MappedInputManager::Button::Power)) {
enterDeepSleep();
return;
}
#endif
// Refresh screen when power button is short-pressed with FORCE_REFRESH setting.
if (mappedInputManager.homeButtonAction() == HomeButtonAction::ToggleFrontlight) {
toggleFrontlight();
}
if (mappedInputManager.homeButtonAction() == HomeButtonAction::Refresh ||
(SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::FORCE_REFRESH &&
mappedInputManager.wasReleased(MappedInputManager::Button::Power))) {
LOG_DBG("MAIN", "Manual screen refresh triggered");
if (!activityManager.handleForcedRefresh()) {
RenderLock lock;
renderer.displayBuffer(HalDisplay::HALF_REFRESH);
}
}
// Refresh the battery icon when USB is plugged or unplugged.
// Placed after sleep guards so we never queue a render that won't be processed.
// Not while reading: there a repaint is a full page re-render (visible
// flash, the AA pass re-running, and a frontlight dip under the refresh
// load); the reader's status bar picks the charging state up on the next
// page turn instead.
if (gpio.wasUsbStateChanged() && !activityManager.isReaderActivity()) {
activityManager.requestUpdate();
}
const unsigned long activityStartTime = millis();
activityManager.loop();
const unsigned long activityDuration = millis() - activityStartTime;
const unsigned long loopDuration = millis() - loopStartTime;
if (loopDuration > maxLoopDuration) {
maxLoopDuration = loopDuration;
if (maxLoopDuration > 50) {
LOG_DBG("LOOP", "New max loop duration: %lu ms (activity: %lu ms)", maxLoopDuration, activityDuration);
}
}
bool skipLoopDelay = false;
{
RenderLock lock(RenderLock::Mode::Try);
if (!lock.ownsLock()) {
// Let rendering advance without treating lock contention as idle.
delay(10);
return;
}
skipLoopDelay = activityManager.skipLoopDelay();