feat: implement M6 daily use interface

This commit is contained in:
2026-09-12 14:27:42 +08:00
parent 8899219333
commit 73190bcb7b
27 changed files with 907 additions and 42 deletions
+18 -1
View File
@@ -13,6 +13,7 @@
#include <filesystem>
#include <fstream>
#include <iterator>
#include <limits>
#include <map>
#include <mutex>
#include <sstream>
@@ -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<std::int64_t>::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;
+4 -1
View File
@@ -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;
+4 -3
View File
@@ -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);
}
@@ -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)
}
+376 -19
View File
@@ -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<Int, SaveSlotSummary?>,
automatic: Map<Int, SaveSlotSummary?>,
) {
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
}
}
@@ -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)
}
@@ -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
}
}
@@ -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<Int, GameAction>()
fun update(pointerId: Int, action: GameAction?): List<VirtualInputTransition> {
val previous = active[pointerId]
if (previous == action) return emptyList()
val transitions = mutableListOf<VirtualInputTransition>()
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<VirtualInputTransition> {
val transitions = active.map { (pointerId, action) -> VirtualInputTransition(pointerId, action, false) }
active.clear()
return transitions
}
}
@@ -11,6 +11,10 @@ public interface GameDao {
@Query("SELECT * FROM games ORDER BY displayName COLLATE NOCASE, sha256")
List<GameEntity> 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<GameEntity> 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);
}
@@ -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");
}
};
}
@@ -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;
}
}
@@ -36,6 +36,9 @@ class LibraryRecovery(filesDir: File, private val dao: GameDao) {
file.name,
GameEntity.STATUS_READY,
System.currentTimeMillis(),
false,
false,
0L,
),
)
recoveredFiles++
@@ -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)
@@ -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()
}
@@ -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<Preferences> 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")
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
<resources>
<string name="app_name">NESLite</string>
<string name="diagnostics_title">NESLite 0.1.x 设备诊断</string>
<string name="diagnostics_instructions">请使用 X5 Lite 原生安卓模式并关闭硬件连发。依次测试方向与 A/B 组合、全部松开、按住时拔出及重新连接;真实键码以页面和导出 JSON 为准。</string>
<string name="diagnostics_title">NESLite 0.6.x 日常使用版</string>
<string name="diagnostics_instructions">可导入你合法持有的 NES ROM,使用手柄或屏幕虚拟键游玩。暂停后可安全保存、恢复和导入导出不含 ROM 的存档包;设备诊断保留在页面下方。</string>
<string name="section_native">JNI 自检</string>
<string name="section_device">手机与显示</string>
<string name="section_controllers">已连接控制器</string>
@@ -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)
}
}
@@ -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))
}
}
@@ -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()
}
}
}
@@ -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)
}
}