#include "SleepActivity.h" #include #include #include #include #include #include "CrossPointSettings.h" #include "CrossPointState.h" #include "fontIds.h" #include "images/CrossLarge.h" #include "util/StringUtils.h" namespace { // Perimeter cache file format: // - 4 bytes: uint32_t file size (for cache invalidation) // - 1 byte: result (0 = white perimeter, 1 = black perimeter) constexpr size_t PERIM_CACHE_SIZE = 5; } // namespace void SleepActivity::onEnter() { Activity::onEnter(); renderPopup("Entering Sleep..."); if (SETTINGS.sleepScreen == CrossPointSettings::SLEEP_SCREEN_MODE::BLANK) { return renderBlankSleepScreen(); } if (SETTINGS.sleepScreen == CrossPointSettings::SLEEP_SCREEN_MODE::CUSTOM) { return renderCustomSleepScreen(); } if (SETTINGS.sleepScreen == CrossPointSettings::SLEEP_SCREEN_MODE::COVER) { return renderCoverSleepScreen(); } renderDefaultSleepScreen(); } void SleepActivity::renderPopup(const char* message) const { const int textWidth = renderer.getTextWidth(UI_12_FONT_ID, message, EpdFontFamily::BOLD); constexpr int margin = 20; const int x = (renderer.getScreenWidth() - textWidth - margin * 2) / 2; constexpr int y = 117; const int w = textWidth + margin * 2; const int h = renderer.getLineHeight(UI_12_FONT_ID) + margin * 2; // renderer.clearScreen(); renderer.fillRect(x - 5, y - 5, w + 10, h + 10, true); renderer.fillRect(x + 5, y + 5, w - 10, h - 10, false); renderer.drawText(UI_12_FONT_ID, x + margin, y + margin, message, true, EpdFontFamily::BOLD); renderer.displayBuffer(); } void SleepActivity::renderCustomSleepScreen() const { // Check if we have a /sleep directory auto dir = SdMan.open("/sleep"); if (dir && dir.isDirectory()) { std::vector files; char name[500]; // collect all valid BMP files for (auto file = dir.openNextFile(); file; file = dir.openNextFile()) { if (file.isDirectory()) { file.close(); continue; } file.getName(name, sizeof(name)); auto filename = std::string(name); if (filename[0] == '.') { file.close(); continue; } if (filename.substr(filename.length() - 4) != ".bmp") { Serial.printf("[%lu] [SLP] Skipping non-.bmp file name: %s\n", millis(), name); file.close(); continue; } Bitmap bitmap(file); if (bitmap.parseHeaders() != BmpReaderError::Ok) { Serial.printf("[%lu] [SLP] Skipping invalid BMP file: %s\n", millis(), name); file.close(); continue; } files.emplace_back(filename); file.close(); } const auto numFiles = files.size(); if (numFiles > 0) { // Generate a random number between 1 and numFiles auto randomFileIndex = random(numFiles); // If we picked the same image as last time, reroll while (numFiles > 1 && randomFileIndex == APP_STATE.lastSleepImage) { randomFileIndex = random(numFiles); } APP_STATE.lastSleepImage = randomFileIndex; APP_STATE.saveToFile(); const auto bmpPath = "/sleep/" + files[randomFileIndex]; FsFile file; if (SdMan.openFileForRead("SLP", bmpPath, file)) { Serial.printf("[%lu] [SLP] Randomly loading: /sleep/%s\n", millis(), files[randomFileIndex].c_str()); delay(100); Bitmap bitmap(file, true); if (bitmap.parseHeaders() == BmpReaderError::Ok) { renderBitmapSleepScreen(bitmap, bmpPath); dir.close(); return; } } } } if (dir) dir.close(); // Look for sleep.bmp on the root of the sd card to determine if we should // render a custom sleep screen instead of the default. FsFile file; const std::string rootSleepPath = "/sleep.bmp"; if (SdMan.openFileForRead("SLP", rootSleepPath, file)) { Bitmap bitmap(file, true); if (bitmap.parseHeaders() == BmpReaderError::Ok) { Serial.printf("[%lu] [SLP] Loading: /sleep.bmp\n", millis()); renderBitmapSleepScreen(bitmap, rootSleepPath); return; } } renderDefaultSleepScreen(); } void SleepActivity::renderDefaultSleepScreen() const { const auto pageWidth = renderer.getScreenWidth(); const auto pageHeight = renderer.getScreenHeight(); renderer.clearScreen(); renderer.drawImage(CrossLarge, (pageWidth + 128) / 2, (pageHeight - 128) / 2, 128, 128); renderer.drawCenteredText(UI_10_FONT_ID, pageHeight / 2 + 70, "CrossPoint", true, EpdFontFamily::BOLD); renderer.drawCenteredText(SMALL_FONT_ID, pageHeight / 2 + 95, "SLEEPING"); // Make sleep screen dark unless light is selected in settings if (SETTINGS.sleepScreen != CrossPointSettings::SLEEP_SCREEN_MODE::LIGHT) { renderer.invertScreen(); } renderer.displayBuffer(EInkDisplay::HALF_REFRESH); } void SleepActivity::renderBitmapSleepScreen(const Bitmap& bitmap, const std::string& bmpPath) const { int x, y; const auto pageWidth = renderer.getScreenWidth(); const auto pageHeight = renderer.getScreenHeight(); float cropX = 0, cropY = 0; int drawWidth = pageWidth; int drawHeight = pageHeight; int fillWidth = pageWidth; // Actual area the image will occupy int fillHeight = pageHeight; Serial.printf("[%lu] [SLP] bitmap %d x %d, screen %d x %d\n", millis(), bitmap.getWidth(), bitmap.getHeight(), pageWidth, pageHeight); const float bitmapRatio = static_cast(bitmap.getWidth()) / static_cast(bitmap.getHeight()); const float screenRatio = static_cast(pageWidth) / static_cast(pageHeight); Serial.printf("[%lu] [SLP] bitmap ratio: %f, screen ratio: %f\n", millis(), bitmapRatio, screenRatio); const auto coverMode = SETTINGS.sleepScreenCoverMode; if (coverMode == CrossPointSettings::SLEEP_SCREEN_COVER_MODE::ACTUAL) { // ACTUAL mode: Show image at actual size, centered (no scaling) x = (pageWidth - bitmap.getWidth()) / 2; y = (pageHeight - bitmap.getHeight()) / 2; // Don't constrain to screen dimensions - drawBitmap will clip drawWidth = 0; drawHeight = 0; fillWidth = bitmap.getWidth(); fillHeight = bitmap.getHeight(); Serial.printf("[%lu] [SLP] ACTUAL mode: centering at %d, %d\n", millis(), x, y); } else if (coverMode == CrossPointSettings::SLEEP_SCREEN_COVER_MODE::CROP) { // CROP mode: Scale to fill screen completely (may crop edges) // Calculate crop values to fill the screen while maintaining aspect ratio if (bitmapRatio > screenRatio) { // Image is wider than screen ratio - crop horizontally cropX = 1.0f - (screenRatio / bitmapRatio); Serial.printf("[%lu] [SLP] CROP mode: cropping x by %f\n", millis(), cropX); } else if (bitmapRatio < screenRatio) { // Image is taller than screen ratio - crop vertically cropY = 1.0f - (bitmapRatio / screenRatio); Serial.printf("[%lu] [SLP] CROP mode: cropping y by %f\n", millis(), cropY); } // After cropping, the image should fill the screen exactly x = 0; y = 0; fillWidth = pageWidth; fillHeight = pageHeight; Serial.printf("[%lu] [SLP] CROP mode: drawing at 0, 0 with crop %f, %f\n", millis(), cropX, cropY); } else { // FIT mode (default): Scale to fit entire image within screen (may have letterboxing) // Calculate the scaled dimensions float scale; if (bitmapRatio > screenRatio) { // Image is wider than screen ratio - fit to width scale = static_cast(pageWidth) / static_cast(bitmap.getWidth()); } else { // Image is taller than screen ratio - fit to height scale = static_cast(pageHeight) / static_cast(bitmap.getHeight()); } fillWidth = static_cast(bitmap.getWidth() * scale); fillHeight = static_cast(bitmap.getHeight() * scale); // Center the scaled image x = (pageWidth - fillWidth) / 2; y = (pageHeight - fillHeight) / 2; Serial.printf("[%lu] [SLP] FIT mode: scale %f, scaled size %d x %d, position %d, %d\n", millis(), scale, fillWidth, fillHeight, x, y); } // Detect perimeter color and clear to matching background const bool isBlackPerimeter = getPerimeterIsBlack(bitmap, bmpPath); const uint8_t clearColor = isBlackPerimeter ? 0x00 : 0xFF; Serial.printf("[%lu] [SLP] drawing to %d x %d\n", millis(), x, y); renderer.clearScreen(clearColor); // If background is black, fill the image area with white first so white pixels render correctly if (isBlackPerimeter) { renderer.fillRect(x, y, fillWidth, fillHeight, false); // false = white } renderer.drawBitmap(bitmap, x, y, drawWidth, drawHeight, cropX, cropY); renderer.displayBuffer(EInkDisplay::HALF_REFRESH); if (bitmap.hasGreyscale()) { bitmap.rewindToData(); renderer.clearScreen(0x00); renderer.setRenderMode(GfxRenderer::GRAYSCALE_LSB); renderer.drawBitmap(bitmap, x, y, drawWidth, drawHeight, cropX, cropY); renderer.copyGrayscaleLsbBuffers(); bitmap.rewindToData(); renderer.clearScreen(0x00); renderer.setRenderMode(GfxRenderer::GRAYSCALE_MSB); renderer.drawBitmap(bitmap, x, y, drawWidth, drawHeight, cropX, cropY); renderer.copyGrayscaleMsbBuffers(); renderer.displayGrayBuffer(); renderer.setRenderMode(GfxRenderer::BW); } } void SleepActivity::renderCoverSleepScreen() const { if (APP_STATE.openEpubPath.empty()) { return renderDefaultSleepScreen(); } std::string coverBmpPath; bool cropped = SETTINGS.sleepScreenCoverMode == CrossPointSettings::SLEEP_SCREEN_COVER_MODE::CROP; // Check if the current book is XTC, TXT, or EPUB if (StringUtils::checkFileExtension(APP_STATE.openEpubPath, ".xtc") || StringUtils::checkFileExtension(APP_STATE.openEpubPath, ".xtch")) { // Handle XTC file Xtc lastXtc(APP_STATE.openEpubPath, "/.crosspoint"); if (!lastXtc.load()) { Serial.println("[SLP] Failed to load last XTC"); return renderDefaultSleepScreen(); } if (!lastXtc.generateCoverBmp()) { Serial.println("[SLP] Failed to generate XTC cover bmp"); return renderDefaultSleepScreen(); } coverBmpPath = lastXtc.getCoverBmpPath(); } else if (StringUtils::checkFileExtension(APP_STATE.openEpubPath, ".txt")) { // Handle TXT file - looks for cover image in the same folder Txt lastTxt(APP_STATE.openEpubPath, "/.crosspoint"); if (!lastTxt.load()) { Serial.println("[SLP] Failed to load last TXT"); return renderDefaultSleepScreen(); } if (!lastTxt.generateCoverBmp()) { Serial.println("[SLP] No cover image found for TXT file"); return renderDefaultSleepScreen(); } coverBmpPath = lastTxt.getCoverBmpPath(); } else if (StringUtils::checkFileExtension(APP_STATE.openEpubPath, ".epub")) { // Handle EPUB file Epub lastEpub(APP_STATE.openEpubPath, "/.crosspoint"); if (!lastEpub.load()) { Serial.println("[SLP] Failed to load last epub"); return renderDefaultSleepScreen(); } if (!lastEpub.generateCoverBmp(cropped)) { Serial.println("[SLP] Failed to generate cover bmp"); return renderDefaultSleepScreen(); } coverBmpPath = lastEpub.getCoverBmpPath(cropped); } else { return renderDefaultSleepScreen(); } FsFile file; if (SdMan.openFileForRead("SLP", coverBmpPath, file)) { Bitmap bitmap(file); if (bitmap.parseHeaders() == BmpReaderError::Ok) { renderBitmapSleepScreen(bitmap, coverBmpPath); return; } } renderDefaultSleepScreen(); } void SleepActivity::renderBlankSleepScreen() const { renderer.clearScreen(); renderer.displayBuffer(EInkDisplay::HALF_REFRESH); } std::string SleepActivity::getPerimeterCachePath(const std::string& bmpPath) { // Convert "/dir/file.bmp" to "/dir/.file.bmp.perim" const size_t lastSlash = bmpPath.find_last_of('/'); if (lastSlash == std::string::npos) { // No directory, just prepend dot return "." + bmpPath + ".perim"; } const std::string dir = bmpPath.substr(0, lastSlash + 1); const std::string filename = bmpPath.substr(lastSlash + 1); return dir + "." + filename + ".perim"; } bool SleepActivity::getPerimeterIsBlack(const Bitmap& bitmap, const std::string& bmpPath) const { const std::string cachePath = getPerimeterCachePath(bmpPath); // Try to read from cache FsFile cacheFile; if (SdMan.openFileForRead("SLP", cachePath, cacheFile)) { uint8_t cacheData[PERIM_CACHE_SIZE]; if (cacheFile.read(cacheData, PERIM_CACHE_SIZE) == PERIM_CACHE_SIZE) { // Extract cached file size const uint32_t cachedSize = static_cast(cacheData[0]) | (static_cast(cacheData[1]) << 8) | (static_cast(cacheData[2]) << 16) | (static_cast(cacheData[3]) << 24); // Get current BMP file size FsFile bmpFile; uint32_t currentSize = 0; if (SdMan.openFileForRead("SLP", bmpPath, bmpFile)) { currentSize = bmpFile.size(); bmpFile.close(); } // Validate cache if (cachedSize == currentSize && currentSize > 0) { const bool result = cacheData[4] != 0; Serial.printf("[%lu] [SLP] Perimeter cache hit for %s: %s\n", millis(), bmpPath.c_str(), result ? "black" : "white"); cacheFile.close(); return result; } Serial.printf("[%lu] [SLP] Perimeter cache invalid (size mismatch: %lu vs %lu)\n", millis(), static_cast(cachedSize), static_cast(currentSize)); } cacheFile.close(); } // Cache miss - calculate perimeter Serial.printf("[%lu] [SLP] Calculating perimeter for %s\n", millis(), bmpPath.c_str()); const bool isBlack = bitmap.detectPerimeterIsBlack(); Serial.printf("[%lu] [SLP] Perimeter detected: %s\n", millis(), isBlack ? "black" : "white"); // Get BMP file size for cache FsFile bmpFile; uint32_t fileSize = 0; if (SdMan.openFileForRead("SLP", bmpPath, bmpFile)) { fileSize = bmpFile.size(); bmpFile.close(); } // Save to cache if (fileSize > 0 && SdMan.openFileForWrite("SLP", cachePath, cacheFile)) { uint8_t cacheData[PERIM_CACHE_SIZE]; cacheData[0] = fileSize & 0xFF; cacheData[1] = (fileSize >> 8) & 0xFF; cacheData[2] = (fileSize >> 16) & 0xFF; cacheData[3] = (fileSize >> 24) & 0xFF; cacheData[4] = isBlack ? 1 : 0; cacheFile.write(cacheData, PERIM_CACHE_SIZE); cacheFile.close(); Serial.printf("[%lu] [SLP] Saved perimeter cache to %s\n", millis(), cachePath.c_str()); } return isBlack; }