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:
101
src/main.cpp
101
src/main.cpp
@@ -18,16 +18,8 @@
|
||||
#include "KOReaderCredentialStore.h"
|
||||
#include "MappedInputManager.h"
|
||||
#include "RecentBooksStore.h"
|
||||
#include "activities/boot_sleep/BootActivity.h"
|
||||
#include "activities/boot_sleep/SleepActivity.h"
|
||||
#include "activities/browser/OpdsBookBrowserActivity.h"
|
||||
#include "activities/home/HomeActivity.h"
|
||||
#include "activities/home/MyLibraryActivity.h"
|
||||
#include "activities/home/RecentBooksActivity.h"
|
||||
#include "activities/network/CrossPointWebServerActivity.h"
|
||||
#include "activities/reader/ReaderActivity.h"
|
||||
#include "activities/settings/SettingsActivity.h"
|
||||
#include "activities/util/FullScreenMessageActivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "activities/ActivityManager.h"
|
||||
#include "components/UITheme.h"
|
||||
#include "fontIds.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
@@ -37,8 +29,8 @@ HalDisplay display;
|
||||
HalGPIO gpio;
|
||||
MappedInputManager mappedInputManager(gpio);
|
||||
GfxRenderer renderer(display);
|
||||
ActivityManager activityManager(renderer, mappedInputManager);
|
||||
FontDecompressor fontDecompressor;
|
||||
Activity* currentActivity;
|
||||
|
||||
// Fonts
|
||||
EpdFont bookerly14RegularFont(&bookerly_14_regular);
|
||||
@@ -133,19 +125,6 @@ EpdFontFamily ui12FontFamily(&ui12RegularFont, &ui12BoldFont);
|
||||
unsigned long t1 = 0;
|
||||
unsigned long t2 = 0;
|
||||
|
||||
void exitActivity() {
|
||||
if (currentActivity) {
|
||||
currentActivity->onExit();
|
||||
delete currentActivity;
|
||||
currentActivity = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void enterNewActivity(Activity* activity) {
|
||||
currentActivity = activity;
|
||||
currentActivity->onEnter();
|
||||
}
|
||||
|
||||
// Verify power button press duration on wake-up from deep sleep
|
||||
// Pre-condition: isWakeupByPowerButton() == true
|
||||
void verifyPowerButtonDuration() {
|
||||
@@ -201,10 +180,10 @@ void waitForPowerRelease() {
|
||||
// Enter deep sleep mode
|
||||
void enterDeepSleep() {
|
||||
HalPowerManager::Lock powerLock; // Ensure we are at normal CPU frequency for sleep preparation
|
||||
APP_STATE.lastSleepFromReader = currentActivity && currentActivity->isReaderActivity();
|
||||
APP_STATE.lastSleepFromReader = activityManager.isReaderActivity();
|
||||
APP_STATE.saveToFile();
|
||||
exitActivity();
|
||||
enterNewActivity(new SleepActivity(renderer, mappedInputManager));
|
||||
|
||||
activityManager.goToSleep();
|
||||
|
||||
display.deepSleep();
|
||||
LOG_DBG("MAIN", "Power button press calibration value: %lu ms", t2 - t1);
|
||||
@@ -213,54 +192,10 @@ void enterDeepSleep() {
|
||||
powerManager.startDeepSleep(gpio);
|
||||
}
|
||||
|
||||
void onGoHome();
|
||||
void onGoToMyLibraryWithPath(const std::string& path);
|
||||
void onGoToRecentBooks();
|
||||
void onGoToReader(const std::string& initialEpubPath) {
|
||||
const std::string bookPath = initialEpubPath; // Copy before exitActivity() invalidates the reference
|
||||
exitActivity();
|
||||
enterNewActivity(new ReaderActivity(renderer, mappedInputManager, bookPath, onGoHome, onGoToMyLibraryWithPath));
|
||||
}
|
||||
|
||||
void onGoToFileTransfer() {
|
||||
exitActivity();
|
||||
enterNewActivity(new CrossPointWebServerActivity(renderer, mappedInputManager, onGoHome));
|
||||
}
|
||||
|
||||
void onGoToSettings() {
|
||||
exitActivity();
|
||||
enterNewActivity(new SettingsActivity(renderer, mappedInputManager, onGoHome));
|
||||
}
|
||||
|
||||
void onGoToMyLibrary() {
|
||||
exitActivity();
|
||||
enterNewActivity(new MyLibraryActivity(renderer, mappedInputManager, onGoHome, onGoToReader));
|
||||
}
|
||||
|
||||
void onGoToRecentBooks() {
|
||||
exitActivity();
|
||||
enterNewActivity(new RecentBooksActivity(renderer, mappedInputManager, onGoHome, onGoToReader));
|
||||
}
|
||||
|
||||
void onGoToMyLibraryWithPath(const std::string& path) {
|
||||
exitActivity();
|
||||
enterNewActivity(new MyLibraryActivity(renderer, mappedInputManager, onGoHome, onGoToReader, path));
|
||||
}
|
||||
|
||||
void onGoToBrowser() {
|
||||
exitActivity();
|
||||
enterNewActivity(new OpdsBookBrowserActivity(renderer, mappedInputManager, onGoHome));
|
||||
}
|
||||
|
||||
void onGoHome() {
|
||||
exitActivity();
|
||||
enterNewActivity(new HomeActivity(renderer, mappedInputManager, onGoToReader, onGoToMyLibrary, onGoToRecentBooks,
|
||||
onGoToSettings, onGoToFileTransfer, onGoToBrowser));
|
||||
}
|
||||
|
||||
void setupDisplayAndFonts() {
|
||||
display.begin();
|
||||
renderer.begin();
|
||||
activityManager.begin();
|
||||
LOG_DBG("MAIN", "Display initialized");
|
||||
|
||||
// Initialize font decompressor for compressed reader fonts
|
||||
@@ -310,8 +245,7 @@ void setup() {
|
||||
if (!Storage.begin()) {
|
||||
LOG_ERR("MAIN", "SD card initialization failed");
|
||||
setupDisplayAndFonts();
|
||||
exitActivity();
|
||||
enterNewActivity(new FullScreenMessageActivity(renderer, mappedInputManager, "SD card error", EpdFontFamily::BOLD));
|
||||
activityManager.goToFullScreenMessage("SD card error", EpdFontFamily::BOLD);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -344,8 +278,7 @@ void setup() {
|
||||
|
||||
setupDisplayAndFonts();
|
||||
|
||||
exitActivity();
|
||||
enterNewActivity(new BootActivity(renderer, mappedInputManager));
|
||||
activityManager.goToBoot();
|
||||
|
||||
APP_STATE.loadFromFile();
|
||||
RECENT_BOOKS.loadFromFile();
|
||||
@@ -354,14 +287,14 @@ void setup() {
|
||||
// crashed (indicated by readerActivityLoadCount > 0)
|
||||
if (APP_STATE.openEpubPath.empty() || !APP_STATE.lastSleepFromReader ||
|
||||
mappedInputManager.isPressed(MappedInputManager::Button::Back) || APP_STATE.readerActivityLoadCount > 0) {
|
||||
onGoHome();
|
||||
activityManager.goHome();
|
||||
} 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();
|
||||
onGoToReader(path);
|
||||
activityManager.goToReader(path);
|
||||
}
|
||||
|
||||
// Ensure we're not still holding the power button before leaving setup
|
||||
@@ -401,7 +334,7 @@ void loop() {
|
||||
|
||||
// Check for any user activity (button press or release) or active background work
|
||||
static unsigned long lastActivityTime = millis();
|
||||
if (gpio.wasAnyPressed() || gpio.wasAnyReleased() || (currentActivity && currentActivity->preventAutoSleep())) {
|
||||
if (gpio.wasAnyPressed() || gpio.wasAnyReleased() || activityManager.preventAutoSleep()) {
|
||||
lastActivityTime = millis(); // Reset inactivity timer
|
||||
powerManager.setPowerSaving(false); // Restore normal CPU frequency on user activity
|
||||
}
|
||||
@@ -410,8 +343,8 @@ void loop() {
|
||||
if (gpio.isPressed(HalGPIO::BTN_POWER) && gpio.isPressed(HalGPIO::BTN_DOWN)) {
|
||||
if (screenshotButtonsReleased) {
|
||||
screenshotButtonsReleased = false;
|
||||
if (currentActivity) {
|
||||
Activity::RenderLock lock(*currentActivity);
|
||||
{
|
||||
RenderLock lock;
|
||||
ScreenshotUtil::takeScreenshot(renderer);
|
||||
}
|
||||
}
|
||||
@@ -439,9 +372,7 @@ void loop() {
|
||||
}
|
||||
|
||||
const unsigned long activityStartTime = millis();
|
||||
if (currentActivity) {
|
||||
currentActivity->loop();
|
||||
}
|
||||
activityManager.loop();
|
||||
const unsigned long activityDuration = millis() - activityStartTime;
|
||||
|
||||
const unsigned long loopDuration = millis() - loopStartTime;
|
||||
@@ -455,7 +386,7 @@ void loop() {
|
||||
// Add delay at the end of the loop to prevent tight spinning
|
||||
// When an activity requests skip loop delay (e.g., webserver running), use yield() for faster response
|
||||
// Otherwise, use longer delay to save power
|
||||
if (currentActivity && currentActivity->skipLoopDelay()) {
|
||||
if (activityManager.skipLoopDelay()) {
|
||||
powerManager.setPowerSaving(false); // Make sure we're at full performance when skipLoopDelay is requested
|
||||
yield(); // Give FreeRTOS a chance to run tasks, but return immediately
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user