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

@@ -0,0 +1,252 @@
#include "ActivityManager.h"
#include <HalPowerManager.h>
#include "boot_sleep/BootActivity.h"
#include "boot_sleep/SleepActivity.h"
#include "browser/OpdsBookBrowserActivity.h"
#include "home/HomeActivity.h"
#include "home/MyLibraryActivity.h"
#include "home/RecentBooksActivity.h"
#include "network/CrossPointWebServerActivity.h"
#include "reader/ReaderActivity.h"
#include "settings/SettingsActivity.h"
#include "util/FullScreenMessageActivity.h"
void ActivityManager::begin() {
xTaskCreate(&renderTaskTrampoline, "ActivityManagerRender",
8192, // Stack size
this, // Parameters
1, // Priority
&renderTaskHandle // Task handle
);
assert(renderTaskHandle != nullptr && "Failed to create render task");
}
void ActivityManager::renderTaskTrampoline(void* param) {
auto* self = static_cast<ActivityManager*>(param);
self->renderTaskLoop();
}
void ActivityManager::renderTaskLoop() {
while (true) {
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
// Acquire the lock before reading currentActivity to avoid a TOCTOU race
// where the main task deletes the activity between the null-check and render().
RenderLock lock;
if (currentActivity) {
HalPowerManager::Lock powerLock; // Ensure we don't go into low-power mode while rendering
currentActivity->render(std::move(lock));
}
}
}
void ActivityManager::loop() {
if (currentActivity) {
// Note: do not hold a lock here, the loop() method must be responsible for acquire one if needed
currentActivity->loop();
}
while (pendingAction != PendingAction::None) {
if (pendingAction == PendingAction::Pop) {
RenderLock lock;
if (!currentActivity) {
// Should never happen in practice
LOG_ERR("ACT", "Pop set but currentActivity is null; ignoring pop request");
pendingAction = PendingAction::None;
continue;
}
ActivityResult pendingResult = std::move(currentActivity->result);
// Destroy the current activity
exitActivity(lock);
pendingAction = PendingAction::None;
if (stackActivities.empty()) {
LOG_DBG("ACT", "No more activities on stack, going home");
lock.unlock(); // goHome may acquire its own lock
goHome();
continue; // Will launch goHome immediately
} else {
currentActivity = std::move(stackActivities.back());
stackActivities.pop_back();
LOG_DBG("ACT", "Popped from activity stack, new size = %zu", stackActivities.size());
// Handle result if necessary
if (currentActivity->resultHandler) {
LOG_DBG("ACT", "Handling result for popped activity");
// Move it here to avoid the case where handler calling another startActivityForResult()
auto handler = std::move(currentActivity->resultHandler);
currentActivity->resultHandler = nullptr;
lock.unlock(); // Handler may acquire its own lock
handler(pendingResult);
}
// Request an update to ensure the popped activity gets re-rendered
if (pendingAction == PendingAction::None) {
requestUpdate();
}
// Handler may request another pending action, we will handle it in the next loop iteration
continue;
}
} else if (pendingActivity) {
// Current activity has requested a new activity to be launched
RenderLock lock;
if (pendingAction == PendingAction::Replace) {
// Destroy the current activity
exitActivity(lock);
// Clear the stack
while (!stackActivities.empty()) {
stackActivities.back()->onExit();
stackActivities.pop_back();
}
} else if (pendingAction == PendingAction::Push) {
// Move current activity to stack
stackActivities.push_back(std::move(currentActivity));
LOG_DBG("ACT", "Pushed to activity stack, new size = %zu", stackActivities.size());
}
pendingAction = PendingAction::None;
currentActivity = std::move(pendingActivity);
lock.unlock(); // onEnter may acquire its own lock
currentActivity->onEnter();
// onEnter may request another pending action, we will handle it in the next loop iteration
continue;
}
}
if (requestedUpdate) {
requestedUpdate = false;
// Using direct notification to signal the render task to update
// Increment counter so multiple rapid calls won't be lost
if (renderTaskHandle) {
xTaskNotify(renderTaskHandle, 1, eIncrement);
}
}
}
void ActivityManager::exitActivity(const RenderLock& lock) {
// Note: lock must be held by the caller
if (currentActivity) {
currentActivity->onExit();
currentActivity.reset();
}
}
void ActivityManager::replaceActivity(std::unique_ptr<Activity>&& newActivity) {
// Note: no lock here, this is usually called by loop() and we may run into deadlock
if (currentActivity) {
// Defer launch if we're currently in an activity, to avoid deleting the current activity
// leading to the "delete this" problem
pendingActivity = std::move(newActivity);
pendingAction = PendingAction::Replace;
} else {
// No current activity, safe to launch immediately
currentActivity = std::move(newActivity);
currentActivity->onEnter();
}
}
void ActivityManager::goToFileTransfer() {
replaceActivity(std::make_unique<CrossPointWebServerActivity>(renderer, mappedInput));
}
void ActivityManager::goToSettings() { replaceActivity(std::make_unique<SettingsActivity>(renderer, mappedInput)); }
void ActivityManager::goToMyLibrary(std::string path) {
replaceActivity(std::make_unique<MyLibraryActivity>(renderer, mappedInput, std::move(path)));
}
void ActivityManager::goToRecentBooks() {
replaceActivity(std::make_unique<RecentBooksActivity>(renderer, mappedInput));
}
void ActivityManager::goToBrowser() {
replaceActivity(std::make_unique<OpdsBookBrowserActivity>(renderer, mappedInput));
}
void ActivityManager::goToReader(std::string path) {
replaceActivity(std::make_unique<ReaderActivity>(renderer, mappedInput, std::move(path)));
}
void ActivityManager::goToSleep() {
replaceActivity(std::make_unique<SleepActivity>(renderer, mappedInput));
loop(); // Important: sleep screen must be rendered immediately, the caller will go to sleep right after this returns
}
void ActivityManager::goToBoot() { replaceActivity(std::make_unique<BootActivity>(renderer, mappedInput)); }
void ActivityManager::goToFullScreenMessage(std::string message, EpdFontFamily::Style style) {
replaceActivity(std::make_unique<FullScreenMessageActivity>(renderer, mappedInput, std::move(message), style));
}
void ActivityManager::goHome() { replaceActivity(std::make_unique<HomeActivity>(renderer, mappedInput)); }
void ActivityManager::pushActivity(std::unique_ptr<Activity>&& activity) {
if (pendingActivity) {
// Should never happen in practice
LOG_ERR("ACT", "pendingActivity while pushActivity is not expected");
pendingActivity.reset();
}
pendingActivity = std::move(activity);
pendingAction = PendingAction::Push;
}
void ActivityManager::popActivity() {
if (pendingActivity) {
// Should never happen in practice
LOG_ERR("ACT", "pendingActivity while popActivity is not expected");
pendingActivity.reset();
}
pendingAction = PendingAction::Pop;
}
bool ActivityManager::preventAutoSleep() const { return currentActivity && currentActivity->preventAutoSleep(); }
bool ActivityManager::isReaderActivity() const { return currentActivity && currentActivity->isReaderActivity(); }
bool ActivityManager::skipLoopDelay() const { return currentActivity && currentActivity->skipLoopDelay(); }
void ActivityManager::requestUpdate(bool immediate) {
if (immediate) {
if (renderTaskHandle) {
xTaskNotify(renderTaskHandle, 1, eIncrement);
}
} else {
// Deferring the update until current loop is finished
// This is to avoid multiple updates being requested in the same loop
requestedUpdate = true;
}
}
// RenderLock
RenderLock::RenderLock() {
xSemaphoreTake(activityManager.renderingMutex, portMAX_DELAY);
isLocked = true;
}
RenderLock::RenderLock(Activity& /* unused */) {
xSemaphoreTake(activityManager.renderingMutex, portMAX_DELAY);
isLocked = true;
}
RenderLock::~RenderLock() {
if (isLocked) {
xSemaphoreGive(activityManager.renderingMutex);
isLocked = false;
}
}
void RenderLock::unlock() {
if (isLocked) {
xSemaphoreGive(activityManager.renderingMutex);
isLocked = false;
}
}