diff --git a/README.md b/README.md index bb291f2..e69b509 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # NESLite -NESLite 是一个面向 Android 的轻量 NES/FC 模拟器前端。当前版本为 1.0.3,内置固定提交的 +NESLite 是一个面向 Android 的轻量 NES/FC 模拟器前端。当前版本为 1.0.4,内置固定提交的 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.3](docs/releases/1.0.3.md),首次发布说明见 [1.0.0](docs/releases/1.0.0.md)。 +[发行版](http://git.m3frame.com/shen/NESLite/releases),本次更新说明见 [1.0.4](docs/releases/1.0.4.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 c22721e..3f1df5f 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 = 1000003 - versionName = "1.0.3" + versionCode = 1000004 + versionName = "1.0.4" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" ndk { diff --git a/app/src/androidTest/java/org/neslite/app/ButtonStateFlowTest.kt b/app/src/androidTest/java/org/neslite/app/ButtonStateFlowTest.kt new file mode 100644 index 0000000..e8db241 --- /dev/null +++ b/app/src/androidTest/java/org/neslite/app/ButtonStateFlowTest.kt @@ -0,0 +1,156 @@ +package org.neslite.app + +import android.os.SystemClock +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.matcher.ViewMatchers.* +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import kotlinx.coroutines.runBlocking +import org.hamcrest.Matchers.allOf +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.neslite.app.input.RoutedInputState +import org.neslite.app.library.GameEntity +import org.neslite.app.settings.AppSettingsStore +import java.io.File +import java.security.MessageDigest + +/** Uses a tiny, self-authored NROM loop; no commercial ROM or device controller is required. */ +@RunWith(AndroidJUnit4::class) +class ButtonStateFlowTest { + @Test fun pauseShortcutInSettingsCannotResumeBehindTheMenu() = withGame { scenario -> + onView(withContentDescription("设置")).perform(click()) + await(scenario) { field(it, "lastSessionState") == "Paused" && field(it, "pendingSessionCommand") == null } + pauseShortcut(scenario) + scenario.onActivity { + assertEquals("Paused", field(it, "lastSessionState")) + assertNull(field(it, "pendingSessionCommand")) + } + pauseShortcut(scenario) // Paused gameplay opens the pause menu. + await(scenario) { field(it, "currentOverlayPage").toString() == "PAUSE_MENU" } + onView(allOf(withText("继续"), isDisplayed())).perform(click()) + await(scenario) { field(it, "lastSessionState") == "Running" && field(it, "pendingSessionCommand") == null } + } + + @Test fun saveResetLoadAndExitCancelRemainInTheCorrectState() = withGame { scenario -> + pauseShortcut(scenario) + await(scenario) { field(it, "currentOverlayPage").toString() == "PAUSE_MENU" && field(it, "pendingSessionCommand") == null } + onView(allOf(withText("保存 1"), withEffectiveVisibility(Visibility.VISIBLE))).perform(scrollTo(), click()) + await(scenario) { field(it, "pendingSessionCommand") == null } + assertTrue(JSONObject(NativeBridge.sessionStatus()).getString("operationCompletion").endsWith(":state_saved")) + onView(allOf(withText("重置游戏"), withEffectiveVisibility(Visibility.VISIBLE))).perform(scrollTo(), click()) + await(scenario) { field(it, "pendingSessionCommand") == null } + onView(allOf(withText("读取 1"), withEffectiveVisibility(Visibility.VISIBLE))).perform(scrollTo(), click()) + await(scenario) { field(it, "pendingSessionCommand") == null } + assertTrue(JSONObject(NativeBridge.sessionStatus()).getString("operationCompletion").endsWith(":state_loaded")) + scenario.onActivity { activity -> + val menu = field(activity, "pauseMenu") as android.view.ViewGroup + (0 until menu.childCount).map { menu.getChildAt(it) }.filterIsInstance() + .single { it.text == "退出游戏" }.performClick() + } + onView(withText("取消")).perform(click()) + scenario.onActivity { + assertEquals("Paused", field(it, "lastSessionState")) + assertNull(field(it, "exitDestination")) + } + onView(allOf(withText("继续"), withEffectiveVisibility(Visibility.VISIBLE))).perform(scrollTo(), click()) + await(scenario) { field(it, "lastSessionState") == "Running" && field(it, "pendingSessionCommand") == null } + } + + @Test fun repeatedSaveAndResumeAreRejectedUntilAcknowledged() = withGame { scenario -> + pauseShortcut(scenario) + await(scenario) { field(it, "lastSessionState") == "Paused" && field(it, "pendingSessionCommand") == null } + scenario.onActivity { + val send = MainActivity::class.java.getDeclaredMethod("sendControlCommand", String::class.java).apply { isAccessible = true } + assertEquals(true, send.invoke(it, "state_save:0")) + assertEquals(false, send.invoke(it, "state_save:0")) + assertEquals(false, send.invoke(it, "run")) + assertEquals(false, send.invoke(it, "stop")) + } + await(scenario) { field(it, "pendingSessionCommand") == null } + scenario.onActivity { assertEquals("Paused", field(it, "lastSessionState")) } + } + + @Test fun resettingWhileHoldingButtonsClearsHeldInputAndFastForward() = withGame { scenario -> + scenario.onActivity { + val input = MainActivity::class.java.getDeclaredMethod("handleVirtualInput", Int::class.javaPrimitiveType, + org.neslite.app.input.GameAction::class.java, Boolean::class.javaPrimitiveType).apply { isAccessible = true } + input.invoke(it, 1, org.neslite.app.input.GameAction.NES_A, true) + input.invoke(it, 2, org.neslite.app.input.GameAction.FAST_FORWARD, true) + val send = MainActivity::class.java.getDeclaredMethod("sendControlCommand", String::class.java).apply { isAccessible = true } + assertEquals(true, send.invoke(it, "reset")) + input.invoke(it, 1, org.neslite.app.input.GameAction.NES_A, false) + input.invoke(it, 2, org.neslite.app.input.GameAction.FAST_FORWARD, false) + val router = field(it, "inputRouter") as org.neslite.app.input.InputRouter + assertEquals(0, router.current().joypadMask) + } + await(scenario) { field(it, "pendingSessionCommand") == null } + val status = JSONObject(NativeBridge.sessionStatus()) + assertFalse(status.getBoolean("fastForward")) + assertEquals(0, status.getJSONObject("input").getInt("baseMask")) + } + + private fun pauseShortcut(scenario: ActivityScenario) = scenario.onActivity { + MainActivity::class.java.getDeclaredMethod("applyRoutedInput", RoutedInputState::class.java) + .apply { isAccessible = true }.invoke(it, RoutedInputState(0, 0, pauseMenuEdge = true)) + } + + private fun field(activity: MainActivity, name: String): Any? = + MainActivity::class.java.getDeclaredField(name).apply { isAccessible = true }.get(activity) + + private fun await(scenario: ActivityScenario, condition: (MainActivity) -> Boolean) { + val deadline = SystemClock.uptimeMillis() + 10000 + while (SystemClock.uptimeMillis() < deadline) { + var ready = false + scenario.onActivity { ready = condition(it) } + if (ready) return + SystemClock.sleep(30) + } + fail("Timed out waiting for button/session state") + } + + private fun withGame(test: (ActivityScenario) -> Unit) { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val settings = AppSettingsStore(context) + val previous = runBlocking { settings.load() } + runBlocking { settings.save(previous.copy(guideCompleted = true)) } + // SEI; JMP $8001. NMI/reset/IRQ vectors all point to $8000. + val rom = ByteArray(16 + 16384 + 8192) + byteArrayOf(0x4e, 0x45, 0x53, 0x1a, 1, 1).copyInto(rom) + byteArrayOf(0x78, 0x4c, 0x01, 0x80.toByte()).copyInto(rom, 16) + for (offset in listOf(0x3ffa, 0x3ffc, 0x3ffe)) rom[16 + offset + 1] = 0x80.toByte() + val hash = MessageDigest.getInstance("SHA-256").digest(rom).joinToString("") { "%02x".format(it) } + val directory = File(context.filesDir, "roms").apply { mkdirs() } + val file = File(directory, "button-flow-fixture.nes").apply { writeBytes(rom) } + val game = GameEntity(hash, "Button state fixture", rom.size.toLong(), "iNES", file.name, + GameEntity.STATUS_READY, 0, false, false, 0) + try { + ActivityScenario.launch(MainActivity::class.java).use { scenario -> + await(scenario) { field(it, "corePreferencesReady") == true && it.hasWindowFocus() } + scenario.onActivity { + MainActivity::class.java.getDeclaredMethod("loadGame", GameEntity::class.java) + .apply { isAccessible = true }.invoke(it, game) + } + await(scenario) { field(it, "lastSessionState") == "Running" && field(it, "pendingSessionCommand") == null } + try { test(scenario) } finally { + val status = JSONObject(NativeBridge.sessionStatus()) + val id = status.optLong("sessionId") + if (id != 0L && status.optString("state") != "Idle") { + NativeBridge.command(id, "stop") + val deadline = SystemClock.uptimeMillis() + 10000 + while (JSONObject(NativeBridge.sessionStatus()).optString("state") != "Idle" && + SystemClock.uptimeMillis() < deadline) SystemClock.sleep(50) + } + } + } + } finally { + file.delete() + runBlocking { settings.save(previous) } + } + } +} diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 6d98da9..71eae60 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_operation_completion_test tests/operation_completion_test.cpp session_rules.cpp) + target_include_directories(neslite_operation_completion_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + neslite_enable_strict_warnings(neslite_operation_completion_test) + add_test(NAME neslite_operation_completion_test COMMAND neslite_operation_completion_test) 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) diff --git a/app/src/main/cpp/core_session.cpp b/app/src/main/cpp/core_session.cpp index ed331af..404d07e 100644 --- a/app/src/main/cpp/core_session.cpp +++ b/app/src/main/cpp/core_session.cpp @@ -115,6 +115,8 @@ struct Host { std::atomic session_id{0}; std::uint64_t completion_id = 0; std::string completion; + std::string executing_command; + OperationCompletion operation; std::string error; std::string system_dir; std::string save_dir; @@ -173,6 +175,7 @@ struct Host { std::lock_guard lock(mutex); ++completion_id; completion = std::to_string(id) + ":" + std::move(result); + operation.record(completion_id, executing_command, completion); } void fail(std::uint64_t id, std::string message) { @@ -643,6 +646,7 @@ struct Host { } bool handle(Command command) { + executing_command = command.name; if (command.name == "shutdown") { unload(); return false; @@ -1059,6 +1063,9 @@ std::string session_status_json() { << ",\"compatibilityProfile\":\"" << compatibility_profile_name(host.compatibility.load()) << "\"" << ",\"state\":\"" << session_state_name(host.state.load(std::memory_order_acquire)) << "\",\"queueDepth\":" << host.commands.size() + << ",\"operationCompletionId\":" << host.operation.id + << ",\"operationCommand\":\"" << json_escape(host.operation.command) << "\"" + << ",\"operationCompletion\":\"" << json_escape(host.operation.result) << "\"" << ",\"completionId\":" << host.completion_id << ",\"completion\":\"" << json_escape(host.completion) << "\",\"error\":\"" << json_escape(host.error) diff --git a/app/src/main/cpp/session_rules.cpp b/app/src/main/cpp/session_rules.cpp index 0073e6f..8424ed7 100644 --- a/app/src/main/cpp/session_rules.cpp +++ b/app/src/main/cpp/session_rules.cpp @@ -18,6 +18,20 @@ const char* session_state_name(SessionState state) { return "Error"; } +bool is_session_operation(std::string_view command) { + return command == "load" || command == "run" || command == "pause" || command == "stop" || + command == "reset" || command == "audio_rebuild" || command == "package_export" || + command == "package_import" || command.starts_with("state_save:") || + command.starts_with("state_load:") || command.starts_with("auto_load:"); +} + +void OperationCompletion::record(std::uint64_t completion_id, std::string_view name, const std::string& value) { + if (!is_session_operation(name)) return; + id = completion_id; + command = name; + result = value; +} + bool command_allowed(SessionState state, std::string_view command) { if (command == "load") return state != SessionState::Loading && state != SessionState::Stopping; if (command == "run") return state == SessionState::Paused; diff --git a/app/src/main/cpp/session_rules.h b/app/src/main/cpp/session_rules.h index 20741dd..387285f 100644 --- a/app/src/main/cpp/session_rules.h +++ b/app/src/main/cpp/session_rules.h @@ -3,12 +3,23 @@ #include #include #include +#include namespace neslite { enum class SessionState { Idle, Loading, Paused, Running, Pausing, Stopping, Error }; const char* session_state_name(SessionState state); +bool is_session_operation(std::string_view command); +// Settings and input acknowledgements must not erase a save/transition result +// before the UI's next status poll. The caller serializes access. +struct OperationCompletion { + std::uint64_t id = 0; + std::string command; + std::string result; + void record(std::uint64_t completion_id, std::string_view name, const std::string& value); +}; + bool command_allowed(SessionState state, std::string_view command); bool command_targets_active_session(std::uint64_t active_session, std::uint64_t command_session); bool required_host_capabilities_available(unsigned core_api_version, unsigned expected_api_version, diff --git a/app/src/main/cpp/tests/operation_completion_test.cpp b/app/src/main/cpp/tests/operation_completion_test.cpp new file mode 100644 index 0000000..1f383e2 --- /dev/null +++ b/app/src/main/cpp/tests/operation_completion_test.cpp @@ -0,0 +1,24 @@ +#include "session_rules.h" +#include +#include + +int main() { + neslite::OperationCompletion completion; + const std::vector operations{"load", "run", "pause", "stop", "reset", "audio_rebuild", + "state_save:0", "state_load:9", "auto_load:2", "package_export", "package_import"}; + std::uint64_t sequence = 0; + for (const auto& command : operations) { + const auto expected_id = ++sequence; + completion.record(expected_id, command, "7:finished"); + for (const auto& noise : {"volume:0.5", "mute:on", "mute:off", "fast:on", "fast:off"}) { + completion.record(++sequence, noise, "7:ignored"); + if (completion.id != expected_id || completion.command != command || completion.result != "7:finished") return 1; + } + } + completion.record(++sequence, "stop", "7:stop_save_failed"); + completion.record(++sequence, "volume:1", "7:volume"); + if (completion.result != "7:stop_save_failed") return 2; + completion.record(++sequence, "stop", "7:stopped_saved"); + if (completion.id != sequence || completion.result != "7:stopped_saved") 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 9117cfa..fb5a9ec 100644 --- a/app/src/main/java/org/neslite/app/MainActivity.kt +++ b/app/src/main/java/org/neslite/app/MainActivity.kt @@ -100,6 +100,8 @@ import org.neslite.app.system.SystemUiPolicy import org.neslite.app.system.UiLayer import org.neslite.app.system.resolveLayoutSafeInsets import org.neslite.app.system.finishRefreshRateProbe +import org.neslite.app.system.matchesPendingCompletion +import org.neslite.app.system.shouldRunLoadedGame import org.neslite.app.system.sessionCommandAllowed import org.neslite.app.system.sessionTransitionSettled import java.io.File @@ -190,6 +192,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private val sampledDisplayModes = mutableSetOf() private var refreshRateProbe: RefreshRateProbe? = null private var pendingSessionCommand: String? = null + private var pendingCommandBaseline = 0L + private var autoRunAfterLoad = false + private var activityStarted = false + private var pendingGameAfterStop: GameEntity? = null private var pendingPauseShowsMenu = false private var exitDestination: ExitDestination? = null private var exitConfirmationPending = false @@ -298,10 +304,22 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { 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" + pendingSessionCommand = savedInstanceState?.getString("exit_pending_command") + pendingCommandBaseline = savedInstanceState?.getLong("pending_command_baseline") ?: 0L + // onStop may enqueue a pause after Android captured savedInstanceState. + val restoredStatus = JSONObject(NativeBridge.sessionStatus()) + if (pendingSessionCommand in setOf("run", "reset") && + restoredStatus.optString("operationCommand") == "pause" && + restoredStatus.optLong("operationCompletionId") > pendingCommandBaseline) { + pendingSessionCommand = "pause_external" } + pendingPauseShowsMenu = pendingSessionCommand == "pause" + pendingSaveExportUri = savedInstanceState?.getString("save_export_uri")?.let(Uri::parse) + pendingSaveExportFile = savedInstanceState?.getString("save_export_file")?.let(::File) + if (pendingSessionCommand in setOf("package_import_read", "package_export_copy")) { + pendingSessionCommand = null // The previous Activity owned this file copy; keep the game paused. + } + exitConfirmationPending = exitDestination != null && pendingSessionCommand != "stop" } foregroundPreparePending = activeSessionId != 0L setContentView(createContentView()) @@ -324,6 +342,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { override fun onStart() { super.onStart() + activityStarted = true inputManager.registerInputDeviceListener(this, null) refreshControllers() if (::emulatorSurface.isInitialized) emulatorSurface.onResume() @@ -334,6 +353,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } override fun onStop() { + activityStarted = false foregroundPreparePending = activeSessionId != 0L pauseForExternalReason("activity_stopped") audioManager.abandonAudioFocusRequest(audioFocusRequest) @@ -364,6 +384,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { outState.putString(STATE_GAME_HASH, activeGameHash) outState.putString("exit_destination", exitDestination?.name) outState.putString("exit_pending_command", pendingSessionCommand) + outState.putLong("pending_command_baseline", pendingCommandBaseline) + outState.putString("save_export_uri", pendingSaveExportUri?.toString()) + outState.putString("save_export_file", pendingSaveExportFile?.absolutePath) super.onSaveInstanceState(outState) } @@ -378,6 +401,19 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } } + private fun postToActiveUi(action: () -> Unit) { + runOnUiThread { if (!isFinishing && !isDestroyed) action() } + } + + private fun canNavigate(): Boolean { + val allowed = pendingSessionCommand == null && !applicationExitPending && exitDestination == null && + lastSessionState !in setOf("Loading", "Pausing", "Stopping") + if (!allowed) Toast.makeText(this, "正在处理,请稍候…", Toast.LENGTH_SHORT).show() + return allowed + } + + private fun operationBaseline(): Long = JSONObject(NativeBridge.sessionStatus()).optLong("operationCompletionId") + private fun installUnifiedBackHandler() { onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() = handleUnifiedBack() @@ -528,12 +564,14 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } private fun openLibraryPage() { + if (!canNavigate()) return if (lastSessionState == "Running" && !pauseForExternalReason("open_library")) return showOverlayPage(OverlayPage.LIBRARY, "游戏列表") refreshLibrary() } private fun openImportPage() { + if (!canNavigate()) return if (lastSessionState == "Running" && !pauseForExternalReason("open_import")) return showOverlayPage(OverlayPage.IMPORT, "导入游戏") } @@ -1067,12 +1105,12 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { ) addView(Button(context).apply { text = "导出存档包(不含 ROM)" - setOnClickListener { createSavePackage.launch("neslite-save-${System.currentTimeMillis()}.nsp") } + setOnClickListener { if (canNavigate()) createSavePackage.launch("neslite-save-${System.currentTimeMillis()}.nsp") } }) addView(Button(context).apply { text = "导入存档包" setOnClickListener { - openSavePackage.launch(arrayOf("application/vnd.neslite.save", "application/octet-stream", "*/*")) + if (canNavigate()) openSavePackage.launch(arrayOf("application/vnd.neslite.save", "application/octet-stream", "*/*")) } }) addView(Button(context).apply { @@ -1170,10 +1208,17 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { applicationExitPending = true clearControllerState() audioManager.abandonAudioFocusRequest(audioFocusRequest) - val pendingWrites = controllerScope.coroutineContext[Job]?.children?.toList().orEmpty() - controllerScope.launch { - pendingWrites.joinAll() - runOnUiThread { finishAndRemoveTask() } + val parent = controllerScope.coroutineContext[Job] + controllerScope.launch(Dispatchers.Main.immediate) { + val current = coroutineContext[Job] + // A profile save can enqueue the matching virtual-button preference write. + // Wait for those follow-up writes too before destroying the Activity. + while (true) { + val writes = parent?.children?.filter { it !== current }?.toList().orEmpty() + if (writes.isEmpty()) break + writes.joinAll() + } + if (!isDestroyed) finishAndRemoveTask() } } @@ -1189,6 +1234,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } private fun showSettings() { + if (!canNavigate()) return val openedFromPause = currentOverlayPage == OverlayPage.PAUSE_MENU if (lastSessionState == "Running" && !pauseForExternalReason("open_settings")) return settingsReturnToPause = openedFromPause @@ -1198,6 +1244,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private fun renderSettings() { if (!::settingsPanel.isInitialized || settingsPanel.visibility != View.VISIBLE) return settingsPanel.removeAllViews() + if (!appSettingsLoaded) { + settingsPanel.addView(body("正在读取设置,请稍候…")) + return + } settingsPanel.addView(section("显示、音频与输入设置")) settingsPanel.addView(Button(this).apply { text = if (appSettings.integerScale) "画面比例:原始整数缩放" else "画面比例:保持 4:3" @@ -1461,7 +1511,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { controllerScope.launch { val loaded = appSettingsStore.load() val loadedCores = runCatching { corePreferencesStore.load() } - runOnUiThread { + postToActiveUi { // A controller profile can finish loading before the application settings. appSettings = virtualButtonSwapsOverride?.let { (swapAB, swapXY) -> loaded.copy(virtualSwapAB = swapAB, virtualSwapXY = swapXY) @@ -1551,12 +1601,13 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } private fun handleVirtualInput(pointerId: Int, action: GameAction, pressed: Boolean) { - if (!gameplayInputActive() && action != GameAction.PAUSE_MENU) return + if (pressed && !gameplayInputActive() && action != GameAction.PAUSE_MENU) return val source = InputSource(-1 - pointerId, InputSourceKind.TOUCH, action.ordinal) applyRoutedInput(inputRouter.update(source, action, pressed)) } private fun showSaveManager() { + if (!canNavigate()) return if (activeSessionId == 0L || activeGameHash.isBlank() || lastSessionState != "Paused") { showEmulatorStatus("请先加载游戏并暂停,再打开存档管理") return @@ -1576,7 +1627,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { val root = File(core.saveBase(filesDir), hash) val manual = (0 until 10).associateWith { SaveCatalogReader.read(File(root, "states/slot-$it.nls")) } val automatic = (0 until 3).associateWith { SaveCatalogReader.read(File(root, "auto/auto-$it.nls")) } - runOnUiThread { + postToActiveUi { if (activeSessionId == session && activeCore == core && activeGameHash == hash) { renderSaveManager(manual, automatic) } @@ -1598,11 +1649,11 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { .forEach { (slot, summary) -> addSaveSlotRow("自动 ${slot + 1}", slot, summary, true) } saveManagerPanel.addView(Button(this).apply { text = "导出存档包(不含 ROM)" - setOnClickListener { createSavePackage.launch("neslite-save-${System.currentTimeMillis()}.nsp") } + setOnClickListener { if (canNavigate()) createSavePackage.launch("neslite-save-${System.currentTimeMillis()}.nsp") } }) saveManagerPanel.addView(Button(this).apply { text = "导入存档包" - setOnClickListener { openSavePackage.launch(arrayOf("application/vnd.neslite.save", "application/octet-stream", "*/*")) } + setOnClickListener { if (canNavigate()) openSavePackage.launch(arrayOf("application/vnd.neslite.save", "application/octet-stream", "*/*")) } }) saveManagerPanel.addView(Button(this).apply { text = "返回暂停菜单" @@ -1644,13 +1695,14 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } private fun showControllerSettings(returnToPause: Boolean, returnToSettings: Boolean = false) { + if (!canNavigate()) return val shouldReturnToPause = returnToPause || settingsReturnToPause || currentOverlayPage == OverlayPage.PAUSE_MENU if (lastSessionState == "Running" && !pauseForExternalReason("open_controller_settings")) return settingsReturnToPause = shouldReturnToPause controllerReturnToSettings = returnToSettings || currentOverlayPage == OverlayPage.SETTINGS || currentOverlayPage == OverlayPage.DIAGNOSTICS - draftProfile = selectedControllerId?.let(controllerProfiles::get) + draftProfile = selectedControllerId?.takeIf { it in readyControllerProfileIds }?.let(controllerProfiles::get) pendingBindingAction = null manualMappingIndex = null bindingCaptureWaitForNeutral = false @@ -1729,6 +1781,14 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { controllerSettingsPanel.removeAllViews() val deviceId = selectedControllerId val controller = controllers.firstOrNull { it.deviceId == deviceId } + if (controller != null && deviceId !in readyControllerProfileIds) { + controllerSettingsPanel.addView(body("正在读取手柄设置,请稍候…")) + controllerSettingsPanel.addView(Button(this).apply { + text = "关闭" + setOnClickListener { closeControllerSettings() } + }) + return + } val profile = if (controller == null) null else draftProfile ?: deviceId?.let(controllerProfiles::get) renderButtonSwapSettings(profile) if (controller == null || profile == null) { @@ -2035,12 +2095,12 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { manualMappingIndex = null bindingCaptureWaitForNeutral = false clearControllerState() - controllerScope.launch { + controllerScope.launch(Dispatchers.Main.immediate) { val result = runCatching { profileStore.save(profile) } - runOnUiThread { + postToActiveUi { if (controllerProfileRevisions[deviceId] != revision || controllerIdentities[deviceId]?.fingerprint() != profile.fingerprint - ) return@runOnUiThread + ) return@postToActiveUi if (result.isSuccess) { inputRouter.clearDevice(deviceId).let(::applyRoutedInput) axisHysteresis.clearDevice(deviceId) @@ -2051,7 +2111,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { if (draftProfile?.copy(origin = ProfileOrigin.CUSTOM) == profile) draftProfile = profile } } - if (selectedControllerId != deviceId) return@runOnUiThread + if (selectedControllerId != deviceId) return@postToActiveUi controllerSettingsMessage = if (result.isSuccess) { "设置已保存,屏幕按键已同步;重连和重启后恢复。" } else { @@ -2072,12 +2132,12 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { manualMappingIndex = null bindingCaptureWaitForNeutral = false clearControllerState() - controllerScope.launch { + controllerScope.launch(Dispatchers.Main.immediate) { val result = runCatching { profileStore.reset(identity) } - runOnUiThread { + postToActiveUi { if (controllerProfileRevisions[deviceId] != revision || controllerIdentities[deviceId]?.fingerprint() != identity.fingerprint() - ) return@runOnUiThread + ) return@postToActiveUi if (result.isSuccess) { inputRouter.clearDevice(deviceId).let(::applyRoutedInput) axisHysteresis.clearDevice(deviceId) @@ -2088,7 +2148,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { draftProfile = defaultProfile } } - if (selectedControllerId != deviceId) return@runOnUiThread + if (selectedControllerId != deviceId) return@postToActiveUi controllerSettingsMessage = if (result.isSuccess) { "已恢复通用默认配置,屏幕按键也已恢复。" } else { @@ -2116,7 +2176,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { controllerScope.launch { val restored = runCatching { profileStore.load(identity) } .getOrElse { profileResolver.resolve(identity) } - runOnUiThread { + postToActiveUi { if (controllerIdentities[controller.deviceId]?.fingerprint() == identity.fingerprint() && controllerProfileRevisions[controller.deviceId] == revision ) { @@ -2239,7 +2299,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { libraryExecutor.execute { runCatching { RomImporter(contentResolver, filesDir, database.games()).import(uri) } .onSuccess { result -> - runOnUiThread { + postToActiveUi { Toast.makeText( this, if (result.duplicate) "内容已存在,已复用原文件" else "导入完成", @@ -2252,7 +2312,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } } .onFailure { error -> - runOnUiThread { + postToActiveUi { val message = "导入失败:${error.message ?: error.javaClass.simpleName}" showEmulatorStatus(message) importStatus.text = message @@ -2268,19 +2328,19 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { runCatching { FolderRomImporter(contentResolver, RomImporter(contentResolver, filesDir, database.games())) .import(uri) { count -> - if (count == 1 || count % 10 == 0) runOnUiThread { + if (count == 1 || count % 10 == 0) postToActiveUi { if (currentOverlayPage == OverlayPage.IMPORT) importStatus.text = "已处理 $count 个 NES 文件…" } } }.onSuccess { result -> - runOnUiThread { + postToActiveUi { val summary = "文件夹导入完成:新增 ${result.imported},重复 ${result.duplicates},失败 ${result.failed}" importStatus.text = summary + result.firstErrors.joinToString("", prefix = if (result.firstErrors.isEmpty()) "" else "\n") { "$it\n" } showEmulatorStatus(summary) refreshLibrary() } }.onFailure { error -> - runOnUiThread { + postToActiveUi { val message = "文件夹导入中断:${error.message ?: error.javaClass.simpleName};已导入的游戏仍保留" importStatus.text = message showEmulatorStatus(message) @@ -2293,7 +2353,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private fun recoverLibrary() { libraryExecutor.execute { val report = LibraryRecovery(filesDir, database.games()).reconcile() - runOnUiThread { + postToActiveUi { if (report.removedTemps + report.recoveredFiles + report.missingRows > 0) { showEmulatorStatus("恢复检查:临时 ${report.removedTemps},恢复 ${report.recoveredFiles},缺失 ${report.missingRows}") } @@ -2306,7 +2366,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { val query = if (::searchInput.isInitialized) searchInput.text.toString().trim() else "" libraryExecutor.execute { val games = database.games().visible(query) - runOnUiThread { + postToActiveUi { gameList.removeAllViews() if (games.isEmpty()) { gameList.addView(body(if (query.isEmpty()) "游戏库为空;请从文件导入 ROM。" else "没有匹配“$query”的游戏;可清空搜索后重试。")) @@ -2360,7 +2420,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { .show() 1 -> libraryExecutor.execute { database.games().setFavorite(game.sha256, !game.favorite) - runOnUiThread { refreshLibrary() } + postToActiveUi { refreshLibrary() } } 2 -> confirmHideGame(game) 3 -> showCorePicker(game) @@ -2390,7 +2450,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { if (game == null) corePreferencesStore.setDefault(requireNotNull(selected)) else corePreferencesStore.setGame(game.sha256, selected) } - runOnUiThread { + postToActiveUi { coreSelectionSaving = false result.onSuccess { corePreferences = if (game == null) corePreferences.copy(defaultCore = requireNotNull(selected)) @@ -2414,7 +2474,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { .setPositiveButton("移除") { _, _ -> libraryExecutor.execute { database.games().hide(game.sha256) - runOnUiThread { refreshLibrary() } + postToActiveUi { refreshLibrary() } } } .setNegativeButton("取消", null) @@ -2435,10 +2495,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { showEmulatorStatus("内核设置尚未读取完成,请稍后重试。") return } - if (pendingSessionCommand != null) { - showEmulatorStatus("正在完成会话状态交接,请稍候。") - return - } + if (!canNavigate()) return val recoveryKey = corePreferences.forGame(game.sha256).recoveryKey(game.sha256) if (crashLoopGuard.isBlocked(recoveryKey)) { AlertDialog.Builder(this) @@ -2456,17 +2513,27 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } private fun loadGameUnchecked(game: GameEntity) { + if (!canNavigate()) return + if (activeSessionId != 0L) { + pendingGameAfterStop = game + if (!sendControlCommand("stop")) pendingGameAfterStop = null + return + } val path = File(File(filesDir, "roms"), game.fileName).absolutePath val selectedCore = corePreferences.forGame(game.sha256) - activeSessionId = NativeBridge.loadRom( + val baseline = operationBaseline() + val newSessionId = NativeBridge.loadRom( path, File(filesDir, "system").apply { mkdirs() }.absolutePath, File(filesDir, "saves").apply { mkdirs() }.absolutePath, game.sha256, selectedCore.id, ) - activeGameHash = game.sha256 - if (activeSessionId != 0L) { + if (newSessionId != 0L) { + activeSessionId = newSessionId + activeGameHash = game.sha256 + pendingCommandBaseline = baseline + autoRunAfterLoad = true activeCore = selectedCore pendingSessionCommand = "load" lastSessionState = "Loading" @@ -2477,26 +2544,28 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } libraryExecutor.execute { database.games().markPlayed(game.sha256, System.currentTimeMillis()) - runOnUiThread { refreshLibrary() } + postToActiveUi { refreshLibrary() } } showEmulatorStatus(if (activeSessionId == 0L) "命令队列已满" else "正在使用 ${selectedCore.label} 加载游戏") } private fun beginSavePackageExport(uri: Uri) { - if (activeSessionId == 0L || lastSessionState != "Paused") { - showEmulatorStatus("请先加载游戏并暂停,再导出存档包") + if (activeSessionId == 0L || !canNavigate() || + !sessionCommandAllowed(null, "package_export", lastSessionState)) { + Toast.makeText(this, "请等待当前操作完成,并在游戏暂停后导出", Toast.LENGTH_LONG).show() return } val temporary = File(cacheDir, "save-export-$activeSessionId.nsp") temporary.delete() File(temporary.absolutePath + ".bak").delete() - pendingSaveExportUri = uri - pendingSaveExportFile = temporary + val baseline = operationBaseline() if (!NativeBridge.savePackageCommand(activeSessionId, "package_export", temporary.absolutePath)) { - pendingSaveExportUri = null - pendingSaveExportFile = null showEmulatorStatus("存档导出命令队列已满") } else { + pendingSaveExportUri = uri + pendingSaveExportFile = temporary + pendingSessionCommand = "package_export" + pendingCommandBaseline = baseline showEmulatorStatus("正在准备不含 ROM 的存档包") } } @@ -2506,6 +2575,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { val source = pendingSaveExportFile ?: return pendingSaveExportUri = null pendingSaveExportFile = null + pendingSessionCommand = "package_export_copy" + val session = activeSessionId libraryExecutor.execute { val result = runCatching { require(source.isFile && source.length() in 1..MAX_SAVE_PACKAGE_BYTES) @@ -2516,22 +2587,26 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } source.delete() File(source.absolutePath + ".bak").delete() - runOnUiThread { - showEmulatorStatus( - if (result.isSuccess) "存档包导出成功(不含 ROM)" else - "存档包导出失败:${result.exceptionOrNull()?.message ?: "无法写入目标"}", - ) + postToActiveUi { + if (activeSessionId == session && pendingSessionCommand == "package_export_copy") { + pendingSessionCommand = null + Toast.makeText(this, if (result.isSuccess) "存档包导出成功(不含 ROM)" else + "存档包导出失败:${result.exceptionOrNull()?.message ?: "无法写入目标"}", Toast.LENGTH_LONG).show() + } } } } private fun beginSavePackageImport(uri: Uri) { - if (activeSessionId == 0L || lastSessionState != "Paused") { - showEmulatorStatus("请先加载对应游戏并暂停,再导入存档包") + if (activeSessionId == 0L || !canNavigate() || + !sessionCommandAllowed(null, "package_import", lastSessionState)) { + Toast.makeText(this, "请等待当前操作完成,并在对应游戏暂停后导入", Toast.LENGTH_LONG).show() return } - val target = File(cacheDir, "save-import-$activeSessionId.nsp") + val session = activeSessionId + val target = File(cacheDir, "save-import-$session.nsp") target.delete() + pendingSessionCommand = "package_import_read" libraryExecutor.execute { val result = runCatching { contentResolver.openInputStream(uri)!!.use { input -> @@ -2539,6 +2614,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { val buffer = ByteArray(DEFAULT_BUFFER_SIZE) var total = 0L while (true) { + check(!Thread.currentThread().isInterrupted) { "导入已取消" } val read = input.read(buffer) if (read < 0) break total += read @@ -2549,16 +2625,26 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } } require(target.length() > 0L) { "存档包为空" } - require(NativeBridge.savePackageCommand(activeSessionId, "package_import", target.absolutePath)) { - "存档导入命令队列已满" - } } if (result.isFailure) target.delete() - runOnUiThread { - showEmulatorStatus( - if (result.isSuccess) "正在校验并导入存档包" else - "存档包导入失败:${result.exceptionOrNull()?.message ?: "无法读取来源"}", - ) + postToActiveUi { + // The worker never reads a mutable Activity session ID or sends native commands. + if (activeSessionId != session || pendingSessionCommand != "package_import_read") { + target.delete() + return@postToActiveUi + } + pendingSessionCommand = null + val baseline = operationBaseline() + if (result.isSuccess && lastSessionState == "Paused" && + NativeBridge.savePackageCommand(session, "package_import", target.absolutePath)) { + pendingSessionCommand = "package_import" + pendingCommandBaseline = baseline + showEmulatorStatus("正在校验并导入存档包") + } else { + target.delete() + Toast.makeText(this, "存档包导入失败:${result.exceptionOrNull()?.message ?: "当前游戏状态不可导入"}", + Toast.LENGTH_LONG).show() + } } } } @@ -2567,11 +2653,12 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { if (::emulatorStatus.isInitialized && activeSessionId != 0L) { val raw = NativeBridge.sessionStatus() runCatching { JSONObject(raw) }.onSuccess { status -> + if (status.optLong("sessionId") != activeSessionId) return@onSuccess val nextState = status.optString("state") if (lastSessionState == "Running" && nextState != "Running") clearControllerState() lastSessionState = nextState - val completionId = status.optLong("completionId") - val completion = status.optString("completion") + val completionId = status.optLong("operationCompletionId") + val completion = status.optString("operationCompletion") val error = status.optString("error") showEmulatorStatus( "内核:${activeCore.label} · 状态:$nextState · $completion" + @@ -2580,7 +2667,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { ) if (completionId != lastCompletionId) { lastCompletionId = completionId - settleSessionTransition(nextState, completion, error) + if (matchesPendingCompletion(pendingSessionCommand, pendingCommandBaseline, completionId, + status.optString("operationCommand"), completion, activeSessionId)) { + settleSessionTransition(nextState, completion, error, status.optBoolean("abnormalSession")) + } recordSystemEvent( "session_completion", JSONObject() @@ -2588,20 +2678,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { .put("completion", completion) .put("error", status.optString("error")), ) - if (completion.endsWith(":loaded")) applyAppSettings() - if (completion.endsWith(":package_exported")) finishSavePackageExport() - if (completion.endsWith(":package_export_failed")) { - pendingSaveExportUri = null - pendingSaveExportFile?.delete() - pendingSaveExportFile = null - } - if (completion.endsWith(":package_imported") || completion.endsWith(":package_import_failed")) { - File(cacheDir, "save-import-$activeSessionId.nsp").delete() - } - if (completion.endsWith(":state_saved") || completion.endsWith(":package_imported")) { - refreshSaveManager() - } + } + if (status.optLong("sessionId") != activeSessionId) return@onSuccess if (nextState == "Running" && error.isBlank() && pendingSessionCommand == null) { emulatorStatus.visibility = View.GONE } @@ -2650,16 +2729,42 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { "输入延迟 ${input.optLong("latencySamples")}/1000,P95 ${String.format(Locale.ROOT, "%.2f", input.optDouble("latencyP95Ms"))} ms(JNI→核心首次采样)" }.onFailure { showEmulatorStatus(raw) } } + if (routeRebuildPending && activeSessionId != 0L && lastSessionState == "Paused" && + pendingSessionCommand == null && activityStarted && exitDestination == null) { + if (requestAudioRebuild("deferred_audio_route_change")) routeRebuildPending = false + } mainHandler.postDelayed(::pollSessionStatus, 250) } - private fun settleSessionTransition(nextState: String, completion: String, error: String) { + private fun settleSessionTransition(nextState: String, completion: String, error: String, abnormalSession: Boolean) { val pending = pendingSessionCommand val settled = sessionTransitionSettled(pending, nextState, completion, error) if (!settled) return pendingSessionCommand = null when (pending) { - "load" -> if (nextState == "Paused") sendControlCommand("run") + "package_export" -> { + if (completion.endsWith(":package_exported")) finishSavePackageExport() + else { + pendingSaveExportUri = null + pendingSaveExportFile?.delete() + pendingSaveExportFile = null + Toast.makeText(this, "存档包导出失败,请重试", Toast.LENGTH_LONG).show() + } + } + "package_import" -> { + File(cacheDir, "save-import-$activeSessionId.nsp").delete() + refreshSaveManager() + Toast.makeText(this, if (completion.endsWith(":package_imported")) "存档包导入成功" else + "存档包导入失败,请检查是否属于当前游戏和内核", Toast.LENGTH_LONG).show() + } + "load" -> { + applyAppSettings() + if (nextState == "Paused" && shouldRunLoadedGame(autoRunAfterLoad, activityStarted, + window.decorView.hasWindowFocus(), currentOverlayPage != null, abnormalSession)) { + sendControlCommand("run") + } else if (nextState in setOf("Paused", "Error") && currentOverlayPage == null) showPauseMenu() + autoRunAfterLoad = false + } "pause" -> if (pendingPauseShowsMenu && nextState == "Paused") showPauseMenu() "pause_external" -> Unit "stop" -> if (nextState == "Idle") { @@ -2679,11 +2784,26 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { val destination = exitDestination exitDestination = null exitConfirmationPending = false - if (destination == ExitDestination.APPLICATION) finishApplication() else openLibraryPage() + routeRebuildPending = false + val nextGame = pendingGameAfterStop + pendingGameAfterStop = null + if (destination == ExitDestination.APPLICATION) finishApplication() + else if (nextGame != null) loadGameUnchecked(nextGame) + else openLibraryPage() } else { + pendingGameAfterStop = null showExitFailure() } } + if (pending?.startsWith("state_save:") == true) refreshSaveManager() + if (pending?.startsWith("state_") == true || pending?.startsWith("auto_load:") == true) { + val message = when (completion.substringAfter(':')) { + "state_saved" -> "存档成功" + "state_loaded", "auto_loaded" -> "已读取存档,游戏保持暂停" + else -> "存档操作失败,请检查槽位或可用空间" + } + Toast.makeText(this, message, Toast.LENGTH_SHORT).show() + } if (exitConfirmationPending && pending != "stop") { if (nextState == "Paused") showExitConfirmation() else { @@ -2692,10 +2812,6 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { Toast.makeText(this, "未能暂停游戏,请稍后重试退出。", Toast.LENGTH_LONG).show() } } - if (routeRebuildPending && nextState == "Paused" && pending != "stop") { - routeRebuildPending = false - requestAudioRebuild("deferred_audio_route_change") - } pendingPauseShowsMenu = false } @@ -2752,8 +2868,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private fun sendControlCommand(command: String): Boolean { if (activeSessionId == 0L) return false - val transitionCommand = command in setOf("run", "pause", "stop") + if (applicationExitPending) return false if (!sessionCommandAllowed(pendingSessionCommand, command, lastSessionState)) { + Toast.makeText(this, "当前操作尚未完成,或此状态下不可使用该按钮", Toast.LENGTH_SHORT).show() showEmulatorStatus( pendingSessionCommand?.let { "正在完成 $it 状态交接,已忽略重复操作。" } ?: "当前状态 $lastSessionState 不接受命令:$command", @@ -2761,26 +2878,28 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { return false } if (command == "run" && audioManager.requestAudioFocus(audioFocusRequest) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { + Toast.makeText(this, "暂时无法取得音频,游戏保持暂停,请稍后继续", Toast.LENGTH_LONG).show() showEmulatorStatus("音频焦点未获准,游戏保持暂停") return false } - if (command == "pause" || command == "stop") clearControllerState() + if (command in setOf("pause", "stop", "reset")) clearControllerState() + val baseline = operationBaseline() if (!NativeBridge.command(activeSessionId, command)) { showEmulatorStatus("命令队列已满:$command") if (command == "run") audioManager.abandonAudioFocusRequest(audioFocusRequest) return false } - if (transitionCommand) { - pendingSessionCommand = command - pendingPauseShowsMenu = command == "pause" - showEmulatorStatus( - when (command) { - "pause" -> "正在安全暂停并请求存档…" - "run" -> "正在恢复游戏资源…" - else -> "正在安全保存并退出…" - }, - ) - } + pendingSessionCommand = command + pendingCommandBaseline = baseline + pendingPauseShowsMenu = command == "pause" + showEmulatorStatus( + when (command) { + "pause" -> "正在安全暂停并请求存档…" + "run" -> "正在恢复游戏资源…" + "stop" -> "正在安全保存并退出…" + else -> "正在处理,请稍候…" + }, + ) when (command) { "run", "stop" -> { hidePauseMenu() @@ -2804,20 +2923,21 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { state.fastForwardChanged?.takeIf { gameplayActive && appSettings.fastForwardEnabled }?.let { enabled -> NativeBridge.command(activeSessionId, if (enabled) "fast:on" else "fast:off") } - if (state.pauseMenuEdge) { - when (lastSessionState) { - "Running" -> sendControlCommand("pause") - "Paused" -> sendControlCommand("run") - } + if (state.pauseMenuEdge && activeSessionId != 0L && exitDestination == null && !applicationExitPending) { + handleUnifiedBack() } } - private fun gameplayInputActive(): Boolean = lastSessionState == "Running" && - overlayScreen.visibility != View.VISIBLE + private fun gameplayInputActive(): Boolean = activeSessionId != 0L && lastSessionState == "Running" && + pendingSessionCommand == null && exitDestination == null && !applicationExitPending && + activityStarted && window.decorView.hasWindowFocus() && overlayScreen.visibility != View.VISIBLE private fun clearControllerState() { if (::virtualGamepad.isInitialized) virtualGamepad.clearInputs() - inputRouter.clearAll() + val cleared = inputRouter.clearAll() + if (cleared.fastForwardChanged == false && activeSessionId != 0L) { + NativeBridge.command(activeSessionId, "fast:off") + } axisHysteresis.clearAll() joypadMask = 0 NativeBridge.setJoypadMask(0) @@ -2825,6 +2945,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } private fun pauseForExternalReason(reason: String): Boolean { + autoRunAfterLoad = false clearControllerState() if (activeSessionId != 0L && pendingSessionCommand != "stop") { if ((lastSessionState in setOf("Paused", "Loading", "Pausing", "Error") && pendingSessionCommand != "run") || @@ -2832,8 +2953,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { recordSystemEvent("external_pause_already_safe", JSONObject().put("reason", reason)) return true } + val baseline = operationBaseline() val queued = NativeBridge.command(activeSessionId, "pause") if (queued) { + pendingCommandBaseline = baseline pendingSessionCommand = "pause_external" pendingPauseShowsMenu = false } @@ -2854,24 +2977,24 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } private fun rebuildAudioForRoute() { - if (activeSessionId == 0L || pendingSessionCommand == "stop") return + if (activeSessionId == 0L || pendingSessionCommand == "stop" || applicationExitPending) return routeRebuildPending = true - if (lastSessionState == "Paused" && pendingSessionCommand == null) { - routeRebuildPending = false - if (!requestAudioRebuild("audio_route_changed") && ::audioStatus.isInitialized) { - audioStatus.text = "音频路由重建命令队列已满;游戏保持暂停" - } - } else if (!pauseForExternalReason("audio_route_changed")) { - routeRebuildPending = false + if (lastSessionState == "Running" || pendingSessionCommand == "run") { + pauseForExternalReason("audio_route_changed") } + // The status poll rebuilds audio after saves and exit dialogs have settled. } private fun requestAudioRebuild(reason: String): Boolean { - if (activeSessionId == 0L || pendingSessionCommand == "stop") return false + if (activeSessionId == 0L || pendingSessionCommand == "stop" || exitDestination != null || applicationExitPending) return false if (pendingSessionCommand == "audio_rebuild") return true if (!sessionCommandAllowed(pendingSessionCommand, "audio_rebuild", lastSessionState)) return false + val baseline = operationBaseline() val queued = NativeBridge.command(activeSessionId, "audio_rebuild") - if (queued) pendingSessionCommand = "audio_rebuild" + if (queued) { + pendingSessionCommand = "audio_rebuild" + pendingCommandBaseline = baseline + } recordSystemEvent( "audio_rebuild_requested", JSONObject().put("reason", reason).put("queued", queued), 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 6cb5c46..bcc4efe 100644 --- a/app/src/main/java/org/neslite/app/system/SystemUiPolicy.kt +++ b/app/src/main/java/org/neslite/app/system/SystemUiPolicy.kt @@ -98,19 +98,32 @@ 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 - return when (command) { - "load" -> state !in setOf("Loading", "Stopping") - "run" -> state == "Paused" - "pause" -> state == "Running" - "stop" -> state in setOf("Paused", "Running", "Error") - else -> true + if (pending != null) return false + return when { + command == "load" -> state in setOf("Idle", "Paused", "Error") + command == "run" -> state == "Paused" + command == "pause" -> state == "Running" + command == "stop" -> state in setOf("Paused", "Running", "Error") + command == "reset" -> state in setOf("Paused", "Running") + command == "audio_rebuild" || command.startsWith("state_save:") || + command.startsWith("state_load:") || command.startsWith("auto_load:") || + command in setOf("package_export", "package_import") -> state == "Paused" + else -> false } } +// A status poll may still contain a previous command's acknowledgement. Only the +// requested operation in the current session, completed after dispatch, can unlock UI. +fun matchesPendingCompletion(pending: String?, baseline: Long, completionId: Long, + command: String, completion: String, sessionId: Long): Boolean = + pending != null && completionId > baseline && sessionId != 0L && + command == (if (pending == "pause_external") "pause" else pending) && + completion.substringBefore(':').toLongOrNull() == sessionId + +fun shouldRunLoadedGame(requested: Boolean, foreground: Boolean, focused: Boolean, + hasOverlay: Boolean, abnormalSession: Boolean): Boolean = + requested && foreground && focused && !hasOverlay && !abnormalSession + fun sessionTransitionSettled(pending: String?, nextState: String, completion: String, error: String = ""): Boolean = when (pending) { "load" -> nextState == "Paused" || nextState == "Error" @@ -120,8 +133,16 @@ fun sessionTransitionSettled(pending: String?, nextState: String, completion: St (nextState == "Paused" && error.startsWith("Exit ") && error.endsWith("failed")) "audio_rebuild" -> nextState == "Paused" && (completion.endsWith(":audio_rebuilt_paused") || completion.endsWith(":audio_unavailable_paused")) - else -> false - } || completion.endsWith(":ignored") || completion.endsWith(":stale") || completion.endsWith(":error") + "reset" -> completion.endsWith(":reset") + "package_export" -> completion.endsWith(":package_exported") || completion.endsWith(":package_export_failed") + "package_import" -> completion.endsWith(":package_imported") || completion.endsWith(":package_import_failed") + else -> when { + pending?.startsWith("state_save:") == true -> completion.endsWith(":state_saved") || completion.endsWith(":state_save_failed") + pending?.startsWith("state_load:") == true -> completion.endsWith(":state_loaded") || completion.endsWith(":state_load_failed") + pending?.startsWith("auto_load:") == true -> completion.endsWith(":auto_loaded") || completion.endsWith(":auto_load_failed") + else -> false + } + } || (pending != null && (completion.endsWith(":ignored") || completion.endsWith(":stale") || completion.endsWith(":error"))) data class RefreshRateSample( val epochMs: Long, diff --git a/app/src/test/java/org/neslite/app/BuildIdentityTest.kt b/app/src/test/java/org/neslite/app/BuildIdentityTest.kt index 6c8fcc1..b767872 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.3-debug", BuildConfig.VERSION_NAME) - assertEquals(1000003, BuildConfig.VERSION_CODE) + assertEquals("1.0.4-debug", BuildConfig.VERSION_NAME) + assertEquals(1000004, BuildConfig.VERSION_CODE) } } diff --git a/app/src/test/java/org/neslite/app/system/ButtonStateMatrixTest.kt b/app/src/test/java/org/neslite/app/system/ButtonStateMatrixTest.kt new file mode 100644 index 0000000..760a8f0 --- /dev/null +++ b/app/src/test/java/org/neslite/app/system/ButtonStateMatrixTest.kt @@ -0,0 +1,74 @@ +package org.neslite.app.system + +import org.junit.Assert.* +import org.junit.Test + +class ButtonStateMatrixTest { + private val states = listOf("Idle", "Loading", "Running", "Pausing", "Paused", "Stopping", "Error") + private val actions = mapOf( + "load" to setOf("Idle", "Paused", "Error"), + "run" to setOf("Paused"), "pause" to setOf("Running"), + "stop" to setOf("Paused", "Running", "Error"), "reset" to setOf("Paused", "Running"), + "audio_rebuild" to setOf("Paused"), "state_save:0" to setOf("Paused"), + "state_load:9" to setOf("Paused"), "auto_load:2" to setOf("Paused"), + "package_export" to setOf("Paused"), "package_import" to setOf("Paused"), + ) + + @Test fun eachButtonAcceptsOnlyItsSupportedSessionStates() { + actions.forEach { (command, allowed) -> states.forEach { state -> + assertEquals("$state / $command", state in allowed, sessionCommandAllowed(null, command, state)) + } } + states.forEach { assertFalse(sessionCommandAllowed(null, "unknown", it)) } + } + + @Test fun rapidClicksCannotCrossAnyPendingOperationIncludingFileCopies() { + (actions.keys + setOf("pause_external", "package_import_read", "package_export_copy")).forEach { pending -> + states.forEach { state -> actions.keys.forEach { command -> + assertFalse("$pending -> $command in $state", sessionCommandAllowed(pending, command, state)) + } } + } + } + + @Test fun oldOrUnrelatedAcknowledgementsDoNotUnlockTheNextCommand() { + assertFalse(matchesPendingCompletion("stop", 10, 10, "stop", "7:stopped_saved", 7)) + assertFalse(matchesPendingCompletion("stop", 10, 11, "fast:off", "7:ignored", 7)) + assertFalse(matchesPendingCompletion("stop", 10, 11, "stop", "6:stale", 7)) + assertFalse(matchesPendingCompletion("state_save:1", 10, 11, "state_save:0", "7:state_saved", 7)) + assertTrue(matchesPendingCompletion("stop", 10, 11, "stop", "7:stop_save_failed", 7)) + assertTrue(matchesPendingCompletion("pause_external", 10, 11, "pause", "7:paused_saved", 7)) + assertFalse(matchesPendingCompletion(null, 10, 11, "pause", "7:paused_saved", 7)) + } + + @Test fun loadingNeverStartsInTheBackgroundOrBehindMenusOrRecoveryDialogs() { + assertTrue(shouldRunLoadedGame(true, true, true, false, false)) + assertFalse(shouldRunLoadedGame(false, true, true, false, false)) + assertFalse(shouldRunLoadedGame(true, false, true, false, false)) + assertFalse(shouldRunLoadedGame(true, true, false, false, false)) + assertFalse(shouldRunLoadedGame(true, true, true, true, false)) + assertFalse(shouldRunLoadedGame(true, true, true, false, true)) + } + + @Test fun everySaveResultIncludingFailureReleasesTheOperationLock() { + mapOf("state_save:0" to listOf("state_saved", "state_save_failed"), + "state_load:0" to listOf("state_loaded", "state_load_failed"), + "auto_load:0" to listOf("auto_loaded", "auto_load_failed"), + "package_export" to listOf("package_exported", "package_export_failed"), + "package_import" to listOf("package_imported", "package_import_failed"), + "reset" to listOf("reset") + ).forEach { (command, results) -> + (results + listOf("ignored", "stale", "error")).forEach { result -> + assertTrue("$command / $result", sessionTransitionSettled(command, "Paused", "7:$result")) + } + assertFalse(sessionTransitionSettled(command, "Paused", "7:muted")) + } + } + + @Test fun pauseShortcutNavigatesSubmenusBeforeResuming() { + listOf(UiLayer.SETTINGS, UiLayer.CONTROLLER_SETTINGS, UiLayer.SAVE_MANAGER, + UiLayer.DIAGNOSTICS, UiLayer.AUXILIARY_PAGE).forEach { + assertNotEquals(BackDecision.RESUME_GAME, SystemUiPolicy.backDecision(it)) + } + assertEquals(BackDecision.RESUME_GAME, SystemUiPolicy.backDecision(UiLayer.PAUSE_MENU)) + assertEquals(BackDecision.IGNORE_TRANSITION, SystemUiPolicy.backDecision(UiLayer.TRANSITION)) + } +} diff --git a/app/src/test/java/org/neslite/app/system/SystemUiPolicyTest.kt b/app/src/test/java/org/neslite/app/system/SystemUiPolicyTest.kt index 8aa9f15..5cacf01 100644 --- a/app/src/test/java/org/neslite/app/system/SystemUiPolicyTest.kt +++ b/app/src/test/java/org/neslite/app/system/SystemUiPolicyTest.kt @@ -95,7 +95,7 @@ class SystemUiPolicyTest { assertEquals(false, sessionCommandAllowed("pause", "run", "Running")) assertEquals(false, sessionCommandAllowed("load", "stop", "Loading")) assertEquals(false, sessionCommandAllowed("audio_rebuild", "run", "Paused")) - assertEquals(true, sessionCommandAllowed("audio_rebuild", "stop", "Paused")) + assertEquals(false, sessionCommandAllowed("audio_rebuild", "stop", "Paused")) assertEquals(true, sessionTransitionSettled("pause", "Paused", "1:paused_saved")) assertEquals(true, sessionTransitionSettled("audio_rebuild", "Paused", "1:audio_rebuilt_paused")) assertEquals(false, sessionTransitionSettled("stop", "Stopping", "")) diff --git a/docs/build.md b/docs/build.md index 01c8ffb..6cba384 100644 --- a/docs/build.md +++ b/docs/build.md @@ -1,7 +1,7 @@ # NESLite 构建与打包 项目的 APK 打包入口统一为根目录 `打包.cmd`,项目内的编译产物、缓存、日志和交付文件统一放入 -`build/`。当前应用版本为 1.0.3,入口从 APK 构建元数据读取版本,不另写一套版本号。 +`build/`。当前应用版本为 1.0.4,入口从 APK 构建元数据读取版本,不另写一套版本号。 ## 一键打包 @@ -14,7 +14,7 @@ .\打包.cmd -NoPause ``` -当前交付文件是 `build/releases/NESLite-1.0.3-debug-arm64-v8a.apk`,旁边的 `.sha256` 保存校验值。 +当前交付文件是 `build/releases/NESLite-1.0.4-debug-arm64-v8a.apk`,旁边的 `.sha256` 保存校验值。 入口检查工具链与固定依赖、编译选定 APK、检查原生库和 APK 的 16 KB 对齐,成功后复制产物。 它不会自动启动单元测试、ROM 遍历、设备测试或发布回归;失败会返回非零退出码,旧交付 APK 不冒充本次成功产物。 @@ -24,7 +24,7 @@ .\打包.cmd release -NoPause ``` -该模式使用项目外的正式密钥,生成 `build/releases/NESLite-1.0.3-arm64-v8a.apk`、原生符号、应用和依赖源码 ZIP、发布清单及校验值。 +该模式使用项目外的正式密钥,生成 `build/releases/NESLite-1.0.4-arm64-v8a.apk`、原生符号、应用和依赖源码 ZIP、发布清单及校验值。 正式打包前必须提交源码并配置签名目录;入口读取 Windows 用户加密的密码,完成签名和签名验证。密钥位置与发布步骤见 [publishing.md](publishing.md)。 一键打包不会运行原 `package-rc.ps1` 的全量 Stage/lint/设备测试包构建,也不表示发布门槛通过。 diff --git a/docs/releases/1.0.4.md b/docs/releases/1.0.4.md new file mode 100644 index 0000000..d110c21 --- /dev/null +++ b/docs/releases/1.0.4.md @@ -0,0 +1,15 @@ +# NESLite 1.0.4 + +修复游戏、暂停、设置、存档与退出之间的按钮状态交叉问题。 + +- 设置等子页面中的暂停快捷键先返回上一级,避免直接恢复游戏。 +- 加载时切到后台或进入异常恢复流程,完成后保持暂停。 +- 存读档、重置、恢复、退出及存档包传输期间拦截重复或交叉操作;完成通知核对游戏会话与具体命令,不受音量、静音和快进通知覆盖。 +- 切换游戏前先安全保存并结束当前游戏,保存失败保留当前会话。 +- 拦截退出后的异步界面更新;退出时等待手柄及屏幕按键配置写入完成。 +- 设置读取完成前暂缓编辑,并按点击顺序保存手柄配置。 +- 重置时清除按键和快进状态,避免松开事件在状态交接期间丢失。 + +正式安装包为 `NESLite-1.0.4-arm64-v8a.apk`,版本号为 1000004,沿用原有正式签名。 +81 项单元测试、6 项原生测试通过,应用及设备测试包编译成功,Android 静态检查无错误。 +新增自制测试 ROM 的按钮流程测试;当前未连接手机,设备测试尚未执行。