From 447a4e385e0f4d5d2566410b65e7655333509495 Mon Sep 17 00:00:00 2001 From: shen Date: Mon, 2 Nov 2026 22:27:11 +0800 Subject: [PATCH] feat: add safe game and app exit controls for 1.0.3 --- README.md | 4 +- app/build.gradle.kts | 4 +- .../java/org/neslite/app/ExitControlsTest.kt | 57 ++++++ app/src/main/cpp/CMakeLists.txt | 4 + app/src/main/cpp/core_session.cpp | 44 ++++- app/src/main/cpp/save_policy.cpp | 9 + app/src/main/cpp/save_policy.h | 8 + app/src/main/cpp/tests/exit_save_test.cpp | 30 +++ .../main/java/org/neslite/app/MainActivity.kt | 181 +++++++++++++++++- .../org/neslite/app/system/SystemUiPolicy.kt | 23 ++- .../java/org/neslite/app/BuildIdentityTest.kt | 4 +- .../org/neslite/app/system/ExitPolicyTest.kt | 60 ++++++ docs/build.md | 6 +- docs/releases/1.0.3.md | 12 ++ docs/usage.md | 2 +- 15 files changed, 417 insertions(+), 31 deletions(-) create mode 100644 app/src/androidTest/java/org/neslite/app/ExitControlsTest.kt create mode 100644 app/src/main/cpp/tests/exit_save_test.cpp create mode 100644 app/src/test/java/org/neslite/app/system/ExitPolicyTest.kt create mode 100644 docs/releases/1.0.3.md diff --git a/README.md b/README.md index 0866ab8..bb291f2 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # NESLite -NESLite 是一个面向 Android 的轻量 NES/FC 模拟器前端。当前版本为 1.0.2,内置固定提交的 +NESLite 是一个面向 Android 的轻量 NES/FC 模拟器前端。当前版本为 1.0.3,内置固定提交的 FCEUmm 和 Nestopia,可设置默认内核,也可长按游戏单独选择,下次打开游戏时生效。两个内核的存档 独立保留。0.9.17 对已确认哈希的“龙珠英雄”自动使用 Dendy 制式,两个内核的桌面启动与菜单检查 通过,详见 [兼容修复记录](docs/reports/long-zhu-ying-xiong-0.9.17.md)。 @@ -8,7 +8,7 @@ FCEUmm 和 Nestopia,可设置默认内核,也可长按游戏单独选择, 见 [显示修复记录](docs/reports/integer-scaling-0.9.18.md)。 源码仓库:[shen/NESLite](http://git.m3frame.com/shen/NESLite)。安装包、源码与校验值见 -[发行版](http://git.m3frame.com/shen/NESLite/releases),本次更新说明见 [1.0.2](docs/releases/1.0.2.md),首次发布说明见 [1.0.0](docs/releases/1.0.0.md)。 +[发行版](http://git.m3frame.com/shen/NESLite/releases),本次更新说明见 [1.0.3](docs/releases/1.0.3.md),首次发布说明见 [1.0.0](docs/releases/1.0.0.md)。 用户已确认产品可发布;历史测试报告中未归档的专项证据仍保留原状态,不据此宣称所有计划测试均已执行。 主界面固定为横屏游戏布局:中央是 4:3 游戏容器,可切换原始像素整数缩放,左右为虚拟按键,左上角提供游戏列表、导入和 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 21fe5dc..c22721e 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -21,8 +21,8 @@ android { applicationId = "org.neslite.app" minSdk = 28 targetSdk = 36 - versionCode = 1000002 - versionName = "1.0.2" + versionCode = 1000003 + versionName = "1.0.3" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" ndk { diff --git a/app/src/androidTest/java/org/neslite/app/ExitControlsTest.kt b/app/src/androidTest/java/org/neslite/app/ExitControlsTest.kt new file mode 100644 index 0000000..42f1a6a --- /dev/null +++ b/app/src/androidTest/java/org/neslite/app/ExitControlsTest.kt @@ -0,0 +1,57 @@ +package org.neslite.app + +import androidx.lifecycle.Lifecycle +import androidx.test.core.app.ActivityScenario +import androidx.test.espresso.Espresso.onView +import androidx.test.espresso.action.ViewActions.click +import androidx.test.espresso.action.ViewActions.scrollTo +import androidx.test.espresso.assertion.ViewAssertions.matches +import androidx.test.espresso.matcher.ViewMatchers.isDisplayed +import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility +import androidx.test.espresso.matcher.ViewMatchers.Visibility +import androidx.test.espresso.matcher.ViewMatchers.withContentDescription +import androidx.test.espresso.matcher.ViewMatchers.withText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.hamcrest.Matchers.allOf +import org.junit.Test +import org.junit.runner.RunWith +import org.neslite.app.settings.AppSettingsStore + +@RunWith(AndroidJUnit4::class) +class ExitControlsTest { + @Test + fun gameExitWithNoSessionOpensLibraryAndApplicationExitClosesTask() = withPreparedSettings { + ActivityScenario.launch(MainActivity::class.java).use { scenario -> + onView(withContentDescription("退出游戏")).perform(click()) + onView(allOf(withText("游戏列表"), isDisplayed())).check(matches(isDisplayed())) + onView(allOf(withText("退出应用"), isDisplayed())).perform(click()) + awaitDestroyed(scenario) + } + } + + @Test + fun settingsOffersApplicationExitWithoutAnActiveGame() = withPreparedSettings { + ActivityScenario.launch(MainActivity::class.java).use { scenario -> + onView(withContentDescription("设置")).perform(click()) + onView(allOf(withText("退出应用"), withEffectiveVisibility(Visibility.VISIBLE))).perform(scrollTo(), click()) + awaitDestroyed(scenario) + } + } + + private fun awaitDestroyed(scenario: ActivityScenario) = runBlocking { + withTimeout(5000L) { + while (scenario.state != Lifecycle.State.DESTROYED) delay(50L) + } + } + + private fun withPreparedSettings(test: () -> Unit) { + val store = AppSettingsStore(InstrumentationRegistry.getInstrumentation().targetContext) + val previous = runBlocking { store.load() } + runBlocking { store.save(previous.copy(guideCompleted = true)) } + try { test() } finally { runBlocking { store.save(previous) } } + } +} diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 22ea90b..6d98da9 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -55,6 +55,10 @@ if(ANDROID) add_dependencies(neslite_jni neslite_nestopia) else() enable_testing() + add_executable(neslite_exit_save_test tests/exit_save_test.cpp save_policy.cpp) + target_include_directories(neslite_exit_save_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + neslite_enable_strict_warnings(neslite_exit_save_test) + add_test(NAME neslite_exit_save_test COMMAND neslite_exit_save_test) add_executable(neslite_native_smoke_test tests/native_smoke_test.cpp ${NESLITE_COMMON_SOURCES} diff --git a/app/src/main/cpp/core_session.cpp b/app/src/main/cpp/core_session.cpp index e5d193f..ed331af 100644 --- a/app/src/main/cpp/core_session.cpp +++ b/app/src/main/cpp/core_session.cpp @@ -234,13 +234,13 @@ struct Host { committed_battery_hash = sha256_hex(battery_snapshot()); } - bool save_battery() { + bool save_battery(bool ensure_committed = false) { auto snapshot = battery_snapshot(); - if (snapshot.empty()) return false; + if (snapshot.empty()) return ensure_committed && core.retro_get_memory_size(RETRO_MEMORY_SAVE_RAM) == 0; const std::string checksum = sha256_hex(snapshot); const auto final_path = std::filesystem::path(save_dir) / rom_hash / "battery" / "battery.sav"; std::error_code exists_error; - if (checksum == committed_battery_hash && std::filesystem::is_regular_file(final_path, exists_error)) return false; + if (!ensure_committed && checksum == committed_battery_hash && std::filesystem::is_regular_file(final_path, exists_error)) return false; const bool success = commit_bytes(final_path, std::move(snapshot)) == CommitResult::Committed; if (success) committed_battery_hash = checksum; return success; @@ -507,7 +507,7 @@ struct Host { return true; } - bool unload() { + bool unload(bool persist = true) { timing.transition(TimingMode::Paused, monotonic_now_ns()); fast_forward = false; audio.set_fast_muted(false); @@ -516,9 +516,11 @@ struct Host { resampler.reset(); bool battery_saved = false; if (loaded) { - battery_saved = save_battery(); - (void)save_auto_point(); - (void)write_session_marker(false); + if (persist) { + battery_saved = save_battery(); + (void)save_auto_point(); + (void)write_session_marker(false); + } core.retro_unload_game(); loaded = false; } @@ -750,9 +752,33 @@ struct Host { } else if (command.name == "stop" && (loaded || state == SessionState::Error) && command_allowed(state.load(), command.name)) { set_state(SessionState::Stopping); - const bool battery_saved = unload(); + timing.transition(TimingMode::Paused, monotonic_now_ns()); + fast_forward = false; + audio.set_fast_muted(false); + audio.stop(); + joypad.store(0, std::memory_order_relaxed); + turbo.store(0, std::memory_order_relaxed); + effective_joypad.store(0, std::memory_order_relaxed); + error.clear(); + const bool had_game = loaded; + if (loaded) { + const auto saved = commit_exit_saves( + [this] { return save_battery(true); }, + [this] { return save_auto_point(); }, + [this] { return write_session_marker(false); }); + if (saved != ExitSaveResult::Committed) { + error = saved == ExitSaveResult::BatteryFailed ? "Exit battery save failed" : + saved == ExitSaveResult::AutoStateFailed ? "Exit auto state save failed" : + "Exit session marker commit failed"; + // Keep the core and ROM alive so saving can be retried. + set_state(SessionState::Paused); + complete(active_id, "stop_save_failed"); + return true; + } + } + (void)unload(false); set_state(SessionState::Idle); - complete(active_id, battery_saved ? "stopped_saved" : "stopped"); + complete(active_id, had_game ? "stopped_saved" : "stopped"); } else { complete(command.session_id, "ignored"); } diff --git a/app/src/main/cpp/save_policy.cpp b/app/src/main/cpp/save_policy.cpp index dea1154..e76352a 100644 --- a/app/src/main/cpp/save_policy.cpp +++ b/app/src/main/cpp/save_policy.cpp @@ -4,6 +4,15 @@ namespace neslite { +ExitSaveResult commit_exit_saves(const std::function& battery, + const std::function& auto_state, + const std::function& closed_marker) { + if (!battery()) return ExitSaveResult::BatteryFailed; + if (!auto_state()) return ExitSaveResult::AutoStateFailed; + if (!closed_marker()) return ExitSaveResult::MarkerFailed; + return ExitSaveResult::Committed; +} + SaveSchedule::SaveSchedule(double battery_interval_seconds, double auto_interval_seconds) : battery_interval_(std::max(0.001, battery_interval_seconds)), auto_interval_(std::max(0.001, auto_interval_seconds)) {} diff --git a/app/src/main/cpp/save_policy.h b/app/src/main/cpp/save_policy.h index 300694b..d77fde8 100644 --- a/app/src/main/cpp/save_policy.h +++ b/app/src/main/cpp/save_policy.h @@ -1,9 +1,17 @@ #pragma once #include +#include namespace neslite { +enum class ExitSaveResult { Committed, BatteryFailed, AutoStateFailed, MarkerFailed }; + +// Close the session marker only after both forms of progress are durable. +ExitSaveResult commit_exit_saves(const std::function& battery, + const std::function& auto_state, + const std::function& closed_marker); + class SaveSchedule { public: SaveSchedule(double battery_interval_seconds, double auto_interval_seconds); diff --git a/app/src/main/cpp/tests/exit_save_test.cpp b/app/src/main/cpp/tests/exit_save_test.cpp new file mode 100644 index 0000000..8e29382 --- /dev/null +++ b/app/src/main/cpp/tests/exit_save_test.cpp @@ -0,0 +1,30 @@ +#include "save_policy.h" + +#include + +int main() { + using neslite::ExitSaveResult; + for (int failure = 0; failure <= 3; ++failure) { + std::vector writes; + bool closed = false; + const auto result = neslite::commit_exit_saves( + [&] { writes.push_back(1); return failure != 1; }, + [&] { writes.push_back(2); return failure != 2; }, + [&] { writes.push_back(3); closed = failure != 3; return closed; }); + const auto expected = failure == 0 ? ExitSaveResult::Committed : + failure == 1 ? ExitSaveResult::BatteryFailed : + failure == 2 ? ExitSaveResult::AutoStateFailed : ExitSaveResult::MarkerFailed; + if (result != expected || closed != (failure == 0)) return 1; + const std::vector expected_writes = failure == 1 ? std::vector{1} : + failure == 2 ? std::vector{1, 2} : std::vector{1, 2, 3}; + if (writes != expected_writes) return 2; + // Retrying after any failure must complete all writes before declaring the session closed. + writes.clear(); + const auto retry = neslite::commit_exit_saves( + [&] { writes.push_back(1); return true; }, + [&] { writes.push_back(2); return true; }, + [&] { writes.push_back(3); closed = true; return true; }); + if (retry != ExitSaveResult::Committed || !closed || writes != std::vector{1, 2, 3}) return 3; + } + return 0; +} diff --git a/app/src/main/java/org/neslite/app/MainActivity.kt b/app/src/main/java/org/neslite/app/MainActivity.kt index c300fc3..9117cfa 100644 --- a/app/src/main/java/org/neslite/app/MainActivity.kt +++ b/app/src/main/java/org/neslite/app/MainActivity.kt @@ -45,6 +45,8 @@ import androidx.core.view.WindowInsetsCompat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.Job +import kotlinx.coroutines.joinAll import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import org.json.JSONArray @@ -85,6 +87,9 @@ import org.neslite.app.settings.AppSettingsStore import org.neslite.app.settings.VirtualDpadSize import org.neslite.app.settings.shouldShowVirtualGamepad import org.neslite.app.system.BackDecision +import org.neslite.app.system.ExitDestination +import org.neslite.app.system.ExitRequestAction +import org.neslite.app.system.exitRequestAction import org.neslite.app.system.CrashLoopGuard import org.neslite.app.system.RefreshRateSample import org.neslite.app.system.RefreshRateSampleBuffer @@ -186,6 +191,12 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private var refreshRateProbe: RefreshRateProbe? = null private var pendingSessionCommand: String? = null private var pendingPauseShowsMenu = false + private var exitDestination: ExitDestination? = null + private var exitConfirmationPending = false + private var exitDialog: AlertDialog? = null + private var exitProgressDialog: AlertDialog? = null + private var applicationExitPending = false + private lateinit var libraryExitButton: Button private var routeRebuildPending = false private var foregroundPreparePending = false private var abnormalRecordedSession = 0L @@ -283,6 +294,15 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { activeCore = NesCore.find(nativeStatus?.optString("coreId")) ?: NesCore.FCEUMM } } + if (activeSessionId != 0L) { + exitDestination = savedInstanceState?.getString("exit_destination")?.let { name -> + ExitDestination.entries.firstOrNull { it.name == name } + } + if (exitDestination != null) { + pendingSessionCommand = savedInstanceState?.getString("exit_pending_command") + exitConfirmationPending = pendingSessionCommand != "stop" + } + } foregroundPreparePending = activeSessionId != 0L setContentView(createContentView()) installWindowInsets() @@ -295,6 +315,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { loadAppSettings() refreshControllers() recoverLibrary() + if (exitDestination != null) { + if (pendingSessionCommand == "stop") showExitProgress() + else if (pendingSessionCommand == null && lastSessionState in setOf("Paused", "Error")) showExitConfirmation() + } pollSessionStatus() } @@ -327,6 +351,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { override fun onDestroy() { recordSystemEvent("activity_destroyed") + exitDialog?.dismiss() + exitProgressDialog?.dismiss() mainHandler.removeCallbacksAndMessages(null) libraryExecutor.shutdownNow() controllerScope.cancel() @@ -336,6 +362,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { override fun onSaveInstanceState(outState: Bundle) { outState.putLong(STATE_SESSION_ID, activeSessionId) outState.putString(STATE_GAME_HASH, activeGameHash) + outState.putString("exit_destination", exitDestination?.name) + outState.putString("exit_pending_command", pendingSessionCommand) super.onSaveInstanceState(outState) } @@ -369,7 +397,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { BackDecision.PAUSE_GAME -> sendControlCommand("pause") BackDecision.SHOW_PAUSE_MENU -> showPauseMenu() BackDecision.IGNORE_TRANSITION -> showEmulatorStatus("正在完成 $lastSessionState 状态交接,请稍候…") - BackDecision.EXIT_ACTIVITY -> finish() + BackDecision.EXIT_ACTIVITY -> requestExit(ExitDestination.APPLICATION) } } @@ -481,6 +509,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { target.visibility = View.VISIBLE overlayTitle.text = title currentOverlayPage = page + libraryExitButton.visibility = if (page == OverlayPage.LIBRARY) View.VISIBLE else View.GONE overlayScreen.setBackgroundColor(if (page == OverlayPage.SETTINGS) Color.rgb(244, 246, 250) else Color.WHITE) setSystemBarsVisible(true) overlayScreen.visibility = View.VISIBLE @@ -798,6 +827,13 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { addView(libraryRailButton) addView(railButton("+", "导入游戏", ::openImportPage)) addView(railButton("⚙", "设置", ::showSettings)) + addView(Button(context).apply { + text = "退出游戏" + contentDescription = "退出游戏" + isAllCaps = false + textSize = 12f + setOnClickListener { requestExit(ExitDestination.LIBRARY) } + }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, dp(38))) }, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, dp(44), Gravity.START or Gravity.TOP).apply { leftMargin = dp(6) @@ -839,6 +875,12 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { overlayTitle, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f), ) + libraryExitButton = Button(context).apply { + text = "退出应用" + visibility = View.GONE + setOnClickListener { requestExit(ExitDestination.APPLICATION) } + } + addView(libraryExitButton) }, LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, @@ -979,6 +1021,14 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { text = "继续" setOnClickListener { sendControlCommand("run") } }) + addView(Button(context).apply { + text = "退出游戏" + setOnClickListener { requestExit(ExitDestination.LIBRARY) } + }) + addView(Button(context).apply { + text = "退出应用" + setOnClickListener { requestExit(ExitDestination.APPLICATION) } + }) addView(Button(context).apply { text = "重置游戏" setOnClickListener { sendControlCommand("reset") } @@ -1029,10 +1079,102 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { text = "手柄设置" setOnClickListener { showControllerSettings(returnToPause = true) } }) - addView(Button(context).apply { - text = "退出游戏" - setOnClickListener { sendControlCommand("stop") } - }) + + } + + private fun requestExit(destination: ExitDestination) { + when (exitRequestAction(destination, activeSessionId != 0L, lastSessionState, + pendingSessionCommand, exitDestination != null || applicationExitPending)) { + ExitRequestAction.WAIT -> Toast.makeText(this, "正在处理,请稍候…", Toast.LENGTH_SHORT).show() + ExitRequestAction.FINISH_APPLICATION -> finishApplication() + ExitRequestAction.OPEN_LIBRARY -> openLibraryPage() + ExitRequestAction.PAUSE_THEN_CONFIRM -> { + exitDestination = destination + exitConfirmationPending = true + if (!sendControlCommand("pause")) { + exitDestination = null + exitConfirmationPending = false + } + } + ExitRequestAction.CONFIRM -> { + exitDestination = destination + showExitConfirmation() + } + } + } + + private fun showExitConfirmation() { + val destination = exitDestination ?: return + exitConfirmationPending = false + val dialog = AlertDialog.Builder(this) + .setTitle(if (destination == ExitDestination.APPLICATION) "退出应用?" else "退出当前游戏?") + .setMessage("将保存当前进度到自动恢复点,不覆盖手动存档。取消后游戏保持暂停。") + .setPositiveButton(if (destination == ExitDestination.APPLICATION) "保存并退出应用" else "保存并返回游戏列表") { _, _ -> + beginSaveAndExit() + } + .setNegativeButton("取消") { _, _ -> exitDestination = null } + .setOnCancelListener { exitDestination = null } + .create() + exitDialog = dialog + dialog.setOnDismissListener { if (exitDialog === dialog) exitDialog = null } + dialog.setOnShowListener { + dialog.getButton(AlertDialog.BUTTON_NEGATIVE).apply { + isFocusableInTouchMode = true + requestFocus() + } + } + dialog.show() + } + + private fun showExitProgress() { + if (exitProgressDialog != null) return + exitProgressDialog = AlertDialog.Builder(this) + .setTitle("正在保存…") + .setMessage("保存完成后退出,请稍候。") + .setCancelable(false) + .show() + } + + private fun beginSaveAndExit() { + if (exitDestination == null) return + if (sendControlCommand("stop")) showExitProgress() + else showExitFailure() + } + + private fun showExitFailure() { + exitProgressDialog?.dismiss() + exitProgressDialog = null + exitConfirmationPending = false + if (exitDestination == null) exitDestination = ExitDestination.LIBRARY + showPauseMenu() + val dialog = AlertDialog.Builder(this) + .setTitle("未能安全退出") + .setMessage("保存未完成,当前游戏仍保留。请检查可用存储空间后重试。") + .setPositiveButton("重试") { _, _ -> beginSaveAndExit() } + .setNegativeButton("留在游戏") { _, _ -> exitDestination = null } + .setOnCancelListener { exitDestination = null } + .create() + exitDialog = dialog + dialog.setOnDismissListener { if (exitDialog === dialog) exitDialog = null } + dialog.setOnShowListener { + dialog.getButton(AlertDialog.BUTTON_NEGATIVE).apply { + isFocusableInTouchMode = true + requestFocus() + } + } + dialog.show() + } + + private fun finishApplication() { + if (applicationExitPending) return + applicationExitPending = true + clearControllerState() + audioManager.abandonAudioFocusRequest(audioFocusRequest) + val pendingWrites = controllerScope.coroutineContext[Job]?.children?.toList().orEmpty() + controllerScope.launch { + pendingWrites.joinAll() + runOnUiThread { finishAndRemoveTask() } + } } private fun showPauseMenu() { @@ -1236,6 +1378,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { setOnClickListener { showCorePicker(null) } }) settingsPanel.addView(body("默认内核用于未单独指定的游戏。长按游戏可单独选择;修改在下次打开时生效,各内核存档独立。")) + settingsPanel.addView(Button(this).apply { + text = "退出应用" + setOnClickListener { requestExit(ExitDestination.APPLICATION) } + }) focusFirstButton(settingsPanel) } @@ -1355,7 +1501,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { emulatorSurface.linearFilter = appSettings.linearFilter } updateVirtualGamepadVisibility() - if (activeSessionId != 0L) { + if (activeSessionId != 0L && pendingSessionCommand != "stop") { applyRoutedInput(directionState) NativeBridge.command(activeSessionId, "volume:${appSettings.volume}") NativeBridge.command(activeSessionId, if (appSettings.muted) "mute:on" else "mute:off") @@ -2434,7 +2580,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { ) if (completionId != lastCompletionId) { lastCompletionId = completionId - settleSessionTransition(nextState, completion) + settleSessionTransition(nextState, completion, error) recordSystemEvent( "session_completion", JSONObject() @@ -2507,9 +2653,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { mainHandler.postDelayed(::pollSessionStatus, 250) } - private fun settleSessionTransition(nextState: String, completion: String) { + private fun settleSessionTransition(nextState: String, completion: String, error: String) { val pending = pendingSessionCommand - val settled = sessionTransitionSettled(pending, nextState, completion) + val settled = sessionTransitionSettled(pending, nextState, completion, error) if (!settled) return pendingSessionCommand = null when (pending) { @@ -2528,7 +2674,22 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { hidePauseMenu() if (::settingsPanel.isInitialized) settingsPanel.visibility = View.GONE if (::saveManagerPanel.isInitialized) saveManagerPanel.visibility = View.GONE - refreshLibrary() + exitProgressDialog?.dismiss() + exitProgressDialog = null + val destination = exitDestination + exitDestination = null + exitConfirmationPending = false + if (destination == ExitDestination.APPLICATION) finishApplication() else openLibraryPage() + } else { + showExitFailure() + } + } + if (exitConfirmationPending && pending != "stop") { + if (nextState == "Paused") showExitConfirmation() + else { + exitDestination = null + exitConfirmationPending = false + Toast.makeText(this, "未能暂停游戏,请稍后重试退出。", Toast.LENGTH_LONG).show() } } if (routeRebuildPending && nextState == "Paused" && pending != "stop") { diff --git a/app/src/main/java/org/neslite/app/system/SystemUiPolicy.kt b/app/src/main/java/org/neslite/app/system/SystemUiPolicy.kt index 457868e..6cb5c46 100644 --- a/app/src/main/java/org/neslite/app/system/SystemUiPolicy.kt +++ b/app/src/main/java/org/neslite/app/system/SystemUiPolicy.kt @@ -1,5 +1,22 @@ package org.neslite.app.system +enum class ExitDestination { LIBRARY, APPLICATION } +enum class ExitRequestAction { FINISH_APPLICATION, OPEN_LIBRARY, PAUSE_THEN_CONFIRM, CONFIRM, WAIT } + +fun exitRequestAction( + destination: ExitDestination, + hasSession: Boolean, + state: String, + pendingCommand: String?, + exitInProgress: Boolean, +): ExitRequestAction = when { + exitInProgress || pendingCommand != null || state in setOf("Loading", "Pausing", "Stopping") -> ExitRequestAction.WAIT + !hasSession -> if (destination == ExitDestination.APPLICATION) ExitRequestAction.FINISH_APPLICATION else ExitRequestAction.OPEN_LIBRARY + state == "Running" -> ExitRequestAction.PAUSE_THEN_CONFIRM + state in setOf("Paused", "Error") -> ExitRequestAction.CONFIRM + else -> ExitRequestAction.WAIT +} + enum class UiLayer { CONTROLLER_SETTINGS, SETTINGS, @@ -81,6 +98,7 @@ fun resolveLayoutSafeInsets( } fun sessionCommandAllowed(pending: String?, command: String, state: String): Boolean { + if (pending == "stop") return false val transition = command in setOf("load", "run", "pause", "stop") if (pending == "audio_rebuild" && command == "stop") return state in setOf("Paused", "Pausing") if (pending != null && (transition || command in setOf("reset", "audio_rebuild"))) return false @@ -93,12 +111,13 @@ fun sessionCommandAllowed(pending: String?, command: String, state: String): Boo } } -fun sessionTransitionSettled(pending: String?, nextState: String, completion: String): Boolean = +fun sessionTransitionSettled(pending: String?, nextState: String, completion: String, error: String = ""): Boolean = when (pending) { "load" -> nextState == "Paused" || nextState == "Error" "pause", "pause_external" -> nextState == "Paused" "run" -> nextState == "Running" - "stop" -> nextState == "Idle" + "stop" -> nextState == "Idle" || completion.endsWith(":stop_save_failed") || + (nextState == "Paused" && error.startsWith("Exit ") && error.endsWith("failed")) "audio_rebuild" -> nextState == "Paused" && (completion.endsWith(":audio_rebuilt_paused") || completion.endsWith(":audio_unavailable_paused")) else -> false diff --git a/app/src/test/java/org/neslite/app/BuildIdentityTest.kt b/app/src/test/java/org/neslite/app/BuildIdentityTest.kt index 2000d23..6c8fcc1 100644 --- a/app/src/test/java/org/neslite/app/BuildIdentityTest.kt +++ b/app/src/test/java/org/neslite/app/BuildIdentityTest.kt @@ -7,7 +7,7 @@ class BuildIdentityTest { @Test fun debugBuildUsesTheDocumentedIdentity() { assertEquals("org.neslite.app.debug", BuildConfig.APPLICATION_ID) - assertEquals("1.0.2-debug", BuildConfig.VERSION_NAME) - assertEquals(1000002, BuildConfig.VERSION_CODE) + assertEquals("1.0.3-debug", BuildConfig.VERSION_NAME) + assertEquals(1000003, BuildConfig.VERSION_CODE) } } diff --git a/app/src/test/java/org/neslite/app/system/ExitPolicyTest.kt b/app/src/test/java/org/neslite/app/system/ExitPolicyTest.kt new file mode 100644 index 0000000..4f0b990 --- /dev/null +++ b/app/src/test/java/org/neslite/app/system/ExitPolicyTest.kt @@ -0,0 +1,60 @@ +package org.neslite.app.system + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ExitPolicyTest { + @Test + fun noGameClosesApplicationOrReturnsToLibraryWithoutConfirmation() { + assertEquals(ExitRequestAction.FINISH_APPLICATION, + exitRequestAction(ExitDestination.APPLICATION, false, "Idle", null, false)) + assertEquals(ExitRequestAction.OPEN_LIBRARY, + exitRequestAction(ExitDestination.LIBRARY, false, "Idle", null, false)) + } + + @Test + fun runningGameMustPauseBeforeEitherExitConfirmation() { + ExitDestination.entries.forEach { destination -> + assertEquals(ExitRequestAction.PAUSE_THEN_CONFIRM, + exitRequestAction(destination, true, "Running", null, false)) + listOf("Paused", "Error").forEach { state -> + assertEquals(ExitRequestAction.CONFIRM, + exitRequestAction(destination, true, state, null, false)) + } + } + } + + @Test + fun duplicateRequestsAndInFlightOperationsCannotCloseTheApp() { + ExitDestination.entries.forEach { destination -> + listOf("Loading", "Pausing", "Stopping").forEach { state -> + assertEquals(ExitRequestAction.WAIT, + exitRequestAction(destination, true, state, null, false)) + } + listOf("load", "pause", "stop", "run", "audio_rebuild").forEach { command -> + assertEquals(ExitRequestAction.WAIT, + exitRequestAction(destination, true, "Paused", command, false)) + } + assertEquals(ExitRequestAction.WAIT, + exitRequestAction(destination, true, "Paused", null, true)) + assertEquals(ExitRequestAction.WAIT, + exitRequestAction(destination, false, "Idle", null, true)) + } + } + + @Test + fun failedSaveSettlesStopWithoutRequiringTheCoreToBeUnloaded() { + assertTrue(sessionTransitionSettled("stop", "Paused", "1:stop_save_failed")) + assertTrue(sessionCommandAllowed(null, "stop", "Paused")) + assertTrue(sessionCommandAllowed(null, "run", "Paused")) + assertFalse(sessionTransitionSettled("stop", "Paused", "1:paused_saved")) + assertFalse(sessionTransitionSettled("stop", "Stopping", "1:paused_saved")) + assertTrue(sessionTransitionSettled("stop", "Idle", "1:stopped_saved")) + // A later settings acknowledgement must not hide a failed stop and leave the progress dialog stuck. + assertTrue(sessionTransitionSettled("stop", "Paused", "1:volume", "Exit auto state save failed")) + assertFalse(sessionTransitionSettled("stop", "Paused", "1:volume", "")) + assertFalse(sessionCommandAllowed("stop", "state_save:0", "Paused")) + } +} diff --git a/docs/build.md b/docs/build.md index 0d3a851..01c8ffb 100644 --- a/docs/build.md +++ b/docs/build.md @@ -1,7 +1,7 @@ # NESLite 构建与打包 项目的 APK 打包入口统一为根目录 `打包.cmd`,项目内的编译产物、缓存、日志和交付文件统一放入 -`build/`。当前应用版本为 1.0.2,入口从 APK 构建元数据读取版本,不另写一套版本号。 +`build/`。当前应用版本为 1.0.3,入口从 APK 构建元数据读取版本,不另写一套版本号。 ## 一键打包 @@ -14,7 +14,7 @@ .\打包.cmd -NoPause ``` -当前交付文件是 `build/releases/NESLite-1.0.2-debug-arm64-v8a.apk`,旁边的 `.sha256` 保存校验值。 +当前交付文件是 `build/releases/NESLite-1.0.3-debug-arm64-v8a.apk`,旁边的 `.sha256` 保存校验值。 入口检查工具链与固定依赖、编译选定 APK、检查原生库和 APK 的 16 KB 对齐,成功后复制产物。 它不会自动启动单元测试、ROM 遍历、设备测试或发布回归;失败会返回非零退出码,旧交付 APK 不冒充本次成功产物。 @@ -24,7 +24,7 @@ .\打包.cmd release -NoPause ``` -该模式使用项目外的正式密钥,生成 `build/releases/NESLite-1.0.2-arm64-v8a.apk`、原生符号、应用和依赖源码 ZIP、发布清单及校验值。 +该模式使用项目外的正式密钥,生成 `build/releases/NESLite-1.0.3-arm64-v8a.apk`、原生符号、应用和依赖源码 ZIP、发布清单及校验值。 正式打包前必须提交源码并配置签名目录;入口读取 Windows 用户加密的密码,完成签名和签名验证。密钥位置与发布步骤见 [publishing.md](publishing.md)。 一键打包不会运行原 `package-rc.ps1` 的全量 Stage/lint/设备测试包构建,也不表示发布门槛通过。 diff --git a/docs/releases/1.0.3.md b/docs/releases/1.0.3.md new file mode 100644 index 0000000..8b4f85a --- /dev/null +++ b/docs/releases/1.0.3.md @@ -0,0 +1,12 @@ +# NESLite 1.0.3 + +新增清晰的“退出游戏”和“退出应用”入口,并加强退出前的进度保存。 + +- 游戏画面左上角和暂停菜单顶部提供“退出游戏”,保存后返回游戏列表。 +- 游戏列表右上角、设置页底部和暂停菜单提供“退出应用”,保存后关闭应用并返回桌面。 +- 有游戏运行时先暂停,再显示确认框,默认选中取消;没有运行游戏时退出应用无需确认。 +- 退出前提交电池进度与自动恢复点,不覆盖手动存档;保存失败保留游戏,支持重试或留在暂停菜单。 +- 退出过程中忽略重复操作,并在页面重建后恢复退出流程。 + +正式安装包为 `NESLite-1.0.3-arm64-v8a.apk`,版本号为 1000003,沿用原有正式签名,可覆盖安装旧正式版。 +75 项单元测试和 5 项原生测试通过,覆盖退出决策、重复请求和保存失败重试;设备界面测试编译通过。当前没有连接测试设备,完整游戏退出与手机桌面返回仍需实机验证。 diff --git a/docs/usage.md b/docs/usage.md index b26459b..44b83c7 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -31,7 +31,7 @@ 提交时间和缩略图。只有原生层确认安全落盘后才显示保存成功。 6. 存档包通过 Android 系统文件选择器导入导出,默认不含 ROM。导入前先加载对应游戏并暂停;哈希、 内核名称/提交、配置、路径、大小或校验不匹配会被拒绝并保留现有有效存档。 -7. 用“退出游戏”正常结束。上次进程异常终止时,再次加载相同游戏只列出校验有效的自动恢复点, +7. 游戏画面左上角和暂停菜单顶部提供“退出游戏”,确认后保存并返回游戏列表。游戏列表右上角、设置页底部和暂停菜单提供“退出应用”;有游戏时确认保存后关闭,无游戏时直接关闭。取消退出会保留暂停状态,保存失败可重试或留在游戏,自动恢复点不会覆盖手动存档。上次进程异常终止时,再次加载相同游戏只列出校验有效的自动恢复点, 不会自动运行或覆盖当前进度;同一游戏和恢复点连续异常两次后会返回列表并阻止重复启动,只有 明确点“手动重试”才再次加载。 8. 系统返回手势与手柄 B 使用相同规则:运行中先安全暂停;各独立页面返回主画面;设置、按键设置、