refactor: implement ActivityManager (#1016)

## Summary

Ref comment:
https://github.com/crosspoint-reader/crosspoint-reader/pull/1010#pullrequestreview-3828854640

This PR introduces `ActivityManager`, which mirrors the same concept of
Activity in Android, where an activity represents a single screen of the
UI. The manager is responsible for launching activities, and ensuring
that only one activity is active at a time.

Main differences from Android's ActivityManager:
- No concept of Bundle or Intent extras
- No onPause/onResume, since we don't have a concept of background
activities
- onActivityResult is implemented via a callback instead of a separate
method, for simplicity

## Key changes

- Single `renderTask` shared across all activities
- No more sub-activity, we manage them using a stack; Results can be
passed via `startActivityForResult` and `setResult`
- Activity can call `finish()` to destroy themself, but the actual
deletion will be handled by `ActivityManager` to avoid `delete this`
pattern

As a bonus: the manager will automatically call `requestUpdate()` when
returning from another activity

## Example usage

**BEFORE**:

```cpp
// caller
    enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
                                               [this](const bool connected) { onWifiSelectionComplete(connected); }));

// subactivity
  onComplete(true); // will eventually call exitActivity(), which deletes the caller instance (dangerous behavior)
``` 

**AFTER**: (mirrors the `startActivityForResult` and `setResult` from
android)

```cpp
// caller
  startActivityForResult(new NetworkModeSelectionActivity(renderer, mappedInput),
                         [this](const ActivityResult& result) { onNetworkModeSelected(result.selectedNetworkMode); });

// subactivity
  ActivityResult result;
  result.isCancelled = false;
  result.selectedNetworkMode = mode;
  setResult(result);
  finish(); // signals to ActivityManager to go back to last activity AFTER this function returns
```

TODO:
- [x] Reconsider if the `Intent` is really necessary or it should be
removed (note: it's inspired by
[Intent](https://developer.android.com/guide/components/intents-common)
from Android API) ==> I decided to keep this pattern fr clarity
- [x] Verify if behavior is still correct (i.e. back from sub-activity)
- [x] Refactor the `ActivityWithSubactivity` to just simple `Activity`
--> We are using a stack for keeping track of sub-activity now
- [x] Use single task for rendering --> avoid allocating 8KB stack per
activity
- [x] Implement the idea of [Activity
result](https://developer.android.com/training/basics/intents/result)
--> Allow sub-activity like Wifi to report back the status (connected,
failed, etc)

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? **PARTIALLY**, some
repetitive migrations are done by Claude, but I'm the one how ultimately
approve it

---------

Co-authored-by: Zach Nelson <zach@zdnelson.com>
This commit is contained in:
Xuan-Son Nguyen
2026-02-27 07:32:40 +01:00
committed by GitHub
parent 5b11e45a36
commit c4fc4effbd
69 changed files with 1095 additions and 1180 deletions

View File

@@ -61,7 +61,7 @@ void applyReaderOrientation(GfxRenderer& renderer, const uint8_t orientation) {
} // namespace
void EpubReaderActivity::onEnter() {
ActivityWithSubactivity::onEnter();
Activity::onEnter();
if (!epub) {
return;
@@ -108,7 +108,7 @@ void EpubReaderActivity::onEnter() {
}
void EpubReaderActivity::onExit() {
ActivityWithSubactivity::onExit();
Activity::onExit();
// Reset orientation back to portrait for the rest of the UI
renderer.setOrientation(GfxRenderer::Orientation::Portrait);
@@ -120,48 +120,9 @@ void EpubReaderActivity::onExit() {
}
void EpubReaderActivity::loop() {
// Pass input responsibility to sub activity if exists
if (subActivity) {
subActivity->loop();
// Deferred exit: process after subActivity->loop() returns to avoid use-after-free
if (pendingSubactivityExit) {
pendingSubactivityExit = false;
exitActivity();
requestUpdate();
skipNextButtonCheck = true; // Skip button processing to ignore stale events
}
// Deferred go home: process after subActivity->loop() returns to avoid race condition
if (pendingGoHome) {
pendingGoHome = false;
exitActivity();
if (onGoHome) {
onGoHome();
}
return; // Don't access 'this' after callback
}
return;
}
// Handle pending go home when no subactivity (e.g., from long press back)
if (pendingGoHome) {
pendingGoHome = false;
if (onGoHome) {
onGoHome();
}
return; // Don't access 'this' after callback
}
// Skip button processing after returning from subactivity
// This prevents stale button release events from triggering actions
// We wait until: (1) all relevant buttons are released, AND (2) wasReleased events have been cleared
if (skipNextButtonCheck) {
const bool confirmCleared = !mappedInput.isPressed(MappedInputManager::Button::Confirm) &&
!mappedInput.wasReleased(MappedInputManager::Button::Confirm);
const bool backCleared = !mappedInput.isPressed(MappedInputManager::Button::Back) &&
!mappedInput.wasReleased(MappedInputManager::Button::Back);
if (confirmCleared && backCleared) {
skipNextButtonCheck = false;
}
if (!epub) {
// Should never happen
finish();
return;
}
@@ -170,22 +131,27 @@ void EpubReaderActivity::loop() {
const int currentPage = section ? section->currentPage + 1 : 0;
const int totalPages = section ? section->pageCount : 0;
float bookProgress = 0.0f;
if (epub && epub->getBookSize() > 0 && section && section->pageCount > 0) {
if (epub->getBookSize() > 0 && section && section->pageCount > 0) {
const float chapterProgress = static_cast<float>(section->currentPage) / static_cast<float>(section->pageCount);
bookProgress = epub->calculateProgress(currentSpineIndex, chapterProgress) * 100.0f;
}
const int bookProgressPercent = clampPercent(static_cast<int>(bookProgress + 0.5f));
exitActivity();
enterNewActivity(new EpubReaderMenuActivity(
this->renderer, this->mappedInput, epub->getTitle(), currentPage, totalPages, bookProgressPercent,
SETTINGS.orientation, !currentPageFootnotes.empty(),
[this](const uint8_t orientation) { onReaderMenuBack(orientation); },
[this](EpubReaderMenuActivity::MenuAction action) { onReaderMenuConfirm(action); }));
startActivityForResult(std::make_unique<EpubReaderMenuActivity>(
renderer, mappedInput, epub->getTitle(), currentPage, totalPages, bookProgressPercent,
SETTINGS.orientation, !currentPageFootnotes.empty()),
[this](const ActivityResult& result) {
// Always apply orientation change even if the menu was cancelled
const auto& menu = std::get<MenuResult>(result.data);
applyOrientation(menu.orientation);
if (!result.isCancelled) {
onReaderMenuConfirm(static_cast<EpubReaderMenuActivity::MenuAction>(menu.action));
}
});
}
// Long press BACK (1s+) goes to file selection
if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) {
onGoBack();
activityManager.goToMyLibrary(epub ? epub->getPath() : "");
return;
}
@@ -274,14 +240,6 @@ void EpubReaderActivity::loop() {
}
}
void EpubReaderActivity::onReaderMenuBack(const uint8_t orientation) {
exitActivity();
// Apply the user-selected orientation when the menu is dismissed.
// This ensures the menu can be navigated without immediately rotating the screen.
applyOrientation(orientation);
requestUpdate();
}
// Translate an absolute percent into a spine index plus a normalized position
// within that spine so we can jump after the section is loaded.
void EpubReaderActivity::jumpToPercent(int percent) {
@@ -348,82 +306,44 @@ void EpubReaderActivity::jumpToPercent(int percent) {
void EpubReaderActivity::onReaderMenuConfirm(EpubReaderMenuActivity::MenuAction action) {
switch (action) {
case EpubReaderMenuActivity::MenuAction::SELECT_CHAPTER: {
// Calculate values BEFORE we start destroying things
const int currentP = section ? section->currentPage : 0;
const int totalP = section ? section->pageCount : 0;
const int spineIdx = currentSpineIndex;
const std::string path = epub->getPath();
// 1. Close the menu
exitActivity();
// 2. Open the Chapter Selector
enterNewActivity(new EpubReaderChapterSelectionActivity(
this->renderer, this->mappedInput, epub, path, spineIdx, currentP, totalP,
[this] {
exitActivity();
requestUpdate();
},
[this](const int newSpineIndex) {
if (currentSpineIndex != newSpineIndex) {
currentSpineIndex = newSpineIndex;
startActivityForResult(
std::make_unique<EpubReaderChapterSelectionActivity>(renderer, mappedInput, epub, path, spineIdx),
[this](const ActivityResult& result) {
if (!result.isCancelled && currentSpineIndex != std::get<ChapterResult>(result.data).spineIndex) {
currentSpineIndex = std::get<ChapterResult>(result.data).spineIndex;
nextPageNumber = 0;
section.reset();
}
exitActivity();
requestUpdate();
},
[this](const int newSpineIndex, const int newPage) {
if (currentSpineIndex != newSpineIndex || (section && section->currentPage != newPage)) {
currentSpineIndex = newSpineIndex;
nextPageNumber = newPage;
section.reset();
}
exitActivity();
requestUpdate();
}));
});
break;
}
case EpubReaderMenuActivity::MenuAction::FOOTNOTES: {
exitActivity();
enterNewActivity(new EpubReaderFootnotesActivity(
this->renderer, this->mappedInput, currentPageFootnotes,
[this] {
// Go back from footnotes list
exitActivity();
requestUpdate();
},
[this](const char* href) {
// Navigate to selected footnote
navigateToHref(href, true);
exitActivity();
requestUpdate();
}));
startActivityForResult(std::make_unique<EpubReaderFootnotesActivity>(renderer, mappedInput, currentPageFootnotes),
[this](const ActivityResult& result) {
if (!result.isCancelled) {
const auto& footnoteResult = std::get<FootnoteResult>(result.data);
navigateToHref(footnoteResult.href, true);
}
requestUpdate();
});
break;
}
case EpubReaderMenuActivity::MenuAction::GO_TO_PERCENT: {
// Launch the slider-based percent selector and return here on confirm/cancel.
float bookProgress = 0.0f;
if (epub && epub->getBookSize() > 0 && section && section->pageCount > 0) {
const float chapterProgress = static_cast<float>(section->currentPage) / static_cast<float>(section->pageCount);
bookProgress = epub->calculateProgress(currentSpineIndex, chapterProgress) * 100.0f;
}
const int initialPercent = clampPercent(static_cast<int>(bookProgress + 0.5f));
exitActivity();
enterNewActivity(new EpubReaderPercentSelectionActivity(
renderer, mappedInput, initialPercent,
[this](const int percent) {
// Apply the new position and exit back to the reader.
jumpToPercent(percent);
exitActivity();
requestUpdate();
},
[this]() {
// Cancel selection and return to the reader.
exitActivity();
requestUpdate();
}));
startActivityForResult(
std::make_unique<EpubReaderPercentSelectionActivity>(renderer, mappedInput, initialPercent),
[this](const ActivityResult& result) {
if (!result.isCancelled) {
jumpToPercent(std::get<PercentResult>(result.data).percent);
}
});
break;
}
case EpubReaderMenuActivity::MenuAction::DISPLAY_QR: {
@@ -444,55 +364,41 @@ void EpubReaderActivity::onReaderMenuConfirm(EpubReaderMenuActivity::MenuAction
}
}
if (!fullText.empty()) {
exitActivity();
enterNewActivity(new QrDisplayActivity(renderer, mappedInput, fullText, [this]() {
exitActivity();
requestUpdate();
}));
startActivityForResult(std::make_unique<QrDisplayActivity>(renderer, mappedInput, fullText),
[this](const ActivityResult& result) {});
break;
}
}
}
// If no text or page loading failed, just close menu
exitActivity();
requestUpdate();
break;
}
case EpubReaderMenuActivity::MenuAction::GO_HOME: {
// Defer go home to avoid race condition with display task
pendingGoHome = true;
break;
onGoHome();
return;
}
case EpubReaderMenuActivity::MenuAction::DELETE_CACHE: {
{
RenderLock lock(*this);
if (epub) {
// 2. BACKUP: Read current progress
// We use the current variables that track our position
if (epub && section) {
uint16_t backupSpine = currentSpineIndex;
uint16_t backupPage = section->currentPage;
uint16_t backupPageCount = section->pageCount;
section.reset();
// 3. WIPE: Clear the cache directory
epub->clearCache();
// 4. RESTORE: Re-setup the directory and rewrite the progress file
epub->setupCacheDir();
saveProgress(backupSpine, backupPage, backupPageCount);
}
}
// Defer go home to avoid race condition with display task
pendingGoHome = true;
break;
onGoHome();
return;
}
case EpubReaderMenuActivity::MenuAction::SCREENSHOT: {
{
RenderLock lock(*this);
pendingScreenshot = true;
}
exitActivity();
requestUpdate();
break;
}
@@ -500,22 +406,19 @@ void EpubReaderActivity::onReaderMenuConfirm(EpubReaderMenuActivity::MenuAction
if (KOREADER_STORE.hasCredentials()) {
const int currentPage = section ? section->currentPage : 0;
const int totalPages = section ? section->pageCount : 0;
exitActivity();
enterNewActivity(new KOReaderSyncActivity(
renderer, mappedInput, epub, epub->getPath(), currentSpineIndex, currentPage, totalPages,
[this]() {
// On cancel - defer exit to avoid use-after-free
pendingSubactivityExit = true;
},
[this](int newSpineIndex, int newPage) {
// On sync complete - update position and defer exit
if (currentSpineIndex != newSpineIndex || (section && section->currentPage != newPage)) {
currentSpineIndex = newSpineIndex;
nextPageNumber = newPage;
section.reset();
startActivityForResult(
std::make_unique<KOReaderSyncActivity>(renderer, mappedInput, epub, epub->getPath(), currentSpineIndex,
currentPage, totalPages),
[this](const ActivityResult& result) {
if (!result.isCancelled) {
const auto& sync = std::get<SyncResult>(result.data);
if (currentSpineIndex != sync.spineIndex || (section && section->currentPage != sync.page)) {
currentSpineIndex = sync.spineIndex;
nextPageNumber = sync.page;
section.reset();
}
}
pendingSubactivityExit = true;
}));
});
}
break;
}
@@ -550,7 +453,7 @@ void EpubReaderActivity::applyOrientation(const uint8_t orientation) {
}
// TODO: Failure handling
void EpubReaderActivity::render(Activity::RenderLock&& lock) {
void EpubReaderActivity::render(RenderLock&& lock) {
if (!epub) {
return;
}
@@ -785,8 +688,8 @@ void EpubReaderActivity::renderStatusBar() const {
GUI.drawStatusBar(renderer, bookProgress, currentPage, pageCount, title);
}
void EpubReaderActivity::navigateToHref(const char* href, const bool savePosition) {
if (!epub || !href) return;
void EpubReaderActivity::navigateToHref(const std::string& hrefStr, const bool savePosition) {
if (!epub) return;
// Push current position onto saved stack
if (savePosition && section && footnoteDepth < MAX_FOOTNOTE_DEPTH) {
@@ -795,8 +698,6 @@ void EpubReaderActivity::navigateToHref(const char* href, const bool savePositio
LOG_DBG("ERS", "Saved position [%d]: spine %d, page %d", footnoteDepth, currentSpineIndex, section->currentPage);
}
std::string hrefStr(href);
// Check for same-file anchor reference (#anchor only)
bool sameFile = !hrefStr.empty() && hrefStr[0] == '#';
@@ -809,7 +710,7 @@ void EpubReaderActivity::navigateToHref(const char* href, const bool savePositio
}
if (targetSpineIndex < 0) {
LOG_DBG("ERS", "Could not resolve href: %s", href);
LOG_DBG("ERS", "Could not resolve href: %s", hrefStr.c_str());
if (savePosition && footnoteDepth > 0) footnoteDepth--; // undo push
return;
}
@@ -821,7 +722,7 @@ void EpubReaderActivity::navigateToHref(const char* href, const bool savePositio
section.reset();
}
requestUpdate();
LOG_DBG("ERS", "Navigated to spine %d for href: %s", targetSpineIndex, href);
LOG_DBG("ERS", "Navigated to spine %d for href: %s", targetSpineIndex, hrefStr.c_str());
}
void EpubReaderActivity::restoreSavedPosition() {

View File

@@ -4,9 +4,9 @@
#include <Epub/Section.h>
#include "EpubReaderMenuActivity.h"
#include "activities/ActivityWithSubactivity.h"
#include "activities/Activity.h"
class EpubReaderActivity final : public ActivityWithSubactivity {
class EpubReaderActivity final : public Activity {
std::shared_ptr<Epub> epub;
std::unique_ptr<Section> section = nullptr;
int currentSpineIndex = 0;
@@ -19,12 +19,8 @@ class EpubReaderActivity final : public ActivityWithSubactivity {
bool pendingPercentJump = false;
// Normalized 0.0-1.0 progress within the target spine item, computed from book percentage.
float pendingSpineProgress = 0.0f;
bool pendingSubactivityExit = false; // Defer subactivity exit to avoid use-after-free
bool pendingGoHome = false; // Defer go home to avoid race condition with display task
bool pendingScreenshot = false;
bool skipNextButtonCheck = false; // Skip button processing for one frame after subactivity exit
const std::function<void()> onGoBack;
const std::function<void()> onGoHome;
// Footnote support
std::vector<FootnoteEntry> currentPageFootnotes;
@@ -42,23 +38,19 @@ class EpubReaderActivity final : public ActivityWithSubactivity {
void saveProgress(int spineIndex, int currentPage, int pageCount);
// Jump to a percentage of the book (0-100), mapping it to spine and page.
void jumpToPercent(int percent);
void onReaderMenuBack(uint8_t orientation);
void onReaderMenuConfirm(EpubReaderMenuActivity::MenuAction action);
void applyOrientation(uint8_t orientation);
// Footnote navigation
void navigateToHref(const char* href, bool savePosition = false);
void navigateToHref(const std::string& href, bool savePosition = false);
void restoreSavedPosition();
public:
explicit EpubReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Epub> epub,
const std::function<void()>& onGoBack, const std::function<void()>& onGoHome)
: ActivityWithSubactivity("EpubReader", renderer, mappedInput),
epub(std::move(epub)),
onGoBack(onGoBack),
onGoHome(onGoHome) {}
explicit EpubReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Epub> epub)
: Activity("EpubReader", renderer, mappedInput), epub(std::move(epub)) {}
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&& lock) override;
void render(RenderLock&& lock) override;
bool isReaderActivity() const override { return true; }
};

View File

@@ -26,7 +26,7 @@ int EpubReaderChapterSelectionActivity::getPageItems() const {
}
void EpubReaderChapterSelectionActivity::onEnter() {
ActivityWithSubactivity::onEnter();
Activity::onEnter();
if (!epub) {
return;
@@ -41,26 +41,28 @@ void EpubReaderChapterSelectionActivity::onEnter() {
requestUpdate();
}
void EpubReaderChapterSelectionActivity::onExit() { ActivityWithSubactivity::onExit(); }
void EpubReaderChapterSelectionActivity::onExit() { Activity::onExit(); }
void EpubReaderChapterSelectionActivity::loop() {
if (subActivity) {
subActivity->loop();
return;
}
const int pageItems = getPageItems();
const int totalItems = getTotalItems();
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
const auto newSpineIndex = epub->getSpineIndexForTocIndex(selectorIndex);
if (newSpineIndex == -1) {
onGoBack();
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
} else {
onSelectSpineIndex(newSpineIndex);
setResult(ChapterResult{newSpineIndex});
finish();
}
} else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
onGoBack();
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
}
buttonNavigator.onNextRelease([this, totalItems] {
@@ -84,7 +86,7 @@ void EpubReaderChapterSelectionActivity::loop() {
});
}
void EpubReaderChapterSelectionActivity::render(Activity::RenderLock&&) {
void EpubReaderChapterSelectionActivity::render(RenderLock&&) {
renderer.clearScreen();
const auto pageWidth = renderer.getScreenWidth();

View File

@@ -3,22 +3,16 @@
#include <memory>
#include "../ActivityWithSubactivity.h"
#include "../Activity.h"
#include "util/ButtonNavigator.h"
class EpubReaderChapterSelectionActivity final : public ActivityWithSubactivity {
class EpubReaderChapterSelectionActivity final : public Activity {
std::shared_ptr<Epub> epub;
std::string epubPath;
ButtonNavigator buttonNavigator;
int currentSpineIndex = 0;
int currentPage = 0;
int totalPagesInSpine = 0;
int selectorIndex = 0;
const std::function<void()> onGoBack;
const std::function<void(int newSpineIndex)> onSelectSpineIndex;
const std::function<void(int newSpineIndex, int newPage)> onSyncPosition;
// Number of items that fit on a page, derived from logical screen height.
// This adapts automatically when switching between portrait and landscape.
int getPageItems() const;
@@ -29,21 +23,13 @@ class EpubReaderChapterSelectionActivity final : public ActivityWithSubactivity
public:
explicit EpubReaderChapterSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
const std::shared_ptr<Epub>& epub, const std::string& epubPath,
const int currentSpineIndex, const int currentPage,
const int totalPagesInSpine, const std::function<void()>& onGoBack,
const std::function<void(int newSpineIndex)>& onSelectSpineIndex,
const std::function<void(int newSpineIndex, int newPage)>& onSyncPosition)
: ActivityWithSubactivity("EpubReaderChapterSelection", renderer, mappedInput),
const int currentSpineIndex)
: Activity("EpubReaderChapterSelection", renderer, mappedInput),
epub(epub),
epubPath(epubPath),
currentSpineIndex(currentSpineIndex),
currentPage(currentPage),
totalPagesInSpine(totalPagesInSpine),
onGoBack(onGoBack),
onSelectSpineIndex(onSelectSpineIndex),
onSyncPosition(onSyncPosition) {}
currentSpineIndex(currentSpineIndex) {}
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
void render(RenderLock&&) override;
};

View File

@@ -10,27 +10,26 @@
#include "fontIds.h"
void EpubReaderFootnotesActivity::onEnter() {
ActivityWithSubactivity::onEnter();
Activity::onEnter();
selectedIndex = 0;
requestUpdate();
}
void EpubReaderFootnotesActivity::onExit() { ActivityWithSubactivity::onExit(); }
void EpubReaderFootnotesActivity::onExit() { Activity::onExit(); }
void EpubReaderFootnotesActivity::loop() {
if (subActivity) {
subActivity->loop();
return;
}
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
onGoBack();
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
return;
}
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
if (selectedIndex >= 0 && selectedIndex < static_cast<int>(footnotes.size())) {
onSelectFootnote(footnotes[selectedIndex].href);
setResult(FootnoteResult{footnotes[selectedIndex].href});
finish();
}
return;
}
@@ -50,7 +49,7 @@ void EpubReaderFootnotesActivity::loop() {
});
}
void EpubReaderFootnotesActivity::render(Activity::RenderLock&&) {
void EpubReaderFootnotesActivity::render(RenderLock&&) {
renderer.clearScreen();
renderer.drawCenteredText(UI_12_FONT_ID, 15, tr(STR_FOOTNOTES), true, EpdFontFamily::BOLD);

View File

@@ -6,29 +6,22 @@
#include <functional>
#include <vector>
#include "../ActivityWithSubactivity.h"
#include "../Activity.h"
#include "util/ButtonNavigator.h"
class EpubReaderFootnotesActivity final : public ActivityWithSubactivity {
class EpubReaderFootnotesActivity final : public Activity {
public:
explicit EpubReaderFootnotesActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
const std::vector<FootnoteEntry>& footnotes,
const std::function<void()>& onGoBack,
const std::function<void(const char*)>& onSelectFootnote)
: ActivityWithSubactivity("EpubReaderFootnotes", renderer, mappedInput),
footnotes(footnotes),
onGoBack(onGoBack),
onSelectFootnote(onSelectFootnote) {}
const std::vector<FootnoteEntry>& footnotes)
: Activity("EpubReaderFootnotes", renderer, mappedInput), footnotes(footnotes) {}
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
void render(RenderLock&&) override;
private:
const std::vector<FootnoteEntry>& footnotes;
const std::function<void()> onGoBack;
const std::function<void(const char*)> onSelectFootnote;
int selectedIndex = 0;
int scrollOffset = 0;
ButtonNavigator buttonNavigator;

View File

@@ -10,17 +10,14 @@
EpubReaderMenuActivity::EpubReaderMenuActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
const std::string& title, const int currentPage, const int totalPages,
const int bookProgressPercent, const uint8_t currentOrientation,
const bool hasFootnotes, const std::function<void(uint8_t)>& onBack,
const std::function<void(MenuAction)>& onAction)
: ActivityWithSubactivity("EpubReaderMenu", renderer, mappedInput),
const bool hasFootnotes)
: Activity("EpubReaderMenu", renderer, mappedInput),
menuItems(buildMenuItems(hasFootnotes)),
title(title),
pendingOrientation(currentOrientation),
currentPage(currentPage),
totalPages(totalPages),
bookProgressPercent(bookProgressPercent),
onBack(onBack),
onAction(onAction) {}
bookProgressPercent(bookProgressPercent) {}
std::vector<EpubReaderMenuActivity::MenuItem> EpubReaderMenuActivity::buildMenuItems(bool hasFootnotes) {
std::vector<MenuItem> items;
@@ -40,18 +37,13 @@ std::vector<EpubReaderMenuActivity::MenuItem> EpubReaderMenuActivity::buildMenuI
}
void EpubReaderMenuActivity::onEnter() {
ActivityWithSubactivity::onEnter();
Activity::onEnter();
requestUpdate();
}
void EpubReaderMenuActivity::onExit() { ActivityWithSubactivity::onExit(); }
void EpubReaderMenuActivity::onExit() { Activity::onExit(); }
void EpubReaderMenuActivity::loop() {
if (subActivity) {
subActivity->loop();
return;
}
// Handle navigation
buttonNavigator.onNext([this] {
selectedIndex = ButtonNavigator::nextIndex(selectedIndex, static_cast<int>(menuItems.size()));
@@ -63,7 +55,6 @@ void EpubReaderMenuActivity::loop() {
requestUpdate();
});
// Use local variables for items we need to check after potential deletion
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
const auto selectedAction = menuItems[selectedIndex].action;
if (selectedAction == MenuAction::ROTATE_SCREEN) {
@@ -73,22 +64,20 @@ void EpubReaderMenuActivity::loop() {
return;
}
// 1. Capture the callback and action locally
auto actionCallback = onAction;
// 2. Execute the callback
actionCallback(selectedAction);
// 3. CRITICAL: Return immediately. 'this' is likely deleted now.
setResult(MenuResult{static_cast<int>(selectedAction), pendingOrientation});
finish();
return;
} else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
// Return the pending orientation to the parent so it can apply on exit.
onBack(pendingOrientation);
return; // Also return here just in case
ActivityResult result;
result.isCancelled = true;
result.data = MenuResult{-1, pendingOrientation};
setResult(std::move(result));
finish();
return;
}
}
void EpubReaderMenuActivity::render(Activity::RenderLock&&) {
void EpubReaderMenuActivity::render(RenderLock&&) {
renderer.clearScreen();
const auto pageWidth = renderer.getScreenWidth();
const auto orientation = renderer.getOrientation();

View File

@@ -2,14 +2,13 @@
#include <Epub.h>
#include <I18n.h>
#include <functional>
#include <string>
#include <vector>
#include "../ActivityWithSubactivity.h"
#include "../Activity.h"
#include "util/ButtonNavigator.h"
class EpubReaderMenuActivity final : public ActivityWithSubactivity {
class EpubReaderMenuActivity final : public Activity {
public:
// Menu actions available from the reader menu.
enum class MenuAction {
@@ -26,14 +25,12 @@ class EpubReaderMenuActivity final : public ActivityWithSubactivity {
explicit EpubReaderMenuActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, const std::string& title,
const int currentPage, const int totalPages, const int bookProgressPercent,
const uint8_t currentOrientation, const bool hasFootnotes,
const std::function<void(uint8_t)>& onBack,
const std::function<void(MenuAction)>& onAction);
const uint8_t currentOrientation, const bool hasFootnotes);
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
void render(RenderLock&&) override;
private:
struct MenuItem {
@@ -56,7 +53,4 @@ class EpubReaderMenuActivity final : public ActivityWithSubactivity {
int currentPage = 0;
int totalPages = 0;
int bookProgressPercent = 0;
const std::function<void(uint8_t)> onBack;
const std::function<void(MenuAction)> onAction;
};

View File

@@ -14,12 +14,12 @@ constexpr int kLargeStep = 10;
} // namespace
void EpubReaderPercentSelectionActivity::onEnter() {
ActivityWithSubactivity::onEnter();
Activity::onEnter();
// Set up rendering task and mark first frame dirty.
requestUpdate();
}
void EpubReaderPercentSelectionActivity::onExit() { ActivityWithSubactivity::onExit(); }
void EpubReaderPercentSelectionActivity::onExit() { Activity::onExit(); }
void EpubReaderPercentSelectionActivity::adjustPercent(const int delta) {
// Apply delta and clamp within 0-100.
@@ -33,19 +33,18 @@ void EpubReaderPercentSelectionActivity::adjustPercent(const int delta) {
}
void EpubReaderPercentSelectionActivity::loop() {
if (subActivity) {
subActivity->loop();
return;
}
// Back cancels, confirm selects, arrows adjust the percent.
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
onCancel();
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
return;
}
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
onSelect(percent);
setResult(PercentResult{percent});
finish();
return;
}
@@ -56,7 +55,7 @@ void EpubReaderPercentSelectionActivity::loop() {
buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Down}, [this] { adjustPercent(-kLargeStep); });
}
void EpubReaderPercentSelectionActivity::render(Activity::RenderLock&&) {
void EpubReaderPercentSelectionActivity::render(RenderLock&&) {
renderer.clearScreen();
// Title and numeric percent value.

View File

@@ -1,26 +1,20 @@
#pragma once
#include <functional>
#include "MappedInputManager.h"
#include "activities/ActivityWithSubactivity.h"
#include "activities/Activity.h"
#include "util/ButtonNavigator.h"
class EpubReaderPercentSelectionActivity final : public ActivityWithSubactivity {
class EpubReaderPercentSelectionActivity final : public Activity {
public:
// Slider-style percent selector for jumping within a book.
explicit EpubReaderPercentSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
const int initialPercent, const std::function<void(int)>& onSelect,
const std::function<void()>& onCancel)
: ActivityWithSubactivity("EpubReaderPercentSelection", renderer, mappedInput),
percent(initialPercent),
onSelect(onSelect),
onCancel(onCancel) {}
const int initialPercent)
: Activity("EpubReaderPercentSelection", renderer, mappedInput), percent(initialPercent) {}
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
void render(RenderLock&&) override;
private:
// Current percent value (0-100) shown on the slider.
@@ -28,11 +22,6 @@ class EpubReaderPercentSelectionActivity final : public ActivityWithSubactivity
ButtonNavigator buttonNavigator;
// Callback invoked when the user confirms a percent.
const std::function<void(int)> onSelect;
// Callback invoked when the user cancels the slider.
const std::function<void()> onCancel;
// Change the current percent by a delta and clamp within bounds.
void adjustPercent(int delta);
};

View File

@@ -51,11 +51,12 @@ void wifiOff() {
} // namespace
void KOReaderSyncActivity::onWifiSelectionComplete(const bool success) {
exitActivity();
if (!success) {
LOG_DBG("KOSync", "WiFi connection failed, exiting");
onCancel();
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
return;
}
@@ -66,7 +67,7 @@ void KOReaderSyncActivity::onWifiSelectionComplete(const bool success) {
state = SYNCING;
statusMessage = tr(STR_SYNCING_TIME);
}
requestUpdate();
requestUpdate(true);
// Sync time with NTP before making API requests
syncTimeWithNTP();
@@ -75,7 +76,7 @@ void KOReaderSyncActivity::onWifiSelectionComplete(const bool success) {
RenderLock lock(*this);
statusMessage = tr(STR_CALC_HASH);
}
requestUpdate();
requestUpdate(true);
performSync();
}
@@ -93,7 +94,7 @@ void KOReaderSyncActivity::performSync() {
state = SYNC_FAILED;
statusMessage = tr(STR_HASH_FAILED);
}
requestUpdate();
requestUpdate(true);
return;
}
@@ -115,7 +116,7 @@ void KOReaderSyncActivity::performSync() {
state = NO_REMOTE_PROGRESS;
hasRemoteProgress = false;
}
requestUpdate();
requestUpdate(true);
return;
}
@@ -125,7 +126,7 @@ void KOReaderSyncActivity::performSync() {
state = SYNC_FAILED;
statusMessage = KOReaderSyncClient::errorString(result);
}
requestUpdate();
requestUpdate(true);
return;
}
@@ -149,7 +150,7 @@ void KOReaderSyncActivity::performSync() {
selectedOption = 0; // Apply remote progress
}
}
requestUpdate();
requestUpdate(true);
}
void KOReaderSyncActivity::performUpload() {
@@ -158,7 +159,6 @@ void KOReaderSyncActivity::performUpload() {
state = UPLOADING;
statusMessage = tr(STR_UPLOAD_PROGRESS);
}
requestUpdate();
requestUpdateAndWait();
// Convert current position to KOReader format
@@ -188,11 +188,11 @@ void KOReaderSyncActivity::performUpload() {
RenderLock lock(*this);
state = UPLOAD_COMPLETE;
}
requestUpdate();
requestUpdate(true);
}
void KOReaderSyncActivity::onEnter() {
ActivityWithSubactivity::onEnter();
Activity::onEnter();
// Check for credentials first
if (!KOREADER_STORE.hasCredentials()) {
@@ -206,7 +206,7 @@ void KOReaderSyncActivity::onEnter() {
LOG_DBG("KOSync", "Already connected to WiFi");
state = SYNCING;
statusMessage = tr(STR_SYNCING_TIME);
requestUpdate();
requestUpdate(true);
// Perform sync directly (will be handled in loop)
xTaskCreate(
@@ -218,7 +218,7 @@ void KOReaderSyncActivity::onEnter() {
RenderLock lock(*self);
self->statusMessage = tr(STR_CALC_HASH);
}
self->requestUpdate();
self->requestUpdate(true);
self->performSync();
vTaskDelete(nullptr);
},
@@ -228,21 +228,17 @@ void KOReaderSyncActivity::onEnter() {
// Launch WiFi selection subactivity
LOG_DBG("KOSync", "Launching WifiSelectionActivity...");
enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
[this](const bool connected) { onWifiSelectionComplete(connected); }));
startActivityForResult(std::make_unique<WifiSelectionActivity>(renderer, mappedInput),
[this](const ActivityResult& result) { onWifiSelectionComplete(!result.isCancelled); });
}
void KOReaderSyncActivity::onExit() {
ActivityWithSubactivity::onExit();
Activity::onExit();
wifiOff();
}
void KOReaderSyncActivity::render(Activity::RenderLock&&) {
if (subActivity) {
return;
}
void KOReaderSyncActivity::render(RenderLock&&) {
const auto pageWidth = renderer.getScreenWidth();
renderer.clearScreen();
@@ -357,49 +353,50 @@ void KOReaderSyncActivity::render(Activity::RenderLock&&) {
}
void KOReaderSyncActivity::loop() {
if (subActivity) {
subActivity->loop();
return;
}
if (state == NO_CREDENTIALS || state == SYNC_FAILED || state == UPLOAD_COMPLETE) {
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
onCancel();
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
}
return;
}
if (state == SHOWING_RESULT) {
// Navigate options
if (mappedInput.wasPressed(MappedInputManager::Button::Up) ||
mappedInput.wasPressed(MappedInputManager::Button::Left)) {
if (mappedInput.wasReleased(MappedInputManager::Button::Up) ||
mappedInput.wasReleased(MappedInputManager::Button::Left)) {
selectedOption = (selectedOption + 1) % 2; // Wrap around among 2 options
requestUpdate();
} else if (mappedInput.wasPressed(MappedInputManager::Button::Down) ||
mappedInput.wasPressed(MappedInputManager::Button::Right)) {
} else if (mappedInput.wasReleased(MappedInputManager::Button::Down) ||
mappedInput.wasReleased(MappedInputManager::Button::Right)) {
selectedOption = (selectedOption + 1) % 2; // Wrap around among 2 options
requestUpdate();
}
if (mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
if (selectedOption == 0) {
// Apply remote progress — WiFi no longer needed
wifiOff();
onSyncComplete(remotePosition.spineIndex, remotePosition.pageNumber);
// Wifi will be turned off in onExit()
setResult(SyncResult{remotePosition.spineIndex, remotePosition.pageNumber});
finish();
} else if (selectedOption == 1) {
// Upload local progress
performUpload();
}
}
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
onCancel();
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
}
return;
}
if (state == NO_REMOTE_PROGRESS) {
if (mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
// Calculate hash if not done yet
if (documentHash.empty()) {
if (KOREADER_STORE.getMatchMethod() == DocumentMatchMethod::FILENAME) {
@@ -411,8 +408,11 @@ void KOReaderSyncActivity::loop() {
performUpload();
}
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
onCancel();
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
}
return;
}

View File

@@ -6,7 +6,7 @@
#include "KOReaderSyncClient.h"
#include "ProgressMapper.h"
#include "activities/ActivityWithSubactivity.h"
#include "activities/Activity.h"
/**
* Activity for syncing reading progress with KOReader sync server.
@@ -18,16 +18,12 @@
* 4. Show comparison and options (Apply/Upload)
* 5. Apply or upload progress
*/
class KOReaderSyncActivity final : public ActivityWithSubactivity {
class KOReaderSyncActivity final : public Activity {
public:
using OnCancelCallback = std::function<void()>;
using OnSyncCompleteCallback = std::function<void(int newSpineIndex, int newPageNumber)>;
explicit KOReaderSyncActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
const std::shared_ptr<Epub>& epub, const std::string& epubPath, int currentSpineIndex,
int currentPage, int totalPagesInSpine, OnCancelCallback onCancel,
OnSyncCompleteCallback onSyncComplete)
: ActivityWithSubactivity("KOReaderSync", renderer, mappedInput),
int currentPage, int totalPagesInSpine)
: Activity("KOReaderSync", renderer, mappedInput),
epub(epub),
epubPath(epubPath),
currentSpineIndex(currentSpineIndex),
@@ -35,14 +31,12 @@ class KOReaderSyncActivity final : public ActivityWithSubactivity {
totalPagesInSpine(totalPagesInSpine),
remoteProgress{},
remotePosition{},
localProgress{},
onCancel(std::move(onCancel)),
onSyncComplete(std::move(onSyncComplete)) {}
localProgress{} {}
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
void render(RenderLock&&) override;
bool preventAutoSleep() override { return state == CONNECTING || state == SYNCING; }
private:
@@ -79,9 +73,6 @@ class KOReaderSyncActivity final : public ActivityWithSubactivity {
// Selection in result screen (0=Apply, 1=Upload)
int selectedOption = 0;
OnCancelCallback onCancel;
OnSyncCompleteCallback onSyncComplete;
void onWifiSelectionComplete(bool success);
void performSync();
void performUpload();

View File

@@ -18,12 +18,12 @@ void QrDisplayActivity::onExit() { Activity::onExit(); }
void QrDisplayActivity::loop() {
if (mappedInput.wasReleased(MappedInputManager::Button::Back) ||
mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
onGoBack();
finish();
return;
}
}
void QrDisplayActivity::render(Activity::RenderLock&&) {
void QrDisplayActivity::render(RenderLock&&) {
renderer.clearScreen();
auto metrics = UITheme::getInstance().getMetrics();
const auto pageWidth = renderer.getScreenWidth();

View File

@@ -7,16 +7,14 @@
class QrDisplayActivity final : public Activity {
public:
explicit QrDisplayActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, const std::string& textPayload,
const std::function<void()>& onGoBack)
: Activity("QrDisplay", renderer, mappedInput), textPayload(textPayload), onGoBack(onGoBack) {}
explicit QrDisplayActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, const std::string& textPayload)
: Activity("QrDisplay", renderer, mappedInput), textPayload(textPayload) {}
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
void render(RenderLock&&) override;
private:
std::string textPayload;
const std::function<void()> onGoBack;
};

View File

@@ -79,41 +79,34 @@ std::unique_ptr<Txt> ReaderActivity::loadTxt(const std::string& path) {
void ReaderActivity::goToLibrary(const std::string& fromBookPath) {
// If coming from a book, start in that book's folder; otherwise start from root
const auto initialPath = fromBookPath.empty() ? "/" : extractFolderPath(fromBookPath);
onGoToLibrary(initialPath);
auto initialPath = fromBookPath.empty() ? "/" : extractFolderPath(fromBookPath);
activityManager.goToMyLibrary(std::move(initialPath));
}
void ReaderActivity::onGoToEpubReader(std::unique_ptr<Epub> epub) {
const auto epubPath = epub->getPath();
currentBookPath = epubPath;
exitActivity();
enterNewActivity(new EpubReaderActivity(
renderer, mappedInput, std::move(epub), [this, epubPath] { goToLibrary(epubPath); }, [this] { onGoBack(); }));
activityManager.replaceActivity(std::make_unique<EpubReaderActivity>(renderer, mappedInput, std::move(epub)));
}
void ReaderActivity::onGoToBmpViewer(const std::string& path) {
exitActivity();
enterNewActivity(new BmpViewerActivity(renderer, mappedInput, path, [this, path] { goToLibrary(path); }));
activityManager.replaceActivity(std::make_unique<BmpViewerActivity>(renderer, mappedInput, path));
}
void ReaderActivity::onGoToXtcReader(std::unique_ptr<Xtc> xtc) {
const auto xtcPath = xtc->getPath();
currentBookPath = xtcPath;
exitActivity();
enterNewActivity(new XtcReaderActivity(
renderer, mappedInput, std::move(xtc), [this, xtcPath] { goToLibrary(xtcPath); }, [this] { onGoBack(); }));
activityManager.replaceActivity(std::make_unique<XtcReaderActivity>(renderer, mappedInput, std::move(xtc)));
}
void ReaderActivity::onGoToTxtReader(std::unique_ptr<Txt> txt) {
const auto txtPath = txt->getPath();
currentBookPath = txtPath;
exitActivity();
enterNewActivity(new TxtReaderActivity(
renderer, mappedInput, std::move(txt), [this, txtPath] { goToLibrary(txtPath); }, [this] { onGoBack(); }));
activityManager.replaceActivity(std::make_unique<TxtReaderActivity>(renderer, mappedInput, std::move(txt)));
}
void ReaderActivity::onEnter() {
ActivityWithSubactivity::onEnter();
Activity::onEnter();
if (initialBookPath.empty()) {
goToLibrary(); // Start from root when entering via Browse
@@ -146,3 +139,5 @@ void ReaderActivity::onEnter() {
onGoToEpubReader(std::move(epub));
}
}
void ReaderActivity::onGoBack() { finish(); }

View File

@@ -1,18 +1,16 @@
#pragma once
#include <memory>
#include "../ActivityWithSubactivity.h"
#include "../Activity.h"
#include "activities/home/MyLibraryActivity.h"
class Epub;
class Xtc;
class Txt;
class ReaderActivity final : public ActivityWithSubactivity {
class ReaderActivity final : public Activity {
std::string initialBookPath;
std::string currentBookPath; // Track current book path for navigation
const std::function<void()> onGoBack;
const std::function<void(const std::string&)> onGoToLibrary;
static std::unique_ptr<Epub> loadEpub(const std::string& path);
static std::unique_ptr<Xtc> loadXtc(const std::string& path);
static std::unique_ptr<Txt> loadTxt(const std::string& path);
@@ -27,14 +25,11 @@ class ReaderActivity final : public ActivityWithSubactivity {
void onGoToTxtReader(std::unique_ptr<Txt> txt);
void onGoToBmpViewer(const std::string& path);
void onGoBack();
public:
explicit ReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string initialBookPath,
const std::function<void()>& onGoBack,
const std::function<void(const std::string&)>& onGoToLibrary)
: ActivityWithSubactivity("Reader", renderer, mappedInput),
initialBookPath(std::move(initialBookPath)),
onGoBack(onGoBack),
onGoToLibrary(onGoToLibrary) {}
explicit ReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string initialBookPath)
: Activity("Reader", renderer, mappedInput), initialBookPath(std::move(initialBookPath)) {}
void onEnter() override;
bool isReaderActivity() const override { return true; }
};

View File

@@ -23,7 +23,7 @@ constexpr uint8_t CACHE_VERSION = 2; // Increment when cache format cha
} // namespace
void TxtReaderActivity::onEnter() {
ActivityWithSubactivity::onEnter();
Activity::onEnter();
if (!txt) {
return;
@@ -61,7 +61,7 @@ void TxtReaderActivity::onEnter() {
}
void TxtReaderActivity::onExit() {
ActivityWithSubactivity::onExit();
Activity::onExit();
// Reset orientation back to portrait for the rest of the UI
renderer.setOrientation(GfxRenderer::Orientation::Portrait);
@@ -74,14 +74,9 @@ void TxtReaderActivity::onExit() {
}
void TxtReaderActivity::loop() {
if (subActivity) {
subActivity->loop();
return;
}
// Long press BACK (1s+) goes to file selection
if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) {
onGoBack();
activityManager.goToMyLibrary(txt ? txt->getPath() : "");
return;
}
@@ -325,7 +320,7 @@ bool TxtReaderActivity::loadPageAtOffset(size_t offset, std::vector<std::string>
return !outLines.empty();
}
void TxtReaderActivity::render(Activity::RenderLock&&) {
void TxtReaderActivity::render(RenderLock&&) {
if (!txt) {
return;
}

View File

@@ -5,18 +5,15 @@
#include <vector>
#include "CrossPointSettings.h"
#include "activities/ActivityWithSubactivity.h"
#include "activities/Activity.h"
class TxtReaderActivity final : public ActivityWithSubactivity {
class TxtReaderActivity final : public Activity {
std::unique_ptr<Txt> txt;
int currentPage = 0;
int totalPages = 1;
int pagesUntilFullRefresh = 0;
const std::function<void()> onGoBack;
const std::function<void()> onGoHome;
// Streaming text reader - stores file offsets for each page
std::vector<size_t> pageOffsets; // File offset for start of each page
std::vector<std::string> currentPageLines;
@@ -45,14 +42,11 @@ class TxtReaderActivity final : public ActivityWithSubactivity {
void loadProgress();
public:
explicit TxtReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Txt> txt,
const std::function<void()>& onGoBack, const std::function<void()>& onGoHome)
: ActivityWithSubactivity("TxtReader", renderer, mappedInput),
txt(std::move(txt)),
onGoBack(onGoBack),
onGoHome(onGoHome) {}
explicit TxtReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Txt> txt)
: Activity("TxtReader", renderer, mappedInput), txt(std::move(txt)) {}
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
void render(RenderLock&&) override;
bool isReaderActivity() const override { return true; }
};

View File

@@ -26,7 +26,7 @@ constexpr unsigned long goHomeMs = 1000;
} // namespace
void XtcReaderActivity::onEnter() {
ActivityWithSubactivity::onEnter();
Activity::onEnter();
if (!xtc) {
return;
@@ -47,7 +47,7 @@ void XtcReaderActivity::onEnter() {
}
void XtcReaderActivity::onExit() {
ActivityWithSubactivity::onExit();
Activity::onExit();
APP_STATE.readerActivityLoadCount = 0;
APP_STATE.saveToFile();
@@ -55,33 +55,22 @@ void XtcReaderActivity::onExit() {
}
void XtcReaderActivity::loop() {
// Pass input responsibility to sub activity if exists
if (subActivity) {
subActivity->loop();
return;
}
// Enter chapter selection activity
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
if (xtc && xtc->hasChapters() && !xtc->getChapters().empty()) {
exitActivity();
enterNewActivity(new XtcReaderChapterSelectionActivity(
this->renderer, this->mappedInput, xtc, currentPage,
[this] {
exitActivity();
requestUpdate();
},
[this](const uint32_t newPage) {
currentPage = newPage;
exitActivity();
requestUpdate();
}));
startActivityForResult(
std::make_unique<XtcReaderChapterSelectionActivity>(renderer, mappedInput, xtc, currentPage),
[this](const ActivityResult& result) {
if (!result.isCancelled) {
currentPage = std::get<PageResult>(result.data).page;
}
});
}
}
// Long press BACK (1s+) goes to file selection
if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) {
onGoBack();
activityManager.goToMyLibrary(xtc ? xtc->getPath() : "");
return;
}
@@ -135,7 +124,7 @@ void XtcReaderActivity::loop() {
}
}
void XtcReaderActivity::render(Activity::RenderLock&&) {
void XtcReaderActivity::render(RenderLock&&) {
if (!xtc) {
return;
}

View File

@@ -9,30 +9,24 @@
#include <Xtc.h>
#include "activities/ActivityWithSubactivity.h"
#include "activities/Activity.h"
class XtcReaderActivity final : public ActivityWithSubactivity {
class XtcReaderActivity final : public Activity {
std::shared_ptr<Xtc> xtc;
uint32_t currentPage = 0;
int pagesUntilFullRefresh = 0;
const std::function<void()> onGoBack;
const std::function<void()> onGoHome;
void renderPage();
void saveProgress() const;
void loadProgress();
public:
explicit XtcReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Xtc> xtc,
const std::function<void()>& onGoBack, const std::function<void()>& onGoHome)
: ActivityWithSubactivity("XtcReader", renderer, mappedInput),
xtc(std::move(xtc)),
onGoBack(onGoBack),
onGoHome(onGoHome) {}
explicit XtcReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Xtc> xtc)
: Activity("XtcReader", renderer, mappedInput), xtc(std::move(xtc)) {}
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
void render(RenderLock&&) override;
bool isReaderActivity() const override { return true; }
};

View File

@@ -59,10 +59,14 @@ void XtcReaderChapterSelectionActivity::loop() {
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
const auto& chapters = xtc->getChapters();
if (!chapters.empty() && selectorIndex >= 0 && selectorIndex < static_cast<int>(chapters.size())) {
onSelectPage(chapters[selectorIndex].startPage);
setResult(PageResult{chapters[selectorIndex].startPage});
finish();
}
} else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
onGoBack();
ActivityResult result;
result.isCancelled = true;
setResult(std::move(result));
finish();
}
buttonNavigator.onNextRelease([this, totalItems] {
@@ -86,7 +90,7 @@ void XtcReaderChapterSelectionActivity::loop() {
});
}
void XtcReaderChapterSelectionActivity::render(Activity::RenderLock&&) {
void XtcReaderChapterSelectionActivity::render(RenderLock&&) {
renderer.clearScreen();
const auto pageWidth = renderer.getScreenWidth();

View File

@@ -12,24 +12,16 @@ class XtcReaderChapterSelectionActivity final : public Activity {
uint32_t currentPage = 0;
int selectorIndex = 0;
const std::function<void()> onGoBack;
const std::function<void(uint32_t newPage)> onSelectPage;
int getPageItems() const;
int findChapterIndexForPage(uint32_t page) const;
public:
explicit XtcReaderChapterSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
const std::shared_ptr<Xtc>& xtc, uint32_t currentPage,
const std::function<void()>& onGoBack,
const std::function<void(uint32_t newPage)>& onSelectPage)
: Activity("XtcReaderChapterSelection", renderer, mappedInput),
xtc(xtc),
currentPage(currentPage),
onGoBack(onGoBack),
onSelectPage(onSelectPage) {}
const std::shared_ptr<Xtc>& xtc, uint32_t currentPage)
: Activity("XtcReaderChapterSelection", renderer, mappedInput), xtc(xtc), currentPage(currentPage) {}
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
void render(RenderLock&&) override;
bool isReaderActivity() const override { return true; }
};