Add context menu to filebrowser

This commit is contained in:
jpirnay
2026-05-16 09:21:49 +02:00
parent 1395676674
commit 9bcc7b5e4f
32 changed files with 470 additions and 56 deletions
+197 -38
View File
@@ -3,16 +3,23 @@
#include <Epub.h>
#include <FsHelpers.h>
#include <GfxRenderer.h>
#include <HalDisplay.h>
#include <HalStorage.h>
#include <I18n.h>
#include <Txt.h>
#include <Xtc.h>
#include <algorithm>
#include "../ActivityManager.h"
#include "../ActivityResult.h"
#include "../settings/SdFirmwareUpdateActivity.h"
#include "../util/BmpViewerActivity.h"
#include "../util/ConfirmationActivity.h"
#include "BookInfoActivity.h"
#include "CrossPointSettings.h"
#include "CrossPointState.h"
#include "FileContextMenuActivity.h"
#include "KOReaderCredentialStore.h"
#include "MappedInputManager.h"
#include "components/UITheme.h"
@@ -133,10 +140,12 @@ void FileBrowserActivity::onExit() {
}
void FileBrowserActivity::clearFileMetadata(const std::string& fullPath) {
// Only clear cache for .epub files
if (FsHelpers::hasEpubExtension(fullPath)) {
Epub(fullPath, "/.crosspoint").clearCache();
LOG_DBG("FileBrowser", "Cleared metadata cache for: %s", fullPath.c_str());
} else if (FsHelpers::hasXtcExtension(fullPath)) {
Xtc(fullPath, "/.crosspoint").clearCache();
LOG_DBG("FileBrowser", "Cleared metadata cache for: %s", fullPath.c_str());
}
}
@@ -229,50 +238,21 @@ void FileBrowserActivity::loop() {
const std::string& entry = files[selectorIndex];
const bool isDirectory = (entry.back() == '/');
std::string entryName = entry;
if (isDirectory) {
entryName.pop_back();
}
if (isDirectory) entryName.pop_back();
std::string cleanBase = basepath;
if (cleanBase.back() != '/') cleanBase += "/";
const std::string fullPath = cleanBase + entryName;
auto handler = [this, fullPath, isDirectory](const ActivityResult& res) {
if (!res.isCancelled) {
LOG_DBG("FileBrowser", "Attempting to delete: %s", fullPath.c_str());
clearFileMetadata(fullPath);
const bool deleted = isDirectory ? Storage.removeDir(fullPath.c_str()) : Storage.remove(fullPath.c_str());
if (deleted) {
LOG_DBG("FileBrowser", "Deleted successfully");
loadFiles();
if (files.empty()) {
selectorIndex = 0;
} else if (selectorIndex >= static_cast<int>(files.size())) {
selectorIndex = static_cast<int>(files.size()) - 1;
}
requestUpdate(true);
} else {
LOG_ERR("FileBrowser", "Failed to delete: %s", fullPath.c_str());
}
} else {
LOG_DBG("FileBrowser", "Delete cancelled by user");
}
};
startActivityForResult(
std::make_unique<ConfirmationActivity>(renderer, mappedInput, tr(STR_DELETE) + std::string("? "), entry),
handler);
doRemove(fullPath, entry, isDirectory);
return;
}
if (ev.button == MappedInputManager::Button::Right && ev.type == ButtonEventManager::PressType::Short) {
if (files.empty()) return;
const std::string& entry = files[selectorIndex];
if (entry.back() != '/' && (FsHelpers::hasEpubExtension(entry) || FsHelpers::hasXtcExtension(entry))) {
std::string cleanBase = basepath;
if (cleanBase.back() != '/') cleanBase += "/";
startActivityForResult(std::make_unique<BookInfoActivity>(renderer, mappedInput, cleanBase + entry),
[this](const ActivityResult&) { requestUpdate(); });
if (entry.back() != '/') {
openContextMenu();
}
return;
}
@@ -332,10 +312,8 @@ void FileBrowserActivity::render(RenderLock&&) {
const char* backLabel = (basepath == "/") ? (mode == Mode::PickFirmware ? tr(STR_BACK) : tr(STR_HOME)) : tr(STR_BACK);
const bool selectingFirmwareFile = mode == Mode::PickFirmware && !files.empty() && files[selectorIndex].back() != '/';
const char* confirmLabel = files.empty() ? "" : (selectingFirmwareFile ? tr(STR_SELECT) : tr(STR_OPEN));
const bool hasInfo =
mode == Mode::Books && !files.empty() && files[selectorIndex].back() != '/' &&
(FsHelpers::hasEpubExtension(files[selectorIndex]) || FsHelpers::hasXtcExtension(files[selectorIndex]));
const auto labels = mappedInput.mapLabels(backLabel, confirmLabel, "", hasInfo ? tr(STR_INFO) : "");
const bool hasContextMenu = mode == Mode::Books && !files.empty() && files[selectorIndex].back() != '/';
const auto labels = mappedInput.mapLabels(backLabel, confirmLabel, "", hasContextMenu ? tr(STR_OPTIONS) : "");
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
renderer.displayBuffer();
@@ -345,4 +323,185 @@ size_t FileBrowserActivity::findEntry(const std::string& name) const {
for (size_t i = 0; i < files.size(); i++)
if (files[i] == name) return i;
return files.size();
}
void FileBrowserActivity::openContextMenu() {
if (files.empty() || selectorIndex < 0 || selectorIndex >= static_cast<int>(files.size())) return;
const std::string& entry = files[selectorIndex];
if (entry.back() == '/') return;
std::string cleanBase = basepath;
if (cleanBase.back() != '/') cleanBase += "/";
const std::string fullPath = cleanBase + entry;
startActivityForResult(std::make_unique<FileContextMenuActivity>(renderer, mappedInput, fullPath),
[this, fullPath, entry](const ActivityResult& res) {
if (res.isCancelled) {
requestUpdate();
return;
}
const auto* menuRes = std::get_if<MenuResult>(&res.data);
if (!menuRes) {
requestUpdate();
return;
}
handleContextMenuAction(menuRes->action, fullPath, entry);
});
}
void FileBrowserActivity::handleContextMenuAction(int action, const std::string& fullPath, const std::string& entry) {
using Action = FileContextMenuActivity::Action;
switch (static_cast<Action>(action)) {
case Action::Open: {
ReturnHint hint;
hint.target = ReturnTo::FileBrowser;
hint.path = basepath;
hint.selectName = entry;
activityManager.replaceWithReader(std::string(fullPath), std::move(hint));
return;
}
case Action::FetchAndOpen: {
if (KOREADER_STORE.hasCredentials() && FsHelpers::hasEpubExtension(fullPath)) {
auto& sync = APP_STATE.koReaderSyncSession;
sync.autoPullEpubPath = fullPath;
sync.exitToHomeAfterSync = false;
APP_STATE.saveToFile();
}
ReturnHint hint;
hint.target = ReturnTo::FileBrowser;
hint.path = basepath;
hint.selectName = entry;
activityManager.replaceWithReader(std::string(fullPath), std::move(hint));
return;
}
case Action::MarkAsRead:
doMarkAsRead(fullPath);
requestUpdate();
return;
case Action::Info:
startActivityForResult(std::make_unique<BookInfoActivity>(renderer, mappedInput, fullPath),
[this](const ActivityResult&) { requestUpdate(); });
return;
case Action::DeleteCache:
doDeleteCache(fullPath, entry);
return;
case Action::SetAsSleepCover:
doSetAsSleepCover(fullPath);
return;
case Action::FlashFirmware:
doFlashFirmware(fullPath);
return;
case Action::Remove:
doRemove(fullPath, entry, false);
return;
default:
requestUpdate();
return;
}
}
void FileBrowserActivity::doMarkAsRead(const std::string& fullPath) {
std::string cachePath;
uint8_t data[7] = {0};
size_t dataLen = 0;
if (FsHelpers::hasEpubExtension(fullPath)) {
Epub epub(fullPath, "/.crosspoint");
epub.setupCacheDir();
cachePath = epub.getCachePath();
// 7-byte EPUB progress: spine(2) + page(2) + pageCount(2) + percent(1)
data[6] = 100;
dataLen = 7;
} else if (FsHelpers::hasXtcExtension(fullPath)) {
Xtc xtc(fullPath, "/.crosspoint");
xtc.setupCacheDir();
cachePath = xtc.getCachePath();
// 5-byte XTC progress: page(4) + percent(1)
data[4] = 100;
dataLen = 5;
} else if (FsHelpers::hasTxtExtension(fullPath) || FsHelpers::hasMarkdownExtension(fullPath)) {
Txt txt(fullPath, "/.crosspoint");
txt.setupCacheDir();
cachePath = txt.getCachePath();
// 7-byte TXT progress: page(2) + offset(4) + percent(1)
data[6] = 100;
dataLen = 7;
} else {
return;
}
FsFile f;
if (Storage.openFileForWrite("FBR", cachePath + "/progress.bin", f)) {
f.write(data, dataLen);
f.close();
LOG_INF("FBR", "Marked as read: %s", fullPath.c_str());
} else {
LOG_ERR("FBR", "Failed to write progress for mark-as-read: %s", fullPath.c_str());
}
}
void FileBrowserActivity::doSetAsSleepCover(const std::string& fullPath) {
if (FsHelpers::hasBmpExtension(fullPath)) {
// BMP: use the shared helper that just does a file copy + settings update.
const bool success = BmpViewerActivity::setBmpFileAsSleepScreen(fullPath);
{
RenderLock lock(*this);
const char* msg = success ? tr(STR_SLEEP_SCREEN_SET) : tr(STR_FAILED_TO_SET_SLEEP_SCREEN);
GUI.drawPopup(renderer, msg);
renderer.displayBuffer(HalDisplay::HALF_REFRESH);
}
requestUpdate();
} else {
// JPG/PNG: must render to framebuffer — open the image viewer so the user can use its Set Sleep button.
ReturnHint hint;
hint.target = ReturnTo::FileBrowser;
hint.path = basepath;
hint.selectName = files[selectorIndex];
activityManager.replaceWithReader(std::string(fullPath), std::move(hint));
}
}
void FileBrowserActivity::doDeleteCache(const std::string& fullPath, const std::string& entry) {
startActivityForResult(
std::make_unique<ConfirmationActivity>(renderer, mappedInput, tr(STR_DELETE_CACHE) + std::string("?"), entry),
[this, fullPath](const ActivityResult& res) {
if (!res.isCancelled) {
clearFileMetadata(fullPath);
LOG_INF("FBR", "Cache deleted for: %s", fullPath.c_str());
}
requestUpdate();
});
}
void FileBrowserActivity::doRemove(const std::string& fullPath, const std::string& entry, bool isDirectory) {
startActivityForResult(
std::make_unique<ConfirmationActivity>(renderer, mappedInput, tr(STR_DELETE) + std::string("? "), entry),
[this, fullPath, isDirectory](const ActivityResult& res) {
if (!res.isCancelled) {
LOG_DBG("FBR", "Attempting to delete: %s", fullPath.c_str());
clearFileMetadata(fullPath);
const bool deleted = isDirectory ? Storage.removeDir(fullPath.c_str()) : Storage.remove(fullPath.c_str());
if (deleted) {
LOG_DBG("FBR", "Deleted successfully");
loadFiles();
if (files.empty()) {
selectorIndex = 0;
} else if (selectorIndex >= static_cast<int>(files.size())) {
selectorIndex = static_cast<int>(files.size()) - 1;
}
requestUpdate(true);
} else {
LOG_ERR("FBR", "Failed to delete: %s", fullPath.c_str());
requestUpdate();
}
} else {
requestUpdate();
}
});
}
void FileBrowserActivity::doFlashFirmware(const std::string& fullPath) {
// Use the pre-selected-path constructor to skip the picker inside SdFirmwareUpdateActivity.
startActivityForResult(std::make_unique<SdFirmwareUpdateActivity>(renderer, mappedInput, fullPath),
[this](const ActivityResult&) { requestUpdate(); });
}
+7 -1
View File
@@ -14,8 +14,14 @@ class FileBrowserActivity final : public Activity {
enum class Mode { Books, PickFirmware };
private:
// Deletion
void clearFileMetadata(const std::string& fullPath);
void openContextMenu();
void handleContextMenuAction(int action, const std::string& fullPath, const std::string& entry);
void doMarkAsRead(const std::string& fullPath);
void doSetAsSleepCover(const std::string& fullPath);
void doDeleteCache(const std::string& fullPath, const std::string& entry);
void doRemove(const std::string& fullPath, const std::string& entry, bool isDirectory);
void doFlashFirmware(const std::string& fullPath);
ButtonNavigator buttonNavigator;
@@ -0,0 +1,116 @@
#include "FileContextMenuActivity.h"
#include <FsHelpers.h>
#include <I18n.h>
#include "../ActivityResult.h"
#include "CrossPointSettings.h"
#include "KOReaderCredentialStore.h"
#include "components/UITheme.h"
#include "../settings/SettingInfo.h"
FileContextMenuActivity::FileContextMenuActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
const std::string& filePath)
: MenuListActivity("FileContextMenu", renderer, mappedInput), filePath(filePath) {
const std::string_view name{filePath};
const bool isBin = FsHelpers::checkFileExtension(name, ".bin");
const bool isEpub = FsHelpers::hasEpubExtension(name);
const bool isXtc = FsHelpers::hasXtcExtension(name);
const bool isTxt = FsHelpers::hasTxtExtension(name) || FsHelpers::hasMarkdownExtension(name);
const bool isImage = FsHelpers::hasBmpExtension(name) || FsHelpers::hasJpgExtension(name) ||
FsHelpers::hasPngExtension(name);
if (isBin) {
menuItems.push_back(SettingInfo::Action(StrId::STR_FLASH_FIRMWARE, SettingAction::None));
menuItems.push_back(SettingInfo::Separator(StrId::STR_NONE_OPT));
menuItems.push_back(SettingInfo::Action(StrId::STR_REMOVE, SettingAction::None));
} else if (isImage) {
menuItems.push_back(SettingInfo::Action(StrId::STR_OPEN, SettingAction::None));
menuItems.push_back(SettingInfo::Action(StrId::STR_SET_SLEEP_SCREEN, SettingAction::None));
menuItems.push_back(SettingInfo::Separator(StrId::STR_NONE_OPT));
menuItems.push_back(SettingInfo::Action(StrId::STR_REMOVE, SettingAction::None));
} else if (isEpub) {
menuItems.push_back(SettingInfo::Action(StrId::STR_OPEN, SettingAction::None));
if (KOREADER_STORE.hasCredentials()) {
menuItems.push_back(SettingInfo::Action(StrId::STR_FETCH_AND_OPEN, SettingAction::None));
}
menuItems.push_back(SettingInfo::Action(StrId::STR_MARK_AS_READ, SettingAction::None));
menuItems.push_back(SettingInfo::Action(StrId::STR_INFO, SettingAction::None));
menuItems.push_back(SettingInfo::Separator(StrId::STR_NONE_OPT));
menuItems.push_back(SettingInfo::Action(StrId::STR_DELETE_CACHE, SettingAction::None));
menuItems.push_back(SettingInfo::Action(StrId::STR_REMOVE, SettingAction::None));
} else if (isXtc) {
menuItems.push_back(SettingInfo::Action(StrId::STR_OPEN, SettingAction::None));
menuItems.push_back(SettingInfo::Action(StrId::STR_MARK_AS_READ, SettingAction::None));
menuItems.push_back(SettingInfo::Action(StrId::STR_INFO, SettingAction::None));
menuItems.push_back(SettingInfo::Separator(StrId::STR_NONE_OPT));
menuItems.push_back(SettingInfo::Action(StrId::STR_DELETE_CACHE, SettingAction::None));
menuItems.push_back(SettingInfo::Action(StrId::STR_REMOVE, SettingAction::None));
} else if (isTxt) {
menuItems.push_back(SettingInfo::Action(StrId::STR_OPEN, SettingAction::None));
menuItems.push_back(SettingInfo::Action(StrId::STR_MARK_AS_READ, SettingAction::None));
menuItems.push_back(SettingInfo::Separator(StrId::STR_NONE_OPT));
menuItems.push_back(SettingInfo::Action(StrId::STR_REMOVE, SettingAction::None));
}
}
void FileContextMenuActivity::onActionSelected(int index) {
const StrId nameId = menuItems[index].nameId;
Action action = Action::None;
if (nameId == StrId::STR_OPEN) {
action = Action::Open;
} else if (nameId == StrId::STR_FETCH_AND_OPEN) {
action = Action::FetchAndOpen;
} else if (nameId == StrId::STR_MARK_AS_READ) {
action = Action::MarkAsRead;
} else if (nameId == StrId::STR_INFO) {
action = Action::Info;
} else if (nameId == StrId::STR_DELETE_CACHE) {
action = Action::DeleteCache;
} else if (nameId == StrId::STR_SET_SLEEP_SCREEN) {
action = Action::SetAsSleepCover;
} else if (nameId == StrId::STR_FLASH_FIRMWARE) {
action = Action::FlashFirmware;
} else if (nameId == StrId::STR_REMOVE) {
action = Action::Remove;
}
if (action == Action::None) return;
MenuResult res;
res.action = static_cast<int>(action);
ActivityResult result{std::move(res)};
result.isCancelled = false;
setResult(std::move(result));
finish();
}
void FileContextMenuActivity::onBackPressed() {
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
}
void FileContextMenuActivity::render(RenderLock&&) {
renderer.clearScreen();
const auto& metrics = UITheme::getInstance().getMetrics();
const Rect contentRect = UITheme::getContentRect(renderer, true, true);
// Show the bare filename (without path) as the header
const auto slashPos = filePath.rfind('/');
const std::string fileName = (slashPos == std::string::npos) ? filePath : filePath.substr(slashPos + 1);
GUI.drawHeader(renderer, Rect{contentRect.x, metrics.topPadding, contentRect.width, metrics.headerHeight},
fileName.c_str());
const int contentTop = metrics.topPadding + metrics.headerHeight + metrics.verticalSpacing;
const int contentHeight = contentRect.height - contentTop - metrics.verticalSpacing;
drawMenuList(Rect{contentRect.x, contentTop, contentRect.width, contentHeight});
const auto labels = mappedInput.mapLabels(tr(STR_BACK), tr(STR_SELECT), "", "");
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
renderer.displayBuffer();
}
@@ -0,0 +1,33 @@
#pragma once
#include <string>
#include "../MenuListActivity.h"
// Context menu shown when the user long-presses the info button on a file in the file browser.
// The available actions depend on file type. The selected action is returned via MenuResult::action.
class FileContextMenuActivity final : public MenuListActivity {
public:
enum class Action {
None = -1,
Open = 0,
FetchAndOpen,
MarkAsRead,
Info,
DeleteCache,
SetAsSleepCover,
FlashFirmware,
Remove,
};
explicit FileContextMenuActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
const std::string& filePath);
void render(RenderLock&&) override;
private:
std::string filePath;
void onActionSelected(int index) override;
void onBackPressed() override;
};
@@ -17,8 +17,23 @@
void SdFirmwareUpdateActivity::onEnter() {
Activity::onEnter();
LOG_INF("FW", "SdFirmwareUpdateActivity build=%s %s recovery=%d", __DATE__, __TIME__, recoveryMode ? 1 : 0);
state = State::PICKING;
launchPicker();
if (!firmwarePath.empty()) {
// Pre-selected path: skip picker and go straight to validation.
{
RenderLock lock(*this);
state = State::VALIDATING;
}
requestUpdateAndWait();
if (!validateFirmware()) {
state = State::FAILED;
requestUpdate();
return;
}
promptConfirmation();
} else {
state = State::PICKING;
launchPicker();
}
}
void SdFirmwareUpdateActivity::launchPicker() {
@@ -31,6 +31,12 @@ class SdFirmwareUpdateActivity : public Activity {
explicit SdFirmwareUpdateActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, bool recoveryMode = false)
: Activity("SdFirmwareUpdate", renderer, mappedInput), recoveryMode(recoveryMode) {}
// Start with a pre-selected firmware path — skips the file picker.
explicit SdFirmwareUpdateActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string preSelectedPath)
: Activity("SdFirmwareUpdate", renderer, mappedInput),
recoveryMode(false),
firmwarePath(std::move(preSelectedPath)) {}
void onEnter() override;
void loop() override;
void render(RenderLock&&) override;
+25 -15
View File
@@ -343,11 +343,23 @@ void BmpViewerActivity::renderError(const char* message) {
renderer.displayBuffer(HalDisplay::HALF_REFRESH);
}
bool BmpViewerActivity::setBmpFileAsSleepScreen(const std::string& filePath) {
const bool success = (filePath == SLEEP_BMP_PATH) ? true : Storage.copyFile("BMP", filePath, SLEEP_BMP_PATH);
if (success) {
SETTINGS.sleepScreen = CrossPointSettings::SLEEP_SCREEN_MODE::CUSTOM;
SETTINGS.saveToFile();
LOG_INF("BMP", "Set %s as sleep screen", filePath.c_str());
} else {
LOG_ERR("BMP", "Failed to copy %s as sleep screen", filePath.c_str());
}
return success;
}
void BmpViewerActivity::setAsSleepScreen() {
bool success = false;
if (FsHelpers::hasBmpExtension(filePath)) {
success = (filePath == SLEEP_BMP_PATH) ? true : Storage.copyFile("BMP", filePath, SLEEP_BMP_PATH);
success = setBmpFileAsSleepScreen(filePath);
} else {
const bool renderedForCapture = renderDecodedImage(false);
if (renderedForCapture) {
@@ -361,27 +373,25 @@ void BmpViewerActivity::setAsSleepScreen() {
if (!success && Storage.exists(SLEEP_BMP_TMP_PATH)) {
Storage.remove(SLEEP_BMP_TMP_PATH);
}
if (success) {
SETTINGS.sleepScreen = CrossPointSettings::SLEEP_SCREEN_MODE::CUSTOM;
SETTINGS.saveToFile();
LOG_INF("BMP", "Set %s as sleep screen", filePath.c_str());
}
}
if (!success) {
LOG_ERR("BMP", "Failed to set %s as sleep screen", filePath.c_str());
{
RenderLock lock(*this);
GUI.drawPopup(renderer, tr(STR_FAILED_TO_SET_SLEEP_SCREEN));
renderer.displayBuffer(HalDisplay::HALF_REFRESH);
}
RenderLock lock(*this);
GUI.drawPopup(renderer, tr(STR_FAILED_TO_SET_SLEEP_SCREEN));
renderer.displayBuffer(HalDisplay::HALF_REFRESH);
return;
}
SETTINGS.sleepScreen = CrossPointSettings::SLEEP_SCREEN_MODE::CUSTOM;
SETTINGS.saveToFile();
LOG_INF("BMP", "Set %s as sleep screen", filePath.c_str());
{
RenderLock lock(*this);
GUI.drawPopup(renderer, tr(STR_SLEEP_SCREEN_SET));
renderer.displayBuffer(HalDisplay::HALF_REFRESH);
}
RenderLock lock(*this);
GUI.drawPopup(renderer, tr(STR_SLEEP_SCREEN_SET));
renderer.displayBuffer(HalDisplay::HALF_REFRESH);
}
void BmpViewerActivity::loop() {
+5
View File
@@ -41,4 +41,9 @@ class BmpViewerActivity final : public Activity {
#endif
void renderError(const char* message);
void setAsSleepScreen();
public:
// Sets a BMP file as the sleep screen without needing an open viewer instance.
// Returns true on success. Only works for .bmp files; for JPG/PNG open BmpViewerActivity.
static bool setBmpFileAsSleepScreen(const std::string& filePath);
};