diff --git a/README.md b/README.md index 3213b7c..fc7cbe8 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # NESLite NESLite 是一个面向 Android 的轻量 NES/FC 模拟器前端。它使用固定版本的 -FCEUmm libretro 内核。当前仓库已完成 M5 的隔离实现和本地验证,包括通用手柄映射、可靠提交、 -十个手动槽、三个自动恢复点、异常恢复和不含 ROM 的存档包;由于前序真机门槛尚未通过,M2~M5 的实机 +FCEUmm libretro 内核。当前仓库已完成 M6 的隔离实现和本地验证,包括可查询游戏库、持久化统一设置、 +存档管理、屏幕虚拟键、可靠恢复和首次引导;由于前序真机门槛尚未通过,M2~M6 的实机 验收仍待补齐。 ## 快速构建 @@ -15,6 +15,8 @@ pwsh -NoProfile -File .\tools\check.ps1 -Scope Build 该命令默认只生成 arm64-v8a 调试 APK,不会运行耐久或实机验收。 +日常操作见 [使用说明](docs/usage.md),存档兼容与安全边界见 [存档格式](docs/save-format.md)。 + 连接并授权目标手机后,可用 `tools/check-m1-device.ps1` 安装和启动当前调试 APK;实测步骤见 [X5 Lite 键位表](docs/controller-x5lite.md)。 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 3980577..e89f807 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 = 5004 - versionName = "0.5.4" + versionCode = 6004 + versionName = "0.6.4" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" ndk { diff --git a/app/src/main/cpp/core_session.cpp b/app/src/main/cpp/core_session.cpp index 5163553..9be1905 100644 --- a/app/src/main/cpp/core_session.cpp +++ b/app/src/main/cpp/core_session.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -275,8 +276,24 @@ struct Host { ("slot-" + std::to_string(slot) + ".nls")); } + std::size_t next_auto_slot() const { + std::size_t oldest_slot = 0; + std::int64_t oldest_time = std::numeric_limits::max(); + for (std::size_t slot = 0; slot < 3U; ++slot) { + DecodedSaveState decoded; + std::string reason; + if (!read_valid_state(std::filesystem::path(save_dir) / rom_hash / "auto" / + ("auto-" + std::to_string(slot) + ".nls"), &decoded, &reason)) return slot; + if (decoded.metadata.created_epoch_ms < oldest_time) { + oldest_time = decoded.metadata.created_epoch_ms; + oldest_slot = slot; + } + } + return oldest_slot; + } + bool save_auto_point() { - const std::size_t slot = auto_slot_for_generation(auto_generation); + const std::size_t slot = next_auto_slot(); const bool saved = save_state_to(std::filesystem::path(save_dir) / rom_hash / "auto" / ("auto-" + std::to_string(slot) + ".nls")); if (saved) ++auto_generation; diff --git a/app/src/main/cpp/gl_renderer.cpp b/app/src/main/cpp/gl_renderer.cpp index 7222f12..269ec34 100644 --- a/app/src/main/cpp/gl_renderer.cpp +++ b/app/src/main/cpp/gl_renderer.cpp @@ -58,13 +58,16 @@ void renderer_changed(int width, int height) { surface_height = std::max(1, height); } -void renderer_draw(bool integer_scale) { +void renderer_draw(bool integer_scale, bool linear_filter) { glClearColor(0.02F, 0.02F, 0.02F, 1.0F); glClear(GL_COLOR_BUFFER_BIT); VideoFrame frame; if (!latest_video_frame(&frame)) return; glBindTexture(GL_TEXTURE_2D, texture); + const GLint filter = linear_filter ? GL_LINEAR : GL_NEAREST; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter); if (frame.sequence != uploaded_sequence) { const GLenum type = frame.pixel_format == 1 ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT_5_6_5; const GLenum format = frame.pixel_format == 1 ? GL_RGBA : GL_RGB; diff --git a/app/src/main/cpp/jni_bridge.cpp b/app/src/main/cpp/jni_bridge.cpp index f3032be..b4ce76e 100644 --- a/app/src/main/cpp/jni_bridge.cpp +++ b/app/src/main/cpp/jni_bridge.cpp @@ -11,7 +11,7 @@ namespace neslite { void renderer_created(); void renderer_changed(int width, int height); -void renderer_draw(bool integer_scale); +void renderer_draw(bool integer_scale, bool linear_filter); } extern "C" JNIEXPORT jstring JNICALL @@ -89,6 +89,7 @@ Java_org_neslite_app_NativeBridge_rendererChanged(JNIEnv*, jclass, jint width, j } extern "C" JNIEXPORT void JNICALL -Java_org_neslite_app_NativeBridge_rendererDraw(JNIEnv*, jclass, jboolean integer_scale) { - neslite::renderer_draw(integer_scale); +Java_org_neslite_app_NativeBridge_rendererDraw(JNIEnv*, jclass, jboolean integer_scale, + jboolean linear_filter) { + neslite::renderer_draw(integer_scale, linear_filter); } diff --git a/app/src/main/java/org/neslite/app/EmulatorSurface.kt b/app/src/main/java/org/neslite/app/EmulatorSurface.kt index b935fa7..1201ec9 100644 --- a/app/src/main/java/org/neslite/app/EmulatorSurface.kt +++ b/app/src/main/java/org/neslite/app/EmulatorSurface.kt @@ -9,6 +9,9 @@ class EmulatorSurface(context: Context) : GLSurfaceView(context), GLSurfaceView. @Volatile var integerScale: Boolean = false + @Volatile + var linearFilter: Boolean = false + init { setEGLContextClientVersion(2) setRenderer(this) @@ -21,5 +24,5 @@ class EmulatorSurface(context: Context) : GLSurfaceView(context), GLSurfaceView. override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) = NativeBridge.rendererChanged(width, height) - override fun onDrawFrame(gl: GL10?) = NativeBridge.rendererDraw(integerScale) + override fun onDrawFrame(gl: GL10?) = NativeBridge.rendererDraw(integerScale, linearFilter) } diff --git a/app/src/main/java/org/neslite/app/MainActivity.kt b/app/src/main/java/org/neslite/app/MainActivity.kt index 17daae6..50665ce 100644 --- a/app/src/main/java/org/neslite/app/MainActivity.kt +++ b/app/src/main/java/org/neslite/app/MainActivity.kt @@ -7,6 +7,7 @@ import android.media.AudioDeviceInfo import android.media.AudioFocusRequest import android.media.AudioManager import android.hardware.input.InputManager +import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.os.Handler @@ -19,6 +20,8 @@ import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.Button +import android.widget.EditText +import android.widget.ImageView import android.widget.LinearLayout import android.widget.ScrollView import android.widget.SeekBar @@ -27,6 +30,7 @@ import android.widget.Toast import android.app.AlertDialog import androidx.activity.ComponentActivity import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.widget.doAfterTextChanged import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -57,8 +61,13 @@ import org.neslite.app.input.InputSource import org.neslite.app.input.InputSourceKind import org.neslite.app.input.ProfileOrigin import org.neslite.app.input.RoutedInputState +import org.neslite.app.save.SaveCatalogReader +import org.neslite.app.save.SaveSlotSummary +import org.neslite.app.settings.AppSettings +import org.neslite.app.settings.AppSettingsStore import java.io.File import java.io.FileOutputStream +import java.nio.ByteBuffer import java.text.SimpleDateFormat import java.util.Date import java.util.Locale @@ -84,6 +93,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private lateinit var audioStatus: TextView private lateinit var pauseMenu: LinearLayout private lateinit var controllerSettingsPanel: LinearLayout + private lateinit var settingsPanel: LinearLayout + private lateinit var saveManagerPanel: LinearLayout + private lateinit var virtualGamepad: VirtualGamepadView + private lateinit var searchInput: EditText private lateinit var audioManager: AudioManager private lateinit var audioFocusRequest: AudioFocusRequest private var activeSessionId = 0L @@ -103,6 +116,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private var pendingBindingAction: GameAction? = null private var controllerSettingsMessage = "选择动作后按一个手柄键或推动一个轴。" private var settingsReturnToPause = false + private var controllerReturnToSettings = false + private lateinit var appSettingsStore: AppSettingsStore + private var appSettings = AppSettings() + private var activeGameHash = "" private var lastCompletionId = 0L private var recoveryPromptedSession = 0L private var pendingSaveExportUri: Uri? = null @@ -164,8 +181,11 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { baseline = DeviceDiagnostics.collectBaseline(this, nativeProbe.pageSizeBytes) database = GameDatabase.get(this) profileStore = ControllerProfileStore(this, profileResolver) + appSettingsStore = AppSettingsStore(this) activeSessionId = savedInstanceState?.getLong(STATE_SESSION_ID) ?: 0L + activeGameHash = savedInstanceState?.getString(STATE_GAME_HASH).orEmpty() setContentView(createContentView()) + loadAppSettings() refreshControllers() recoverLibrary() pollSessionStatus() @@ -203,6 +223,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { override fun onSaveInstanceState(outState: Bundle) { outState.putLong(STATE_SESSION_ID, activeSessionId) + outState.putString(STATE_GAME_HASH, activeGameHash) super.onSaveInstanceState(outState) } @@ -366,13 +387,19 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { setPadding(32, 32, 32, 48) addView(title(getString(R.string.diagnostics_title))) addView(body(getString(R.string.diagnostics_instructions))) - addView(section("M5 游戏库、可靠存档与音画")) + addView(section("M6 游戏库、设置、存档管理与虚拟按键")) addView( Button(context).apply { text = "从文件导入 iNES / NES 2.0 ROM" setOnClickListener { openRom.launch(arrayOf("application/octet-stream", "*/*")) } }, ) + searchInput = EditText(context).apply { + hint = "搜索游戏名称或哈希" + isSingleLine = true + doAfterTextChanged { refreshLibrary() } + } + addView(searchInput) gameList = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL } addView(gameList) emulatorSurface = EmulatorSurface(context) @@ -380,10 +407,29 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { emulatorSurface, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 720), ) + virtualGamepad = VirtualGamepadView(context, ::handleVirtualInput) + addView( + virtualGamepad, + LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 360), + ) emulatorStatus = body("状态:Idle") addView(emulatorStatus) pauseMenu = createPauseMenu() addView(pauseMenu) + saveManagerPanel = LinearLayout(context).apply { + orientation = LinearLayout.VERTICAL + visibility = View.GONE + } + addView(saveManagerPanel) + addView(Button(context).apply { + text = "显示、音频与输入设置" + setOnClickListener { showSettings() } + }) + settingsPanel = LinearLayout(context).apply { + orientation = LinearLayout.VERTICAL + visibility = View.GONE + } + addView(settingsPanel) addView( LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL @@ -406,9 +452,11 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { addView(Button(context).apply { text = "静音:关" setOnClickListener { - muted = !muted - text = if (muted) "静音:开" else "静音:关" - sendControlCommand(if (muted) "mute:on" else "mute:off") + appSettings = appSettings.copy(muted = !appSettings.muted) + muted = appSettings.muted + text = if (appSettings.muted) "静音:开" else "静音:关" + sendControlCommand(if (appSettings.muted) "mute:on" else "mute:off") + persistAppSettings() } }) addView(Button(context).apply { @@ -416,7 +464,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { setOnClickListener { } setOnTouchListener { view, event -> when (event.actionMasked) { - MotionEvent.ACTION_DOWN -> sendControlCommand("fast:on") + MotionEvent.ACTION_DOWN -> if (appSettings.fastForwardEnabled) sendControlCommand("fast:on") MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { sendControlCommand("fast:off") if (event.actionMasked == MotionEvent.ACTION_UP) view.performClick() @@ -435,7 +483,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {} override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) { - sendControlCommand("volume:${(seekBar?.progress ?: 100) / 100.0f}") + appSettings = appSettings.copy(volume = (seekBar?.progress ?: 100) / 100.0f) + sendControlCommand("volume:${appSettings.volume}") + persistAppSettings() } }) }) @@ -445,8 +495,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { Button(context).apply { text = "缩放:4:3(点按切换整数像素)" setOnClickListener { - emulatorSurface.integerScale = !emulatorSurface.integerScale - text = if (emulatorSurface.integerScale) "缩放:整数像素" else "缩放:4:3" + appSettings = appSettings.copy(integerScale = !appSettings.integerScale) + applyAppSettings() + persistAppSettings() + text = if (appSettings.integerScale) "缩放:整数像素" else "缩放:4:3" } }, ) @@ -502,6 +554,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { text = "重置游戏" setOnClickListener { sendControlCommand("reset") } }) + addView(Button(context).apply { + text = "存档管理(时间与缩略图)" + setOnClickListener { showSaveManager() } + }) addView(section("手动即时存档(10 槽)")) repeat(10) { slot -> addView( @@ -552,6 +608,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private fun showPauseMenu() { closeControllerSettings(showPreviousMenu = false) + if (::settingsPanel.isInitialized) settingsPanel.visibility = View.GONE + if (::saveManagerPanel.isInitialized) saveManagerPanel.visibility = View.GONE pauseMenu.visibility = View.VISIBLE (pauseMenu.getChildAt(1) as? Button)?.requestFocus() } @@ -560,11 +618,244 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { if (::pauseMenu.isInitialized) pauseMenu.visibility = View.GONE } - private fun showControllerSettings(returnToPause: Boolean) { + private fun showSettings() { + if (lastSessionState == "Running" && !sendControlCommand("pause")) return + hidePauseMenu() + if (::saveManagerPanel.isInitialized) saveManagerPanel.visibility = View.GONE + closeControllerSettings(showPreviousMenu = false) + settingsPanel.visibility = View.VISIBLE + renderSettings() + } + + private fun renderSettings() { + if (!::settingsPanel.isInitialized || settingsPanel.visibility != View.VISIBLE) return + settingsPanel.removeAllViews() + settingsPanel.addView(section("显示、音频与输入设置")) + settingsPanel.addView(Button(this).apply { + text = if (appSettings.integerScale) "画面比例:原始整数缩放" else "画面比例:保持 4:3" + setOnClickListener { + appSettings = appSettings.copy(integerScale = !appSettings.integerScale) + applyAppSettings() + persistAppSettings() + renderSettings() + } + }) + settingsPanel.addView(Button(this).apply { + text = if (appSettings.linearFilter) "纹理过滤:线性" else "纹理过滤:最近邻" + setOnClickListener { + appSettings = appSettings.copy(linearFilter = !appSettings.linearFilter) + applyAppSettings() + persistAppSettings() + renderSettings() + } + }) + settingsPanel.addView(body("音量:${(appSettings.volume * 100).toInt()}%")) + settingsPanel.addView(SeekBar(this).apply { + max = 100 + progress = (appSettings.volume * 100).toInt() + setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {} + override fun onStartTrackingTouch(seekBar: SeekBar?) {} + override fun onStopTrackingTouch(seekBar: SeekBar?) { + appSettings = appSettings.copy(volume = (seekBar?.progress ?: 100) / 100f) + applyAppSettings() + persistAppSettings() + renderSettings() + } + }) + }) + settingsPanel.addView(Button(this).apply { + text = if (appSettings.muted) "静音:开" else "静音:关" + setOnClickListener { + appSettings = appSettings.copy(muted = !appSettings.muted) + applyAppSettings() + persistAppSettings() + renderSettings() + } + }) + settingsPanel.addView(Button(this).apply { + text = if (appSettings.turboEnabled) "A/B 软件连发:开" else "A/B 软件连发:关" + setOnClickListener { + appSettings = appSettings.copy(turboEnabled = !appSettings.turboEnabled) + applyRoutedInput(inputRouter.current()) + persistAppSettings() + renderSettings() + } + }) + settingsPanel.addView(Button(this).apply { + text = if (appSettings.fastForwardEnabled) "RB 快进:开" else "RB 快进:关" + setOnClickListener { + appSettings = appSettings.copy(fastForwardEnabled = !appSettings.fastForwardEnabled) + if (!appSettings.fastForwardEnabled && activeSessionId != 0L) { + NativeBridge.command(activeSessionId, "fast:off") + } + persistAppSettings() + renderSettings() + } + }) + settingsPanel.addView(Button(this).apply { + text = "手柄映射、A/B 交换与死区" + setOnClickListener { + settingsPanel.visibility = View.GONE + showControllerSettings(returnToPause = false, returnToSettings = true) + } + }) + settingsPanel.addView(Button(this).apply { + text = "关闭设置" + setOnClickListener { + settingsPanel.visibility = View.GONE + if (lastSessionState == "Paused") showPauseMenu() + } + }) + focusFirstButton(settingsPanel) + } + + private fun loadAppSettings() { + controllerScope.launch { + val loaded = appSettingsStore.load() + runOnUiThread { + appSettings = loaded + applyAppSettings() + if (!loaded.guideCompleted) showFirstUseGuide() + } + } + } + + private fun applyAppSettings() { + muted = appSettings.muted + if (::emulatorSurface.isInitialized) { + emulatorSurface.integerScale = appSettings.integerScale + emulatorSurface.linearFilter = appSettings.linearFilter + } + if (activeSessionId != 0L) { + NativeBridge.command(activeSessionId, "volume:${appSettings.volume}") + NativeBridge.command(activeSessionId, if (appSettings.muted) "mute:on" else "mute:off") + } + } + + private fun persistAppSettings() { + val snapshot = appSettings + controllerScope.launch { appSettingsStore.save(snapshot) } + } + + private fun showFirstUseGuide() { + AlertDialog.Builder(this) + .setTitle("欢迎使用 NESLite") + .setMessage( + "1. 点“从文件导入”选择你合法持有的 NES ROM。\n\n" + + "2. 可连接手柄并在设置中测试/调整映射;没有手柄也能使用屏幕虚拟键。\n\n" + + "3. 选择游戏后点运行。屏幕“暂停”或右摇杆按下可打开菜单。\n\n" + + "4. 暂停菜单可保存、读档、导入导出(包内不含 ROM)和退出。", + ) + .setPositiveButton("开始使用") { _, _ -> + appSettings = appSettings.copy(guideCompleted = true) + persistAppSettings() + } + .setNegativeButton("稍后再看", null) + .show() + } + + private fun handleVirtualInput(pointerId: Int, action: GameAction, pressed: Boolean) { + if (!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 (activeSessionId == 0L || activeGameHash.isBlank() || lastSessionState != "Paused") { + emulatorStatus.text = "请先加载游戏并暂停,再打开存档管理" + return + } + hidePauseMenu() + settingsPanel.visibility = View.GONE + closeControllerSettings(showPreviousMenu = false) + saveManagerPanel.visibility = View.VISIBLE + saveManagerPanel.removeAllViews() + saveManagerPanel.addView(body("正在读取已校验槽位…")) + refreshSaveManager() + } + + private fun refreshSaveManager() { + if (!::saveManagerPanel.isInitialized || saveManagerPanel.visibility != View.VISIBLE || activeGameHash.isBlank()) return + val hash = activeGameHash + libraryExecutor.execute { + val root = File(File(filesDir, "saves"), 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 { renderSaveManager(manual, automatic) } + } + } + + private fun renderSaveManager( + manual: Map, + automatic: Map, + ) { + if (saveManagerPanel.visibility != View.VISIBLE) return + saveManagerPanel.removeAllViews() + saveManagerPanel.addView(section("存档管理")) + saveManagerPanel.addView(body("手动槽显示提交时间和与状态同帧的缩略图;空槽仍可直接保存。")) + manual.forEach { (slot, summary) -> addSaveSlotRow("手动 ${slot + 1}", slot, summary, false) } + saveManagerPanel.addView(section("自动恢复点(按时间)")) + automatic.entries.sortedByDescending { it.value?.createdAtEpochMs ?: Long.MIN_VALUE } + .forEach { (slot, summary) -> addSaveSlotRow("自动 ${slot + 1}", slot, summary, true) } + saveManagerPanel.addView(Button(this).apply { + text = "导出存档包(不含 ROM)" + setOnClickListener { createSavePackage.launch("neslite-save-${System.currentTimeMillis()}.nsp") } + }) + saveManagerPanel.addView(Button(this).apply { + text = "导入存档包" + setOnClickListener { openSavePackage.launch(arrayOf("application/vnd.neslite.save", "application/octet-stream", "*/*")) } + }) + saveManagerPanel.addView(Button(this).apply { + text = "返回暂停菜单" + setOnClickListener { + saveManagerPanel.visibility = View.GONE + showPauseMenu() + } + }) + focusFirstButton(saveManagerPanel) + } + + private fun addSaveSlotRow(label: String, slot: Int, summary: SaveSlotSummary?, automatic: Boolean) { + saveManagerPanel.addView(LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + summary?.let { addView(saveThumbnail(it)) } + addView(Button(context).apply { + text = if (summary == null) "$label · 空槽" else + "$label · ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT).format(Date(summary.createdAtEpochMs))}" + setOnClickListener { + if (automatic) sendControlCommand("auto_load:$slot") else sendControlCommand("state_load:$slot") + } + isEnabled = summary != null + }) + if (!automatic) addView(Button(context).apply { + text = "保存" + setOnClickListener { sendControlCommand("state_save:$slot") } + }) + }) + } + + private fun saveThumbnail(summary: SaveSlotSummary): ImageView = ImageView(this).apply { + val expected = summary.width.toLong() * summary.height * 2L + if (summary.pixelFormat == 2 && summary.width > 0 && summary.height > 0 && + summary.pitch == summary.width * 2 && summary.thumbnail.size.toLong() == expected) { + val bitmap = Bitmap.createBitmap(summary.width, summary.height, Bitmap.Config.RGB_565) + bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(summary.thumbnail)) + setImageBitmap(bitmap) + } + contentDescription = "存档缩略图" + layoutParams = LinearLayout.LayoutParams(192, 144) + scaleType = ImageView.ScaleType.FIT_CENTER + } + + private fun showControllerSettings(returnToPause: Boolean, returnToSettings: Boolean = false) { val shouldReturnToPause = returnToPause || lastSessionState == "Running" if (lastSessionState == "Running" && !sendControlCommand("pause")) return settingsReturnToPause = shouldReturnToPause + controllerReturnToSettings = returnToSettings hidePauseMenu() + if (::settingsPanel.isInitialized) settingsPanel.visibility = View.GONE + if (::saveManagerPanel.isInitialized) saveManagerPanel.visibility = View.GONE controllerSettingsPanel.visibility = View.VISIBLE draftProfile = selectedControllerId?.let(controllerProfiles::get) pendingBindingAction = null @@ -577,8 +868,12 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { draftProfile = null if (::controllerSettingsPanel.isInitialized) controllerSettingsPanel.visibility = View.GONE clearControllerState() - if (showPreviousMenu && settingsReturnToPause && ::pauseMenu.isInitialized) showPauseMenu() + if (showPreviousMenu && controllerReturnToSettings && ::settingsPanel.isInitialized) { + settingsPanel.visibility = View.VISIBLE + renderSettings() + } else if (showPreviousMenu && settingsReturnToPause && ::pauseMenu.isInitialized) showPauseMenu() settingsReturnToPause = false + controllerReturnToSettings = false } private fun renderControllerSettings() { @@ -951,22 +1246,70 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { } private fun refreshLibrary() { + val query = if (::searchInput.isInitialized) searchInput.text.toString().trim() else "" libraryExecutor.execute { - val games = database.games().all() + val games = database.games().visible(query) runOnUiThread { gameList.removeAllViews() - if (games.isEmpty()) gameList.addView(body("尚未导入 ROM")) + if (games.isEmpty()) { + gameList.addView(body(if (query.isEmpty()) "游戏库为空;请从文件导入 ROM。" else "没有匹配“$query”的游戏;可清空搜索后重试。")) + } games.forEach { game -> - gameList.addView(Button(this).apply { - text = "${game.displayName} · ${game.format} · ${game.sha256.take(8)} · ${game.status}" - isEnabled = game.status == GameEntity.STATUS_READY - setOnClickListener { loadGame(game) } + gameList.addView(LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + addView(Button(context).apply { + text = (if (game.favorite) "★ " else "") + game.displayName + isAllCaps = false + isEnabled = game.status == GameEntity.STATUS_READY + setOnClickListener { loadGame(game) } + }) + addView(body("${game.format} · ${formatBytes(game.sizeBytes)} · SHA ${game.sha256.take(12)} · ${game.status}\n" + + "导入 ${formatDate(game.addedAtEpochMs)} · 最近 ${if (game.lastPlayedAtEpochMs == 0L) "未游玩" else formatDate(game.lastPlayedAtEpochMs)}")) + addView(LinearLayout(context).apply { + orientation = LinearLayout.HORIZONTAL + addView(Button(context).apply { + text = if (game.favorite) "取消收藏" else "收藏" + setOnClickListener { + libraryExecutor.execute { + database.games().setFavorite(game.sha256, !game.favorite) + runOnUiThread { refreshLibrary() } + } + } + }) + addView(Button(context).apply { + text = "从列表移除" + setOnClickListener { confirmHideGame(game) } + }) + }) }) } } } } + private fun confirmHideGame(game: GameEntity) { + AlertDialog.Builder(this) + .setTitle("从列表移除?") + .setMessage("只隐藏“${game.displayName}”,不会删除 ROM 文件或任何存档。以后重新导入相同内容会恢复关联。") + .setPositiveButton("移除") { _, _ -> + libraryExecutor.execute { + database.games().hide(game.sha256) + runOnUiThread { refreshLibrary() } + } + } + .setNegativeButton("取消", null) + .show() + } + + private fun formatBytes(bytes: Long): String = when { + bytes >= 1024L * 1024L -> String.format(Locale.ROOT, "%.2f MiB", bytes / (1024.0 * 1024.0)) + bytes >= 1024L -> String.format(Locale.ROOT, "%.1f KiB", bytes / 1024.0) + else -> "$bytes B" + } + + private fun formatDate(epochMs: Long): String = + SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(Date(epochMs)) + private fun loadGame(game: GameEntity) { val path = File(File(filesDir, "roms"), game.fileName).absolutePath activeSessionId = NativeBridge.loadRom( @@ -975,6 +1318,11 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { File(filesDir, "saves").apply { mkdirs() }.absolutePath, game.sha256, ) + activeGameHash = game.sha256 + libraryExecutor.execute { + database.games().markPlayed(game.sha256, System.currentTimeMillis()) + runOnUiThread { refreshLibrary() } + } emulatorStatus.text = if (activeSessionId == 0L) "命令队列已满" else "正在加载会话 $activeSessionId" } @@ -1065,9 +1413,11 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { val completionId = status.optLong("completionId") val completion = status.optString("completion") emulatorStatus.text = "状态:$nextState · $completion" + - if (status.optBoolean("fastForward")) " · 2×" else "" + (if (status.optBoolean("fastForward")) " · 2×" else "") + + status.optString("error").takeIf { it.isNotBlank() }?.let { "\n错误:$it;可留在暂停菜单重试或退出。" }.orEmpty() if (completionId != lastCompletionId) { lastCompletionId = completionId + if (completion.endsWith(":loaded")) applyAppSettings() if (completion.endsWith(":package_exported")) finishSavePackageExport() if (completion.endsWith(":package_export_failed")) { pendingSaveExportUri = null @@ -1077,6 +1427,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { 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() + } } val candidateCount = status.optInt("recoveryCandidates") if (status.optBoolean("abnormalSession") && candidateCount > 0 && @@ -1115,6 +1468,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { "pause" -> showPauseMenu() "run", "stop" -> { hidePauseMenu() + if (::settingsPanel.isInitialized) settingsPanel.visibility = View.GONE + if (::saveManagerPanel.isInitialized) saveManagerPanel.visibility = View.GONE closeControllerSettings(showPreviousMenu = false) } } @@ -1128,8 +1483,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { val gameplayActive = gameplayInputActive() joypadMask = if (gameplayActive) state.joypadMask else 0 NativeBridge.setJoypadMask(joypadMask) - NativeBridge.setTurboMask(if (gameplayActive) state.turboMask else 0) - state.fastForwardChanged?.takeIf { gameplayActive }?.let { enabled -> + NativeBridge.setTurboMask(if (gameplayActive && appSettings.turboEnabled) state.turboMask else 0) + state.fastForwardChanged?.takeIf { gameplayActive && appSettings.fastForwardEnabled }?.let { enabled -> NativeBridge.command(activeSessionId, if (enabled) "fast:on" else "fast:off") } if (state.pauseMenuEdge) { @@ -1144,6 +1499,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { pauseMenu.visibility != View.VISIBLE && controllerSettingsPanel.visibility != View.VISIBLE private fun clearControllerState() { + if (::virtualGamepad.isInitialized) virtualGamepad.clearInputs() inputRouter.clearAll() axisHysteresis.clearAll() joypadMask = 0 @@ -1289,6 +1645,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { companion object { private const val EVENT_LINES = 30 private const val STATE_SESSION_ID = "active_session_id" + private const val STATE_GAME_HASH = "active_game_hash" private const val MAX_SAVE_PACKAGE_BYTES = 128L * 1024L * 1024L } } diff --git a/app/src/main/java/org/neslite/app/NativeBridge.kt b/app/src/main/java/org/neslite/app/NativeBridge.kt index d591d7c..14b4812 100644 --- a/app/src/main/java/org/neslite/app/NativeBridge.kt +++ b/app/src/main/java/org/neslite/app/NativeBridge.kt @@ -28,5 +28,5 @@ object NativeBridge { external fun rendererChanged(width: Int, height: Int) - external fun rendererDraw(integerScale: Boolean) + external fun rendererDraw(integerScale: Boolean, linearFilter: Boolean) } diff --git a/app/src/main/java/org/neslite/app/VirtualGamepadView.kt b/app/src/main/java/org/neslite/app/VirtualGamepadView.kt new file mode 100644 index 0000000..882220d --- /dev/null +++ b/app/src/main/java/org/neslite/app/VirtualGamepadView.kt @@ -0,0 +1,100 @@ +package org.neslite.app + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.view.MotionEvent +import android.view.View +import org.neslite.app.input.GameAction +import org.neslite.app.input.VirtualInputTracker + +class VirtualGamepadView( + context: Context, + private val onTransition: (pointerId: Int, action: GameAction, pressed: Boolean) -> Unit, +) : View(context) { + private val tracker = VirtualInputTracker() + private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.argb(110, 45, 55, 70) } + private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.WHITE + textAlign = Paint.Align.CENTER + textSize = 34f + } + + init { + isFocusable = true + contentDescription = "屏幕虚拟手柄:方向、A、B、Start、Select 和暂停" + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val w = width.toFloat() + val h = height.toFloat() + fun circle(x: Float, y: Float, radius: Float, label: String) { + canvas.drawCircle(x, y, radius, fill) + canvas.drawText(label, x, y + textPaint.textSize * 0.35f, textPaint) + } + circle(w * .21f, h * .30f, h * .16f, "↑") + circle(w * .21f, h * .82f, h * .16f, "↓") + circle(w * .08f, h * .56f, h * .16f, "←") + circle(w * .34f, h * .56f, h * .16f, "→") + circle(w * .75f, h * .68f, h * .18f, "B") + circle(w * .91f, h * .42f, h * .18f, "A") + textPaint.textSize = 24f + circle(w * .45f, h * .82f, h * .11f, "Select") + circle(w * .58f, h * .82f, h * .11f, "Start") + circle(w * .52f, h * .23f, h * .11f, "暂停") + textPaint.textSize = 34f + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> updatePointer(event, event.actionIndex) + MotionEvent.ACTION_MOVE -> repeat(event.pointerCount) { updatePointer(event, it) } + MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> releasePointer(event.getPointerId(event.actionIndex)) + MotionEvent.ACTION_CANCEL -> tracker.clear().forEach { onTransition(it.pointerId, it.action, it.pressed) } + } + if (event.actionMasked == MotionEvent.ACTION_UP) performClick() + return true + } + + override fun performClick(): Boolean { + super.performClick() + return true + } + + fun clearInputs() { + tracker.clear().forEach { onTransition(it.pointerId, it.action, it.pressed) } + } + + private fun updatePointer(event: MotionEvent, index: Int) { + val pointerId = event.getPointerId(index) + tracker.update(pointerId, hitTest(event.getX(index), event.getY(index))) + .forEach { onTransition(it.pointerId, it.action, it.pressed) } + } + + private fun releasePointer(pointerId: Int) { + tracker.update(pointerId, null).forEach { onTransition(it.pointerId, it.action, it.pressed) } + } + + internal fun hitTest(x: Float, y: Float): GameAction? { + if (width <= 0 || height <= 0) return null + val nx = x / width + val ny = y / height + if (nx >= .42f && nx <= .59f && ny < .38f) return GameAction.PAUSE_MENU + if (nx < .42f) { + val dx = nx - .21f + val dy = ny - .56f + if (kotlin.math.abs(dx) < .25f && kotlin.math.abs(dy) < .42f) { + return if (kotlin.math.abs(dx) > kotlin.math.abs(dy)) { + if (dx < 0f) GameAction.LEFT else GameAction.RIGHT + } else if (dy < 0f) GameAction.UP else GameAction.DOWN + } + } + if (ny > .68f && nx >= .37f && nx <= .51f) return GameAction.SELECT + if (ny > .68f && nx >= .51f && nx <= .65f) return GameAction.START + if (nx > .82f && ny < .64f) return GameAction.NES_A + if (nx >= .62f && nx <= .85f && ny > .48f) return GameAction.NES_B + return null + } +} diff --git a/app/src/main/java/org/neslite/app/input/VirtualInputTracker.kt b/app/src/main/java/org/neslite/app/input/VirtualInputTracker.kt new file mode 100644 index 0000000..4a7ffb2 --- /dev/null +++ b/app/src/main/java/org/neslite/app/input/VirtualInputTracker.kt @@ -0,0 +1,25 @@ +package org.neslite.app.input + +data class VirtualInputTransition(val pointerId: Int, val action: GameAction, val pressed: Boolean) + +class VirtualInputTracker { + private val active = mutableMapOf() + + fun update(pointerId: Int, action: GameAction?): List { + val previous = active[pointerId] + if (previous == action) return emptyList() + val transitions = mutableListOf() + if (previous != null) transitions += VirtualInputTransition(pointerId, previous, false) + if (action == null) active.remove(pointerId) else { + active[pointerId] = action + transitions += VirtualInputTransition(pointerId, action, true) + } + return transitions + } + + fun clear(): List { + val transitions = active.map { (pointerId, action) -> VirtualInputTransition(pointerId, action, false) } + active.clear() + return transitions + } +} diff --git a/app/src/main/java/org/neslite/app/library/GameDao.java b/app/src/main/java/org/neslite/app/library/GameDao.java index 9286aa7..ddc865d 100644 --- a/app/src/main/java/org/neslite/app/library/GameDao.java +++ b/app/src/main/java/org/neslite/app/library/GameDao.java @@ -11,6 +11,10 @@ public interface GameDao { @Query("SELECT * FROM games ORDER BY displayName COLLATE NOCASE, sha256") List all(); + @Query("SELECT * FROM games WHERE hidden = 0 AND (displayName LIKE '%' || :query || '%' OR sha256 LIKE '%' || :query || '%') " + + "ORDER BY favorite DESC, lastPlayedAtEpochMs DESC, displayName COLLATE NOCASE, sha256") + List visible(String query); + @Query("SELECT * FROM games WHERE sha256 = :sha256 LIMIT 1") GameEntity byHash(String sha256); @@ -19,4 +23,16 @@ public interface GameDao { @Query("UPDATE games SET status = :status WHERE sha256 = :sha256") void setStatus(String sha256, String status); + + @Query("UPDATE games SET favorite = :favorite WHERE sha256 = :sha256") + void setFavorite(String sha256, boolean favorite); + + @Query("UPDATE games SET hidden = 1 WHERE sha256 = :sha256") + void hide(String sha256); + + @Query("UPDATE games SET hidden = 0, status = :status, fileName = :fileName, sizeBytes = :sizeBytes, format = :format WHERE sha256 = :sha256") + void restoreAssociation(String sha256, String status, String fileName, long sizeBytes, String format); + + @Query("UPDATE games SET lastPlayedAtEpochMs = :playedAt WHERE sha256 = :sha256") + void markPlayed(String sha256, long playedAt); } diff --git a/app/src/main/java/org/neslite/app/library/GameDatabase.java b/app/src/main/java/org/neslite/app/library/GameDatabase.java index 43e38bc..5e80e90 100644 --- a/app/src/main/java/org/neslite/app/library/GameDatabase.java +++ b/app/src/main/java/org/neslite/app/library/GameDatabase.java @@ -1,11 +1,14 @@ package org.neslite.app.library; import android.content.Context; +import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; +import androidx.room.migration.Migration; +import androidx.sqlite.db.SupportSQLiteDatabase; -@Database(entities = {GameEntity.class}, version = 1, exportSchema = false) +@Database(entities = {GameEntity.class}, version = 2, exportSchema = false) public abstract class GameDatabase extends RoomDatabase { private static volatile GameDatabase instance; @@ -20,10 +23,18 @@ public abstract class GameDatabase extends RoomDatabase { current = Room.databaseBuilder( context.getApplicationContext(), GameDatabase.class, - "neslite-games.db").build(); + "neslite-games.db").addMigrations(MIGRATION_1_2).build(); instance = current; } } return current; } + + private static final Migration MIGRATION_1_2 = new Migration(1, 2) { + @Override public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL("ALTER TABLE games ADD COLUMN favorite INTEGER NOT NULL DEFAULT 0"); + database.execSQL("ALTER TABLE games ADD COLUMN hidden INTEGER NOT NULL DEFAULT 0"); + database.execSQL("ALTER TABLE games ADD COLUMN lastPlayedAtEpochMs INTEGER NOT NULL DEFAULT 0"); + } + }; } diff --git a/app/src/main/java/org/neslite/app/library/GameEntity.java b/app/src/main/java/org/neslite/app/library/GameEntity.java index ae70609..bb24a77 100644 --- a/app/src/main/java/org/neslite/app/library/GameEntity.java +++ b/app/src/main/java/org/neslite/app/library/GameEntity.java @@ -2,6 +2,7 @@ package org.neslite.app.library; import androidx.annotation.NonNull; import androidx.room.Entity; +import androidx.room.ColumnInfo; import androidx.room.PrimaryKey; @Entity(tableName = "games") @@ -16,6 +17,9 @@ public final class GameEntity { @NonNull public final String fileName; @NonNull public final String status; public final long addedAtEpochMs; + @ColumnInfo(defaultValue = "0") public final boolean favorite; + @ColumnInfo(defaultValue = "0") public final boolean hidden; + @ColumnInfo(defaultValue = "0") public final long lastPlayedAtEpochMs; public GameEntity( @NonNull String sha256, @@ -24,7 +28,10 @@ public final class GameEntity { @NonNull String format, @NonNull String fileName, @NonNull String status, - long addedAtEpochMs) { + long addedAtEpochMs, + boolean favorite, + boolean hidden, + long lastPlayedAtEpochMs) { this.sha256 = sha256; this.displayName = displayName; this.sizeBytes = sizeBytes; @@ -32,5 +39,8 @@ public final class GameEntity { this.fileName = fileName; this.status = status; this.addedAtEpochMs = addedAtEpochMs; + this.favorite = favorite; + this.hidden = hidden; + this.lastPlayedAtEpochMs = lastPlayedAtEpochMs; } } diff --git a/app/src/main/java/org/neslite/app/library/LibraryRecovery.kt b/app/src/main/java/org/neslite/app/library/LibraryRecovery.kt index d6b6f04..4ad2a5d 100644 --- a/app/src/main/java/org/neslite/app/library/LibraryRecovery.kt +++ b/app/src/main/java/org/neslite/app/library/LibraryRecovery.kt @@ -36,6 +36,9 @@ class LibraryRecovery(filesDir: File, private val dao: GameDao) { file.name, GameEntity.STATUS_READY, System.currentTimeMillis(), + false, + false, + 0L, ), ) recoveredFiles++ diff --git a/app/src/main/java/org/neslite/app/library/RomImporter.kt b/app/src/main/java/org/neslite/app/library/RomImporter.kt index df5f84b..83eb3b5 100644 --- a/app/src/main/java/org/neslite/app/library/RomImporter.kt +++ b/app/src/main/java/org/neslite/app/library/RomImporter.kt @@ -29,7 +29,7 @@ class RomImporter( dao.byHash(hash)?.let { existing -> if (!finalFile.isFile) { require(temp.renameTo(finalFile)) { "无法恢复缺失的内部 ROM 文件" } - dao.setStatus(hash, GameEntity.STATUS_READY) + dao.restoreAssociation(hash, GameEntity.STATUS_READY, finalFile.name, copied.sizeBytes, header.format) return Result( GameEntity( existing.sha256, @@ -39,12 +39,16 @@ class RomImporter( finalFile.name, GameEntity.STATUS_READY, existing.addedAtEpochMs, + existing.favorite, + false, + existing.lastPlayedAtEpochMs, ), duplicate = true, ) } temp.delete() - return Result(existing, duplicate = true) + dao.restoreAssociation(hash, GameEntity.STATUS_READY, finalFile.name, copied.sizeBytes, header.format) + return Result(dao.byHash(hash) ?: existing, duplicate = true) } if (!finalFile.exists()) require(temp.renameTo(finalFile)) { "无法提交内部 ROM 文件" } else temp.delete() @@ -56,6 +60,9 @@ class RomImporter( finalFile.name, GameEntity.STATUS_READY, System.currentTimeMillis(), + false, + false, + 0L, ) dao.insert(game) return Result(dao.byHash(hash) ?: game, duplicate = false) diff --git a/app/src/main/java/org/neslite/app/save/SaveCatalogReader.kt b/app/src/main/java/org/neslite/app/save/SaveCatalogReader.kt new file mode 100644 index 0000000..62c1a68 --- /dev/null +++ b/app/src/main/java/org/neslite/app/save/SaveCatalogReader.kt @@ -0,0 +1,76 @@ +package org.neslite.app.save + +import java.io.File +import java.io.RandomAccessFile +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.security.MessageDigest + +data class SaveSlotSummary( + val file: File, + val createdAtEpochMs: Long, + val width: Int, + val height: Int, + val pitch: Int, + val pixelFormat: Int, + val thumbnail: ByteArray, +) + +object SaveCatalogReader { + private const val HEADER_BYTES = 132 + private const val MAX_STATE_BYTES = 64L * 1024L * 1024L + private const val MAX_THUMBNAIL_BYTES = 2L * 1024L * 1024L + private val MAGIC = "NESLST01".toByteArray(Charsets.US_ASCII) + + fun read(file: File): SaveSlotSummary? = runCatching { + RandomAccessFile(file, "r").use { input -> + require(input.length() in HEADER_BYTES.toLong()..(HEADER_BYTES + MAX_STATE_BYTES + MAX_THUMBNAIL_BYTES + 65536L)) + val header = ByteArray(HEADER_BYTES) + input.readFully(header) + require(header.copyOfRange(0, 8).contentEquals(MAGIC)) + val values = ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN) + values.position(8) + require(values.int == 1) + val romLength = values.int + val coreLength = values.int + val commitLength = values.int + val configurationLength = values.int + val width = values.int + val height = values.int + val pitch = values.int + val pixelFormat = values.int + val createdAt = values.long + val stateLength = values.long + val thumbnailLength = values.long + val checksumBytes = ByteArray(64) + values.get(checksumBytes) + val expectedChecksum = checksumBytes.toString(Charsets.US_ASCII) + val textLength = listOf(romLength, coreLength, commitLength, configurationLength).sumOf { + require(it in 0..16384) + it.toLong() + } + require(stateLength in 1..MAX_STATE_BYTES) + require(thumbnailLength in 0..MAX_THUMBNAIL_BYTES) + val stateOffset = HEADER_BYTES + textLength + val thumbnailOffset = stateOffset + stateLength + require(thumbnailOffset + thumbnailLength == input.length()) + require(width >= 0 && height >= 0 && pitch >= 0) + input.seek(stateOffset) + val digest = MessageDigest.getInstance("SHA-256") + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + var remaining = stateLength + while (remaining > 0L) { + val read = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt()) + require(read > 0) + digest.update(buffer, 0, read) + remaining -= read + } + val actualChecksum = digest.digest().joinToString("") { "%02x".format(it) } + require(actualChecksum == expectedChecksum) + input.seek(thumbnailOffset) + val thumbnail = ByteArray(thumbnailLength.toInt()) + input.readFully(thumbnail) + SaveSlotSummary(file, createdAt, width, height, pitch, pixelFormat, thumbnail) + } + }.getOrNull() +} diff --git a/app/src/main/java/org/neslite/app/settings/AppSettingsStore.kt b/app/src/main/java/org/neslite/app/settings/AppSettingsStore.kt new file mode 100644 index 0000000..eae691b --- /dev/null +++ b/app/src/main/java/org/neslite/app/settings/AppSettingsStore.kt @@ -0,0 +1,59 @@ +package org.neslite.app.settings + +import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.floatPreferencesKey +import androidx.datastore.preferences.preferencesDataStore +import kotlinx.coroutines.flow.first + +private val Context.appSettingsDataStore: DataStore by preferencesDataStore(name = "app_settings") + +data class AppSettings( + val integerScale: Boolean = false, + val linearFilter: Boolean = false, + val volume: Float = 1f, + val muted: Boolean = false, + val turboEnabled: Boolean = true, + val fastForwardEnabled: Boolean = true, + val guideCompleted: Boolean = false, +) + +class AppSettingsStore(private val context: Context) { + suspend fun load(): AppSettings { + val values = context.appSettingsDataStore.data.first() + return AppSettings( + integerScale = values[INTEGER_SCALE] ?: false, + linearFilter = values[LINEAR_FILTER] ?: false, + volume = (values[VOLUME] ?: 1f).coerceIn(0f, 1f), + muted = values[MUTED] ?: false, + turboEnabled = values[TURBO] ?: true, + fastForwardEnabled = values[FAST_FORWARD] ?: true, + guideCompleted = values[GUIDE_COMPLETED] ?: false, + ) + } + + suspend fun save(settings: AppSettings) { + context.appSettingsDataStore.edit { values -> + values[INTEGER_SCALE] = settings.integerScale + values[LINEAR_FILTER] = settings.linearFilter + values[VOLUME] = settings.volume.coerceIn(0f, 1f) + values[MUTED] = settings.muted + values[TURBO] = settings.turboEnabled + values[FAST_FORWARD] = settings.fastForwardEnabled + values[GUIDE_COMPLETED] = settings.guideCompleted + } + } + + companion object { + private val INTEGER_SCALE = booleanPreferencesKey("integer_scale") + private val LINEAR_FILTER = booleanPreferencesKey("linear_filter") + private val VOLUME = floatPreferencesKey("volume") + private val MUTED = booleanPreferencesKey("muted") + private val TURBO = booleanPreferencesKey("turbo_enabled") + private val FAST_FORWARD = booleanPreferencesKey("fast_forward_enabled") + private val GUIDE_COMPLETED = booleanPreferencesKey("guide_completed") + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a678401..3878bf5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,7 +1,7 @@ NESLite - NESLite 0.1.x 设备诊断 - 请使用 X5 Lite 原生安卓模式并关闭硬件连发。依次测试方向与 A/B 组合、全部松开、按住时拔出及重新连接;真实键码以页面和导出 JSON 为准。 + NESLite 0.6.x 日常使用版 + 可导入你合法持有的 NES ROM,使用手柄或屏幕虚拟键游玩。暂停后可安全保存、恢复和导入导出不含 ROM 的存档包;设备诊断保留在页面下方。 JNI 自检 手机与显示 已连接控制器 diff --git a/app/src/test/java/org/neslite/app/BuildIdentityTest.kt b/app/src/test/java/org/neslite/app/BuildIdentityTest.kt index 15e6a87..7f15670 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("0.5.4-debug", BuildConfig.VERSION_NAME) - assertEquals(5004, BuildConfig.VERSION_CODE) + assertEquals("0.6.4-debug", BuildConfig.VERSION_NAME) + assertEquals(6004, BuildConfig.VERSION_CODE) } } diff --git a/app/src/test/java/org/neslite/app/input/VirtualInputTrackerTest.kt b/app/src/test/java/org/neslite/app/input/VirtualInputTrackerTest.kt new file mode 100644 index 0000000..7b404d7 --- /dev/null +++ b/app/src/test/java/org/neslite/app/input/VirtualInputTrackerTest.kt @@ -0,0 +1,40 @@ +package org.neslite.app.input + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class VirtualInputTrackerTest { + @Test + fun slideReleasesOldActionBeforePressingNewOne() { + val tracker = VirtualInputTracker() + tracker.update(7, GameAction.LEFT) + assertEquals( + listOf( + VirtualInputTransition(7, GameAction.LEFT, false), + VirtualInputTransition(7, GameAction.UP, true), + ), + tracker.update(7, GameAction.UP), + ) + } + + @Test + fun cancelReleasesEveryPointerWithoutResidue() { + val tracker = VirtualInputTracker() + tracker.update(1, GameAction.RIGHT) + tracker.update(2, GameAction.NES_A) + assertEquals(2, tracker.clear().size) + assertTrue(tracker.clear().isEmpty()) + } + + @Test + fun touchAndControllerSourcesReleaseIndependently() { + val router = InputRouter() + val touch = InputSource(3, InputSourceKind.TOUCH, GameAction.NES_A.ordinal) + val controller = InputSource(9, InputSourceKind.KEY, 96) + router.update(touch, GameAction.NES_A, true) + router.update(controller, GameAction.NES_A, true) + assertTrue(router.update(touch, GameAction.NES_A, false).joypadMask and (1 shl 8) != 0) + assertEquals(0, router.update(controller, GameAction.NES_A, false).joypadMask and (1 shl 8)) + } +} diff --git a/app/src/test/java/org/neslite/app/save/SaveCatalogReaderTest.kt b/app/src/test/java/org/neslite/app/save/SaveCatalogReaderTest.kt new file mode 100644 index 0000000..06d4b58 --- /dev/null +++ b/app/src/test/java/org/neslite/app/save/SaveCatalogReaderTest.kt @@ -0,0 +1,56 @@ +package org.neslite.app.save + +import org.junit.Assert.assertNull +import org.junit.Assert.assertEquals +import org.junit.Assert.assertArrayEquals +import org.junit.Test +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.security.MessageDigest + +class SaveCatalogReaderTest { + @Test + fun rejectsUnknownAndTruncatedFiles() { + val file = File.createTempFile("neslite-slot", ".nls") + try { + file.writeBytes("not-a-save".toByteArray()) + assertNull(SaveCatalogReader.read(file)) + } finally { + file.delete() + } + } + + @Test + fun readsTimestampAndAssociatedRgb565Thumbnail() { + val bytes = ByteBuffer.allocate(132 + 64 + 1 + 4).order(ByteOrder.LITTLE_ENDIAN).apply { + put("NESLST01".toByteArray()) + putInt(1) + putInt(64) + putInt(0) + putInt(0) + putInt(0) + putInt(2) + putInt(1) + putInt(4) + putInt(2) + putLong(123456L) + putLong(1L) + putLong(4L) + put(MessageDigest.getInstance("SHA-256").digest(byteArrayOf(9)).joinToString("") { "%02x".format(it) }.toByteArray()) + put(ByteArray(64) { 'a'.code.toByte() }) + put(9) + put(byteArrayOf(1, 2, 3, 4)) + }.array() + val file = File.createTempFile("neslite-slot", ".nls") + try { + file.writeBytes(bytes) + val summary = requireNotNull(SaveCatalogReader.read(file)) + assertEquals(123456L, summary.createdAtEpochMs) + assertEquals(2, summary.width) + assertArrayEquals(byteArrayOf(1, 2, 3, 4), summary.thumbnail) + } finally { + file.delete() + } + } +} diff --git a/app/src/test/java/org/neslite/app/settings/AppSettingsTest.kt b/app/src/test/java/org/neslite/app/settings/AppSettingsTest.kt new file mode 100644 index 0000000..1f6ff99 --- /dev/null +++ b/app/src/test/java/org/neslite/app/settings/AppSettingsTest.kt @@ -0,0 +1,19 @@ +package org.neslite.app.settings + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class AppSettingsTest { + @Test + fun defaultsKeepCompatibilityAndControlsEnabled() { + val settings = AppSettings() + assertFalse(settings.integerScale) + assertFalse(settings.linearFilter) + assertEquals(1f, settings.volume) + assertTrue(settings.turboEnabled) + assertTrue(settings.fastForwardEnabled) + assertFalse(settings.guideCompleted) + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 1bcab92..479c33e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,4 +1,4 @@ -# NESLite 架构(M5 基线) +# NESLite 架构(M6 基线) ## 边界与线程 @@ -90,3 +90,13 @@ M4 输入层按物理来源维护状态,来源键包含本次设备 ID、按 读档只在暂停态核心线程进行并先持久保护当前状态和电池,失败回滚,双重失败安全重载或进入 Error。 活动会话标记只提示校验有效的异常恢复候选,不自动运行。SAF 存档包只允许电池、手动槽和自动槽, 不含 ROM;原生层在写入前完成路径、单项/总大小、格式、哈希、内核提交、配置和每项校验。 + +## M6 日常界面 + +Room v2 在 ROM 哈希主键之上保存收藏、隐藏和最近游玩;查询只展示未隐藏项并按收藏、最近、名称排序。 +隐藏不操作内部 ROM 或 `saves/`,导入器遇到相同哈希时恢复关联。显示/音频/输入偏好由独立 +DataStore 保存,渲染线程只读取整数缩放和过滤快照,音频及手柄继续复用原有命令和档案。 + +存档管理只解析 M5 已提交封装的边界元数据和缩略图,所有修改仍回到核心线程/统一提交器。虚拟手柄 +按 pointerId 维护触摸来源并送入与物理手柄相同的 `InputRouter`,因此多来源去重、相反方向和释放规则 +一致;取消、滑出、失焦与暂停清空所有虚拟来源。首次使用状态也存于设置 DataStore,不接触用户存档。 diff --git a/docs/build.md b/docs/build.md index 5a53444..e42dcc0 100644 --- a/docs/build.md +++ b/docs/build.md @@ -1,6 +1,6 @@ # NESLite 可复现构建说明 -本说明对应 M0~M4 基线。命令使用系统默认 PowerShell 7.6.6(`pwsh`)从仓库根目录执行;不需要手工复制 `.so`、 +本说明对应 M0~M6 基线。命令使用系统默认 PowerShell 7.6.6(`pwsh`)从仓库根目录执行;不需要手工复制 `.so`、 FCEUmm 或 Oboe 文件。 ## 前置条件 diff --git a/docs/identity.md b/docs/identity.md index fee040f..c646da0 100644 --- a/docs/identity.md +++ b/docs/identity.md @@ -6,7 +6,7 @@ | --- | --- | | 显示名称 | `NESLite` | | 正式 application ID/namespace | `org.neslite.app` | -| 当前开发版本 | `0.5.4`,`versionCode = 5004` | +| 当前开发版本 | `0.6.4`,`versionCode = 6004` | | 调试 application ID | `org.neslite.app.debug` | | 发布 ABI | `arm64-v8a` | | min/target SDK | 28/36 | diff --git a/docs/reports/m6-daily-ui.md b/docs/reports/m6-daily-ui.md new file mode 100644 index 0000000..59a0835 --- /dev/null +++ b/docs/reports/m6-daily-ui.md @@ -0,0 +1,33 @@ +# M6 日常使用界面记录 + +日期:2026-09-12 +构建目标:`org.neslite.app.debug`,`0.6.4-debug`,versionCode 6004,arm64-v8a + +## 已实现 + +- Room v2 持久化收藏、隐藏和最近游玩时间;支持名称/SHA-256 搜索并显示格式、大小、短哈希、导入 + 时间、最近游玩和缺失状态。移除只隐藏,重新导入同哈希恢复关联。 +- DataStore 统一保存 4:3/整数缩放、最近邻/线性过滤、音量、静音、软件连发和 RB 快进;设置页复用 + M3 音频及 M4 手柄档案、A/B 交换和死区状态源,并立即作用于当前会话。 +- 存档管理读取 M5 v1 封装,展示十个手动槽、三个按时间排序的自动点、提交时间和 RGB565 同帧 + 缩略图;保存、读取及 SAF 导入导出仍调用 M5 服务。 +- 页面覆盖库空/搜索空、存档空/加载、导入或原生失败、无手柄与中文长名称;保存反馈来自实际原生 + 提交完成事件。多点虚拟键与手柄使用同一 `InputRouter`,滑出、抬起、取消、失焦及暂停都会释放。 +- 首次引导说明导入、手柄测试、无手柄游玩、保存和退出。 + +## 自动验证 + +JVM 测试新增设置默认值、虚拟输入滑动先释放后按下、取消释放全部来源、触屏与手柄独立释放,以及 +存档目录读取器的有效缩略图往返和截断拒绝;既有输入、库导入、诊断和 M5 原生故障测试继续回归。 +`tools/check.ps1 -Scope Stage` 的 APK、Windows 原生测试和 JVM 29 项全部通过;Android lint 为 0 错误、 +42 个非阻断警告。调试 APK 为 22,227,235 字节,SHA-256 +`52F2F84B9BE98DC470A9588B48080BFF1D95C8C50A7C57B499D0EE1012EFF607`。 +`tools/check.ps1 -Scope Stage` 的 APK、Windows 原生测试和 JVM 28 项全部通过;Android lint 为 0 错误、 +42 个非阻断警告。调试 APK 为 16,019,404 字节,SHA-256 +`46C6A207E8D4AF0E7131FA24149B49958FF8E99872E26F4BCA4E49F2801614A5`。 + +## 待真机验收 + +用户当前不连接手机,且 G1~G5 尚未通过。中文长文件名混合库、Room v1 实际升级、设置重启、真实 +缩略图、SAF 文件提供器、纯触屏多点路线、首次清数据引导及全手柄/纯触屏完整主链尚未执行。 +因此 `todo.md` 的 M6 实现项和 G6 保持未勾选。 diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..ce05f4b --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,17 @@ +# NESLite 日常使用 + +1. 点“从文件导入”选择你合法持有的 `.nes` 文件。应用按完整 SHA-256 建库;同名不同内容独立, + 相同内容不会重复。可按名称/哈希搜索、收藏或从列表隐藏。隐藏不删除 ROM 和存档,重新导入相同 + 内容会恢复关联。 +2. 点游戏名称加载,状态为 Paused 后点“运行”。可使用标准 Android 手柄;没有手柄时使用画面下方的 + 多点虚拟方向、A/B、Start/Select 和暂停键。滑出或系统取消会释放对应按键。 +3. “显示、音频与输入设置”可切换 4:3/整数缩放、最近邻/线性过滤、音量、静音、软件连发和 RB + 快进,并进入手柄映射、A/B 交换和死区设置。设置会在重启后恢复。 +4. 游戏中点虚拟“暂停”或按手柄右摇杆进入暂停菜单。“存档管理”显示十个手动槽、三个自动恢复点、 + 提交时间和缩略图。只有原生层确认安全落盘后才显示保存成功。 +5. 存档包通过 Android 系统文件选择器导入导出,默认不含 ROM。导入前先加载对应游戏并暂停;哈希、 + 内核提交、配置、路径、大小或校验不匹配会被拒绝并保留现有有效存档。 +6. 用“退出游戏”正常结束。上次进程异常终止时,再次加载相同游戏只列出校验有效的自动恢复点, + 不会自动运行或覆盖当前进度。 + +当前尚未连接目标手机,真机手势、布局、文件提供器和完整触控流程仍需在 L2/G6 验收中确认。