Initial commit: RomM Companion desktop v0.1.0
CI / frontend (push) Successful in 56s
CI / rust-check (push) Successful in 3m25s

This commit is contained in:
Seth Wade committed 2026-11-30 22:27:44 -05:00
commit 238a23c528
41 files changed
+17214

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run build
rust-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Linux Tauri system dependencies
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libgtk-3-dev
- uses: dtolnay/rust-toolchain@stable
- run: cargo test --manifest-path src-tauri/Cargo.toml
+15
View File
@@ -0,0 +1,15 @@
# Dependencies & build outputs
node_modules/
dist/
src-tauri/target/
src-tauri/gen/
# Local private notes
references.md
# OS & editor files
.DS_Store
Thumbs.db
*.log
.vscode/
.idea/
+49
View File
@@ -0,0 +1,49 @@
# RomM Companion
Cross-platform desktop companion app (macOS, Windows, Linux) built with **Tauri v2 (Rust + React/TypeScript)** for syncing save files, save states, and ROMs from standalone emulators with **RomM 5.1.0**.
## Features
- **RomM 5.1.0 Native Auth & Device Registration**
- Passwordless **Device Pairing** (`/api/auth/device/init` + `/api/auth/device/token`)
- **One-Time Pair Code** (`/api/client-tokens/exchange`) or raw API token
- **Username & Password** OAuth2 (`/api/token`)
- Automatic device registration (`/api/devices`)
- **Two-Way Save Sync & Backups**
- Uses RomM 5.1.0's `/api/sync/negotiate` protocol with stable save slots, SHA-256 content hashing, download confirmations (`/api/saves/{id}/downloaded`), and session completion (`/api/sync/sessions/{id}/complete`).
- Automatic timestamped local backups before any server save overwrites a local file or folder, with one-click restore in **Saves & States → Backups**.
- Interactive conflict resolution (**Keep Local** vs **Keep Server**) when both sides change independently.
- **Save States Sync**
- Syncs emulator save states via `/api/states`.
- **Cross-Platform Emulator Auto-Detection + Custom Rules**
- Built-in presets for **Dolphin** (GC/Wii), **PCSX2** (PS2), **RPCS3** (PS3), **Cemu** (Wii U), **DuckStation** (PS1), **PPSSPP** (PSP), **Ryujinx** (Switch), **Azahar / Citra** (3DS), **melonDS** (DS), **mGBA** (GB/GBC/GBA), **Flycast** (Dreamcast), **xemu** (Xbox), and **Xenia** (Xbox 360).
- Handles single-file saves, memory cards, and folder-per-game saves (deterministically zipped for RomM sync and safely extracted on download).
- Add custom emulator rules for any folder/extension layout.
- **ROM Library, Hash Matching & Downloads**
- Browse RomM platforms & ROMs and download directly to a local folder with live progress.
- Scan local ROM folders using streaming **CRC32 / MD5 / SHA1** lookup against `/api/roms/by-hash` with filename fallback.
- **Background File Watcher & System Tray**
- Debounced recursive file watcher triggers automatic sync when emulators write saves.
- System tray menu (*Open RomM Companion*, *Sync Saves Now*, *Quit*) with optional minimize-to-tray.
## Running in Development
Make sure Rust (`$HOME/.cargo/bin`) and Node.js are on your `PATH`:
```bash
export PATH="$HOME/.cargo/bin:$PATH"
npm install
npm run tauri dev
```
## Building Native Installers (macOS / Windows / Linux)
```bash
export PATH="$HOME/.cargo/bin:$PATH"
npm run tauri build
```
Tauri produces native installers in `src-tauri/target/release/bundle/`:
- **macOS**: `.dmg` / `.app`
- **Windows**: `.msi` / `.exe` (NSIS)
- **Linux**: `.AppImage` / `.deb` / `.rpm`
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>RomM Companion</title>
</head>
<body class="bg-slate-950 text-slate-100 antialiased selection:bg-indigo-500/30">
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
{"openapi":"3.1.0","info":{"title":"RomM API","version":"5.1.0"},"paths":{"/api/heartbeat":{"get":{"tags":["system"],"summary":"Heartbeat","description":"Endpoint to set the CSRF token in cache and return all the basic RomM config\n\nReturns:\n HeartbeatReturn: TypedDict structure with all the defined values in the HeartbeatReturn class.","operationId":"heartbeat_api_heartbeat_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HeartbeatResponse"}}}}}}},"/api/heartbeat/metadata/{source}":{"get":{"tags":["system"],"summary":"Metadata Heartbeat","description":"Endpoint to return the heartbeat of the metadata sources","operationId":"metadata_heartbeat_api_heartbeat_metadata__source__get","parameters":[{"name":"source","in":"path","required":true,"schema":{"type":"string","title":"Source"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"boolean","title":"Response Metadata Heartbeat Api Heartbeat Metadata Source Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/api/setup/library":{"get":{"tags":["system"],"summary":"Get Setup Library Info","description":"Get library structure information for setup wizard.\n\nOnly accessible during initial setup (no admin users) or with authentication.\n\nReturns:\n - detected_structure: \"struct_a\" (roms/{platform}), \"struct_b\" ({platform}/roms), or None\n - existing_platforms: list of objects with fs_slug and rom_count\n - supported_platforms: list of all supported platforms with metadata","operationId":"get_setup_library_info_api_setup_library_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"OAuth2PasswordBearer":[]},{"HTTPBasic":[]}]}},"/api/setup/platforms":{"post":{"tags":["system"],"summary":"Create Setup Platforms","description":"Create platform folders during setup wizard.\n\nOnly accessible during initial setup (no admin users) or with authentication.\n\nArgs:\n platform_slugs: List of platform fs_slugs to create\n\nReturns:\n - success: bool\n - created_count: number of platforms created\n - message: success or error message","operationId":"create_setup_platforms_api_setup_platforms_post","requestBody":{"content":{"application/json":{"schema":{"items":{"type":"string"},"type":"array","title":"Platform Slugs"}}},"required":true},"responses":{"201":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"OAuth2PasswordBearer":[]},{"HTTPBasic":[]}]}},"/api/login":{"post":{"tags":["auth"],"summary":"Login","description":"Session login endpoint\n\nArgs:\n request (Request): Fastapi Request object\n credentials: Defaults to Depends(HTTPBasic()).\n\nRaises:\n CredentialsException: Invalid credentials\n UserDisabledException: Auth is disabled","operationId":"login_api_login_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"HTTPBasic":[]}]}},"/api/logout":{"post":{"tags":["auth"],"summary":"Logout","description":"Session logout endpoint\n\nArgs:\n request (Request): Fastapi Request object\n\nReturns:\n Optional[dict]: When OIDC RP-Initiated Logout is enabled and the session\n contains an OIDC id_token, returns a dict with the OIDC end-session URL\n so the client can redirect the browser to log out of the OIDC provider.","operationId":"logout_api_logout_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/OIDCLogoutResponse"},{"type":"null"}],"title":"Response Logout Api Logout Post"}}}}}}},"/api/token":{"post":{"tags":["auth"],"summary":"Token","description":"OAuth2 token endpoint\n\nArgs:\n form_data (Annotated[OAuth2RequestForm, Depends): Form Data with OAuth2 info\n\nRaises:\n HTTPException: Missing refresh token\n HTTPException: Invalid refresh token\n HTTPException: Missing username or password\n HTTPException: Invalid username or password\n HTTPException: Client credentials are not yet supported\n HTTPException: Invalid or unsupported grant type\n HTTPException: Insufficient scope\n\nReturns:\n TokenResponse: TypedDict with the new generated token info","operationId":"token_api_token_post","requestBody":{"content":{"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/Body_token_api_token_post"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TokenResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/compoLine truncated
+2778
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "romm-companion",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"@tauri-apps/api": "^2.5.0",
"@tauri-apps/plugin-dialog": "^2.2.1",
"@tauri-apps/plugin-opener": "^2.2.6",
"lucide-react": "^0.511.0",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.7",
"@tauri-apps/cli": "^2.5.0",
"@types/react": "^19.1.4",
"@types/react-dom": "^19.1.4",
"@vitejs/plugin-react": "^4.7.0",
"tailwindcss": "^4.1.7",
"typescript": "^5.8.3",
"vite": "^6.3.5"
}
}
+5800
View File
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
[package]
name = "romm-companion"
version = "0.1.0"
description = "Cross-platform RomM 5.1.0 companion for save/state sync, ROM matching, and emulator detection"
authors = ["RomM Companion"]
edition = "2021"
[lib]
name = "romm_companion_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = ["tray-icon", "image-png"] }
tauri-plugin-dialog = "2"
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "stream", "rustls-tls"] }
chrono = { version = "0.4", features = ["serde"] }
directories = "6"
walkdir = "2"
notify = "8"
notify-debouncer-mini = "0.6"
sha2 = "0.10"
sha1 = "0.10"
md-5 = "0.10"
crc32fast = "1"
hex = "0.4"
uuid = { version = "1", features = ["v4"] }
hostname = "0.4"
thiserror = "2"
futures-util = "0.3"
zip = { version = "2", default-features = false, features = ["deflate"] }
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
+11
View File
@@ -0,0 +1,11 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"dialog:default",
"opener:default"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 507 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 529 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

File diff suppressed because it is too large. Load diff
+197
View File
@@ -0,0 +1,197 @@
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionConfig {
pub server_url: String,
pub access_token: Option<String>,
pub refresh_token: Option<String>,
pub username: Option<String>,
pub device_id: Option<String>,
pub device_name: String,
pub client_device_identifier: String,
}
impl Default for ConnectionConfig {
fn default() -> Self {
let host = hostname::get()
.ok()
.and_then(|h| h.into_string().ok())
.unwrap_or_else(|| "My Computer".to_string());
Self {
server_url: String::new(),
access_token: None,
refresh_token: None,
username: None,
device_id: None,
device_name: format!("{} (RomM Companion)", host),
client_device_identifier: Uuid::new_v4().to_string(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SaveStructure {
/// Individual save files named after the ROM (e.g. `Game (USA).sav`, `Game.mcr`)
FilePerGame,
/// Directory per game (e.g. RPCS3, Ryujinx, Cemu, Azahar, PPSSPP) — zipped as a single archive for RomM sync
FolderPerGame,
/// Shared memory card / system file (e.g. PCSX2 Mcd001.ps2, Dolphin MemoryCardA.USA.raw)
MemoryCard,
}
fn default_folder_depth() -> usize {
1
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EmulatorRule {
pub id: String,
pub name: String,
pub platform_slugs: Vec<String>,
pub save_dir: String,
pub state_dir: Option<String>,
pub rom_dir: Option<String>,
pub save_extensions: Vec<String>,
pub state_extensions: Vec<String>,
pub structure: SaveStructure,
#[serde(default = "default_folder_depth")]
pub folder_depth: usize,
pub enabled: bool,
pub is_custom: bool,
pub sync_states: bool,
/// Optional default slot name sent to RomM `/api/sync/negotiate`
pub default_slot: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ManualLink {
pub local_path: String,
pub rom_id: i64,
pub rom_name: String,
pub emulator_id: String,
pub slot: String,
pub is_state: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WatcherSettings {
pub enabled: bool,
pub debounce_seconds: u64,
pub auto_sync_on_change: bool,
pub max_backups_per_save: usize,
pub minimize_to_tray: bool,
pub default_rom_download_dir: Option<String>,
}
impl Default for WatcherSettings {
fn default() -> Self {
Self {
enabled: true,
debounce_seconds: 5,
auto_sync_on_change: true,
max_backups_per_save: 10,
minimize_to_tray: true,
default_rom_download_dir: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncLogEntry {
pub id: String,
pub timestamp: String,
pub level: String, // "info" | "success" | "warning" | "error"
pub action: String,
pub message: String,
pub rom_id: Option<i64>,
pub file_path: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct AppConfig {
pub connection: ConnectionConfig,
pub emulators: Vec<EmulatorRule>,
pub manual_links: HashMap<String, ManualLink>,
pub settings: WatcherSettings,
/// Tracks last-known local content hash per canonical path for state/save change detection
pub synced_state_hashes: HashMap<String, String>,
pub sync_logs: Vec<SyncLogEntry>,
}
pub fn app_data_dir() -> PathBuf {
if let Some(proj) = ProjectDirs::from("com", "romm", "RomMCompanion") {
let dir = proj.data_local_dir().to_path_buf();
let _ = fs::create_dir_all(&dir);
dir
} else {
let dir = PathBuf::from(".romm-companion");
let _ = fs::create_dir_all(&dir);
dir
}
}
pub fn backups_dir() -> PathBuf {
let dir = app_data_dir().join("backups");
let _ = fs::create_dir_all(&dir);
dir
}
pub fn config_file_path() -> PathBuf {
app_data_dir().join("config.json")
}
pub fn load_config() -> AppConfig {
let path = config_file_path();
if let Ok(raw) = fs::read_to_string(&path) {
if let Ok(cfg) = serde_json::from_str::<AppConfig>(&raw) {
return cfg;
}
}
AppConfig::default()
}
pub fn save_config(cfg: &AppConfig) -> Result<(), String> {
let path = config_file_path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let json = serde_json::to_string_pretty(cfg).map_err(|e| e.to_string())?;
fs::write(&path, json).map_err(|e| e.to_string())
}
pub fn push_log(
cfg: &mut AppConfig,
level: &str,
action: &str,
message: impl Into<String>,
rom_id: Option<i64>,
file_path: Option<String>,
) {
cfg.sync_logs.insert(
0,
SyncLogEntry {
id: Uuid::new_v4().to_string(),
timestamp: chrono::Utc::now().to_rfc3339(),
level: level.to_string(),
action: action.to_string(),
message: message.into(),
rom_id,
file_path,
},
);
if cfg.sync_logs.len() > 250 {
cfg.sync_logs.truncate(250);
}
}
+433
View File
@@ -0,0 +1,433 @@
use crate::config::{EmulatorRule, SaveStructure};
use directories::BaseDirs;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EmulatorPresetInfo {
pub id: String,
pub name: String,
pub category: String, // "console" | "handheld"
pub platform_slugs: Vec<String>,
pub detected: bool,
pub detected_save_dir: Option<String>,
pub detected_state_dir: Option<String>,
pub default_save_dir: String,
pub default_state_dir: Option<String>,
pub save_extensions: Vec<String>,
pub state_extensions: Vec<String>,
pub structure: SaveStructure,
pub folder_depth: usize,
pub notes: String,
}
fn home_dir() -> PathBuf {
BaseDirs::new()
.map(|b| b.home_dir().to_path_buf())
.unwrap_or_else(|| PathBuf::from("."))
}
fn config_dir() -> PathBuf {
BaseDirs::new()
.map(|b| b.config_dir().to_path_buf())
.unwrap_or_else(home_dir)
}
fn data_dir() -> PathBuf {
BaseDirs::new()
.map(|b| b.data_dir().to_path_buf())
.unwrap_or_else(home_dir)
}
fn data_local_dir() -> PathBuf {
BaseDirs::new()
.map(|b| b.data_local_dir().to_path_buf())
.unwrap_or_else(home_dir)
}
fn first_existing(candidates: &[PathBuf]) -> Option<PathBuf> {
candidates.iter().find(|p| p.exists()).cloned()
}
fn path_to_string(p: &Path) -> String {
p.to_string_lossy().to_string()
}
struct PresetDef {
id: &'static str,
name: &'static str,
category: &'static str,
platform_slugs: Vec<&'static str>,
save_candidates: Vec<PathBuf>,
state_candidates: Vec<PathBuf>,
save_extensions: Vec<&'static str>,
state_extensions: Vec<&'static str>,
structure: SaveStructure,
folder_depth: usize,
notes: &'static str,
}
fn build_preset_defs() -> Vec<PresetDef> {
let home = home_dir();
let cfg = config_dir();
let data = data_dir();
let local = data_local_dir();
#[cfg(target_os = "macos")]
let app_support = home.join("Library/Application Support");
#[cfg(not(target_os = "macos"))]
let app_support = data.clone();
let docs = home.join("Documents");
vec![
// ---------- Standalone Console Emulators ----------
PresetDef {
id: "dolphin",
name: "Dolphin (GameCube / Wii)",
category: "console",
platform_slugs: vec!["ngc", "gc", "gamecube", "wii"],
save_candidates: vec![
app_support.join("Dolphin/GC"),
docs.join("Dolphin Emulator/GC"),
data.join("dolphin-emu/GC"),
home.join(".local/share/dolphin-emu/GC"),
home.join(".var/app/org.DolphinEmu.dolphin-emu/data/dolphin-emu/GC"),
],
state_candidates: vec![
app_support.join("Dolphin/StateSaves"),
docs.join("Dolphin Emulator/StateSaves"),
data.join("dolphin-emu/StateSaves"),
home.join(".local/share/dolphin-emu/StateSaves"),
home.join(".var/app/org.DolphinEmu.dolphin-emu/data/dolphin-emu/StateSaves"),
],
save_extensions: vec!["gci", "raw", "sav", "bin"],
state_extensions: vec!["s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", "sav"],
structure: SaveStructure::FilePerGame,
folder_depth: 1,
notes: "Supports GCI Folder mode (recommended for per-game matching) and raw memory cards.",
},
PresetDef {
id: "pcsx2",
name: "PCSX2 (PlayStation 2)",
category: "console",
platform_slugs: vec!["ps2"],
save_candidates: vec![
app_support.join("PCSX2/memcards"),
docs.join("PCSX2/memcards"),
cfg.join("PCSX2/memcards"),
home.join(".config/PCSX2/memcards"),
home.join(".var/app/net.pcsx2.PCSX2/config/PCSX2/memcards"),
],
state_candidates: vec![
app_support.join("PCSX2/sstates"),
docs.join("PCSX2/sstates"),
cfg.join("PCSX2/sstates"),
home.join(".config/PCSX2/sstates"),
home.join(".var/app/net.pcsx2.PCSX2/config/PCSX2/sstates"),
],
save_extensions: vec!["ps2", "mcd"],
state_extensions: vec!["p2s"],
structure: SaveStructure::MemoryCard,
folder_depth: 1,
notes: "Tip: Enable Folder Memory Cards in PCSX2 or link individual .ps2 cards to ROMs.",
},
PresetDef {
id: "rpcs3",
name: "RPCS3 (PlayStation 3)",
category: "console",
platform_slugs: vec!["ps3"],
save_candidates: vec![
app_support.join("rpcs3/dev_hdd0/home/00000001/savedata"),
cfg.join("rpcs3/dev_hdd0/home/00000001/savedata"),
home.join(".config/rpcs3/dev_hdd0/home/00000001/savedata"),
home.join(".var/app/net.rpcs3.RPCS3/config/rpcs3/dev_hdd0/home/00000001/savedata"),
],
state_candidates: vec![
app_support.join("rpcs3/savestates"),
cfg.join("rpcs3/savestates"),
home.join(".config/rpcs3/savestates"),
home.join(".var/app/net.rpcs3.RPCS3/config/rpcs3/savestates"),
],
save_extensions: vec![],
state_extensions: vec!["sav"],
structure: SaveStructure::FolderPerGame,
folder_depth: 1,
notes: "Each PS3 title stores a folder inside savedata; zipped automatically for RomM sync.",
},
PresetDef {
id: "cemu",
name: "Cemu (Wii U)",
category: "console",
platform_slugs: vec!["wiiu"],
save_candidates: vec![
app_support.join("Cemu/mlc01/usr/save"),
data.join("Cemu/mlc01/usr/save"),
local.join("Cemu/mlc01/usr/save"),
home.join(".local/share/Cemu/mlc01/usr/save"),
home.join(".var/app/info.cemu.Cemu/data/Cemu/mlc01/usr/save"),
],
state_candidates: vec![],
save_extensions: vec![],
state_extensions: vec![],
structure: SaveStructure::FolderPerGame,
folder_depth: 2,
notes: "Wii U title save directories inside mlc01/usr/save/<high>/<low> (depth 2) are zipped per title for RomM.",
},
PresetDef {
id: "duckstation",
name: "DuckStation (PlayStation)",
category: "console",
platform_slugs: vec!["psx", "ps1", "ps"],
save_candidates: vec![
app_support.join("DuckStation/memcards"),
docs.join("DuckStation/memcards"),
data.join("duckstation/memcards"),
home.join(".local/share/duckstation/memcards"),
home.join(".var/app/org.duckstation.DuckStation/data/duckstation/memcards"),
],
state_candidates: vec![
app_support.join("DuckStation/savestates"),
docs.join("DuckStation/savestates"),
data.join("duckstation/savestates"),
home.join(".local/share/duckstation/savestates"),
home.join(".var/app/org.duckstation.DuckStation/data/duckstation/savestates"),
],
save_extensions: vec!["mcd", "mcr", "srm"],
state_extensions: vec!["sav"],
structure: SaveStructure::FilePerGame,
folder_depth: 1,
notes: "Works best with 'Separate Card Per Game (Title)' enabled in DuckStation.",
},
PresetDef {
id: "ppsspp",
name: "PPSSPP (PSP)",
category: "console",
platform_slugs: vec!["psp"],
save_candidates: vec![
cfg.join("ppsspp/PSP/SAVEDATA"),
home.join(".config/ppsspp/PSP/SAVEDATA"),
docs.join("PPSSPP/PSP/SAVEDATA"),
home.join(".var/app/org.ppsspp.PPSSPP/config/ppsspp/PSP/SAVEDATA"),
],
state_candidates: vec![
cfg.join("ppsspp/PSP/PPSSPP_STATE"),
home.join(".config/ppsspp/PSP/PPSSPP_STATE"),
docs.join("PPSSPP/PSP/PPSSPP_STATE"),
home.join(".var/app/org.ppsspp.PPSSPP/config/ppsspp/PSP/PPSSPP_STATE"),
],
save_extensions: vec![],
state_extensions: vec!["ppst"],
structure: SaveStructure::FolderPerGame,
folder_depth: 1,
notes: "PSP savedata folders are zipped per game; PPSSPP_STATE .ppst files sync as save states.",
},
PresetDef {
id: "ryujinx",
name: "Ryujinx (Nintendo Switch)",
category: "console",
platform_slugs: vec!["switch", "ns", "nintendo-switch"],
save_candidates: vec![
app_support.join("Ryujinx/bis/user/save"),
cfg.join("Ryujinx/bis/user/save"),
data.join("Ryujinx/bis/user/save"),
home.join(".config/Ryujinx/bis/user/save"),
],
state_candidates: vec![],
save_extensions: vec![],
state_extensions: vec![],
structure: SaveStructure::FolderPerGame,
folder_depth: 1,
notes: "Switch save folders under bis/user/save are archived per title; link Title IDs in Saves view.",
},
PresetDef {
id: "azahar",
name: "Azahar / Citra (Nintendo 3DS)",
category: "console",
platform_slugs: vec!["3ds", "n3ds"],
save_candidates: vec![
app_support.join("Azahar/sdmc/Nintendo 3DS"),
app_support.join("Citra/sdmc/Nintendo 3DS"),
data.join("azahar-emu/sdmc/Nintendo 3DS"),
data.join("citra-emu/sdmc/Nintendo 3DS"),
home.join(".local/share/azahar-emu/sdmc/Nintendo 3DS"),
home.join(".local/share/citra-emu/sdmc/Nintendo 3DS"),
],
state_candidates: vec![
app_support.join("Azahar/states"),
app_support.join("Citra/states"),
data.join("azahar-emu/states"),
data.join("citra-emu/states"),
home.join(".local/share/azahar-emu/states"),
],
save_extensions: vec!["sav", "dat"],
state_extensions: vec!["cst"],
structure: SaveStructure::FolderPerGame,
folder_depth: 5,
notes: "Detects both Azahar and legacy Citra 3DS directories (depth 5 reaches <id0>/<id1>/title/<high>/<low>).",
},
// ---------- Handheld & PC-Adjacent Emulators ----------
PresetDef {
id: "melonds",
name: "melonDS (Nintendo DS / DSi)",
category: "handheld",
platform_slugs: vec!["nds", "ds", "dsi"],
save_candidates: vec![
app_support.join("melonDS"),
cfg.join("melonDS"),
home.join(".config/melonDS"),
home.join(".var/app/net.kuribo64.melonDS/config/melonDS"),
],
state_candidates: vec![
app_support.join("melonDS"),
cfg.join("melonDS"),
home.join(".config/melonDS"),
],
save_extensions: vec!["sav", "dsv"],
state_extensions: vec!["ml0", "ml1", "ml2", "ml3", "ml4", "ml5", "ml6", "ml7", "ml8", "mln"],
structure: SaveStructure::FilePerGame,
folder_depth: 1,
notes: "Point to your melonDS saves folder (or ROM folder if saves live alongside .nds files).",
},
PresetDef {
id: "mgba",
name: "mGBA (GB / GBC / GBA)",
category: "handheld",
platform_slugs: vec!["gba", "gbc", "gb"],
save_candidates: vec![
app_support.join("mGBA"),
cfg.join("mgba"),
home.join(".config/mgba"),
home.join(".var/app/io.mgba.mGBA/config/mgba"),
],
state_candidates: vec![
app_support.join("mGBA"),
cfg.join("mgba"),
home.join(".config/mgba"),
],
save_extensions: vec!["sav", "srm"],
state_extensions: vec!["ss0", "ss1", "ss2", "ss3", "ss4", "ss5", "ss6", "ss7", "ss8", "ss9"],
structure: SaveStructure::FilePerGame,
folder_depth: 1,
notes: "Matches .sav/.srm files by ROM name; set save directory to your mGBA save/ROM path.",
},
PresetDef {
id: "flycast",
name: "Flycast (Dreamcast / Naomi)",
category: "handheld",
platform_slugs: vec!["dc", "dreamcast", "naomi"],
save_candidates: vec![
app_support.join("Flycast/data"),
data.join("flycast/data"),
home.join(".local/share/flycast/data"),
home.join(".var/app/org.flycast.Flycast/data/flycast/data"),
],
state_candidates: vec![
app_support.join("Flycast/data"),
data.join("flycast/data"),
home.join(".local/share/flycast/data"),
],
save_extensions: vec!["bin", "vmu"],
state_extensions: vec!["state", "state1", "state2", "state3"],
structure: SaveStructure::FilePerGame,
folder_depth: 1,
notes: "Enable 'Per-Game VMUs' in Flycast for automatic per-game ROM matching.",
},
PresetDef {
id: "xemu",
name: "xemu (Original Xbox)",
category: "handheld",
platform_slugs: vec!["xbox"],
save_candidates: vec![
app_support.join("xemu/xemu"),
data.join("xemu/xemu"),
home.join(".local/share/xemu/xemu"),
home.join(".var/app/app.xemu.xemu/data/xemu/xemu"),
],
state_candidates: vec![],
save_extensions: vec!["qcow2", "bin", "sav"],
state_extensions: vec![],
structure: SaveStructure::MemoryCard,
folder_depth: 1,
notes: "Tracks xemu memory unit / extracted save folders.",
},
PresetDef {
id: "xenia",
name: "Xenia (Xbox 360)",
category: "handheld",
platform_slugs: vec!["xbox360", "x360"],
save_candidates: vec![
docs.join("Xenia/content"),
local.join("Xenia/content"),
data.join("xenia/content"),
],
state_candidates: vec![],
save_extensions: vec![],
state_extensions: vec![],
structure: SaveStructure::FolderPerGame,
folder_depth: 1,
notes: "Xbox 360 title save folders under Xenia/content are archived per game.",
},
]
}
pub fn detect_emulator_presets() -> Vec<EmulatorPresetInfo> {
build_preset_defs()
.into_iter()
.map(|d| {
let detected_save = first_existing(&d.save_candidates);
let detected_state = first_existing(&d.state_candidates);
let default_save = detected_save
.as_ref()
.or_else(|| d.save_candidates.first())
.map(|p| path_to_string(p))
.unwrap_or_default();
let default_state = detected_state
.as_ref()
.or_else(|| d.state_candidates.first())
.map(|p| path_to_string(p));
EmulatorPresetInfo {
id: d.id.to_string(),
name: d.name.to_string(),
category: d.category.to_string(),
platform_slugs: d.platform_slugs.into_iter().map(String::from).collect(),
detected: detected_save.is_some(),
detected_save_dir: detected_save.map(|p| path_to_string(&p)),
detected_state_dir: detected_state.map(|p| path_to_string(&p)),
default_save_dir: default_save,
default_state_dir: default_state,
save_extensions: d.save_extensions.into_iter().map(String::from).collect(),
state_extensions: d.state_extensions.into_iter().map(String::from).collect(),
structure: d.structure,
folder_depth: d.folder_depth,
notes: d.notes.to_string(),
}
})
.collect()
}
pub fn preset_to_rule(preset: &EmulatorPresetInfo) -> EmulatorRule {
EmulatorRule {
id: preset.id.clone(),
name: preset.name.clone(),
platform_slugs: preset.platform_slugs.clone(),
save_dir: preset
.detected_save_dir
.clone()
.unwrap_or_else(|| preset.default_save_dir.clone()),
state_dir: preset
.detected_state_dir
.clone()
.or_else(|| preset.default_state_dir.clone()),
rom_dir: None,
save_extensions: preset.save_extensions.clone(),
state_extensions: preset.state_extensions.clone(),
structure: preset.structure.clone(),
folder_depth: preset.folder_depth,
enabled: preset.detected,
is_custom: false,
sync_states: preset.default_state_dir.is_some(),
default_slot: "default".to_string(),
}
}
+134
View File
@@ -0,0 +1,134 @@
mod commands;
mod config;
mod emulators;
mod matcher;
mod nextui_sd;
mod romm_api;
mod sync_engine;
mod watcher;
use commands::{refresh_watcher_internal, AppState};
use config::load_config;
use std::sync::Mutex;
use tauri::menu::{Menu, MenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
use tauri::{Emitter, Manager, WindowEvent};
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let cfg = load_config();
let app_state = AppState {
config: Mutex::new(cfg),
rom_cache: Mutex::new(Vec::new()),
conflicts: Mutex::new(Vec::new()),
watcher: Mutex::new(None),
};
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.manage(app_state)
.setup(|app| {
// Start background file watcher if enabled
let state = app.state::<AppState>();
let _ = refresh_watcher_internal(app.handle().clone(), &state);
// Build cross-platform system tray menu
let show_item = MenuItem::with_id(app, "show", "Open RomM Companion", true, None::<&str>)?;
let sync_item = MenuItem::with_id(app, "sync", "Sync Saves Now", true, None::<&str>)?;
let quit_item = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&show_item, &sync_item, &quit_item])?;
let mut tray_builder = TrayIconBuilder::with_id("main-tray")
.menu(&menu)
.tooltip("RomM Companion — Save Sync");
if let Some(icon) = app.default_window_icon() {
tray_builder = tray_builder.icon(icon.clone());
}
tray_builder
.on_menu_event(|app, event| match event.id.as_ref() {
"show" => {
if let Some(win) = app.get_webview_window("main") {
let _ = win.show();
let _ = win.set_focus();
}
}
"sync" => {
let _ = app.emit("tray:sync-now", ());
}
"quit" => {
app.exit(0);
}
_ => {}
})
.on_tray_icon_event(|tray, event| {
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = event
{
let app = tray.app_handle();
if let Some(win) = app.get_webview_window("main") {
let _ = win.show();
let _ = win.set_focus();
}
}
})
.build(app)?;
Ok(())
})
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
let state = window.state::<AppState>();
let minimize = state.config.lock().unwrap().settings.minimize_to_tray;
if minimize {
let _ = window.hide();
api.prevent_close();
}
}
})
.invoke_handler(tauri::generate_handler![
commands::get_app_state,
commands::test_server,
commands::start_device_auth,
commands::poll_device_auth,
commands::exchange_pair_code,
commands::connect_with_token,
commands::login_with_password,
commands::disconnect,
commands::get_emulator_presets,
commands::auto_populate_detected_emulators,
commands::upsert_emulator_rule,
commands::delete_emulator_rule,
commands::fetch_platforms,
commands::fetch_roms,
commands::refresh_rom_cache,
commands::scan_local_rom_folder,
commands::download_rom_to_folder,
commands::download_single_save,
commands::download_single_state,
commands::upload_single_save,
commands::discover_local_saves,
commands::link_save_to_rom,
commands::unlink_save,
commands::fetch_remote_saves_and_states,
commands::run_full_sync,
commands::resolve_sync_conflict,
commands::list_backups,
commands::restore_backup,
commands::save_settings,
commands::clear_sync_logs,
commands::restart_watcher,
commands::detect_nextui_volumes,
commands::inspect_nextui_card,
commands::rename_nextui_handheld,
commands::sync_nextui_card,
commands::download_rom_to_nextui,
])
.run(tauri::generate_context!())
.expect("error while running RomM Companion");
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
romm_companion_lib::run()
}
+568
View File
@@ -0,0 +1,568 @@
use crate::config::{EmulatorRule, ManualLink, SaveStructure};
use crate::romm_api::SimpleRomSchema;
use chrono::{DateTime, Utc};
use crc32fast::Hasher as Crc32Hasher;
use md5::{Digest as Md5Digest, Md5};
use serde::{Deserialize, Serialize};
use sha1::Sha1;
use sha2::Sha256;
use std::collections::{HashMap, HashSet};
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use zip::write::SimpleFileOptions;
use zip::ZipWriter;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiscoveredSaveItem {
pub local_path: String,
pub file_name: String,
pub emulator_id: String,
pub emulator_name: String,
pub is_directory: bool,
pub is_state: bool,
pub size_bytes: u64,
pub updated_at: String,
pub slot: String,
pub matched_rom_id: Option<i64>,
pub matched_rom_name: Option<String>,
pub matched_platform: Option<String>,
pub match_confidence: f32,
pub match_source: String, // "manual" | "exact" | "fuzzy" | "unmatched"
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LocalRomScanResult {
pub local_path: String,
pub file_name: String,
pub size_bytes: u64,
pub crc32: Option<String>,
pub md5: Option<String>,
pub sha1: Option<String>,
pub matched_rom_id: Option<i64>,
pub matched_rom_name: Option<String>,
pub matched_platform: Option<String>,
pub match_source: String, // "hash" | "filename" | "unmatched"
}
/// Strips parenthesized/bracketed ROM tags like `(USA)`, `(Rev 1)`, `[!]` and normalizes for matching.
pub fn normalize_title(input: &str) -> String {
let mut cleaned = String::with_capacity(input.len());
let mut paren_depth = 0usize;
let mut bracket_depth = 0usize;
for ch in input.chars() {
match ch {
'(' => paren_depth += 1,
')' => paren_depth = paren_depth.saturating_sub(1),
'[' => bracket_depth += 1,
']' => bracket_depth = bracket_depth.saturating_sub(1),
_ if paren_depth == 0 && bracket_depth == 0 => {
if ch.is_alphanumeric() {
for lc in ch.to_lowercase() {
cleaned.push(lc);
}
} else {
cleaned.push(' ');
}
}
_ => {}
}
}
cleaned
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
fn tokenize(norm: &str) -> HashSet<String> {
norm.split_whitespace()
.filter(|t| t.len() >= 2)
.map(|s| s.to_string())
.collect()
}
pub fn similarity_score(a: &str, b: &str) -> f32 {
let na = normalize_title(a);
let nb = normalize_title(b);
if na.is_empty() || nb.is_empty() {
return 0.0;
}
if na == nb {
return 1.0;
}
if na.contains(&nb) || nb.contains(&na) {
let min_len = na.len().min(nb.len()) as f32;
let max_len = na.len().max(nb.len()) as f32;
if min_len >= 4.0 {
return 0.78 + 0.18 * (min_len / max_len);
}
}
let ta = tokenize(&na);
let tb = tokenize(&nb);
if ta.is_empty() || tb.is_empty() {
return 0.0;
}
let inter = ta.intersection(&tb).count() as f32;
let union = ta.union(&tb).count() as f32;
inter / union
}
pub fn match_name_to_roms<'a>(
candidate_stem: &str,
platform_slugs: &[String],
roms: &'a [SimpleRomSchema],
) -> Option<(&'a SimpleRomSchema, f32, &'static str)> {
let cand_lower = candidate_stem.trim().to_lowercase();
let cand_norm = normalize_title(candidate_stem);
if cand_norm.is_empty() && cand_lower.is_empty() {
return None;
}
let mut best: Option<(&SimpleRomSchema, f32, &'static str)> = None;
for rom in roms {
let platform_bonus: f32 = if platform_slugs.is_empty() {
0.0
} else {
let p_slug = rom.platform_slug.to_lowercase();
let p_fs = rom.platform_fs_slug.to_lowercase();
if platform_slugs
.iter()
.any(|s| s.eq_ignore_ascii_case(&p_slug) || s.eq_ignore_ascii_case(&p_fs))
{
0.08
} else {
-0.12
}
};
// 1. Exact stem match on fs_name_no_ext or fs_name_no_tags
if rom.fs_name_no_ext.to_lowercase() == cand_lower
|| rom.fs_name_no_tags.to_lowercase() == cand_lower
{
let score = (1.0 + platform_bonus).min(1.0);
if best.map_or(true, |(_, bs, _)| score > bs) {
best = Some((rom, score, "exact"));
}
continue;
}
// 2. Fuzzy similarity against fs_name_no_tags and display name
let mut sim = similarity_score(candidate_stem, &rom.fs_name_no_tags);
if let Some(ref name) = rom.name {
sim = sim.max(similarity_score(candidate_stem, name));
}
let adjusted = (sim + platform_bonus).clamp(0.0, 1.0);
if sim >= 0.55 && best.map_or(true, |(_, bs, _)| adjusted > bs) {
let src = if sim >= 0.99 { "exact" } else { "fuzzy" };
best = Some((rom, adjusted, src));
}
}
best
}
pub fn discover_saves_for_emulators(
emulators: &[EmulatorRule],
roms: &[SimpleRomSchema],
manual_links: &HashMap<String, ManualLink>,
) -> Vec<DiscoveredSaveItem> {
let mut results = Vec::new();
for emu in emulators.iter().filter(|e| e.enabled) {
// 1. Regular saves
let save_root = Path::new(&emu.save_dir);
if save_root.exists() {
match emu.structure {
SaveStructure::FolderPerGame => {
let depth = emu.folder_depth.max(1);
for entry in WalkDir::new(save_root)
.min_depth(depth)
.max_depth(depth)
.into_iter()
.flatten()
{
let path = entry.path();
if !path.is_dir() {
continue;
}
let leaf_name = entry.file_name().to_string_lossy().to_string();
if leaf_name.starts_with('.') {
continue;
}
let archive_base = if depth > 1 {
path.strip_prefix(save_root)
.ok()
.map(|rel| {
rel.components()
.map(|c| c.as_os_str().to_string_lossy().to_string())
.collect::<Vec<_>>()
.join("_")
})
.unwrap_or_else(|| leaf_name.clone())
} else {
leaf_name.clone()
};
let (size, updated) = dir_size_and_mtime(path);
if size == 0 {
continue;
}
results.push(build_discovered_item(
path,
format!("{}.zip", archive_base),
&leaf_name,
emu,
true,
false,
size,
updated,
roms,
manual_links,
));
}
}
SaveStructure::FilePerGame | SaveStructure::MemoryCard => {
for entry in WalkDir::new(save_root)
.max_depth(3)
.into_iter()
.flatten()
{
let path = entry.path();
if !path.is_file() {
continue;
}
if !matches_extensions(path, &emu.save_extensions) {
continue;
}
let file_name = path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
if file_name.starts_with('.') {
continue;
}
let stem = path
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| file_name.clone());
let (size, updated) = file_size_and_mtime(path);
results.push(build_discovered_item(
path,
file_name,
&stem,
emu,
false,
false,
size,
updated,
roms,
manual_links,
));
}
}
}
}
// 2. Save states (when enabled and state_dir exists)
if emu.sync_states {
if let Some(ref sdir) = emu.state_dir {
let state_root = Path::new(sdir);
if state_root.exists() && !emu.state_extensions.is_empty() {
for entry in WalkDir::new(state_root)
.max_depth(3)
.into_iter()
.flatten()
{
let path = entry.path();
if !path.is_file() {
continue;
}
if !matches_extensions(path, &emu.state_extensions) {
continue;
}
let file_name = path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
if file_name.starts_with('.') {
continue;
}
let stem = path
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| file_name.clone());
let (size, updated) = file_size_and_mtime(path);
results.push(build_discovered_item(
path,
file_name,
&stem,
emu,
false,
true,
size,
updated,
roms,
manual_links,
));
}
}
}
}
}
results
}
#[allow(clippy::too_many_arguments)]
fn build_discovered_item(
path: &Path,
file_name: String,
stem: &str,
emu: &EmulatorRule,
is_directory: bool,
is_state: bool,
size_bytes: u64,
updated_at: String,
roms: &[SimpleRomSchema],
manual_links: &HashMap<String, ManualLink>,
) -> DiscoveredSaveItem {
let path_str = path.to_string_lossy().to_string();
if let Some(link) = manual_links.get(&path_str) {
let rom_platform = roms
.iter()
.find(|r| r.id == link.rom_id)
.map(|r| r.platform_display_name.clone());
return DiscoveredSaveItem {
local_path: path_str,
file_name,
emulator_id: emu.id.clone(),
emulator_name: emu.name.clone(),
is_directory,
is_state,
size_bytes,
updated_at,
slot: link.slot.clone(),
matched_rom_id: Some(link.rom_id),
matched_rom_name: Some(link.rom_name.clone()),
matched_platform: rom_platform,
match_confidence: 1.0,
match_source: "manual".to_string(),
};
}
if let Some((rom, conf, src)) = match_name_to_roms(stem, &emu.platform_slugs, roms) {
DiscoveredSaveItem {
local_path: path_str,
file_name,
emulator_id: emu.id.clone(),
emulator_name: emu.name.clone(),
is_directory,
is_state,
size_bytes,
updated_at,
slot: emu.default_slot.clone(),
matched_rom_id: Some(rom.id),
matched_rom_name: Some(rom.name.clone().unwrap_or_else(|| rom.fs_name_no_ext.clone())),
matched_platform: Some(rom.platform_display_name.clone()),
match_confidence: conf,
match_source: src.to_string(),
}
} else {
DiscoveredSaveItem {
local_path: path_str,
file_name,
emulator_id: emu.id.clone(),
emulator_name: emu.name.clone(),
is_directory,
is_state,
size_bytes,
updated_at,
slot: emu.default_slot.clone(),
matched_rom_id: None,
matched_rom_name: None,
matched_platform: None,
match_confidence: 0.0,
match_source: "unmatched".to_string(),
}
}
}
fn matches_extensions(path: &Path, exts: &[String]) -> bool {
if exts.is_empty() {
return true;
}
let ext = match path.extension().and_then(|e| e.to_str()) {
Some(e) => e.to_lowercase(),
None => return false,
};
exts.iter().any(|allowed| allowed.eq_ignore_ascii_case(&ext))
}
fn file_size_and_mtime(path: &Path) -> (u64, String) {
match fs::metadata(path) {
Ok(m) => {
let dt: DateTime<Utc> = m
.modified()
.map(DateTime::<Utc>::from)
.unwrap_or_else(|_| Utc::now());
(m.len(), dt.to_rfc3339())
}
Err(_) => (0, Utc::now().to_rfc3339()),
}
}
fn dir_size_and_mtime(dir: &Path) -> (u64, String) {
let mut total = 0u64;
let mut latest: Option<std::time::SystemTime> = None;
for entry in WalkDir::new(dir).into_iter().flatten() {
if entry.path().is_file() {
if let Ok(m) = entry.metadata() {
total += m.len();
if let Ok(mt) = m.modified() {
if latest.map_or(true, |l| mt > l) {
latest = Some(mt);
}
}
}
}
}
let dt: DateTime<Utc> = latest.map(DateTime::<Utc>::from).unwrap_or_else(Utc::now);
(total, dt.to_rfc3339())
}
/// Reads a save file or deterministically zips a save directory into bytes, and returns `(bytes, sha256_hex)`.
pub fn read_save_payload_and_hash(path: &Path, is_directory: bool) -> Result<(Vec<u8>, String), String> {
let bytes = if is_directory {
zip_directory_deterministic(path)?
} else {
fs::read(path).map_err(|e| format!("Failed to read {}: {}", path.display(), e))?
};
let mut hasher = Sha256::new();
hasher.update(&bytes);
let hash = hex::encode(hasher.finalize());
Ok((bytes, hash))
}
fn zip_directory_deterministic(dir: &Path) -> Result<Vec<u8>, String> {
let mut files: Vec<PathBuf> = WalkDir::new(dir)
.into_iter()
.flatten()
.filter(|e| e.path().is_file())
.map(|e| e.into_path())
.collect();
files.sort();
let mut cursor = std::io::Cursor::new(Vec::new());
{
let mut zip = ZipWriter::new(&mut cursor);
let options = SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated)
.last_modified_time(zip::DateTime::default());
for file_path in files {
let rel = file_path
.strip_prefix(dir)
.map_err(|e| e.to_string())?
.to_string_lossy()
.replace('\\', "/");
zip.start_file(rel, options).map_err(|e| e.to_string())?;
let data = fs::read(&file_path).map_err(|e| e.to_string())?;
zip.write_all(&data).map_err(|e| e.to_string())?;
}
zip.finish().map_err(|e| e.to_string())?;
}
Ok(cursor.into_inner())
}
/// Computes CRC32, MD5, and SHA1 in a single streaming pass over a local ROM file.
/// Skips hashing files larger than `max_hash_bytes` (e.g. 512 MB) unless requested, falling back to filename matching.
pub fn compute_rom_hashes(
path: &Path,
max_hash_bytes: u64,
) -> Result<(u64, Option<String>, Option<String>, Option<String>), String> {
let meta = fs::metadata(path).map_err(|e| e.to_string())?;
let size = meta.len();
if size > max_hash_bytes {
return Ok((size, None, None, None));
}
let mut file = File::open(path).map_err(|e| e.to_string())?;
let mut crc = Crc32Hasher::new();
let mut md5 = Md5::new();
let mut sha1 = Sha1::new();
let mut buf = vec![0u8; 256 * 1024];
loop {
let n = file.read(&mut buf).map_err(|e| e.to_string())?;
if n == 0 {
break;
}
let chunk = &buf[..n];
crc.update(chunk);
md5.update(chunk);
sha1.update(chunk);
}
let crc_hex = format!("{:08x}", crc.finalize());
let md5_hex = hex::encode(md5.finalize());
let sha1_hex = hex::encode(sha1.finalize());
Ok((size, Some(crc_hex), Some(md5_hex), Some(sha1_hex)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normalize_title_strips_region_and_revision_tags() {
assert_eq!(
normalize_title("The Legend of Zelda - The Wind Waker (USA) (Rev 1) [!]"),
"the legend of zelda the wind waker"
);
assert_eq!(normalize_title("Super_Mario_Sunshine.gci"), "super mario sunshine gci");
}
#[test]
fn test_similarity_score_matches_cleaned_titles() {
let score = similarity_score(
"Metroid Prime (USA)",
"Metroid Prime (Europe) (En,Fr,De,Es,It)",
);
assert!(score >= 0.99, "expected >= 0.99, got {}", score);
let partial = similarity_score("Paper Mario TTYD", "Super Mario Sunshine");
assert!(partial < 0.55, "expected < 0.55, got {}", partial);
}
#[test]
fn test_folder_per_game_nested_depth() {
let base = std::env::temp_dir().join(format!("romm_depth_test_{}", uuid::Uuid::new_v4()));
let nested = base.join("00050000").join("101c9400");
fs::create_dir_all(&nested).unwrap();
fs::write(nested.join("save.dat"), b"hello-wiiu").unwrap();
let rule = EmulatorRule {
id: "cemu".into(),
name: "Cemu".into(),
platform_slugs: vec!["wiiu".into()],
save_dir: base.to_string_lossy().to_string(),
state_dir: None,
rom_dir: None,
save_extensions: vec![],
state_extensions: vec![],
structure: SaveStructure::FolderPerGame,
folder_depth: 2,
enabled: true,
is_custom: false,
sync_states: false,
default_slot: "default".into(),
};
let found = discover_saves_for_emulators(&[rule], &[], &HashMap::new());
let _ = fs::remove_dir_all(&base);
assert_eq!(found.len(), 1);
assert_eq!(found[0].file_name, "00050000_101c9400.zip");
assert!(found[0].is_directory);
}
}
+881
View File
@@ -0,0 +1,881 @@
use crate::config::{push_log, AppConfig, ManualLink};
use crate::matcher::{match_name_to_roms, read_save_payload_and_hash};
use crate::romm_api::{ClientSaveState, RommClient, SimpleRomSchema};
use crate::sync_engine::{create_backup, write_downloaded_save, SyncConflictItem, SyncRunSummary};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DetectedNextUiVolume {
pub path: String,
pub label: String,
pub detected_platform: String, // "tg5050" | "tg5040" | "nextui"
pub device_label: String,
pub system_tags: Vec<String>,
pub has_saves: bool,
pub has_roms: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NextUiSdSaveItem {
pub local_path: String,
pub file_name: String,
pub system_tag: String,
pub is_directory: bool,
pub is_state: bool,
pub size_bytes: u64,
pub updated_at: String,
pub slot: String,
pub matched_rom_id: Option<i64>,
pub matched_rom_name: Option<String>,
pub matched_platform: Option<String>,
pub match_confidence: f32,
pub match_source: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NextUiCardInspection {
pub sd_root: String,
pub detected_platform: String,
pub device_name: String,
pub handheld_device_id: Option<String>,
pub system_tags: Vec<String>,
pub saves: Vec<NextUiSdSaveItem>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct HandheldDeviceMeta {
device_id: Option<String>,
device_name: String,
}
fn handheld_meta_path(sd_root: &Path) -> PathBuf {
sd_root.join(".userdata/shared/romm-companion/handheld_device.json")
}
pub fn load_handheld_meta(sd_root: &Path, default_name: &str) -> (Option<String>, String) {
let p = handheld_meta_path(sd_root);
if let Ok(raw) = fs::read_to_string(&p) {
if let Ok(meta) = serde_json::from_str::<HandheldDeviceMeta>(&raw) {
return (meta.device_id, meta.device_name);
}
}
(None, default_name.to_string())
}
pub fn save_handheld_meta(sd_root: &Path, device_id: Option<String>, device_name: &str) {
let p = handheld_meta_path(sd_root);
if let Some(parent) = p.parent() {
let _ = fs::create_dir_all(parent);
}
let meta = HandheldDeviceMeta {
device_id,
device_name: device_name.to_string(),
};
if let Ok(json) = serde_json::to_string_pretty(&meta) {
let _ = fs::write(&p, json);
}
}
pub fn tag_to_romm_slugs(tag: &str) -> Vec<String> {
let list: &[&str] = match tag.trim().to_uppercase().as_str() {
"GB" => &["gb"],
"GBC" => &["gbc"],
"GBA" | "MGBA" | "GPSP" => &["gba"],
"FC" | "NES" => &["nes", "famicom"],
"SFC" | "SNES" | "SUPA" => &["snes", "sfam"],
"N64" => &["n64"],
"NDS" | "DS" => &["nds", "ds"],
"PS" | "PSX" | "PS1" => &["psx", "ps1", "ps"],
"PSP" => &["psp"],
"MD" | "GEN" => &["genesis", "md", "megadrive"],
"SMS" => &["sms"],
"GG" => &["gamegear", "gg"],
"SEGACD" | "MCD" | "SCD" => &["segacd"],
"32X" => &["sega32x", "32x"],
"DC" | "DREAMCAST" => &["dc", "dreamcast"],
"SATURN" | "SS" => &["saturn"],
"PCE" | "TG16" => &["tg16", "turbografx16", "pce"],
"PCECD" | "TGCD" => &["turbografx-cd", "pcecd"],
"NGP" | "NGPC" => &["ngp", "ngpc"],
"WS" | "WSC" => &["wonderswan", "wonderswan-color"],
"PKM" | "POKEMINI" => &["pokemon-mini", "pokemini"],
"VB" => &["virtualboy", "vb"],
"A2600" | "2600" | "ATARI" => &["atari2600"],
"A7800" | "7800" => &["atari7800"],
"LYNX" => &["lynx"],
"FBN" | "FBNEO" | "ARCADE" | "MAME" | "CPS1" | "CPS2" | "CPS3" => &["arcade", "fbneo"],
"NEOGEO" | "NEO" => &["neogeo", "arcade"],
"PICO" | "PICO8" => &["pico8"],
_ => return vec![tag.to_lowercase()],
};
list.iter().map(|s| s.to_string()).collect()
}
pub fn romm_slug_to_default_tag(slug: &str) -> String {
match slug.to_lowercase().as_str() {
"gb" => "GB",
"gbc" => "GBC",
"gba" => "GBA",
"nes" | "famicom" => "FC",
"snes" | "sfam" => "SFC",
"n64" => "N64",
"nds" | "ds" => "NDS",
"psx" | "ps1" | "ps" => "PS",
"psp" => "PSP",
"genesis" | "md" | "megadrive" => "MD",
"sms" => "SMS",
"gamegear" | "gg" => "GG",
"segacd" => "SEGACD",
"sega32x" | "32x" => "32X",
"dc" | "dreamcast" => "DC",
"saturn" => "SATURN",
"tg16" | "turbografx16" | "pce" => "PCE",
"ngp" | "ngpc" => "NGPC",
"wonderswan" | "wonderswan-color" => "WSC",
"virtualboy" | "vb" => "VB",
"lynx" => "LYNX",
"neogeo" => "NEOGEO",
"arcade" | "fbneo" => "FBN",
"pico8" => "PICO",
other => return other.to_uppercase(),
}
.to_string()
}
fn extract_tag_from_rom_folder(name: &str) -> Option<String> {
let open = name.rfind('(')?;
let close = name.rfind(')')?;
if close > open + 1 {
let tag = name[open + 1..close].trim();
if !tag.is_empty() {
return Some(tag.to_string());
}
}
None
}
fn detect_platform_on_root(root: &Path) -> (String, String) {
if root.join("Tools/tg5050").exists()
|| root.join("Emus/tg5050").exists()
|| root.join(".userdata/tg5050").exists()
{
(
"tg5050".to_string(),
"TrimUI Smart Pro S (NextUI USB)".to_string(),
)
} else if root.join("Tools/tg5040").exists()
|| root.join("Emus/tg5040").exists()
|| root.join(".userdata/tg5040").exists()
{
(
"tg5040".to_string(),
"TrimUI Brick / Smart Pro (NextUI USB)".to_string(),
)
} else {
("nextui".to_string(), "NextUI Handheld (USB)".to_string())
}
}
fn collect_system_tags(root: &Path) -> Vec<String> {
let mut tags: Vec<String> = Vec::new();
if let Ok(entries) = fs::read_dir(root.join("Saves")) {
for e in entries.flatten() {
if e.path().is_dir() {
let n = e.file_name().to_string_lossy().to_string();
if !n.starts_with('.') && !tags.iter().any(|t| t.eq_ignore_ascii_case(&n)) {
tags.push(n);
}
}
}
}
if let Ok(entries) = fs::read_dir(root.join("Roms")) {
for e in entries.flatten() {
if e.path().is_dir() {
let n = e.file_name().to_string_lossy().to_string();
if let Some(tag) = extract_tag_from_rom_folder(&n) {
if !tags.iter().any(|t| t.eq_ignore_ascii_case(&tag)) {
tags.push(tag);
}
}
}
}
}
tags.sort();
tags
}
fn is_likely_nextui_root(root: &Path) -> bool {
let has_saves = root.join("Saves").is_dir();
let has_roms = root.join("Roms").is_dir();
if !has_saves && !has_roms {
return false;
}
let has_markers = root.join(".userdata").is_dir()
|| root.join("Tools/tg5040").is_dir()
|| root.join("Tools/tg5050").is_dir()
|| root.join("Emus/tg5040").is_dir()
|| root.join("Emus/tg5050").is_dir()
|| root.join("Bios").is_dir();
if has_markers {
return true;
}
// Check for NextUI-style `System (TAG)` folder inside Roms/
if has_roms {
if let Ok(entries) = fs::read_dir(root.join("Roms")) {
for e in entries.flatten() {
if e.path().is_dir()
&& extract_tag_from_rom_folder(&e.file_name().to_string_lossy()).is_some()
{
return true;
}
}
}
}
false
}
/// Scans mounted removable volumes on macOS, Linux, and Windows for NextUI SD cards.
pub fn detect_nextui_volumes() -> Vec<DetectedNextUiVolume> {
let mut candidates: Vec<PathBuf> = Vec::new();
#[cfg(target_os = "macos")]
{
if let Ok(entries) = fs::read_dir("/Volumes") {
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
candidates.push(p);
}
}
}
}
#[cfg(target_os = "linux")]
{
let user = std::env::var("USER").unwrap_or_default();
for base in [
PathBuf::from("/mnt"),
PathBuf::from(format!("/media/{}", user)),
PathBuf::from(format!("/run/media/{}", user)),
] {
if let Ok(entries) = fs::read_dir(base) {
for e in entries.flatten() {
if e.path().is_dir() {
candidates.push(e.path());
}
}
}
}
}
#[cfg(target_os = "windows")]
{
for letter in b'D'..=b'Z' {
let p = PathBuf::from(format!("{}:\\", letter as char));
if p.exists() {
candidates.push(p);
}
}
}
let mut found = Vec::new();
for root in candidates {
if !is_likely_nextui_root(&root) {
continue;
}
let (platform, device_label) = detect_platform_on_root(&root);
let label = root
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| root.to_string_lossy().to_string());
found.push(DetectedNextUiVolume {
path: root.to_string_lossy().to_string(),
label,
detected_platform: platform,
device_label,
system_tags: collect_system_tags(&root),
has_saves: root.join("Saves").is_dir(),
has_roms: root.join("Roms").is_dir(),
});
}
found
}
/// Classifies a file inside `<sd_root>/Saves/<TAG>/` as Save vs Save State and returns `(is_state, clean_stem)`.
pub fn classify_nextui_save_file(path: &Path) -> Option<(bool, String)> {
let file_name = path.file_name()?.to_str()?;
if file_name.starts_with('.') || file_name.ends_with(".romm_part") {
return None;
}
let lower = file_name.to_lowercase();
if lower.ends_with(".png")
|| lower.ends_with(".jpg")
|| lower.ends_with(".txt")
|| lower.ends_with(".json")
|| lower.ends_with(".cfg")
|| lower.ends_with(".auto")
{
return None;
}
let (is_state, without_save_ext) = if let Some(idx) = lower.rfind(".state") {
(true, &file_name[..idx])
} else if lower.ends_with(".ppst") {
(true, &file_name[..file_name.len() - 5])
} else if let Some(dot) = lower.rfind('.') {
let ext = &lower[dot + 1..];
if (ext.starts_with("st") || ext.starts_with("ss"))
&& ext.len() <= 4
&& ext.len() > 2
&& ext[2..].chars().all(|c| c.is_ascii_digit())
{
(true, &file_name[..dot])
} else if matches!(
ext,
"sav" | "srm" | "mcr" | "mcd" | "dsv" | "eep" | "fla" | "mpk" | "vmu" | "bin" | "rtc" | "brm"
) {
(false, &file_name[..dot])
} else {
return None;
}
} else {
return None;
};
let rom_exts = [
".gba", ".gbc", ".gb", ".nes", ".sfc", ".smc", ".n64", ".z64", ".v64", ".nds", ".iso",
".chd", ".pbp", ".cue", ".bin", ".cso", ".md", ".gen", ".sms", ".gg", ".pce", ".ngp",
".ngc", ".ws", ".wsc", ".zip", ".7z", ".min", ".vb", ".lnx", ".a26", ".a78",
];
let mut stem = without_save_ext.to_string();
let stem_lower = stem.to_lowercase();
for rext in rom_exts {
if stem_lower.ends_with(rext) {
stem.truncate(stem.len() - rext.len());
break;
}
}
Some((is_state, stem))
}
pub fn inspect_nextui_card(
sd_root: &Path,
roms: &[SimpleRomSchema],
manual_links: &HashMap<String, ManualLink>,
) -> NextUiCardInspection {
let (platform, default_name) = detect_platform_on_root(sd_root);
let (handheld_device_id, device_name) = load_handheld_meta(sd_root, &default_name);
let system_tags = collect_system_tags(sd_root);
let saves = discover_saves_on_card(sd_root, roms, manual_links);
NextUiCardInspection {
sd_root: sd_root.to_string_lossy().to_string(),
detected_platform: platform,
device_name,
handheld_device_id,
system_tags,
saves,
}
}
pub fn discover_saves_on_card(
sd_root: &Path,
roms: &[SimpleRomSchema],
manual_links: &HashMap<String, ManualLink>,
) -> Vec<NextUiSdSaveItem> {
let saves_root = sd_root.join("Saves");
if !saves_root.is_dir() {
return Vec::new();
}
let mut out = Vec::new();
let Ok(tag_dirs) = fs::read_dir(&saves_root) else {
return out;
};
for tag_entry in tag_dirs.flatten() {
let tag_path = tag_entry.path();
if !tag_path.is_dir() {
continue;
}
let tag = tag_entry.file_name().to_string_lossy().to_string();
if tag.starts_with('.') {
continue;
}
let slugs = tag_to_romm_slugs(&tag);
// Handle PSP folder saves under /Saves/PSP/PSP/SAVEDATA/
if tag.eq_ignore_ascii_case("PSP") {
let psp_dir = tag_path.join("PSP/SAVEDATA");
if psp_dir.is_dir() {
if let Ok(entries) = fs::read_dir(&psp_dir) {
for e in entries.flatten() {
let p = e.path();
if !p.is_dir() {
continue;
}
let name = e.file_name().to_string_lossy().to_string();
if name.starts_with('.') {
continue;
}
let (size, updated) = dir_size_and_mtime(&p);
if size == 0 {
continue;
}
out.push(build_sd_item(
&p,
format!("{}.zip", name),
&name,
&tag,
&slugs,
true,
false,
size,
updated,
roms,
manual_links,
));
}
}
}
}
for entry in WalkDir::new(&tag_path).max_depth(2).into_iter().flatten() {
let p = entry.path();
if !p.is_file() {
continue;
}
let Some((is_state, stem)) = classify_nextui_save_file(p) else {
continue;
};
let file_name = p
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
let (size, updated) = file_size_and_mtime(p);
out.push(build_sd_item(
p,
file_name,
&stem,
&tag,
&slugs,
false,
is_state,
size,
updated,
roms,
manual_links,
));
}
}
out
}
#[allow(clippy::too_many_arguments)]
fn build_sd_item(
path: &Path,
file_name: String,
stem: &str,
tag: &str,
slugs: &[String],
is_directory: bool,
is_state: bool,
size_bytes: u64,
updated_at: String,
roms: &[SimpleRomSchema],
manual_links: &HashMap<String, ManualLink>,
) -> NextUiSdSaveItem {
let local_path = path.to_string_lossy().to_string();
if let Some(link) = manual_links.get(&local_path) {
let plat = roms
.iter()
.find(|r| r.id == link.rom_id)
.map(|r| r.platform_display_name.clone());
return NextUiSdSaveItem {
local_path,
file_name,
system_tag: tag.to_string(),
is_directory,
is_state,
size_bytes,
updated_at,
slot: link.slot.clone(),
matched_rom_id: Some(link.rom_id),
matched_rom_name: Some(link.rom_name.clone()),
matched_platform: plat,
match_confidence: 1.0,
match_source: "manual".to_string(),
};
}
if let Some((rom, conf, src)) = match_name_to_roms(stem, slugs, roms) {
NextUiSdSaveItem {
local_path,
file_name,
system_tag: tag.to_string(),
is_directory,
is_state,
size_bytes,
updated_at,
slot: "default".to_string(),
matched_rom_id: Some(rom.id),
matched_rom_name: Some(rom.name.clone().unwrap_or_else(|| rom.fs_name_no_ext.clone())),
matched_platform: Some(rom.platform_display_name.clone()),
match_confidence: conf,
match_source: src.to_string(),
}
} else {
NextUiSdSaveItem {
local_path,
file_name,
system_tag: tag.to_string(),
is_directory,
is_state,
size_bytes,
updated_at,
slot: "default".to_string(),
matched_rom_id: None,
matched_rom_name: None,
matched_platform: None,
match_confidence: 0.0,
match_source: "unmatched".to_string(),
}
}
}
/// Resolves the target `/Roms/<System> (<TAG>)/` directory on the NextUI SD card for a RomM platform.
pub fn resolve_nextui_rom_folder(
sd_root: &Path,
platform_slug: &str,
platform_display_name: &str,
) -> PathBuf {
let roms_root = sd_root.join("Roms");
if let Ok(entries) = fs::read_dir(&roms_root) {
for e in entries.flatten() {
let p = e.path();
if !p.is_dir() {
continue;
}
let name = e.file_name().to_string_lossy().to_string();
if let Some(tag) = extract_tag_from_rom_folder(&name) {
let slugs = tag_to_romm_slugs(&tag);
if slugs.iter().any(|s| s.eq_ignore_ascii_case(platform_slug)) {
return p;
}
}
}
}
let tag = romm_slug_to_default_tag(platform_slug);
let safe_name = platform_display_name.replace(['/', '\\', ':', '*', '?', '"', '<', '>', '|'], "");
roms_root.join(format!("{} ({})", safe_name.trim(), tag))
}
/// Runs a full two-way RomM 5.1.0 save + state sync for a mounted NextUI SD card.
pub async fn sync_nextui_card(
client: &RommClient,
cfg: &mut AppConfig,
roms: &[SimpleRomSchema],
sd_root: &Path,
sync_states: bool,
) -> Result<SyncRunSummary, String> {
let (_, default_name) = detect_platform_on_root(sd_root);
let (mut handheld_device_id, device_name) = load_handheld_meta(sd_root, &default_name);
// Register a dedicated RomM device for this handheld SD card if not registered yet
if handheld_device_id.is_none() {
if let Ok(dev) = client.register_device(&device_name).await {
handheld_device_id = Some(dev.id.clone());
save_handheld_meta(sd_root, Some(dev.id), &device_name);
}
}
let effective_device_id = handheld_device_id.or_else(|| cfg.connection.device_id.clone());
let discovered = discover_saves_on_card(sd_root, roms, &cfg.manual_links);
let rom_by_id: HashMap<i64, &SimpleRomSchema> = roms.iter().map(|r| (r.id, r)).collect();
let mut summary = SyncRunSummary {
session_id: None,
uploaded_saves: 0,
downloaded_saves: 0,
uploaded_states: 0,
up_to_date: 0,
conflicts: Vec::new(),
errors: Vec::new(),
};
let matched_saves: Vec<&NextUiSdSaveItem> = discovered
.iter()
.filter(|d| !d.is_state && d.matched_rom_id.is_some())
.collect();
let matched_states: Vec<&NextUiSdSaveItem> = discovered
.iter()
.filter(|d| d.is_state && d.matched_rom_id.is_some())
.collect();
let mut local_map: HashMap<(i64, String), (&NextUiSdSaveItem, Vec<u8>)> = HashMap::new();
let mut client_states: Vec<ClientSaveState> = Vec::new();
for item in matched_saves {
let Some(rom_id) = item.matched_rom_id else {
continue;
};
match read_save_payload_and_hash(Path::new(&item.local_path), item.is_directory) {
Ok((bytes, hash)) => {
let slot = if item.slot.trim().is_empty() {
"default".to_string()
} else {
item.slot.clone()
};
client_states.push(ClientSaveState {
rom_id,
file_name: item.file_name.clone(),
slot: Some(slot.clone()),
emulator: Some(format!("nextui-{}", item.system_tag.to_lowercase())),
content_hash: Some(hash),
updated_at: item.updated_at.clone(),
file_size_bytes: bytes.len() as i64,
});
local_map.insert((rom_id, slot), (item, bytes));
}
Err(e) => summary.errors.push(format!("{}: {}", item.file_name, e)),
}
}
if !client_states.is_empty() || effective_device_id.is_some() {
let neg = client
.negotiate_sync(effective_device_id.clone(), client_states)
.await?;
summary.session_id = Some(neg.session_id);
let mut completed = 0i64;
let mut failed = 0i64;
for op in neg.operations {
let slot_key = op.slot.clone().unwrap_or_else(|| "default".to_string());
match op.action.as_str() {
"no_op" => summary.up_to_date += 1,
"upload" => {
if let Some((item, bytes)) = local_map.get(&(op.rom_id, slot_key.clone())) {
let emu_id = format!("nextui-{}", item.system_tag.to_lowercase());
match client
.upload_save(
op.rom_id,
Some(&emu_id),
Some(&slot_key),
effective_device_id.as_deref(),
Some(neg.session_id),
true,
&item.file_name,
bytes.clone(),
)
.await
{
Ok(_) => {
summary.uploaded_saves += 1;
completed += 1;
push_log(
cfg,
"success",
"nextui_upload",
format!("[NextUI USB] Uploaded {} ({})", item.file_name, item.system_tag),
Some(op.rom_id),
Some(item.local_path.clone()),
);
}
Err(e) => {
failed += 1;
summary.errors.push(format!("Upload {}: {}", item.file_name, e));
}
}
}
}
"download" => {
let Some(save_id) = op.save_id else {
continue;
};
let target = local_map
.get(&(op.rom_id, slot_key.clone()))
.map(|(item, _)| (PathBuf::from(&item.local_path), item.is_directory))
.or_else(|| {
rom_by_id.get(&op.rom_id).map(|rom| {
let tag = romm_slug_to_default_tag(&rom.platform_slug);
let is_dir = tag == "PSP" && op.file_name.ends_with(".zip");
let name = if is_dir {
op.file_name
.strip_suffix(".zip")
.unwrap_or(&op.file_name)
.to_string()
} else {
op.file_name.clone()
};
(sd_root.join("Saves").join(tag).join(name), is_dir)
})
});
if let Some((dest_path, is_dir)) = target {
match client
.download_save_bytes(
save_id,
effective_device_id.as_deref(),
Some(neg.session_id),
)
.await
{
Ok(bytes) => {
let _ = create_backup(
&dest_path,
op.rom_id,
is_dir,
cfg.settings.max_backups_per_save,
);
match write_downloaded_save(&dest_path, &bytes, is_dir) {
Ok(()) => {
if let Some(ref did) = effective_device_id {
let _ = client
.confirm_save_downloaded(save_id, did)
.await;
}
summary.downloaded_saves += 1;
completed += 1;
push_log(
cfg,
"success",
"nextui_download",
format!("[NextUI USB] Downloaded {} to SD card (backup saved)", op.file_name),
Some(op.rom_id),
Some(dest_path.to_string_lossy().to_string()),
);
}
Err(e) => {
failed += 1;
summary.errors.push(format!("Write {}: {}", op.file_name, e));
}
}
}
Err(e) => {
failed += 1;
summary.errors.push(format!("Download {}: {}", op.file_name, e));
}
}
}
}
"conflict" => {
if let Some((item, _)) = local_map.get(&(op.rom_id, slot_key.clone())) {
summary.conflicts.push(SyncConflictItem {
id: format!("nextui:{}:{}:{}", op.rom_id, slot_key, op.save_id.unwrap_or(0)),
rom_id: op.rom_id,
rom_name: item
.matched_rom_name
.clone()
.unwrap_or_else(|| format!("ROM #{}", op.rom_id)),
save_id: op.save_id,
local_path: item.local_path.clone(),
file_name: item.file_name.clone(),
is_directory: item.is_directory,
emulator_id: format!("nextui-{}", item.system_tag.to_lowercase()),
slot: slot_key,
local_updated_at: item.updated_at.clone(),
server_updated_at: op.server_updated_at.clone(),
reason: format!("[NextUI SD] {}", op.reason),
});
}
}
_ => {}
}
}
let _ = client
.complete_sync_session(neg.session_id, completed, failed)
.await;
}
if sync_states {
for item in matched_states {
let Some(rom_id) = item.matched_rom_id else {
continue;
};
match read_save_payload_and_hash(Path::new(&item.local_path), false) {
Ok((bytes, hash)) => {
if cfg.synced_state_hashes.get(&item.local_path) == Some(&hash) {
summary.up_to_date += 1;
continue;
}
let existing = client
.get_states(Some(rom_id), None)
.await
.unwrap_or_default()
.into_iter()
.find(|s| s.file_name.eq_ignore_ascii_case(&item.file_name));
let emu_id = format!("nextui-{}", item.system_tag.to_lowercase());
let res = if let Some(remote) = existing {
client.update_state(remote.id, &item.file_name, bytes).await
} else {
client
.upload_state(rom_id, Some(&emu_id), &item.file_name, bytes)
.await
};
match res {
Ok(_) => {
cfg.synced_state_hashes.insert(item.local_path.clone(), hash);
summary.uploaded_states += 1;
push_log(
cfg,
"success",
"nextui_state",
format!("[NextUI USB] Synced state {} ({})", item.file_name, item.system_tag),
Some(rom_id),
Some(item.local_path.clone()),
);
}
Err(e) => summary.errors.push(format!("State {}: {}", item.file_name, e)),
}
}
Err(e) => summary.errors.push(format!("State {}: {}", item.file_name, e)),
}
}
}
Ok(summary)
}
fn file_size_and_mtime(path: &Path) -> (u64, String) {
match fs::metadata(path) {
Ok(m) => {
let dt: DateTime<Utc> = m
.modified()
.map(DateTime::<Utc>::from)
.unwrap_or_else(|_| Utc::now());
(m.len(), dt.to_rfc3339())
}
Err(_) => (0, Utc::now().to_rfc3339()),
}
}
fn dir_size_and_mtime(dir: &Path) -> (u64, String) {
let mut total = 0u64;
let mut latest: Option<std::time::SystemTime> = None;
for entry in WalkDir::new(dir).into_iter().flatten() {
if entry.path().is_file() {
if let Ok(m) = entry.metadata() {
total += m.len();
if let Ok(mt) = m.modified() {
if latest.map_or(true, |l| mt > l) {
latest = Some(mt);
}
}
}
}
}
let dt: DateTime<Utc> = latest.map(DateTime::<Utc>::from).unwrap_or_else(Utc::now);
(total, dt.to_rfc3339())
}
+835
View File
@@ -0,0 +1,835 @@
use futures_util::StreamExt;
use reqwest::multipart::{Form, Part};
use reqwest::{Client, Method, RequestBuilder};
use serde::{Deserialize, Serialize};
use std::path::Path;
use tokio::io::AsyncWriteExt;
#[derive(Debug, Clone)]
pub struct RommClient {
http: Client,
base_url: String,
token: Option<String>,
}
// ---------- Auth Schemas (RomM 5.1.0) ----------
#[derive(Debug, Serialize)]
pub struct DeviceAuthInitPayload {
pub client_device_identifier: String,
pub name: String,
pub client: String,
pub platform: Option<String>,
pub client_version: Option<String>,
pub requested_scopes: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceAuthInitResponse {
pub device_code: String,
pub user_code: String,
pub verification_path: String,
pub verification_path_complete: String,
pub expires_in: i64,
pub interval: i64,
}
#[derive(Debug, Serialize)]
pub struct DeviceAuthTokenPayload {
pub device_code: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceAuthTokenResponse {
pub access_token: String,
pub device_id: String,
pub scopes: Vec<String>,
pub expires_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenResponse {
pub access_token: String,
pub token_type: String,
pub expires: Option<i64>,
pub refresh_token: Option<String>,
pub refresh_expires: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientTokenCreateSchema {
pub id: i64,
pub name: String,
pub scopes: Vec<String>,
pub expires_at: Option<String>,
pub device_id: Option<String>,
pub raw_token: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserSchema {
pub id: i64,
pub username: String,
pub email: Option<String>,
pub role: Option<serde_json::Value>,
pub current_device_id: Option<String>,
}
// ---------- Device Schemas ----------
#[derive(Debug, Serialize)]
pub struct DeviceCreatePayload {
pub name: Option<String>,
pub platform: Option<String>,
pub client: Option<String>,
pub client_version: Option<String>,
pub hostname: Option<String>,
pub sync_mode: Option<String>,
pub allow_existing: bool,
pub allow_duplicate: bool,
pub reset_syncs: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceSchema {
pub id: String,
pub user_id: i64,
pub name: Option<String>,
pub platform: Option<String>,
pub client: Option<String>,
pub client_version: Option<String>,
pub hostname: Option<String>,
pub sync_enabled: Option<bool>,
pub sync_mode: Option<String>,
}
// ---------- Platform & ROM Schemas ----------
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlatformSchema {
pub id: i64,
pub slug: String,
pub fs_slug: String,
pub name: String,
pub display_name: String,
pub rom_count: i64,
pub url_logo: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RomFileSchema {
pub id: i64,
pub rom_id: i64,
pub file_name: String,
pub file_path: String,
pub file_size_bytes: i64,
pub full_path: String,
pub crc_hash: Option<String>,
pub md5_hash: Option<String>,
pub sha1_hash: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimpleRomSchema {
pub id: i64,
pub platform_id: i64,
pub platform_slug: String,
pub platform_fs_slug: String,
pub platform_display_name: String,
pub fs_name: String,
pub fs_name_no_tags: String,
pub fs_name_no_ext: String,
pub fs_extension: String,
pub fs_size_bytes: i64,
pub name: Option<String>,
pub slug: Option<String>,
pub path_cover_small: Option<String>,
pub url_cover: Option<String>,
pub crc_hash: Option<String>,
pub md5_hash: Option<String>,
pub sha1_hash: Option<String>,
pub ra_hash: Option<String>,
#[serde(default)]
pub regions: Vec<String>,
#[serde(default)]
pub files: Vec<RomFileSchema>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RomPageResponse {
pub items: Vec<SimpleRomSchema>,
pub total: i64,
pub limit: i64,
pub offset: i64,
}
// ---------- Save, State & Sync Negotiation Schemas (RomM 5.1.0) ----------
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SaveSchema {
pub id: i64,
pub rom_id: i64,
pub user_id: i64,
pub file_name: String,
pub file_name_no_tags: String,
pub file_name_no_ext: String,
pub file_extension: String,
pub file_size_bytes: i64,
pub download_path: String,
pub created_at: String,
pub updated_at: String,
pub emulator: Option<String>,
pub slot: Option<String>,
pub content_hash: Option<String>,
pub origin_device_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateSchema {
pub id: i64,
pub rom_id: i64,
pub user_id: i64,
pub file_name: String,
pub file_name_no_tags: String,
pub file_name_no_ext: String,
pub file_extension: String,
pub file_size_bytes: i64,
pub download_path: String,
pub created_at: String,
pub updated_at: String,
pub emulator: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientSaveState {
pub rom_id: i64,
pub file_name: String,
pub slot: Option<String>,
pub emulator: Option<String>,
pub content_hash: Option<String>,
pub updated_at: String,
pub file_size_bytes: i64,
}
#[derive(Debug, Serialize)]
pub struct SyncNegotiatePayload {
pub device_id: Option<String>,
pub saves: Vec<ClientSaveState>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncOperationSchema {
pub action: String, // "upload" | "download" | "conflict" | "no_op"
pub rom_id: i64,
pub save_id: Option<i64>,
pub file_name: String,
pub slot: Option<String>,
pub emulator: Option<String>,
pub reason: String,
pub server_updated_at: Option<String>,
pub server_content_hash: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncNegotiateResponse {
pub session_id: i64,
pub operations: Vec<SyncOperationSchema>,
pub total_upload: i64,
pub total_download: i64,
pub total_conflict: i64,
pub total_no_op: i64,
}
#[derive(Debug, Serialize)]
pub struct SyncCompletePayload {
pub operations_completed: i64,
pub operations_failed: i64,
}
#[derive(Debug, Serialize)]
struct ConfirmDownloadPayload {
device_id: String,
}
#[derive(Debug, Serialize)]
struct PairExchangePayload {
code: String,
}
impl RommClient {
pub fn new(base_url: &str, token: Option<String>) -> Result<Self, String> {
let normalized = base_url.trim().trim_end_matches('/').to_string();
if normalized.is_empty() {
return Err("RomM server URL is required".into());
}
let http = Client::builder()
.user_agent("RomM-Companion/0.1.0")
.build()
.map_err(|e| format!("Failed to create HTTP client: {e}"))?;
Ok(Self {
http,
base_url: normalized,
token,
})
}
pub fn base_url(&self) -> &str {
&self.base_url
}
fn request(&self, method: Method, path: &str) -> RequestBuilder {
let url = format!("{}{}", self.base_url, path);
let mut req = self.http.request(method, url);
if let Some(ref token) = self.token {
req = req.bearer_auth(token);
}
req
}
async fn parse_json<T: for<'de> Deserialize<'de>>(
resp: reqwest::Response,
) -> Result<T, String> {
let status = resp.status();
let text = resp
.text()
.await
.map_err(|e| format!("Failed to read response body: {e}"))?;
if !status.is_success() {
return Err(format!("HTTP {}: {}", status.as_u16(), text));
}
serde_json::from_str(&text)
.map_err(|e| format!("Failed to parse JSON ({}): {}", e, &text[..text.len().min(300)]))
}
// ---------- Auth ----------
pub async fn heartbeat(&self) -> Result<serde_json::Value, String> {
let resp = self
.request(Method::GET, "/api/heartbeat")
.send()
.await
.map_err(|e| format!("Could not reach RomM server: {e}"))?;
Self::parse_json(resp).await
}
pub async fn get_me(&self) -> Result<UserSchema, String> {
let resp = self
.request(Method::GET, "/api/users/me")
.send()
.await
.map_err(|e| format!("Request failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn device_auth_init(
&self,
client_device_identifier: &str,
device_name: &str,
) -> Result<DeviceAuthInitResponse, String> {
let payload = DeviceAuthInitPayload {
client_device_identifier: client_device_identifier.to_string(),
name: device_name.to_string(),
client: "romm-companion".to_string(),
platform: Some(std::env::consts::OS.to_string()),
client_version: Some("0.1.0".to_string()),
requested_scopes: vec![
"me.read".into(),
"roms.read".into(),
"platforms.read".into(),
"assets.read".into(),
"assets.write".into(),
"devices.read".into(),
"devices.write".into(),
"roms.user.read".into(),
"roms.user.write".into(),
],
};
let resp = self
.request(Method::POST, "/api/auth/device/init")
.json(&payload)
.send()
.await
.map_err(|e| format!("Device auth init failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn device_auth_poll(
&self,
device_code: &str,
) -> Result<Option<DeviceAuthTokenResponse>, String> {
let resp = self
.request(Method::POST, "/api/auth/device/token")
.json(&DeviceAuthTokenPayload {
device_code: device_code.to_string(),
})
.send()
.await
.map_err(|e| format!("Device auth poll failed: {e}"))?;
let status = resp.status();
let text = resp.text().await.map_err(|e| e.to_string())?;
if status.is_success() {
let parsed: DeviceAuthTokenResponse =
serde_json::from_str(&text).map_err(|e| format!("Parse error: {e}"))?;
return Ok(Some(parsed));
}
// Pending approval typically returns 400/428/403 with authorization_pending
if status.as_u16() == 400 || status.as_u16() == 428 || status.as_u16() == 202 {
if text.contains("pending") || text.contains("slow_down") {
return Ok(None);
}
}
Err(format!("HTTP {}: {}", status.as_u16(), text))
}
pub async fn exchange_pair_code(&self, code: &str) -> Result<ClientTokenCreateSchema, String> {
let resp = self
.request(Method::POST, "/api/client-tokens/exchange")
.json(&PairExchangePayload {
code: code.trim().to_string(),
})
.send()
.await
.map_err(|e| format!("Pair code exchange failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn login_password(
&self,
username: &str,
password: &str,
) -> Result<TokenResponse, String> {
let scopes = "me.read roms.read platforms.read assets.read assets.write devices.read devices.write roms.user.read roms.user.write";
let resp = self
.request(Method::POST, "/api/token")
.form(&[
("grant_type", "password"),
("username", username),
("password", password),
("scope", scopes),
])
.send()
.await
.map_err(|e| format!("Login request failed: {e}"))?;
Self::parse_json(resp).await
}
// ---------- Devices ----------
pub async fn register_device(&self, name: &str) -> Result<DeviceSchema, String> {
let host = hostname::get()
.ok()
.and_then(|h| h.into_string().ok());
let payload = DeviceCreatePayload {
name: Some(name.to_string()),
platform: Some(std::env::consts::OS.to_string()),
client: Some("romm-companion".to_string()),
client_version: Some("0.1.0".to_string()),
hostname: host,
sync_mode: Some("api".to_string()),
allow_existing: true,
allow_duplicate: false,
reset_syncs: false,
};
let resp = self
.request(Method::POST, "/api/devices")
.json(&payload)
.send()
.await
.map_err(|e| format!("Register device failed: {e}"))?;
Self::parse_json(resp).await
}
// ---------- Platforms & ROMs ----------
pub async fn get_platforms(&self) -> Result<Vec<PlatformSchema>, String> {
let resp = self
.request(Method::GET, "/api/platforms")
.send()
.await
.map_err(|e| format!("Get platforms failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn get_roms(
&self,
platform_id: Option<i64>,
search_term: Option<&str>,
limit: i64,
offset: i64,
) -> Result<RomPageResponse, String> {
let mut req = self.request(Method::GET, "/api/roms").query(&[
("limit", limit.to_string()),
("offset", offset.to_string()),
("with_files", "true".to_string()),
]);
if let Some(pid) = platform_id {
req = req.query(&[("platform_ids", pid.to_string())]);
}
if let Some(term) = search_term {
if !term.trim().is_empty() {
req = req.query(&[("search_term", term.trim().to_string())]);
}
}
let resp = req
.send()
.await
.map_err(|e| format!("Get ROMs failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn get_all_roms_for_platforms(
&self,
platform_ids: &[i64],
) -> Result<Vec<SimpleRomSchema>, String> {
let mut all = Vec::new();
if platform_ids.is_empty() {
let mut offset = 0;
loop {
let page = self.get_roms(None, None, 200, offset).await?;
let count = page.items.len() as i64;
all.extend(page.items);
offset += count;
if count == 0 || offset >= page.total {
break;
}
}
} else {
for &pid in platform_ids {
let mut offset = 0;
loop {
let page = self.get_roms(Some(pid), None, 200, offset).await?;
let count = page.items.len() as i64;
all.extend(page.items);
offset += count;
if count == 0 || offset >= page.total {
break;
}
}
}
}
Ok(all)
}
pub async fn get_rom_by_hash(
&self,
crc_hash: Option<&str>,
md5_hash: Option<&str>,
sha1_hash: Option<&str>,
) -> Result<Option<SimpleRomSchema>, String> {
let mut req = self.request(Method::GET, "/api/roms/by-hash");
if let Some(h) = crc_hash {
req = req.query(&[("crc_hash", h)]);
}
if let Some(h) = md5_hash {
req = req.query(&[("md5_hash", h)]);
}
if let Some(h) = sha1_hash {
req = req.query(&[("sha1_hash", h)]);
}
let resp = req
.send()
.await
.map_err(|e| format!("Hash lookup failed: {e}"))?;
if resp.status().as_u16() == 404 {
return Ok(None);
}
let rom: SimpleRomSchema = Self::parse_json(resp).await?;
Ok(Some(rom))
}
pub async fn download_rom(
&self,
rom_id: i64,
file_name: &str,
dest_path: &Path,
mut on_progress: impl FnMut(u64, Option<u64>),
) -> Result<(), String> {
let encoded = urlencoding_path_segment(file_name);
let path = format!("/api/roms/{}/content/{}", rom_id, encoded);
let resp = self
.request(Method::GET, &path)
.send()
.await
.map_err(|e| format!("ROM download request failed: {e}"))?;
if !resp.status().is_success() {
return Err(format!("ROM download failed with HTTP {}", resp.status()));
}
let total = resp.content_length();
if let Some(parent) = dest_path.parent() {
tokio::fs::create_dir_all(parent)
.await
.map_err(|e| format!("Failed to create destination folder: {e}"))?;
}
let tmp_path = dest_path.with_extension("romm_part");
let mut file = tokio::fs::File::create(&tmp_path)
.await
.map_err(|e| format!("Failed to create file: {e}"))?;
let mut stream = resp.bytes_stream();
let mut downloaded: u64 = 0;
while let Some(chunk) = stream.next().await {
let bytes = chunk.map_err(|e| format!("Download stream error: {e}"))?;
file.write_all(&bytes)
.await
.map_err(|e| format!("Disk write error: {e}"))?;
downloaded += bytes.len() as u64;
on_progress(downloaded, total);
}
file.flush().await.map_err(|e| e.to_string())?;
drop(file);
tokio::fs::rename(&tmp_path, dest_path)
.await
.map_err(|e| format!("Failed to finalize downloaded ROM: {e}"))?;
Ok(())
}
// ---------- Saves & Sync Negotiation ----------
pub async fn get_saves(
&self,
rom_id: Option<i64>,
platform_id: Option<i64>,
device_id: Option<&str>,
) -> Result<Vec<SaveSchema>, String> {
let mut req = self.request(Method::GET, "/api/saves");
if let Some(id) = rom_id {
req = req.query(&[("rom_id", id.to_string())]);
}
if let Some(pid) = platform_id {
req = req.query(&[("platform_id", pid.to_string())]);
}
if let Some(did) = device_id {
req = req.query(&[("device_id", did.to_string())]);
}
let resp = req
.send()
.await
.map_err(|e| format!("Get saves failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn negotiate_sync(
&self,
device_id: Option<String>,
saves: Vec<ClientSaveState>,
) -> Result<SyncNegotiateResponse, String> {
let resp = self
.request(Method::POST, "/api/sync/negotiate")
.json(&SyncNegotiatePayload { device_id, saves })
.send()
.await
.map_err(|e| format!("Sync negotiate failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn upload_save(
&self,
rom_id: i64,
emulator: Option<&str>,
slot: Option<&str>,
device_id: Option<&str>,
session_id: Option<i64>,
overwrite: bool,
file_name: &str,
bytes: Vec<u8>,
) -> Result<SaveSchema, String> {
let mut req = self.request(Method::POST, "/api/saves").query(&[
("rom_id", rom_id.to_string()),
("overwrite", overwrite.to_string()),
]);
if let Some(e) = emulator {
req = req.query(&[("emulator", e)]);
}
if let Some(s) = slot {
req = req.query(&[("slot", s)]);
}
if let Some(d) = device_id {
req = req.query(&[("device_id", d)]);
}
if let Some(sid) = session_id {
req = req.query(&[("session_id", sid.to_string())]);
}
let part = Part::bytes(bytes)
.file_name(file_name.to_string())
.mime_str("application/octet-stream")
.map_err(|e| e.to_string())?;
let form = Form::new().part("saveFile", part);
let resp = req
.multipart(form)
.send()
.await
.map_err(|e| format!("Upload save failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn download_save_bytes(
&self,
save_id: i64,
device_id: Option<&str>,
session_id: Option<i64>,
) -> Result<Vec<u8>, String> {
let mut req = self.request(Method::GET, &format!("/api/saves/{}/content", save_id));
if let Some(d) = device_id {
req = req.query(&[("device_id", d)]);
}
if let Some(sid) = session_id {
req = req.query(&[("session_id", sid.to_string())]);
}
let resp = req
.send()
.await
.map_err(|e| format!("Download save failed: {e}"))?;
if !resp.status().is_success() {
return Err(format!("Download save failed: HTTP {}", resp.status()));
}
resp.bytes()
.await
.map(|b| b.to_vec())
.map_err(|e| format!("Failed reading save bytes: {e}"))
}
pub async fn confirm_save_downloaded(
&self,
save_id: i64,
device_id: &str,
) -> Result<(), String> {
let resp = self
.request(Method::POST, &format!("/api/saves/{}/downloaded", save_id))
.json(&ConfirmDownloadPayload {
device_id: device_id.to_string(),
})
.send()
.await
.map_err(|e| format!("Confirm download failed: {e}"))?;
if !resp.status().is_success() {
let status = resp.status();
let txt = resp.text().await.unwrap_or_default();
return Err(format!("Confirm download HTTP {}: {}", status, txt));
}
Ok(())
}
pub async fn complete_sync_session(
&self,
session_id: i64,
completed: i64,
failed: i64,
) -> Result<(), String> {
let resp = self
.request(
Method::POST,
&format!("/api/sync/sessions/{}/complete", session_id),
)
.json(&SyncCompletePayload {
operations_completed: completed,
operations_failed: failed,
})
.send()
.await
.map_err(|e| format!("Complete sync session failed: {e}"))?;
if !resp.status().is_success() {
let status = resp.status();
let txt = resp.text().await.unwrap_or_default();
return Err(format!("Complete sync session HTTP {}: {}", status, txt));
}
Ok(())
}
// ---------- Save States ----------
pub async fn get_states(
&self,
rom_id: Option<i64>,
platform_id: Option<i64>,
) -> Result<Vec<StateSchema>, String> {
let mut req = self.request(Method::GET, "/api/states");
if let Some(id) = rom_id {
req = req.query(&[("rom_id", id.to_string())]);
}
if let Some(pid) = platform_id {
req = req.query(&[("platform_id", pid.to_string())]);
}
let resp = req
.send()
.await
.map_err(|e| format!("Get states failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn upload_state(
&self,
rom_id: i64,
emulator: Option<&str>,
file_name: &str,
bytes: Vec<u8>,
) -> Result<StateSchema, String> {
let mut req = self
.request(Method::POST, "/api/states")
.query(&[("rom_id", rom_id.to_string())]);
if let Some(e) = emulator {
req = req.query(&[("emulator", e)]);
}
let part = Part::bytes(bytes)
.file_name(file_name.to_string())
.mime_str("application/octet-stream")
.map_err(|e| e.to_string())?;
let form = Form::new().part("stateFile", part);
let resp = req
.multipart(form)
.send()
.await
.map_err(|e| format!("Upload state failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn update_state(
&self,
state_id: i64,
file_name: &str,
bytes: Vec<u8>,
) -> Result<StateSchema, String> {
let part = Part::bytes(bytes)
.file_name(file_name.to_string())
.mime_str("application/octet-stream")
.map_err(|e| e.to_string())?;
let form = Form::new().part("stateFile", part);
let resp = self
.request(Method::PUT, &format!("/api/states/{}", state_id))
.multipart(form)
.send()
.await
.map_err(|e| format!("Update state failed: {e}"))?;
Self::parse_json(resp).await
}
pub async fn download_state_bytes(&self, state_id: i64) -> Result<Vec<u8>, String> {
let resp = self
.request(Method::GET, &format!("/api/states/{}/content", state_id))
.send()
.await
.map_err(|e| format!("Download state failed: {e}"))?;
if !resp.status().is_success() {
return Err(format!("Download state failed: HTTP {}", resp.status()));
}
resp.bytes()
.await
.map(|b| b.to_vec())
.map_err(|e| format!("Failed reading state bytes: {e}"))
}
}
fn urlencoding_path_segment(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char);
}
_ => {
out.push_str(&format!("%{:02X}", b));
}
}
}
out
}
+503
View File
@@ -0,0 +1,503 @@
use crate::config::{backups_dir, push_log, AppConfig};
use crate::matcher::{discover_saves_for_emulators, read_save_payload_and_hash, DiscoveredSaveItem};
use crate::romm_api::{ClientSaveState, RommClient, SimpleRomSchema};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use zip::ZipArchive;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncConflictItem {
pub id: String,
pub rom_id: i64,
pub rom_name: String,
pub save_id: Option<i64>,
pub local_path: String,
pub file_name: String,
pub is_directory: bool,
pub emulator_id: String,
pub slot: String,
pub local_updated_at: String,
pub server_updated_at: Option<String>,
pub reason: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncRunSummary {
pub session_id: Option<i64>,
pub uploaded_saves: usize,
pub downloaded_saves: usize,
pub uploaded_states: usize,
pub up_to_date: usize,
pub conflicts: Vec<SyncConflictItem>,
pub errors: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BackupEntry {
pub backup_path: String,
pub rom_id: String,
pub file_name: String,
pub created_at: String,
pub size_bytes: u64,
}
pub fn create_backup(
local_path: &Path,
rom_id: i64,
is_directory: bool,
max_backups: usize,
) -> Result<Option<PathBuf>, String> {
if !local_path.exists() {
return Ok(None);
}
let rom_backup_dir = backups_dir().join(rom_id.to_string());
fs::create_dir_all(&rom_backup_dir).map_err(|e| format!("Failed creating backup dir: {e}"))?;
let stamp = Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
let base_name = local_path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "save".to_string());
let dest = if is_directory {
let (zip_bytes, _) = read_save_payload_and_hash(local_path, true)?;
let zip_path = rom_backup_dir.join(format!("{}_{}.zip", stamp, base_name));
fs::write(&zip_path, zip_bytes).map_err(|e| format!("Backup write failed: {e}"))?;
zip_path
} else {
let copy_path = rom_backup_dir.join(format!("{}_{}", stamp, base_name));
fs::copy(local_path, &copy_path).map_err(|e| format!("Backup copy failed: {e}"))?;
copy_path
};
// Prune oldest backups beyond max_backups
if max_backups > 0 {
if let Ok(entries) = fs::read_dir(&rom_backup_dir) {
let mut files: Vec<PathBuf> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.is_file())
.collect();
files.sort();
if files.len() > max_backups {
let to_remove = files.len() - max_backups;
for old in files.into_iter().take(to_remove) {
let _ = fs::remove_file(old);
}
}
}
}
Ok(Some(dest))
}
pub fn write_downloaded_save(
dest_path: &Path,
bytes: &[u8],
is_directory: bool,
) -> Result<(), String> {
if is_directory {
fs::create_dir_all(dest_path).map_err(|e| format!("Failed creating save dir: {e}"))?;
let cursor = Cursor::new(bytes);
let mut archive =
ZipArchive::new(cursor).map_err(|e| format!("Downloaded archive is not a valid zip: {e}"))?;
for i in 0..archive.len() {
let mut file = archive.by_index(i).map_err(|e| e.to_string())?;
let Some(enclosed) = file.enclosed_name().map(|p| p.to_path_buf()) else {
continue;
};
let out_path = dest_path.join(enclosed);
if file.is_dir() {
fs::create_dir_all(&out_path).map_err(|e| e.to_string())?;
} else {
if let Some(parent) = out_path.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let mut out_file = fs::File::create(&out_path).map_err(|e| e.to_string())?;
std::io::copy(&mut file, &mut out_file).map_err(|e| e.to_string())?;
}
}
Ok(())
} else {
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
fs::write(dest_path, bytes).map_err(|e| format!("Failed writing save file: {e}"))
}
}
pub fn list_all_backups() -> Vec<BackupEntry> {
let root = backups_dir();
let mut out = Vec::new();
if let Ok(rom_dirs) = fs::read_dir(&root) {
for rom_dir in rom_dirs.flatten() {
if !rom_dir.path().is_dir() {
continue;
}
let rom_id = rom_dir.file_name().to_string_lossy().to_string();
if let Ok(files) = fs::read_dir(rom_dir.path()) {
for f in files.flatten() {
let p = f.path();
if !p.is_file() {
continue;
}
let meta = fs::metadata(&p).ok();
let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);
let created = meta
.and_then(|m| m.modified().ok())
.map(|t| chrono::DateTime::<Utc>::from(t).to_rfc3339())
.unwrap_or_default();
out.push(BackupEntry {
backup_path: p.to_string_lossy().to_string(),
rom_id: rom_id.clone(),
file_name: f.file_name().to_string_lossy().to_string(),
created_at: created,
size_bytes: size,
});
}
}
}
}
out.sort_by(|a, b| b.created_at.cmp(&a.created_at));
out
}
pub fn restore_backup_to_path(
backup_path: &Path,
target_path: &Path,
is_directory: bool,
) -> Result<(), String> {
let bytes = fs::read(backup_path).map_err(|e| format!("Failed reading backup: {e}"))?;
write_downloaded_save(target_path, &bytes, is_directory)
}
pub async fn run_sync(
client: &RommClient,
cfg: &mut AppConfig,
roms: &[SimpleRomSchema],
) -> Result<SyncRunSummary, String> {
let discovered = discover_saves_for_emulators(&cfg.emulators, roms, &cfg.manual_links);
let rom_by_id: HashMap<i64, &SimpleRomSchema> = roms.iter().map(|r| (r.id, r)).collect();
let mut summary = SyncRunSummary {
session_id: None,
uploaded_saves: 0,
downloaded_saves: 0,
uploaded_states: 0,
up_to_date: 0,
conflicts: Vec::new(),
errors: Vec::new(),
};
// Split matched saves vs matched states
let matched_saves: Vec<&DiscoveredSaveItem> = discovered
.iter()
.filter(|d| !d.is_state && d.matched_rom_id.is_some())
.collect();
let matched_states: Vec<&DiscoveredSaveItem> = discovered
.iter()
.filter(|d| d.is_state && d.matched_rom_id.is_some())
.collect();
// Map (rom_id, slot) -> (DiscoveredSaveItem, bytes, hash)
let mut local_save_map: HashMap<(i64, String), (&DiscoveredSaveItem, Vec<u8>, String)> =
HashMap::new();
let mut client_states: Vec<ClientSaveState> = Vec::new();
for item in matched_saves {
let Some(rom_id) = item.matched_rom_id else {
continue;
};
let path = Path::new(&item.local_path);
match read_save_payload_and_hash(path, item.is_directory) {
Ok((bytes, hash)) => {
let slot = if item.slot.trim().is_empty() {
"default".to_string()
} else {
item.slot.clone()
};
client_states.push(ClientSaveState {
rom_id,
file_name: item.file_name.clone(),
slot: Some(slot.clone()),
emulator: Some(item.emulator_id.clone()),
content_hash: Some(hash.clone()),
updated_at: item.updated_at.clone(),
file_size_bytes: bytes.len() as i64,
});
local_save_map.insert((rom_id, slot), (item, bytes, hash));
}
Err(e) => {
summary.errors.push(format!("{}: {}", item.file_name, e));
}
}
}
// 1. Negotiate two-way save sync with RomM 5.1.0
if !client_states.is_empty() || cfg.connection.device_id.is_some() {
let neg = client
.negotiate_sync(cfg.connection.device_id.clone(), client_states)
.await?;
summary.session_id = Some(neg.session_id);
let mut ops_completed = 0i64;
let mut ops_failed = 0i64;
for op in neg.operations {
let slot_key = op.slot.clone().unwrap_or_else(|| "default".to_string());
match op.action.as_str() {
"no_op" => {
summary.up_to_date += 1;
}
"upload" => {
if let Some((item, bytes, _hash)) = local_save_map.get(&(op.rom_id, slot_key.clone())) {
match client
.upload_save(
op.rom_id,
Some(&item.emulator_id),
Some(&slot_key),
cfg.connection.device_id.as_deref(),
Some(neg.session_id),
true,
&item.file_name,
bytes.clone(),
)
.await
{
Ok(_) => {
summary.uploaded_saves += 1;
ops_completed += 1;
push_log(
cfg,
"success",
"upload_save",
format!(
"Uploaded save '{}' for {}",
item.file_name,
item.matched_rom_name.as_deref().unwrap_or("ROM")
),
Some(op.rom_id),
Some(item.local_path.clone()),
);
}
Err(e) => {
ops_failed += 1;
summary.errors.push(format!("Upload {}: {}", item.file_name, e));
push_log(
cfg,
"error",
"upload_save",
format!("Failed uploading {}: {}", item.file_name, e),
Some(op.rom_id),
Some(item.local_path.clone()),
);
}
}
}
}
"download" => {
let Some(save_id) = op.save_id else {
continue;
};
// Determine local target path: either existing matched local file, or emulator save_dir
let target_info = local_save_map
.get(&(op.rom_id, slot_key.clone()))
.map(|(item, _, _)| (PathBuf::from(&item.local_path), item.is_directory))
.or_else(|| {
// Find enabled emulator matching op.emulator, or inherit from the ROM's platform slug
let matched_emu = op
.emulator
.as_ref()
.and_then(|emu_id| {
cfg.emulators
.iter()
.find(|e| e.enabled && e.id.eq_ignore_ascii_case(emu_id))
})
.or_else(|| {
rom_by_id.get(&op.rom_id).and_then(|rom| {
cfg.emulators.iter().find(|e| {
e.enabled
&& e.platform_slugs.iter().any(|s| {
s.eq_ignore_ascii_case(&rom.platform_slug)
|| s.eq_ignore_ascii_case(&rom.platform_fs_slug)
})
})
})
});
matched_emu.map(|e| {
let is_dir =
e.structure == crate::config::SaveStructure::FolderPerGame;
let target_path = if is_dir {
let trimmed = op
.file_name
.strip_suffix(".zip")
.unwrap_or(&op.file_name);
if e.folder_depth > 1 {
let parts: Vec<&str> =
trimmed.splitn(e.folder_depth, '_').collect();
let mut p = PathBuf::from(&e.save_dir);
for part in parts {
p.push(part);
}
p
} else {
PathBuf::from(&e.save_dir).join(trimmed)
}
} else {
PathBuf::from(&e.save_dir).join(&op.file_name)
};
(target_path, is_dir)
})
});
if let Some((target_path, is_dir)) = target_info {
match client
.download_save_bytes(
save_id,
cfg.connection.device_id.as_deref(),
Some(neg.session_id),
)
.await
{
Ok(bytes) => {
let _ = create_backup(
&target_path,
op.rom_id,
is_dir,
cfg.settings.max_backups_per_save,
);
match write_downloaded_save(&target_path, &bytes, is_dir) {
Ok(()) => {
if let Some(ref dev_id) = cfg.connection.device_id {
let _ = client
.confirm_save_downloaded(save_id, dev_id)
.await;
}
summary.downloaded_saves += 1;
ops_completed += 1;
push_log(
cfg,
"success",
"download_save",
format!("Downloaded '{}' (backup created)", op.file_name),
Some(op.rom_id),
Some(target_path.to_string_lossy().to_string()),
);
}
Err(e) => {
ops_failed += 1;
summary.errors.push(format!("Write {}: {}", op.file_name, e));
}
}
}
Err(e) => {
ops_failed += 1;
summary.errors.push(format!("Download {}: {}", op.file_name, e));
}
}
}
}
"conflict" => {
if let Some((item, _, _)) = local_save_map.get(&(op.rom_id, slot_key.clone())) {
let conflict = SyncConflictItem {
id: format!("{}:{}:{}", op.rom_id, slot_key, op.save_id.unwrap_or(0)),
rom_id: op.rom_id,
rom_name: item
.matched_rom_name
.clone()
.unwrap_or_else(|| format!("ROM #{}", op.rom_id)),
save_id: op.save_id,
local_path: item.local_path.clone(),
file_name: item.file_name.clone(),
is_directory: item.is_directory,
emulator_id: item.emulator_id.clone(),
slot: slot_key,
local_updated_at: item.updated_at.clone(),
server_updated_at: op.server_updated_at.clone(),
reason: op.reason.clone(),
};
push_log(
cfg,
"warning",
"conflict",
format!("Conflict detected for '{}': {}", item.file_name, op.reason),
Some(op.rom_id),
Some(item.local_path.clone()),
);
summary.conflicts.push(conflict);
}
}
_ => {}
}
}
let _ = client
.complete_sync_session(neg.session_id, ops_completed, ops_failed)
.await;
}
// 2. Sync Save States (/api/states) for changed local state files
for item in matched_states {
let Some(rom_id) = item.matched_rom_id else {
continue;
};
let path = Path::new(&item.local_path);
match read_save_payload_and_hash(path, false) {
Ok((bytes, hash)) => {
if cfg.synced_state_hashes.get(&item.local_path) == Some(&hash) {
summary.up_to_date += 1;
continue;
}
// Check if a remote state with same file_name exists for this ROM
let existing = client
.get_states(Some(rom_id), None)
.await
.unwrap_or_default()
.into_iter()
.find(|s| s.file_name.eq_ignore_ascii_case(&item.file_name));
let res = if let Some(remote_state) = existing {
client
.update_state(remote_state.id, &item.file_name, bytes)
.await
} else {
client
.upload_state(rom_id, Some(&item.emulator_id), &item.file_name, bytes)
.await
};
match res {
Ok(_) => {
cfg.synced_state_hashes.insert(item.local_path.clone(), hash);
summary.uploaded_states += 1;
push_log(
cfg,
"success",
"upload_state",
format!("Synced save state '{}'", item.file_name),
Some(rom_id),
Some(item.local_path.clone()),
);
}
Err(e) => {
summary
.errors
.push(format!("State {}: {}", item.file_name, e));
}
}
}
Err(e) => {
summary.errors.push(format!("State {}: {}", item.file_name, e));
}
}
}
Ok(summary)
}
+66
View File
@@ -0,0 +1,66 @@
use crate::config::EmulatorRule;
use notify_debouncer_mini::{new_debouncer, notify::RecursiveMode, DebounceEventResult, Debouncer};
use std::path::PathBuf;
use std::time::Duration;
use tauri::{AppHandle, Emitter};
pub struct WatcherHandle {
_debouncer: Debouncer<notify::RecommendedWatcher>,
pub watched_paths: Vec<String>,
}
pub fn start_watcher(
app: AppHandle,
emulators: &[EmulatorRule],
debounce_seconds: u64,
) -> Result<WatcherHandle, String> {
let debounce = Duration::from_secs(debounce_seconds.max(1));
let app_clone = app.clone();
let mut debouncer = new_debouncer(debounce, move |res: DebounceEventResult| {
if let Ok(events) = res {
let paths: Vec<String> = events
.into_iter()
.map(|e| e.path.to_string_lossy().to_string())
.filter(|p| !p.contains(".romm_part") && !p.contains(".DS_Store"))
.collect();
if !paths.is_empty() {
let _ = app_clone.emit("watcher:change", paths);
}
}
})
.map_err(|e| format!("Failed to initialize file watcher: {e}"))?;
let mut watched_paths = Vec::new();
for emu in emulators.iter().filter(|e| e.enabled) {
let save_p = PathBuf::from(&emu.save_dir);
if save_p.exists() {
if debouncer
.watcher()
.watch(&save_p, RecursiveMode::Recursive)
.is_ok()
{
watched_paths.push(emu.save_dir.clone());
}
}
if emu.sync_states {
if let Some(ref sdir) = emu.state_dir {
let state_p = PathBuf::from(sdir);
if state_p.exists() && sdir != &emu.save_dir {
if debouncer
.watcher()
.watch(&state_p, RecursiveMode::Recursive)
.is_ok()
{
watched_paths.push(sdir.clone());
}
}
}
}
}
Ok(WatcherHandle {
_debouncer: debouncer,
watched_paths,
})
}
+38
View File
@@ -0,0 +1,38 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "RomM Companion",
"version": "0.1.0",
"identifier": "com.romm.companion",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "npm run build",
"frontendDist": "../dist"
},
"app": {
"windows": [
{
"title": "RomM Companion",
"width": 1240,
"height": 820,
"minWidth": 960,
"minHeight": 640,
"resizable": true
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.ico",
"icons/icon.png"
]
}
}
+234
View File
@@ -0,0 +1,234 @@
import React, { useCallback, useEffect, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import {
FolderSync,
Gamepad2,
HardDrive,
LayoutDashboard,
Library,
Settings,
Usb,
} from "lucide-react";
import { api } from "./lib/tauri";
import type { AppStateSnapshot, DiscoveredSaveItem, SyncRunSummary } from "./lib/types";
import { OnboardingConnect } from "./components/OnboardingConnect";
import { Dashboard } from "./components/Dashboard";
import { EmulatorsView } from "./components/EmulatorsView";
import { LibraryView } from "./components/LibraryView";
import { SavesStatesView } from "./components/SavesStatesView";
import { HandheldView } from "./components/HandheldView";
import { SettingsView } from "./components/SettingsView";
type NavPage = "dashboard" | "emulators" | "handheld" | "library" | "saves" | "settings";
export default function App() {
const [appState, setAppState] = useState<AppStateSnapshot | null>(null);
const [page, setPage] = useState<NavPage>("dashboard");
const [discoveredSaves, setDiscoveredSaves] = useState<DiscoveredSaveItem[]>([]);
const [syncing, setSyncing] = useState(false);
const [lastSummary, setLastSummary] = useState<SyncRunSummary | null>(null);
const refreshAll = useCallback(async () => {
const snap = await api.getAppState();
setAppState(snap);
if (snap.connected) {
const saves = await api.discoverLocalSaves();
setDiscoveredSaves(saves);
}
}, []);
const handleSyncNow = useCallback(async () => {
setSyncing(true);
try {
const summary = await api.runFullSync();
setLastSummary(summary);
await refreshAll();
} catch (e) {
console.error("Sync failed:", e);
} finally {
setSyncing(false);
}
}, [refreshAll]);
useEffect(() => {
refreshAll();
}, [refreshAll]);
// Listen to file watcher & system tray events from Rust backend
useEffect(() => {
const unlistenWatcher = listen<string[]>("watcher:change", async () => {
const snap = await api.getAppState();
setAppState(snap);
if (snap.connected && snap.settings.autoSyncOnChange) {
await handleSyncNow();
} else if (snap.connected) {
const saves = await api.discoverLocalSaves();
setDiscoveredSaves(saves);
}
});
const unlistenTray = listen("tray:sync-now", async () => {
await handleSyncNow();
});
return () => {
unlistenWatcher.then((u) => u());
unlistenTray.then((u) => u());
};
}, [handleSyncNow]);
const handleConnected = async () => {
await api.refreshRomCache().catch(() => {});
await refreshAll();
};
const handleAutoDetect = async () => {
await api.autoPopulateDetectedEmulators();
await refreshAll();
};
const handleResolveConflict = async (
id: string,
resolution: "keep_local" | "keep_server"
) => {
await api.resolveSyncConflict(id, resolution);
await refreshAll();
};
const handleClearLogs = async () => {
await api.clearSyncLogs();
await refreshAll();
};
const handleDisconnect = async () => {
const snap = await api.disconnect();
setAppState(snap);
setDiscoveredSaves([]);
setLastSummary(null);
};
if (!appState) {
return (
<div className="min-h-screen flex items-center justify-center bg-slate-950 text-slate-400 text-sm">
Loading RomM Companion...
</div>
);
}
if (!appState.connected) {
return (
<OnboardingConnect
initialServerUrl={appState.serverUrl}
initialDeviceName={appState.deviceName}
onConnected={handleConnected}
/>
);
}
const navItems: { id: NavPage; label: string; icon: React.ComponentType<{ className?: string }> }[] =
[
{ id: "dashboard", label: "Dashboard", icon: LayoutDashboard },
{ id: "emulators", label: "Emulators", icon: HardDrive },
{ id: "handheld", label: "NextUI USB / SD", icon: Usb },
{ id: "saves", label: "Saves & States", icon: FolderSync },
{ id: "library", label: "ROM Library", icon: Library },
{ id: "settings", label: "Settings", icon: Settings },
];
return (
<div className="min-h-screen flex bg-slate-950 text-slate-100">
{/* Sidebar */}
<aside className="w-60 shrink-0 border-r border-slate-800/90 bg-slate-900/50 p-4 flex flex-col justify-between">
<div className="space-y-6">
<div className="flex items-center gap-2.5 px-2">
<div className="w-9 h-9 rounded-xl bg-indigo-600/20 border border-indigo-500/40 flex items-center justify-center text-indigo-400">
<Gamepad2 className="w-5 h-5" />
</div>
<div className="min-w-0">
<div className="font-bold text-sm tracking-tight">RomM Companion</div>
<div className="text-[11px] text-slate-500 truncate">RomM 5.1.0 Sync</div>
</div>
</div>
<nav className="space-y-1">
{navItems.map((item) => {
const Icon = item.icon;
const active = page === item.id;
return (
<button
key={item.id}
onClick={() => setPage(item.id)}
className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm font-medium transition cursor-pointer ${
active
? "bg-indigo-600 text-white shadow-sm"
: "text-slate-400 hover:text-slate-100 hover:bg-slate-800/60"
}`}
>
<Icon className="w-4 h-4" />
<span>{item.label}</span>
{item.id === "dashboard" && appState.conflicts.length > 0 && (
<span className="ml-auto text-[10px] px-1.5 py-0.5 rounded-full bg-amber-500 text-slate-950 font-bold">
{appState.conflicts.length}
</span>
)}
</button>
);
})}
</nav>
</div>
<div className="p-3 rounded-xl bg-slate-900 border border-slate-800 text-xs space-y-1">
<div className="flex items-center gap-1.5">
<span
className={`w-2 h-2 rounded-full ${
appState.watcherActive ? "bg-emerald-400" : "bg-slate-500"
}`}
/>
<span className="font-medium text-slate-200 truncate">
{appState.username || "Connected"}
</span>
</div>
<div className="text-[11px] text-slate-500 truncate">{appState.serverUrl}</div>
</div>
</aside>
{/* Main Content */}
<main className="flex-1 p-7 overflow-y-auto">
{page === "dashboard" && (
<Dashboard
appState={appState}
discoveredSaves={discoveredSaves}
syncing={syncing}
lastSummary={lastSummary}
onSyncNow={handleSyncNow}
onResolveConflict={handleResolveConflict}
onClearLogs={handleClearLogs}
onAutoDetect={handleAutoDetect}
/>
)}
{page === "emulators" && (
<EmulatorsView emulators={appState.emulators} onRefreshState={refreshAll} />
)}
{page === "handheld" && <HandheldView onRefreshState={refreshAll} />}
{page === "saves" && (
<SavesStatesView discoveredSaves={discoveredSaves} onRefreshSaves={refreshAll} />
)}
{page === "library" && (
<LibraryView
defaultDownloadDir={appState.settings.defaultRomDownloadDir}
emulators={appState.emulators}
discoveredSaves={discoveredSaves}
onRefreshAll={refreshAll}
/>
)}
{page === "settings" && (
<SettingsView
appState={appState}
onRefreshState={refreshAll}
onDisconnect={handleDisconnect}
/>
)}
</main>
</div>
);
}
+247
View File
@@ -0,0 +1,247 @@
import React from "react";
import {
AlertTriangle,
CheckCircle2,
CloudDownload,
CloudUpload,
Eye,
FolderSync,
HardDrive,
Loader2,
RefreshCw,
Trash2,
} from "lucide-react";
import type { AppStateSnapshot, DiscoveredSaveItem, SyncRunSummary } from "../lib/types";
interface Props {
appState: AppStateSnapshot;
discoveredSaves: DiscoveredSaveItem[];
syncing: boolean;
lastSummary: SyncRunSummary | null;
onSyncNow: () => void;
onResolveConflict: (id: string, resolution: "keep_local" | "keep_server") => void;
onClearLogs: () => void;
onAutoDetect: () => void;
}
export const Dashboard: React.FC<Props> = ({
appState,
discoveredSaves,
syncing,
lastSummary,
onSyncNow,
onResolveConflict,
onClearLogs,
onAutoDetect,
}) => {
const matchedCount = discoveredSaves.filter((s) => s.matchedRomId !== null).length;
const enabledEmulators = appState.emulators.filter((e) => e.enabled).length;
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight">Dashboard</h2>
<p className="text-sm text-slate-400">
Connected to <span className="text-slate-200">{appState.serverUrl}</span> as{" "}
<span className="text-indigo-400 font-medium">{appState.username}</span>
</p>
</div>
<div className="flex items-center gap-2.5">
{appState.emulators.length === 0 && (
<button
onClick={onAutoDetect}
className="px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-sm font-medium transition cursor-pointer"
>
Auto-Detect Emulators
</button>
)}
<button
onClick={onSyncNow}
disabled={syncing}
className="px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium flex items-center gap-2 shadow-lg shadow-indigo-950/50 transition cursor-pointer disabled:opacity-50"
>
{syncing ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<RefreshCw className="w-4 h-4" />
)}
{syncing ? "Syncing..." : "Sync Saves & States"}
</button>
</div>
</div>
{/* Stat Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800">
<div className="flex items-center justify-between text-slate-400 text-xs font-medium mb-2">
<span>ACTIVE EMULATORS</span>
<HardDrive className="w-4 h-4 text-indigo-400" />
</div>
<div className="text-2xl font-bold">{enabledEmulators}</div>
<div className="text-xs text-slate-500 mt-1">
{appState.emulators.length} configured rules
</div>
</div>
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800">
<div className="flex items-center justify-between text-slate-400 text-xs font-medium mb-2">
<span>MATCHED SAVES / STATES</span>
<FolderSync className="w-4 h-4 text-emerald-400" />
</div>
<div className="text-2xl font-bold">
{matchedCount}{" "}
<span className="text-sm font-normal text-slate-500">/ {discoveredSaves.length}</span>
</div>
<div className="text-xs text-slate-500 mt-1">
{appState.cachedRomCount} ROMs indexed from RomM
</div>
</div>
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800">
<div className="flex items-center justify-between text-slate-400 text-xs font-medium mb-2">
<span>FILE WATCHER</span>
<Eye
className={`w-4 h-4 ${appState.watcherActive ? "text-emerald-400" : "text-slate-500"}`}
/>
</div>
<div className="text-2xl font-bold">
{appState.watcherActive ? "Active" : "Paused"}
</div>
<div className="text-xs text-slate-500 mt-1">
Watching {appState.watchedPaths.length} folder(s)
</div>
</div>
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800">
<div className="flex items-center justify-between text-slate-400 text-xs font-medium mb-2">
<span>CONFLICTS</span>
<AlertTriangle
className={`w-4 h-4 ${appState.conflicts.length > 0 ? "text-amber-400" : "text-slate-500"}`}
/>
</div>
<div className="text-2xl font-bold">{appState.conflicts.length}</div>
<div className="text-xs text-slate-500 mt-1">
{appState.conflicts.length === 0 ? "All saves clean" : "Needs your decision"}
</div>
</div>
</div>
{/* Last Sync Summary Banner */}
{lastSummary && (
<div className="p-4 rounded-xl bg-indigo-950/40 border border-indigo-500/30 flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2.5 text-sm">
<CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
<span>
Last sync completed: <strong>{lastSummary.uploadedSaves}</strong> saves uploaded,{" "}
<strong>{lastSummary.downloadedSaves}</strong> downloaded,{" "}
<strong>{lastSummary.uploadedStates}</strong> states synced,{" "}
<strong>{lastSummary.upToDate}</strong> already up to date.
</span>
</div>
{lastSummary.errors.length > 0 && (
<span className="text-xs text-rose-300">
{lastSummary.errors.length} error(s) — check log below
</span>
)}
</div>
)}
{/* Pending Conflicts */}
{appState.conflicts.length > 0 && (
<div className="space-y-3">
<h3 className="text-sm font-semibold uppercase tracking-wider text-amber-400 flex items-center gap-2">
<AlertTriangle className="w-4 h-4" /> Save Conflicts Requiring Resolution
</h3>
<div className="space-y-2.5">
{appState.conflicts.map((c) => (
<div
key={c.id}
className="p-4 rounded-xl bg-amber-950/25 border border-amber-500/40 flex flex-wrap items-center justify-between gap-4"
>
<div className="space-y-1">
<div className="font-semibold text-sm">
{c.romName}{" "}
<span className="text-xs font-normal text-slate-400">
({c.fileName} • slot: {c.slot})
</span>
</div>
<div className="text-xs text-slate-400">{c.reason}</div>
<div className="text-xs text-slate-500">
Local: {new Date(c.localUpdatedAt).toLocaleString()} | Server:{" "}
{c.serverUpdatedAt ? new Date(c.serverUpdatedAt).toLocaleString() : "Unknown"}
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => onResolveConflict(c.id, "keep_local")}
className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<CloudUpload className="w-3.5 h-3.5" /> Keep Local (Upload)
</button>
<button
onClick={() => onResolveConflict(c.id, "keep_server")}
className="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<CloudDownload className="w-3.5 h-3.5" /> Keep Server (Backup Local)
</button>
</div>
</div>
))}
</div>
</div>
)}
{/* Activity Log */}
<div className="rounded-xl bg-slate-900/80 border border-slate-800 overflow-hidden">
<div className="px-4 py-3 border-b border-slate-800 flex items-center justify-between">
<h3 className="text-sm font-semibold">Recent Sync Activity</h3>
{appState.logs.length > 0 && (
<button
onClick={onClearLogs}
className="text-xs text-slate-400 hover:text-slate-200 flex items-center gap-1 cursor-pointer"
>
<Trash2 className="w-3.5 h-3.5" /> Clear
</button>
)}
</div>
<div className="divide-y divide-slate-800/70 max-h-80 overflow-y-auto">
{appState.logs.length === 0 ? (
<div className="p-6 text-center text-sm text-slate-500">
No sync activity yet. Configure an emulator and click <strong>Sync Saves & States</strong>.
</div>
) : (
appState.logs.slice(0, 50).map((log) => (
<div key={log.id} className="px-4 py-2.5 flex items-start justify-between gap-3 text-xs">
<div className="flex items-start gap-2.5">
<span
className={`mt-1 w-2 h-2 rounded-full shrink-0 ${
log.level === "success"
? "bg-emerald-400"
: log.level === "warning"
? "bg-amber-400"
: log.level === "error"
? "bg-rose-400"
: "bg-sky-400"
}`}
/>
<div>
<div className="text-slate-200">{log.message}</div>
{log.filePath && (
<div className="text-[11px] text-slate-500 font-mono truncate max-w-xl">
{log.filePath}
</div>
)}
</div>
</div>
<span className="text-slate-500 shrink-0">
{new Date(log.timestamp).toLocaleTimeString()}
</span>
</div>
))
)}
</div>
</div>
</div>
);
};
+487
View File
@@ -0,0 +1,487 @@
import React, { useEffect, useState } from "react";
import {
CheckCircle2,
FolderOpen,
Plus,
Sparkles,
Trash2,
X,
} from "lucide-react";
import { api } from "../lib/tauri";
import type { EmulatorPresetInfo, EmulatorRule, SaveStructure } from "../lib/types";
interface Props {
emulators: EmulatorRule[];
onRefreshState: () => Promise<void>;
}
export const EmulatorsView: React.FC<Props> = ({ emulators, onRefreshState }) => {
const [presets, setPresets] = useState<EmulatorPresetInfo[]>([]);
const [editing, setEditing] = useState<EmulatorRule | null>(null);
const [extInput, setExtInput] = useState("");
const [stateExtInput, setStateExtInput] = useState("");
const [slugInput, setSlugInput] = useState("");
useEffect(() => {
api.getEmulatorPresets().then(setPresets).catch(console.error);
}, []);
const openEditor = (rule: EmulatorRule) => {
setEditing({ ...rule });
setExtInput(rule.saveExtensions.join(", "));
setStateExtInput(rule.stateExtensions.join(", "));
setSlugInput(rule.platformSlugs.join(", "));
};
const handleAddPreset = async (p: EmulatorPresetInfo) => {
const rule: EmulatorRule = {
id: p.id,
name: p.name,
platformSlugs: p.platformSlugs,
saveDir: p.detectedSaveDir || p.defaultSaveDir,
stateDir: p.detectedStateDir || p.defaultStateDir,
romDir: null,
saveExtensions: p.saveExtensions,
stateExtensions: p.stateExtensions,
structure: p.structure,
folderDepth: p.folderDepth || 1,
enabled: true,
isCustom: false,
syncStates: Boolean(p.detectedStateDir || p.defaultStateDir),
defaultSlot: "default",
};
openEditor(rule);
};
const handleNewCustom = () => {
openEditor({
id: `custom-${Date.now()}`,
name: "Custom Emulator",
platformSlugs: [],
saveDir: "",
stateDir: null,
romDir: null,
saveExtensions: ["sav", "srm"],
stateExtensions: ["state"],
structure: "file_per_game",
folderDepth: 1,
enabled: true,
isCustom: true,
syncStates: false,
defaultSlot: "default",
});
};
const handleSaveRule = async (e: React.FormEvent) => {
e.preventDefault();
if (!editing) return;
const cleaned: EmulatorRule = {
...editing,
saveExtensions: extInput
.split(",")
.map((s) => s.trim().replace(/^\./, ""))
.filter(Boolean),
stateExtensions: stateExtInput
.split(",")
.map((s) => s.trim().replace(/^\./, ""))
.filter(Boolean),
platformSlugs: slugInput
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean),
};
await api.upsertEmulatorRule(cleaned);
setEditing(null);
await onRefreshState();
};
const handleToggleEnabled = async (rule: EmulatorRule) => {
await api.upsertEmulatorRule({ ...rule, enabled: !rule.enabled });
await onRefreshState();
};
const handleDelete = async (id: string) => {
await api.deleteEmulatorRule(id);
await onRefreshState();
};
const handleAutoDetectAll = async () => {
await api.autoPopulateDetectedEmulators();
await onRefreshState();
};
const configuredIds = new Set(emulators.map((e) => e.id));
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight">Emulators & Save Rules</h2>
<p className="text-sm text-slate-400">
Auto-detect standalone console & handheld emulators or define custom save folders.
</p>
</div>
<div className="flex items-center gap-2">
<button
onClick={handleAutoDetectAll}
className="px-3.5 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-sm font-medium flex items-center gap-2 cursor-pointer"
>
<Sparkles className="w-4 h-4 text-indigo-400" /> Auto-Add Detected
</button>
<button
onClick={handleNewCustom}
className="px-3.5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium flex items-center gap-2 cursor-pointer"
>
<Plus className="w-4 h-4" /> Custom Rule
</button>
</div>
</div>
{/* Configured Rules */}
<div className="space-y-3">
<h3 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
Configured Rules ({emulators.length})
</h3>
{emulators.length === 0 ? (
<div className="p-6 rounded-xl bg-slate-900/60 border border-dashed border-slate-800 text-center text-sm text-slate-400">
No emulators configured yet. Click <strong>Auto-Add Detected</strong> or pick a preset
below.
</div>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{emulators.map((rule) => (
<div
key={rule.id}
className="p-4 rounded-xl bg-slate-900/90 border border-slate-800 flex flex-col justify-between gap-3"
>
<div className="flex items-start justify-between gap-3">
<div>
<div className="flex items-center gap-2">
<span className="font-semibold text-sm">{rule.name}</span>
<span className="text-[11px] px-2 py-0.5 rounded-full bg-slate-800 text-slate-300">
{rule.structure.replace(/_/g, " ")}
</span>
</div>
<div className="text-xs text-slate-400 font-mono mt-1 break-all">
Saves: {rule.saveDir || "(not set)"}
</div>
{rule.romDir && (
<div className="text-xs text-emerald-400/90 font-mono break-all">
ROMs: {rule.romDir}
</div>
)}
{rule.syncStates && rule.stateDir && (
<div className="text-xs text-slate-500 font-mono break-all">
States: {rule.stateDir}
</div>
)}
</div>
<label className="inline-flex items-center cursor-pointer">
<input
type="checkbox"
checked={rule.enabled}
onChange={() => handleToggleEnabled(rule)}
className="sr-only peer"
/>
<div className="w-9 h-5 bg-slate-700 rounded-full peer peer-checked:bg-indigo-600 relative after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />
</label>
</div>
<div className="flex items-center justify-between pt-2 border-t border-slate-800/80">
<div className="flex flex-wrap gap-1">
{rule.platformSlugs.map((slug) => (
<span
key={slug}
className="text-[10px] uppercase px-1.5 py-0.5 rounded bg-indigo-950/70 text-indigo-300 border border-indigo-500/20"
>
{slug}
</span>
))}
</div>
<div className="flex items-center gap-2">
<button
onClick={() => openEditor(rule)}
className="text-xs text-indigo-400 hover:text-indigo-300 font-medium cursor-pointer"
>
Edit
</button>
<button
onClick={() => handleDelete(rule.id)}
className="text-xs text-slate-500 hover:text-rose-400 cursor-pointer"
title="Remove rule"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
</div>
</div>
))}
</div>
)}
</div>
{/* Presets Catalog */}
<div className="space-y-3">
<h3 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
Built-In Emulator Presets
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{presets.map((p) => {
const added = configuredIds.has(p.id);
return (
<div
key={p.id}
className="p-4 rounded-xl bg-slate-900/60 border border-slate-800/90 flex flex-col justify-between gap-3"
>
<div>
<div className="flex items-center justify-between gap-2">
<span className="font-medium text-sm">{p.name}</span>
{p.detected ? (
<span className="inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-emerald-950/70 text-emerald-300 border border-emerald-500/30">
<CheckCircle2 className="w-3 h-3" /> Detected
</span>
) : (
<span className="text-[11px] px-2 py-0.5 rounded-full bg-slate-800 text-slate-400">
Not found
</span>
)}
</div>
<p className="text-xs text-slate-400 mt-1.5 leading-relaxed">{p.notes}</p>
</div>
<div className="flex items-center justify-between">
<span className="text-[11px] text-slate-500 capitalize">{p.category}</span>
<button
onClick={() => handleAddPreset(p)}
className={`px-3 py-1 rounded-lg text-xs font-medium cursor-pointer transition ${
added
? "bg-slate-800 text-slate-300 hover:bg-slate-700"
: "bg-indigo-600/20 text-indigo-300 border border-indigo-500/30 hover:bg-indigo-600/30"
}`}
>
{added ? "Reconfigure" : "+ Add Preset"}
</button>
</div>
</div>
);
})}
</div>
</div>
{/* Edit Modal */}
{editing && (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
<form
onSubmit={handleSaveRule}
className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-4 shadow-2xl max-h-[90vh] overflow-y-auto"
>
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Configure Emulator Rule</h3>
<button
type="button"
onClick={() => setEditing(null)}
className="text-slate-400 hover:text-white cursor-pointer"
>
<X className="w-5 h-5" />
</button>
</div>
<div className="space-y-3">
<div>
<label className="block text-xs text-slate-400 mb-1">Display Name</label>
<input
required
value={editing.name}
onChange={(e) => setEditing({ ...editing, name: e.target.value })}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">Save Directory</label>
<div className="flex gap-2">
<input
required
value={editing.saveDir}
onChange={(e) => setEditing({ ...editing, saveDir: e.target.value })}
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
type="button"
onClick={async () => {
const dir = await api.pickFolder("Select Save Directory");
if (dir) setEditing({ ...editing, saveDir: dir });
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs flex items-center gap-1 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Browse
</button>
</div>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">
ROMs Directory (games for this platform download here automatically)
</label>
<div className="flex gap-2">
<input
value={editing.romDir || ""}
onChange={(e) => setEditing({ ...editing, romDir: e.target.value || null })}
placeholder="Optional — e.g. ~/ROMs/GameCube"
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
type="button"
onClick={async () => {
const dir = await api.pickFolder("Select ROMs Directory for This Emulator");
if (dir) setEditing({ ...editing, romDir: dir });
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs flex items-center gap-1 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Browse
</button>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs text-slate-400 mb-1">Save Layout</label>
<select
value={editing.structure}
onChange={(e) =>
setEditing({ ...editing, structure: e.target.value as SaveStructure })
}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
>
<option value="file_per_game">File per game (.sav, .mcd)</option>
<option value="folder_per_game">Folder per game (zipped)</option>
<option value="memory_card">Memory card (.ps2, .raw)</option>
</select>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">Default RomM Slot</label>
<input
value={editing.defaultSlot}
onChange={(e) => setEditing({ ...editing, defaultSlot: e.target.value })}
placeholder="default"
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
</div>
{editing.structure === "folder_per_game" && (
<div>
<label className="block text-xs text-slate-400 mb-1">
Nested Folder Depth (1 = direct subfolders, 2 = Cemu high/low, 5 = 3DS title tree)
</label>
<input
type="number"
min={1}
max={6}
value={editing.folderDepth || 1}
onChange={(e) =>
setEditing({
...editing,
folderDepth: Math.max(1, Math.min(6, Number(e.target.value) || 1)),
})
}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
)}
<div>
<label className="block text-xs text-slate-400 mb-1">
RomM Platform Slugs (comma-separated, e.g. ps2, ngc, wii, switch)
</label>
<input
value={slugInput}
onChange={(e) => setSlugInput(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">
Save Extensions (comma-separated, empty = all files/folders)
</label>
<input
value={extInput}
onChange={(e) => setExtInput(e.target.value)}
placeholder="sav, srm, gci, mcd"
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
</div>
<div className="pt-2 border-t border-slate-800 space-y-2.5">
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input
type="checkbox"
checked={editing.syncStates}
onChange={(e) => setEditing({ ...editing, syncStates: e.target.checked })}
className="rounded border-slate-700"
/>
Also sync Save States (/api/states)
</label>
{editing.syncStates && (
<>
<div>
<label className="block text-xs text-slate-400 mb-1">
Save States Directory
</label>
<div className="flex gap-2">
<input
value={editing.stateDir || ""}
onChange={(e) =>
setEditing({ ...editing, stateDir: e.target.value || null })
}
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
type="button"
onClick={async () => {
const dir = await api.pickFolder("Select Save States Directory");
if (dir) setEditing({ ...editing, stateDir: dir });
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs flex items-center gap-1 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Browse
</button>
</div>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">
State Extensions (comma-separated)
</label>
<input
value={stateExtInput}
onChange={(e) => setStateExtInput(e.target.value)}
placeholder="p2s, ppst, s01, ss0, sav"
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
</div>
</>
)}
</div>
</div>
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
onClick={() => setEditing(null)}
className="px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-sm cursor-pointer"
>
Cancel
</button>
<button
type="submit"
className="px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium cursor-pointer"
>
Save Rule
</button>
</div>
</form>
</div>
)}
</div>
);
};
+574
View File
@@ -0,0 +1,574 @@
import React, { useCallback, useEffect, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import {
Archive,
CheckCircle2,
Download,
Folder,
FolderOpen,
HardDrive,
Link2,
Loader2,
RefreshCw,
Search,
Usb,
X,
} from "lucide-react";
import { api } from "../lib/tauri";
import {
formatBytes,
type DetectedNextUiVolume,
type NextUiCardInspection,
type NextUiSdSaveItem,
type PlatformSchema,
type SimpleRomSchema,
type SyncRunSummary,
} from "../lib/types";
interface Props {
onRefreshState: () => Promise<void>;
}
export const HandheldView: React.FC<Props> = ({ onRefreshState }) => {
const [volumes, setVolumes] = useState<DetectedNextUiVolume[]>([]);
const [selectedRoot, setSelectedRoot] = useState<string>("");
const [inspection, setInspection] = useState<NextUiCardInspection | null>(null);
const [syncStates, setSyncStates] = useState(true);
const [syncing, setSyncing] = useState(false);
const [lastSummary, setLastSummary] = useState<SyncRunSummary | null>(null);
const [toast, setToast] = useState<string | null>(null);
const [subTab, setSubTab] = useState<"saves" | "roms">("saves");
// Manual save linking
const [linkingItem, setLinkingItem] = useState<NextUiSdSaveItem | null>(null);
const [linkSearch, setLinkSearch] = useState("");
const [linkResults, setLinkResults] = useState<SimpleRomSchema[]>([]);
// Send ROMs to SD card
const [platforms, setPlatforms] = useState<PlatformSchema[]>([]);
const [selectedPlatform, setSelectedPlatform] = useState<number | null>(null);
const [romSearch, setRomSearch] = useState("");
const [roms, setRoms] = useState<SimpleRomSchema[]>([]);
const [loadingRoms, setLoadingRoms] = useState(false);
const [downloadingId, setDownloadingId] = useState<number | null>(null);
const [downloadPct, setDownloadPct] = useState(0);
const scanVolumes = useCallback(async () => {
const vols = await api.detectNextUiVolumes();
setVolumes(vols);
if (vols.length > 0 && !selectedRoot) {
setSelectedRoot(vols[0].path);
}
}, [selectedRoot]);
const inspectCard = useCallback(async (root: string) => {
if (!root) {
setInspection(null);
return;
}
const info = await api.inspectNextUiCard(root);
setInspection(info);
}, []);
useEffect(() => {
scanVolumes();
api.fetchPlatforms().then(setPlatforms).catch(() => {});
const unlistenPromise = listen<{ romId: number; downloaded: number; total: number | null }>(
"rom:download-progress",
(event) => {
const { romId, downloaded, total } = event.payload;
setDownloadingId(romId);
if (total && total > 0) {
setDownloadPct(Math.round((downloaded / total) * 100));
}
}
);
return () => {
unlistenPromise.then((u) => u());
};
}, [scanVolumes]);
useEffect(() => {
if (selectedRoot) {
inspectCard(selectedRoot);
}
}, [selectedRoot, inspectCard]);
const loadRoms = useCallback(async () => {
setLoadingRoms(true);
try {
const page = await api.fetchRoms({
platformId: selectedPlatform,
searchTerm: romSearch || null,
limit: 80,
offset: 0,
});
setRoms(page.items);
} catch (e) {
setToast(String(e));
} finally {
setLoadingRoms(false);
}
}, [selectedPlatform, romSearch]);
useEffect(() => {
if (subTab === "roms") {
loadRoms();
}
}, [subTab, selectedPlatform, loadRoms]);
const handleBrowseSd = async () => {
const picked = await api.pickFolder("Select Mounted NextUI SD Card Root");
if (picked) {
setSelectedRoot(picked);
}
};
const handleSyncCard = async () => {
if (!selectedRoot) return;
setSyncing(true);
setToast(null);
try {
const summary = await api.syncNextUiCard(selectedRoot, syncStates);
setLastSummary(summary);
await inspectCard(selectedRoot);
await onRefreshState();
} catch (e) {
setToast(`Sync failed: ${e}`);
} finally {
setSyncing(false);
}
};
const handleSendRom = async (rom: SimpleRomSchema) => {
if (!selectedRoot) return;
setDownloadingId(rom.id);
setDownloadPct(0);
setToast(null);
try {
const dest = await api.downloadRomToNextUi({
sdRoot: selectedRoot,
romId: rom.id,
fileName: rom.fs_name,
platformSlug: rom.platform_slug,
platformDisplayName: rom.platform_display_name,
});
setToast(`Sent to SD card: ${dest}`);
await inspectCard(selectedRoot);
} catch (e) {
setToast(`Transfer failed: ${e}`);
} finally {
setDownloadingId(null);
setDownloadPct(0);
}
};
const openLinker = async (item: NextUiSdSaveItem) => {
setLinkingItem(item);
setLinkSearch("");
const page = await api.fetchRoms({ limit: 30, offset: 0 });
setLinkResults(page.items);
};
const handleLink = async (rom: SimpleRomSchema) => {
if (!linkingItem) return;
await api.linkSaveToRom({
localPath: linkingItem.localPath,
romId: rom.id,
romName: rom.name || rom.fs_name_no_ext,
emulatorId: `nextui-${linkingItem.systemTag.toLowerCase()}`,
slot: linkingItem.slot || "default",
isState: linkingItem.isState,
});
setLinkingItem(null);
if (selectedRoot) await inspectCard(selectedRoot);
};
const matchedCount = inspection
? inspection.saves.filter((s) => s.matchedRomId !== null).length
: 0;
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight flex items-center gap-2.5">
<Usb className="w-6 h-6 text-indigo-400" />
NextUI Handheld (USB / SD Card)
</h2>
<p className="text-sm text-slate-400">
Sync saves, states, and ROMs with your TrimUI Smart Pro S / Brick over USB Storage or
an SD card reader — no handheld Wi-Fi needed.
</p>
</div>
<div className="flex items-center gap-2">
<button
onClick={scanVolumes}
className="px-3.5 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<RefreshCw className="w-3.5 h-3.5" /> Rescan Drives
</button>
<button
onClick={handleBrowseSd}
className="px-3.5 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Select SD Folder
</button>
</div>
</div>
{/* Detected Drives Strip */}
{volumes.length > 0 && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{volumes.map((v) => {
const active = selectedRoot === v.path;
return (
<button
key={v.path}
onClick={() => setSelectedRoot(v.path)}
className={`text-left p-4 rounded-xl border transition cursor-pointer ${
active
? "bg-indigo-950/40 border-indigo-500/60"
: "bg-slate-900/80 border-slate-800 hover:border-slate-700"
}`}
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 font-semibold text-sm">
<HardDrive className="w-4 h-4 text-emerald-400" />
{v.label}
</div>
<span className="text-[11px] px-2 py-0.5 rounded-full bg-indigo-950 text-indigo-300 border border-indigo-500/30">
{v.detectedPlatform}
</span>
</div>
<div className="text-xs text-slate-400 mt-1">{v.deviceLabel}</div>
<div className="text-[11px] font-mono text-slate-500 mt-1 truncate">{v.path}</div>
</button>
);
})}
</div>
)}
{!inspection ? (
<div className="p-8 rounded-2xl bg-slate-900/70 border border-dashed border-slate-800 text-center space-y-3">
<Usb className="w-8 h-8 text-slate-500 mx-auto" />
<div className="text-sm font-medium text-slate-300">No NextUI SD card selected</div>
<p className="text-xs text-slate-500 max-w-md mx-auto">
Plug your TrimUI Smart Pro S into your computer in <strong>USB Storage</strong> mode (or
insert its microSD card), then click <strong>Rescan Drives</strong> or{" "}
<strong>Select SD Folder</strong>.
</p>
</div>
) : (
<>
{/* Active SD Card Summary & Sync Action */}
<div className="p-5 rounded-2xl bg-slate-900/90 border border-slate-800 flex flex-wrap items-center justify-between gap-4">
<div className="space-y-1.5">
<div className="flex items-center gap-2">
<span className="font-semibold text-base">{inspection.deviceName}</span>
<span className="text-[11px] uppercase px-2 py-0.5 rounded-full bg-emerald-950 text-emerald-300 border border-emerald-500/30">
{inspection.detectedPlatform}
</span>
</div>
<div className="text-xs text-slate-400 font-mono">{inspection.sdRoot}</div>
<div className="flex flex-wrap gap-1.5 pt-1">
{inspection.systemTags.map((tag) => (
<span
key={tag}
className="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 font-mono"
>
{tag}
</span>
))}
</div>
</div>
<div className="flex flex-col items-end gap-2">
<button
onClick={handleSyncCard}
disabled={syncing}
className="px-4 py-2.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium flex items-center gap-2 shadow-lg shadow-indigo-950/50 transition cursor-pointer disabled:opacity-50"
>
{syncing ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<RefreshCw className="w-4 h-4" />
)}
{syncing ? "Syncing SD Card..." : "Sync SD Card with RomM"}
</button>
<label className="flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer">
<input
type="checkbox"
checked={syncStates}
onChange={(e) => setSyncStates(e.target.checked)}
/>
Also sync Save States (/api/states)
</label>
</div>
</div>
{lastSummary && (
<div className="p-3.5 rounded-xl bg-indigo-950/40 border border-indigo-500/30 text-sm flex items-center gap-2.5">
<CheckCircle2 className="w-4 h-4 text-emerald-400 shrink-0" />
<span>
SD Card Sync Complete: <strong>{lastSummary.uploadedSaves}</strong> saves uploaded,{" "}
<strong>{lastSummary.downloadedSaves}</strong> downloaded to SD card,{" "}
<strong>{lastSummary.uploadedStates}</strong> states synced,{" "}
<strong>{lastSummary.upToDate}</strong> up to date
{lastSummary.conflicts.length > 0 &&
` • ${lastSummary.conflicts.length} conflict(s) (see Dashboard)`}
</span>
</div>
)}
{toast && (
<div className="p-3 rounded-lg bg-slate-900 border border-indigo-500/40 text-xs text-indigo-200">
{toast}
</div>
)}
{/* Sub-tabs */}
<div className="flex gap-1 p-1 bg-slate-900 border border-slate-800 rounded-xl w-fit">
<button
onClick={() => setSubTab("saves")}
className={`px-3.5 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
subTab === "saves" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
SD Saves & States ({matchedCount}/{inspection.saves.length} matched)
</button>
<button
onClick={() => setSubTab("roms")}
className={`px-3.5 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
subTab === "roms" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
Send ROMs to SD Card
</button>
</div>
{subTab === "saves" ? (
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{inspection.saves.length === 0 ? (
<div className="p-8 text-center text-sm text-slate-500">
No saves found under <code>/Saves/&lt;TAG&gt;/</code> on this SD card yet.
</div>
) : (
inspection.saves.map((item) => (
<div
key={item.localPath}
className="px-4 py-3 flex flex-wrap items-center justify-between gap-4"
>
<div className="min-w-0 space-y-0.5">
<div className="flex items-center gap-2">
{item.isDirectory ? (
<Folder className="w-4 h-4 text-amber-400 shrink-0" />
) : (
<Archive className="w-4 h-4 text-indigo-400 shrink-0" />
)}
<span className="font-medium text-sm truncate">{item.fileName}</span>
<span className="text-[10px] uppercase px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 font-mono">
{item.systemTag}
</span>
<span
className={`text-[10px] uppercase px-1.5 py-0.5 rounded ${
item.isState
? "bg-purple-950 text-purple-300"
: "bg-indigo-950 text-indigo-300"
}`}
>
{item.isState ? "State" : "Save"}
</span>
</div>
<div className="text-xs text-slate-500 font-mono truncate max-w-xl">
{formatBytes(item.sizeBytes)} • {item.localPath}
</div>
</div>
<div className="flex items-center gap-2.5 shrink-0">
{item.matchedRomId ? (
<div className="text-right">
<div className="text-xs font-medium text-emerald-400 flex items-center gap-1 justify-end">
<CheckCircle2 className="w-3.5 h-3.5" />
{item.matchedRomName}
</div>
<div className="text-[11px] text-slate-500">
{item.matchedPlatform} • {item.matchSource}
</div>
</div>
) : (
<span className="text-xs text-amber-400">Unmatched</span>
)}
<button
onClick={() => openLinker(item)}
className="px-2.5 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs font-medium flex items-center gap-1 cursor-pointer"
>
<Link2 className="w-3.5 h-3.5" /> {item.matchedRomId ? "Relink" : "Link"}
</button>
</div>
</div>
))
)}
</div>
) : (
<div className="space-y-3">
<div className="flex flex-wrap gap-2">
<select
value={selectedPlatform ?? ""}
onChange={(e) =>
setSelectedPlatform(e.target.value ? Number(e.target.value) : null)
}
className="px-3 py-2 rounded-lg bg-slate-900 border border-slate-800 text-sm"
>
<option value="">All Platforms ({platforms.length})</option>
{platforms.map((p) => (
<option key={p.id} value={p.id}>
{p.display_name} ({p.rom_count})
</option>
))}
</select>
<form
onSubmit={(e) => {
e.preventDefault();
loadRoms();
}}
className="flex-1 flex gap-2 min-w-[200px]"
>
<div className="relative flex-1">
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
<input
value={romSearch}
onChange={(e) => setRomSearch(e.target.value)}
placeholder="Search RomM games to copy to your TrimUI..."
className="w-full pl-9 pr-3 py-2 bg-slate-900 border border-slate-800 rounded-lg text-sm"
/>
</div>
<button
type="submit"
className="px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-sm font-medium cursor-pointer"
>
Search
</button>
</form>
</div>
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{loadingRoms ? (
<div className="p-8 flex items-center justify-center gap-2 text-sm text-slate-400">
<Loader2 className="w-4 h-4 animate-spin" /> Loading ROMs...
</div>
) : roms.length === 0 ? (
<div className="p-8 text-center text-sm text-slate-500">No ROMs found.</div>
) : (
roms.map((rom) => {
const isDl = downloadingId === rom.id;
return (
<div
key={rom.id}
className="px-4 py-3 flex items-center justify-between gap-4"
>
<div className="min-w-0">
<div className="font-medium text-sm truncate">
{rom.name || rom.fs_name_no_ext}
</div>
<div className="text-xs text-slate-400 flex items-center gap-2 mt-0.5">
<span className="px-1.5 py-0.5 rounded bg-indigo-950/70 text-indigo-300 text-[11px]">
{rom.platform_display_name}
</span>
<span className="font-mono text-slate-500 truncate max-w-md">
{rom.fs_name}
</span>
<span>{formatBytes(rom.fs_size_bytes)}</span>
</div>
</div>
<button
onClick={() => handleSendRom(rom)}
disabled={downloadingId !== null}
className="px-3 py-1.5 rounded-lg bg-indigo-600/20 hover:bg-indigo-600 text-indigo-200 hover:text-white border border-indigo-500/30 text-xs font-medium flex items-center gap-1.5 shrink-0 transition cursor-pointer disabled:opacity-50"
>
{isDl ? (
<>
<Loader2 className="w-3.5 h-3.5 animate-spin" /> {downloadPct}%
</>
) : (
<>
<Download className="w-3.5 h-3.5" /> Send to SD
</>
)}
</button>
</div>
);
})
)}
</div>
</div>
)}
</>
)}
{/* Manual Link Modal */}
{linkingItem && (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
<div className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-4 shadow-2xl">
<div className="flex items-center justify-between">
<div>
<h3 className="text-base font-semibold">Link SD Save to RomM Game</h3>
<p className="text-xs text-slate-400 font-mono truncate max-w-md">
{linkingItem.fileName}
</p>
</div>
<button
onClick={() => setLinkingItem(null)}
className="text-slate-400 hover:text-white cursor-pointer"
>
<X className="w-5 h-5" />
</button>
</div>
<form
onSubmit={async (e) => {
e.preventDefault();
const page = await api.fetchRoms({ searchTerm: linkSearch, limit: 30, offset: 0 });
setLinkResults(page.items);
}}
className="flex gap-2"
>
<input
value={linkSearch}
onChange={(e) => setLinkSearch(e.target.value)}
placeholder="Search RomM games..."
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
<button
type="submit"
className="px-3.5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium cursor-pointer"
>
Search
</button>
</form>
<div className="max-h-64 overflow-y-auto divide-y divide-slate-800 border border-slate-800 rounded-xl">
{linkResults.map((rom) => (
<button
key={rom.id}
onClick={() => handleLink(rom)}
className="w-full text-left px-3.5 py-2.5 hover:bg-slate-800/70 flex items-center justify-between gap-2 cursor-pointer"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">
{rom.name || rom.fs_name_no_ext}
</div>
<div className="text-xs text-slate-500 truncate">{rom.fs_name}</div>
</div>
<span className="text-[11px] px-2 py-0.5 rounded bg-indigo-950 text-indigo-300 shrink-0">
{rom.platform_display_name}
</span>
</button>
))}
</div>
</div>
</div>
)}
</div>
);
};
+680
View File
@@ -0,0 +1,680 @@
import React, { useEffect, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import {
Archive,
CheckCircle2,
CloudDownload,
CloudUpload,
Download,
FolderSearch,
Hash,
Loader2,
Search,
X,
} from "lucide-react";
import { api } from "../lib/tauri";
import {
formatBytes,
type DiscoveredSaveItem,
type EmulatorRule,
type LocalRomScanResult,
type PlatformSchema,
type RemoteSavesAndStates,
type SimpleRomSchema,
} from "../lib/types";
interface Props {
defaultDownloadDir: string | null;
emulators: EmulatorRule[];
discoveredSaves: DiscoveredSaveItem[];
onRefreshAll: () => Promise<void>;
}
function findEmulatorForRom(
emulators: EmulatorRule[],
rom: SimpleRomSchema
): EmulatorRule | undefined {
const matches = (e: EmulatorRule) =>
e.platformSlugs.some(
(s) =>
s.toLowerCase() === rom.platform_slug.toLowerCase() ||
s.toLowerCase() === rom.platform_fs_slug.toLowerCase()
);
return emulators.find((e) => e.enabled && matches(e)) || emulators.find(matches);
}
export const LibraryView: React.FC<Props> = ({
defaultDownloadDir,
emulators,
discoveredSaves,
onRefreshAll,
}) => {
const [tab, setTab] = useState<"romm" | "scanner">("romm");
const [platforms, setPlatforms] = useState<PlatformSchema[]>([]);
const [selectedPlatform, setSelectedPlatform] = useState<number | null>(null);
const [search, setSearch] = useState("");
const [roms, setRoms] = useState<SimpleRomSchema[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [downloadingId, setDownloadingId] = useState<number | null>(null);
const [downloadPct, setDownloadPct] = useState<number>(0);
const [toast, setToast] = useState<string | null>(null);
// Per-game Saves & States modal
const [activeRom, setActiveRom] = useState<SimpleRomSchema | null>(null);
const [remoteAssets, setRemoteAssets] = useState<RemoteSavesAndStates | null>(null);
const [loadingAssets, setLoadingAssets] = useState(false);
const [busyAction, setBusyAction] = useState<string | null>(null);
// Local ROM folder scanner state
const [scanFolder, setScanFolder] = useState("");
const [useHashLookup, setUseHashLookup] = useState(true);
const [scanning, setScanning] = useState(false);
const [scanResults, setScanResults] = useState<LocalRomScanResult[]>([]);
useEffect(() => {
api.fetchPlatforms().then(setPlatforms).catch(console.error);
const unlistenPromise = listen<{ romId: number; downloaded: number; total: number | null }>(
"rom:download-progress",
(event) => {
const { romId, downloaded, total } = event.payload;
setDownloadingId(romId);
if (total && total > 0) {
setDownloadPct(Math.round((downloaded / total) * 100));
}
}
);
return () => {
unlistenPromise.then((u) => u());
};
}, []);
const loadRoms = async () => {
setLoading(true);
try {
const page = await api.fetchRoms({
platformId: selectedPlatform,
searchTerm: search || null,
limit: 80,
offset: 0,
});
setRoms(page.items);
setTotal(page.total);
} catch (e) {
setToast(String(e));
} finally {
setLoading(false);
}
};
useEffect(() => {
loadRoms();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedPlatform]);
const handleDownloadRom = async (rom: SimpleRomSchema) => {
const inheritedEmu = findEmulatorForRom(emulators, rom);
let dest: string | null = inheritedEmu?.romDir || defaultDownloadDir;
if (!dest) {
dest = await api.pickFolder(`Choose Download Folder for ${rom.name || rom.fs_name}`);
}
if (!dest) return;
setDownloadingId(rom.id);
setDownloadPct(0);
setToast(null);
try {
const savedPath = await api.downloadRomToFolder({
romId: rom.id,
fileName: rom.fs_name,
destFolder: dest,
platformSlug: rom.platform_slug,
platformFsSlug: rom.platform_fs_slug,
});
setToast(`Downloaded to ${savedPath}`);
} catch (e) {
setToast(`Download failed: ${e}`);
} finally {
setDownloadingId(null);
setDownloadPct(0);
}
};
const openGameSaves = async (rom: SimpleRomSchema) => {
setActiveRom(rom);
setRemoteAssets(null);
setLoadingAssets(true);
try {
const data = await api.fetchRemoteSavesAndStates(rom.id);
setRemoteAssets(data);
} catch (e) {
setToast(`Failed to load saves for ${rom.name || rom.fs_name}: ${e}`);
} finally {
setLoadingAssets(false);
}
};
const handlePullSave = async (
rom: SimpleRomSchema,
saveId: number,
fileName: string,
emulatorHint: string | null
) => {
const inheritedEmu = findEmulatorForRom(emulators, rom);
let destOverride: string | null = null;
if (!inheritedEmu || !inheritedEmu.saveDir) {
destOverride = await api.pickFolder(`Select Save Folder for ${rom.platform_display_name}`);
if (!destOverride) return;
}
setBusyAction(`save-${saveId}`);
setToast(null);
try {
const placed = await api.downloadSingleSave({
saveId,
romId: rom.id,
fileName,
platformSlug: rom.platform_slug,
platformFsSlug: rom.platform_fs_slug,
emulatorHint,
destOverride,
});
setToast(`Downloaded save to ${placed}`);
await onRefreshAll();
} catch (e) {
setToast(`Save download failed: ${e}`);
} finally {
setBusyAction(null);
}
};
const handlePullState = async (
rom: SimpleRomSchema,
stateId: number,
fileName: string,
emulatorHint: string | null
) => {
const inheritedEmu = findEmulatorForRom(emulators, rom);
let destOverride: string | null = null;
if (!inheritedEmu || (!inheritedEmu.stateDir && !inheritedEmu.saveDir)) {
destOverride = await api.pickFolder(
`Select Save States Folder for ${rom.platform_display_name}`
);
if (!destOverride) return;
}
setBusyAction(`state-${stateId}`);
setToast(null);
try {
const placed = await api.downloadSingleState({
stateId,
romId: rom.id,
fileName,
platformSlug: rom.platform_slug,
platformFsSlug: rom.platform_fs_slug,
emulatorHint,
destOverride,
});
setToast(`Downloaded state to ${placed}`);
await onRefreshAll();
} catch (e) {
setToast(`State download failed: ${e}`);
} finally {
setBusyAction(null);
}
};
const handlePushLocal = async (item: DiscoveredSaveItem, rom: SimpleRomSchema) => {
setBusyAction(`push-${item.localPath}`);
setToast(null);
try {
await api.uploadSingleSave({
localPath: item.localPath,
fileName: item.fileName,
romId: rom.id,
emulatorId: item.emulatorId,
slot: item.slot || "default",
isDirectory: item.isDirectory,
isState: item.isState,
});
setToast(`Uploaded '${item.fileName}' to RomM!`);
const refreshed = await api.fetchRemoteSavesAndStates(rom.id);
setRemoteAssets(refreshed);
await onRefreshAll();
} catch (e) {
setToast(`Upload failed: ${e}`);
} finally {
setBusyAction(null);
}
};
const handleScanLocal = async () => {
let folder = scanFolder;
if (!folder) {
const picked = await api.pickFolder("Select Local ROMs Folder");
if (!picked) return;
folder = picked;
setScanFolder(picked);
}
setScanning(true);
setToast(null);
try {
const res = await api.scanLocalRomFolder(folder, useHashLookup);
setScanResults(res);
} catch (e) {
setToast(String(e));
} finally {
setScanning(false);
}
};
const activeInheritedEmu = activeRom ? findEmulatorForRom(emulators, activeRom) : undefined;
const activeLocalItems = activeRom
? discoveredSaves.filter((s) => s.matchedRomId === activeRom.id)
: [];
return (
<div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight">ROM Library & Hash Matcher</h2>
<p className="text-sm text-slate-400">
ROMs and individual saves automatically inherit the configured emulator paths for their
system.
</p>
</div>
<div className="flex gap-1 p-1 bg-slate-900 border border-slate-800 rounded-xl">
<button
onClick={() => setTab("romm")}
className={`px-3.5 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
tab === "romm" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
RomM Library ({total})
</button>
<button
onClick={() => setTab("scanner")}
className={`px-3.5 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
tab === "scanner" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
Local ROM Scanner
</button>
</div>
</div>
{toast && (
<div className="p-3 rounded-lg bg-slate-900 border border-indigo-500/40 text-xs text-indigo-200 break-all">
{toast}
</div>
)}
{tab === "romm" ? (
<>
<div className="flex flex-wrap gap-2.5">
<select
value={selectedPlatform ?? ""}
onChange={(e) =>
setSelectedPlatform(e.target.value ? Number(e.target.value) : null)
}
className="px-3 py-2 rounded-lg bg-slate-900 border border-slate-800 text-sm"
>
<option value="">All Platforms ({platforms.length})</option>
{platforms.map((p) => (
<option key={p.id} value={p.id}>
{p.display_name} ({p.rom_count})
</option>
))}
</select>
<form
onSubmit={(e) => {
e.preventDefault();
loadRoms();
}}
className="flex-1 flex gap-2 min-w-[220px]"
>
<div className="relative flex-1">
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search ROMs by title or filename..."
className="w-full pl-9 pr-3 py-2 bg-slate-900 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
<button
type="submit"
className="px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-sm font-medium cursor-pointer"
>
Search
</button>
</form>
</div>
<div className="rounded-xl bg-slate-900/80 border border-slate-800 overflow-hidden">
{loading ? (
<div className="p-10 flex items-center justify-center gap-2 text-slate-400 text-sm">
<Loader2 className="w-4 h-4 animate-spin" /> Loading ROMs from RomM...
</div>
) : roms.length === 0 ? (
<div className="p-10 text-center text-sm text-slate-500">No ROMs found.</div>
) : (
<div className="divide-y divide-slate-800/80">
{roms.map((rom) => {
const isDl = downloadingId === rom.id;
const inherited = findEmulatorForRom(emulators, rom);
return (
<div
key={rom.id}
className="px-4 py-3 flex items-center justify-between gap-4 hover:bg-slate-800/30 transition"
>
<div className="min-w-0">
<div className="font-medium text-sm truncate">
{rom.name || rom.fs_name_no_ext}
</div>
<div className="text-xs text-slate-400 flex flex-wrap items-center gap-2 mt-0.5">
<span className="px-1.5 py-0.5 rounded bg-indigo-950/70 text-indigo-300 text-[11px]">
{rom.platform_display_name}
</span>
{inherited && (
<span
className="px-1.5 py-0.5 rounded bg-emerald-950/70 text-emerald-300 text-[11px]"
title={
inherited.romDir
? `ROMs → ${inherited.romDir}\nSaves → ${inherited.saveDir}`
: `Saves → ${inherited.saveDir}`
}
>
→ {inherited.name}
</span>
)}
<span className="font-mono text-slate-500 truncate max-w-md">
{rom.fs_name}
</span>
<span>{formatBytes(rom.fs_size_bytes)}</span>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<button
onClick={() => openGameSaves(rom)}
className="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs font-medium flex items-center gap-1.5 cursor-pointer transition"
title="Inspect, download, or upload individual saves & states for this game"
>
<Archive className="w-3.5 h-3.5 text-indigo-400" /> Saves
</button>
<button
onClick={() => handleDownloadRom(rom)}
disabled={downloadingId !== null}
className="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-indigo-600 text-xs font-medium flex items-center gap-1.5 transition cursor-pointer disabled:opacity-50"
title={
inherited?.romDir
? `Download directly into ${inherited.romDir}`
: "Download ROM"
}
>
{isDl ? (
<>
<Loader2 className="w-3.5 h-3.5 animate-spin" /> {downloadPct}%
</>
) : (
<>
<Download className="w-3.5 h-3.5" /> Download
</>
)}
</button>
</div>
</div>
);
})}
</div>
)}
</div>
</>
) : (
<div className="space-y-4">
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800 space-y-3">
<div className="flex flex-wrap gap-2">
<input
value={scanFolder}
onChange={(e) => setScanFolder(e.target.value)}
placeholder="Choose a local ROM directory to scan..."
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
onClick={async () => {
const dir = await api.pickFolder("Select Local ROMs Folder");
if (dir) setScanFolder(dir);
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs font-medium cursor-pointer"
>
Browse
</button>
<button
onClick={handleScanLocal}
disabled={scanning}
className="px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
>
{scanning ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<FolderSearch className="w-3.5 h-3.5" />
)}
Scan & Match
</button>
</div>
<label className="flex items-center gap-2 text-xs text-slate-300 cursor-pointer">
<input
type="checkbox"
checked={useHashLookup}
onChange={(e) => setUseHashLookup(e.target.checked)}
/>
<Hash className="w-3.5 h-3.5 text-indigo-400" />
Compute CRC32 / MD5 / SHA1 hashes and query RomM <code>/api/roms/by-hash</code> (up
to 512 MB per file; larger ISOs match by filename)
</label>
</div>
{scanResults.length > 0 && (
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{scanResults.map((item) => (
<div
key={item.localPath}
className="px-4 py-3 flex items-center justify-between gap-4"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">{item.fileName}</div>
<div className="text-xs text-slate-500 flex flex-wrap gap-2 mt-0.5 font-mono">
<span>{formatBytes(item.sizeBytes)}</span>
{item.crc32 && <span>CRC32: {item.crc32}</span>}
</div>
</div>
<div className="text-right shrink-0">
{item.matchedRomId ? (
<div className="flex items-center gap-1.5 text-xs text-emerald-400">
<CheckCircle2 className="w-3.5 h-3.5" />
<span>{item.matchedRomName}</span>
<span className="px-1.5 py-0.5 rounded bg-emerald-950 text-emerald-300 text-[10px] uppercase">
{item.matchSource}
</span>
</div>
) : (
<span className="text-xs text-slate-500">Unmatched</span>
)}
</div>
</div>
))}
</div>
)}
</div>
)}
{/* Per-Game Individual Saves & States Modal */}
{activeRom && (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
<div className="w-full max-w-2xl bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-5 shadow-2xl max-h-[85vh] overflow-y-auto">
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="text-lg font-semibold">
{activeRom.name || activeRom.fs_name_no_ext}
</h3>
<p className="text-xs text-slate-400 mt-0.5">
{activeRom.platform_display_name} •{" "}
{activeInheritedEmu ? (
<span className="text-emerald-400">
Inherited Emulator: {activeInheritedEmu.name} ({activeInheritedEmu.saveDir})
</span>
) : (
<span className="text-amber-400">
No emulator configured for {activeRom.platform_slug} (will prompt for folder)
</span>
)}
</p>
</div>
<button
onClick={() => setActiveRom(null)}
className="text-slate-400 hover:text-white cursor-pointer"
>
<X className="w-5 h-5" />
</button>
</div>
{loadingAssets ? (
<div className="py-8 flex items-center justify-center gap-2 text-sm text-slate-400">
<Loader2 className="w-4 h-4 animate-spin" /> Loading saves & states from RomM...
</div>
) : (
<div className="space-y-5">
{/* Server Saves */}
<div className="space-y-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
RomM Server Saves ({remoteAssets?.saves.length ?? 0})
</h4>
{!remoteAssets || remoteAssets.saves.length === 0 ? (
<div className="p-3 rounded-xl bg-slate-950/60 border border-slate-800 text-xs text-slate-500">
No saves stored on RomM for this game yet.
</div>
) : (
<div className="rounded-xl bg-slate-950/60 border border-slate-800 divide-y divide-slate-800/80">
{remoteAssets.saves.map((s) => (
<div
key={s.id}
className="px-3.5 py-2.5 flex items-center justify-between gap-3"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">{s.file_name}</div>
<div className="text-[11px] text-slate-500">
Slot: {s.slot || "manual"} • {formatBytes(s.file_size_bytes)} •{" "}
{new Date(s.updated_at).toLocaleString()}
</div>
</div>
<button
onClick={() =>
handlePullSave(activeRom, s.id, s.file_name, s.emulator)
}
disabled={busyAction !== null}
className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium flex items-center gap-1.5 shrink-0 cursor-pointer disabled:opacity-50"
>
{busyAction === `save-${s.id}` ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<CloudDownload className="w-3.5 h-3.5" />
)}
Pull to Emulator
</button>
</div>
))}
</div>
)}
</div>
{/* Server States */}
<div className="space-y-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
RomM Server Save States ({remoteAssets?.states.length ?? 0})
</h4>
{!remoteAssets || remoteAssets.states.length === 0 ? (
<div className="p-3 rounded-xl bg-slate-950/60 border border-slate-800 text-xs text-slate-500">
No save states stored on RomM for this game yet.
</div>
) : (
<div className="rounded-xl bg-slate-950/60 border border-slate-800 divide-y divide-slate-800/80">
{remoteAssets.states.map((st) => (
<div
key={st.id}
className="px-3.5 py-2.5 flex items-center justify-between gap-3"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">{st.file_name}</div>
<div className="text-[11px] text-slate-500">
{formatBytes(st.file_size_bytes)} •{" "}
{new Date(st.updated_at).toLocaleString()}
</div>
</div>
<button
onClick={() =>
handlePullState(activeRom, st.id, st.file_name, st.emulator)
}
disabled={busyAction !== null}
className="px-3 py-1.5 rounded-lg bg-purple-600 hover:bg-purple-500 text-xs font-medium flex items-center gap-1.5 shrink-0 cursor-pointer disabled:opacity-50"
>
{busyAction === `state-${st.id}` ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<CloudDownload className="w-3.5 h-3.5" />
)}
Pull State
</button>
</div>
))}
</div>
)}
</div>
{/* Local Saves & States for this ROM */}
<div className="space-y-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
Local Saves & States ({activeLocalItems.length})
</h4>
{activeLocalItems.length === 0 ? (
<div className="p-3 rounded-xl bg-slate-950/60 border border-slate-800 text-xs text-slate-500">
No local saves matched to this game yet.
</div>
) : (
<div className="rounded-xl bg-slate-950/60 border border-slate-800 divide-y divide-slate-800/80">
{activeLocalItems.map((item) => (
<div
key={item.localPath}
className="px-3.5 py-2.5 flex items-center justify-between gap-3"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">{item.fileName}</div>
<div className="text-[11px] text-slate-500 font-mono truncate">
{item.isState ? "State" : `Save • ${item.slot}`} •{" "}
{formatBytes(item.sizeBytes)} • {item.localPath}
</div>
</div>
<button
onClick={() => handlePushLocal(item, activeRom)}
disabled={busyAction !== null}
className="px-3 py-1.5 rounded-lg bg-emerald-600/20 hover:bg-emerald-600 text-emerald-200 hover:text-white border border-emerald-500/30 text-xs font-medium flex items-center gap-1.5 shrink-0 cursor-pointer disabled:opacity-50 transition"
>
{busyAction === `push-${item.localPath}` ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<CloudUpload className="w-3.5 h-3.5" />
)}
Push to RomM
</button>
</div>
))}
</div>
)}
</div>
</div>
)}
</div>
</div>
)}
</div>
);
};
+350
View File
@@ -0,0 +1,350 @@
import React, { useEffect, useRef, useState } from "react";
import {
CheckCircle2,
ExternalLink,
Gamepad2,
KeyRound,
Loader2,
Lock,
Server,
Smartphone,
} from "lucide-react";
import { api } from "../lib/tauri";
import type { DeviceAuthInitResponse } from "../lib/types";
interface Props {
initialServerUrl: string;
initialDeviceName: string;
onConnected: () => Promise<void>;
}
type AuthTab = "device" | "token" | "password";
export const OnboardingConnect: React.FC<Props> = ({
initialServerUrl,
initialDeviceName,
onConnected,
}) => {
const [serverUrl, setServerUrl] = useState(initialServerUrl || "https://");
const [deviceName, setDeviceName] = useState(initialDeviceName);
const [tab, setTab] = useState<AuthTab>("device");
const [pairCode, setPairCode] = useState("");
const [rawToken, setRawToken] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [deviceAuth, setDeviceAuth] = useState<DeviceAuthInitResponse | null>(null);
const [loading, setLoading] = useState(false);
const [serverOk, setServerOk] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const pollRef = useRef<number | null>(null);
useEffect(() => {
return () => {
if (pollRef.current) window.clearInterval(pollRef.current);
};
}, []);
const handleTestServer = async () => {
setError(null);
setServerOk(null);
setLoading(true);
try {
await api.testServer(serverUrl);
setServerOk("Connected to RomM server!");
} catch (e) {
setError(String(e));
} finally {
setLoading(false);
}
};
const handleStartDeviceAuth = async () => {
setError(null);
setLoading(true);
try {
const init = await api.startDeviceAuth(serverUrl, deviceName);
setDeviceAuth(init);
const base = serverUrl.trim().replace(/\/+$/, "");
const verifyUrl = init.verification_path_complete.startsWith("http")
? init.verification_path_complete
: `${base}${init.verification_path_complete}`;
await api.openExternalUrl(verifyUrl).catch(() => {});
if (pollRef.current) window.clearInterval(pollRef.current);
const intervalMs = Math.max((init.interval || 5) * 1000, 2500);
pollRef.current = window.setInterval(async () => {
try {
const user = await api.pollDeviceAuth(serverUrl, init.device_code);
if (user) {
if (pollRef.current) window.clearInterval(pollRef.current);
setDeviceAuth(null);
await onConnected();
}
} catch (err) {
if (pollRef.current) window.clearInterval(pollRef.current);
setDeviceAuth(null);
setError(String(err));
}
}, intervalMs);
} catch (e) {
setError(String(e));
} finally {
setLoading(false);
}
};
const handleTokenOrPair = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setLoading(true);
try {
if (pairCode.trim()) {
await api.exchangePairCode(serverUrl, pairCode.trim());
} else if (rawToken.trim()) {
await api.connectWithToken(serverUrl, rawToken.trim());
} else {
throw new Error("Enter either a pair code or an API token.");
}
await onConnected();
} catch (err) {
setError(String(err));
} finally {
setLoading(false);
}
};
const handlePasswordLogin = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setLoading(true);
try {
await api.loginWithPassword(serverUrl, username, password);
await onConnected();
} catch (err) {
setError(String(err));
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center p-6 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-indigo-950/60 via-slate-950 to-slate-950">
<div className="w-full max-w-xl bg-slate-900/90 border border-slate-800 rounded-2xl shadow-2xl p-8 backdrop-blur">
<div className="flex items-center gap-3 mb-6">
<div className="w-11 h-11 rounded-xl bg-indigo-600/20 border border-indigo-500/40 flex items-center justify-center text-indigo-400">
<Gamepad2 className="w-6 h-6" />
</div>
<div>
<h1 className="text-xl font-bold tracking-tight">RomM Companion</h1>
<p className="text-sm text-slate-400">
Sync saves, states & ROMs for standalone emulators with RomM 5.1.0
</p>
</div>
</div>
{/* Server URL & Device Name */}
<div className="space-y-4 mb-6">
<div>
<label className="block text-xs font-medium uppercase tracking-wider text-slate-400 mb-1.5">
RomM Server URL
</label>
<div className="flex gap-2">
<div className="relative flex-1">
<Server className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
<input
type="url"
value={serverUrl}
onChange={(e) => setServerUrl(e.target.value)}
placeholder="https://rom.example.com"
className="w-full pl-9 pr-3 py-2.5 bg-slate-950 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
<button
type="button"
onClick={handleTestServer}
disabled={loading}
className="px-3.5 py-2.5 text-sm font-medium rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 transition cursor-pointer"
>
Test
</button>
</div>
{serverOk && (
<p className="mt-1.5 text-xs text-emerald-400 flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5" /> {serverOk}
</p>
)}
</div>
<div>
<label className="block text-xs font-medium uppercase tracking-wider text-slate-400 mb-1.5">
This Device Name
</label>
<input
type="text"
value={deviceName}
onChange={(e) => setDeviceName(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
</div>
{/* Auth Method Tabs */}
<div className="grid grid-cols-3 gap-1 p-1 bg-slate-950 rounded-xl border border-slate-800 mb-5">
{(
[
{ id: "device", label: "Device Pairing", icon: Smartphone },
{ id: "token", label: "Pair Code / Token", icon: KeyRound },
{ id: "password", label: "Username", icon: Lock },
] as const
).map((t) => {
const Icon = t.icon;
const active = tab === t.id;
return (
<button
key={t.id}
type="button"
onClick={() => {
setTab(t.id);
setError(null);
}}
className={`flex items-center justify-center gap-1.5 py-2 px-2 rounded-lg text-xs font-medium transition cursor-pointer ${
active
? "bg-indigo-600 text-white shadow"
: "text-slate-400 hover:text-slate-200"
}`}
>
<Icon className="w-3.5 h-3.5" />
{t.label}
</button>
);
})}
</div>
{tab === "device" && (
<div className="space-y-4">
{!deviceAuth ? (
<>
<p className="text-sm text-slate-400">
Start passwordless device pairing via RomM 5.1.0. Your browser will open so you
can approve this machine in one click.
</p>
<button
type="button"
onClick={handleStartDeviceAuth}
disabled={loading}
className="w-full py-2.5 px-4 rounded-lg bg-indigo-600 hover:bg-indigo-500 font-medium text-sm flex items-center justify-center gap-2 transition cursor-pointer disabled:opacity-50"
>
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <ExternalLink className="w-4 h-4" />}
Pair This Device with RomM
</button>
</>
) : (
<div className="p-4 rounded-xl bg-indigo-950/40 border border-indigo-500/40 text-center space-y-3">
<p className="text-xs uppercase tracking-wider text-indigo-300 font-medium">
Approve this code in your RomM browser tab
</p>
<div className="text-3xl font-mono font-bold tracking-widest text-white">
{deviceAuth.user_code}
</div>
<div className="flex items-center justify-center gap-2 text-xs text-slate-400">
<Loader2 className="w-3.5 h-3.5 animate-spin text-indigo-400" />
Waiting for approval...
</div>
<button
type="button"
onClick={() => {
const base = serverUrl.trim().replace(/\/+$/, "");
const url = deviceAuth.verification_path_complete.startsWith("http")
? deviceAuth.verification_path_complete
: `${base}${deviceAuth.verification_path_complete}`;
api.openExternalUrl(url);
}}
className="text-xs text-indigo-400 hover:underline cursor-pointer"
>
Re-open approval page in browser
</button>
</div>
)}
</div>
)}
{tab === "token" && (
<form onSubmit={handleTokenOrPair} className="space-y-3">
<div>
<label className="block text-xs text-slate-400 mb-1">
One-Time Pair Code (from RomM Client Tokens)
</label>
<input
type="text"
value={pairCode}
onChange={(e) => setPairCode(e.target.value)}
placeholder="e.g. ABCD-1234"
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm font-mono focus:outline-none focus:border-indigo-500"
/>
</div>
<div className="text-center text-xs text-slate-500">— or —</div>
<div>
<label className="block text-xs text-slate-400 mb-1">Raw Client API Token</label>
<input
type="password"
value={rawToken}
onChange={(e) => setRawToken(e.target.value)}
placeholder="Paste bearer token..."
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm font-mono focus:outline-none focus:border-indigo-500"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full py-2.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 font-medium text-sm flex items-center justify-center gap-2 transition cursor-pointer disabled:opacity-50"
>
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
Connect
</button>
</form>
)}
{tab === "password" && (
<form onSubmit={handlePasswordLogin} className="space-y-3">
<div>
<label className="block text-xs text-slate-400 mb-1">Username</label>
<input
type="text"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">Password</label>
<input
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full py-2.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 font-medium text-sm flex items-center justify-center gap-2 transition cursor-pointer disabled:opacity-50"
>
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
Sign In
</button>
</form>
)}
{error && (
<div className="mt-4 p-3 rounded-lg bg-rose-950/60 border border-rose-500/40 text-xs text-rose-200 break-words">
{error}
</div>
)}
</div>
</div>
);
};
+382
View File
@@ -0,0 +1,382 @@
import React, { useEffect, useState } from "react";
import {
Archive,
CheckCircle2,
CloudUpload,
Folder,
History,
Link2,
Loader2,
RefreshCw,
Search,
Unlink,
X,
} from "lucide-react";
import { api } from "../lib/tauri";
import {
formatBytes,
type BackupEntry,
type DiscoveredSaveItem,
type SimpleRomSchema,
} from "../lib/types";
interface Props {
discoveredSaves: DiscoveredSaveItem[];
onRefreshSaves: () => Promise<void>;
}
export const SavesStatesView: React.FC<Props> = ({ discoveredSaves, onRefreshSaves }) => {
const [subTab, setSubTab] = useState<"local" | "backups">("local");
const [filter, setFilter] = useState<"all" | "matched" | "unmatched" | "states">("all");
const [linkingItem, setLinkingItem] = useState<DiscoveredSaveItem | null>(null);
const [romSearch, setRomSearch] = useState("");
const [romResults, setRomResults] = useState<SimpleRomSchema[]>([]);
const [slotInput, setSlotInput] = useState("default");
const [backups, setBackups] = useState<BackupEntry[]>([]);
const [toast, setToast] = useState<string | null>(null);
const [uploadingPath, setUploadingPath] = useState<string | null>(null);
const handleUploadSingle = async (item: DiscoveredSaveItem) => {
if (!item.matchedRomId) return;
setUploadingPath(item.localPath);
setToast(null);
try {
await api.uploadSingleSave({
localPath: item.localPath,
fileName: item.fileName,
romId: item.matchedRomId,
emulatorId: item.emulatorId,
slot: item.slot || "default",
isDirectory: item.isDirectory,
isState: item.isState,
});
setToast(`Uploaded '${item.fileName}' to RomM!`);
await onRefreshSaves();
} catch (e) {
setToast(`Upload failed: ${e}`);
} finally {
setUploadingPath(null);
}
};
useEffect(() => {
if (subTab === "backups") {
api.listBackups().then(setBackups).catch(console.error);
}
}, [subTab]);
const filtered = discoveredSaves.filter((s) => {
if (filter === "matched") return s.matchedRomId !== null;
if (filter === "unmatched") return s.matchedRomId === null;
if (filter === "states") return s.isState;
return true;
});
const openLinker = async (item: DiscoveredSaveItem) => {
setLinkingItem(item);
setSlotInput(item.slot || "default");
setRomSearch("");
const page = await api.fetchRoms({ limit: 30, offset: 0 });
setRomResults(page.items);
};
const searchRomsForLink = async (e: React.FormEvent) => {
e.preventDefault();
const page = await api.fetchRoms({ searchTerm: romSearch, limit: 30, offset: 0 });
setRomResults(page.items);
};
const handleLink = async (rom: SimpleRomSchema) => {
if (!linkingItem) return;
await api.linkSaveToRom({
localPath: linkingItem.localPath,
romId: rom.id,
romName: rom.name || rom.fs_name_no_ext,
emulatorId: linkingItem.emulatorId,
slot: slotInput || "default",
isState: linkingItem.isState,
});
setLinkingItem(null);
await onRefreshSaves();
};
const handleUnlink = async (localPath: string) => {
await api.unlinkSave(localPath);
await onRefreshSaves();
};
const handleRestoreBackup = async (b: BackupEntry) => {
const destFolder = await api.pickFolder("Select Target Folder to Restore Backup Into");
if (!destFolder) return;
const isZip = b.fileName.endsWith(".zip");
const targetPath = `${destFolder}/${b.fileName.replace(/^\d{8}T\d{6}Z_/, "").replace(/\.zip$/, "")}`;
try {
await api.restoreBackup(b.backupPath, targetPath, isZip);
setToast(`Restored backup to ${targetPath}`);
} catch (e) {
setToast(`Restore failed: ${e}`);
}
};
return (
<div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight">Saves, States & Backups</h2>
<p className="text-sm text-slate-400">
Inspect matched save files & save states, manually link Title ID folders, or restore
automatic backups.
</p>
</div>
<div className="flex items-center gap-2">
<div className="flex gap-1 p-1 bg-slate-900 border border-slate-800 rounded-xl">
<button
onClick={() => setSubTab("local")}
className={`px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
subTab === "local" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
Local Saves ({discoveredSaves.length})
</button>
<button
onClick={() => setSubTab("backups")}
className={`px-3 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1 cursor-pointer ${
subTab === "backups"
? "bg-indigo-600 text-white"
: "text-slate-400 hover:text-white"
}`}
>
<History className="w-3.5 h-3.5" /> Backups
</button>
</div>
<button
onClick={onRefreshSaves}
className="p-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 cursor-pointer"
title="Rescan local save folders"
>
<RefreshCw className="w-4 h-4" />
</button>
</div>
</div>
{toast && (
<div className="p-3 rounded-lg bg-slate-900 border border-indigo-500/40 text-xs text-indigo-200">
{toast}
</div>
)}
{subTab === "local" ? (
<>
<div className="flex flex-wrap gap-2">
{(["all", "matched", "unmatched", "states"] as const).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1.5 rounded-lg text-xs font-medium capitalize cursor-pointer border ${
filter === f
? "bg-indigo-600/20 border-indigo-500/50 text-indigo-300"
: "bg-slate-900 border-slate-800 text-slate-400 hover:text-slate-200"
}`}
>
{f}
</button>
))}
</div>
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{filtered.length === 0 ? (
<div className="p-8 text-center text-sm text-slate-500">
No saves discovered matching this filter. Make sure at least one emulator rule is
enabled in <strong>Emulators</strong>.
</div>
) : (
filtered.map((item) => (
<div
key={item.localPath}
className="px-4 py-3 flex flex-wrap items-center justify-between gap-4"
>
<div className="min-w-0 space-y-1">
<div className="flex items-center gap-2">
{item.isDirectory ? (
<Folder className="w-4 h-4 text-amber-400 shrink-0" />
) : (
<Archive className="w-4 h-4 text-indigo-400 shrink-0" />
)}
<span className="font-medium text-sm truncate">{item.fileName}</span>
<span
className={`text-[10px] uppercase px-1.5 py-0.5 rounded font-medium ${
item.isState
? "bg-purple-950 text-purple-300"
: "bg-slate-800 text-slate-300"
}`}
>
{item.isState ? "State" : `Save • ${item.slot}`}
</span>
</div>
<div className="text-xs text-slate-500 font-mono truncate max-w-2xl">
{item.emulatorName} • {formatBytes(item.sizeBytes)} • {item.localPath}
</div>
</div>
<div className="flex items-center gap-2.5 shrink-0">
{item.matchedRomId ? (
<div className="text-right">
<div className="text-xs font-medium text-emerald-400 flex items-center gap-1 justify-end">
<CheckCircle2 className="w-3.5 h-3.5" />
{item.matchedRomName}
</div>
<div className="text-[11px] text-slate-500">
{item.matchedPlatform} • {item.matchSource} (
{Math.round(item.matchConfidence * 100)}%)
</div>
</div>
) : (
<span className="text-xs text-amber-400">Unmatched</span>
)}
{item.matchedRomId && (
<button
onClick={() => handleUploadSingle(item)}
disabled={uploadingPath !== null}
className="px-2.5 py-1.5 rounded-lg bg-indigo-600/20 hover:bg-indigo-600 text-indigo-200 hover:text-white border border-indigo-500/30 text-xs font-medium flex items-center gap-1 cursor-pointer disabled:opacity-50 transition"
title="Push this save directly to RomM"
>
{uploadingPath === item.localPath ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<CloudUpload className="w-3.5 h-3.5" />
)}
Push
</button>
)}
<button
onClick={() => openLinker(item)}
className="px-2.5 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs font-medium flex items-center gap-1 cursor-pointer"
>
<Link2 className="w-3.5 h-3.5" /> {item.matchedRomId ? "Relink" : "Link ROM"}
</button>
{item.matchSource === "manual" && (
<button
onClick={() => handleUnlink(item.localPath)}
className="p-1.5 rounded-lg bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-300 cursor-pointer"
title="Remove manual link"
>
<Unlink className="w-3.5 h-3.5" />
</button>
)}
</div>
</div>
))
)}
</div>
</>
) : (
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{backups.length === 0 ? (
<div className="p-8 text-center text-sm text-slate-500">
No local backups yet. Backups are automatically created before any server save
overwrites a local file.
</div>
) : (
backups.map((b) => (
<div
key={b.backupPath}
className="px-4 py-3 flex items-center justify-between gap-4"
>
<div>
<div className="text-sm font-medium">{b.fileName}</div>
<div className="text-xs text-slate-500">
ROM #{b.romId} • {formatBytes(b.sizeBytes)} •{" "}
{new Date(b.createdAt).toLocaleString()}
</div>
</div>
<button
onClick={() => handleRestoreBackup(b)}
className="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-indigo-600 text-xs font-medium cursor-pointer transition"
>
Restore to Folder
</button>
</div>
))
)}
</div>
)}
{/* Manual Link Modal */}
{linkingItem && (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
<div className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-4 shadow-2xl">
<div className="flex items-center justify-between">
<div>
<h3 className="text-base font-semibold">Link Save to RomM Game</h3>
<p className="text-xs text-slate-400 font-mono truncate max-w-md">
{linkingItem.fileName}
</p>
</div>
<button
onClick={() => setLinkingItem(null)}
className="text-slate-400 hover:text-white cursor-pointer"
>
<X className="w-5 h-5" />
</button>
</div>
{!linkingItem.isState && (
<div>
<label className="block text-xs text-slate-400 mb-1">
RomM Save Slot Name (kept consistent across syncs)
</label>
<input
value={slotInput}
onChange={(e) => setSlotInput(e.target.value)}
className="w-full px-3 py-1.5 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
)}
<form onSubmit={searchRomsForLink} className="flex gap-2">
<div className="relative flex-1">
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
<input
value={romSearch}
onChange={(e) => setRomSearch(e.target.value)}
placeholder="Search RomM games..."
className="w-full pl-9 pr-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
<button
type="submit"
className="px-3.5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium cursor-pointer"
>
Search
</button>
</form>
<div className="max-h-64 overflow-y-auto divide-y divide-slate-800 border border-slate-800 rounded-xl">
{romResults.map((rom) => (
<button
key={rom.id}
onClick={() => handleLink(rom)}
className="w-full text-left px-3.5 py-2.5 hover:bg-slate-800/70 flex items-center justify-between gap-2 cursor-pointer"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">
{rom.name || rom.fs_name_no_ext}
</div>
<div className="text-xs text-slate-500 truncate">{rom.fs_name}</div>
</div>
<span className="text-[11px] px-2 py-0.5 rounded bg-indigo-950 text-indigo-300 shrink-0">
{rom.platform_display_name}
</span>
</button>
))}
</div>
</div>
</div>
)}
</div>
);
};
+171
View File
@@ -0,0 +1,171 @@
import React, { useState } from "react";
import { FolderOpen, LogOut, Save } from "lucide-react";
import { api } from "../lib/tauri";
import type { AppStateSnapshot, WatcherSettings } from "../lib/types";
interface Props {
appState: AppStateSnapshot;
onRefreshState: () => Promise<void>;
onDisconnect: () => Promise<void>;
}
export const SettingsView: React.FC<Props> = ({
appState,
onRefreshState,
onDisconnect,
}) => {
const [settings, setSettings] = useState<WatcherSettings>(appState.settings);
const [deviceName, setDeviceName] = useState(appState.deviceName);
const [savedMsg, setSavedMsg] = useState(false);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
await api.saveSettings(settings, deviceName);
await onRefreshState();
setSavedMsg(true);
setTimeout(() => setSavedMsg(false), 2500);
};
return (
<div className="space-y-6 max-w-2xl">
<div>
<h2 className="text-2xl font-bold tracking-tight">Settings</h2>
<p className="text-sm text-slate-400">
Configure background watching, backup retention, tray behavior, and device identity.
</p>
</div>
<form
onSubmit={handleSave}
className="p-6 rounded-2xl bg-slate-900/80 border border-slate-800 space-y-5"
>
<div>
<label className="block text-xs font-medium uppercase tracking-wider text-slate-400 mb-1.5">
Device Name
</label>
<input
value={deviceName}
onChange={(e) => setDeviceName(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
<p className="text-xs text-slate-500 mt-1">
RomM Device ID: <span className="font-mono">{appState.deviceId || "Not registered"}</span>
</p>
</div>
<div className="space-y-3 pt-2 border-t border-slate-800">
<label className="flex items-center justify-between text-sm cursor-pointer">
<span>Enable Background File Watcher</span>
<input
type="checkbox"
checked={settings.enabled}
onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })}
/>
</label>
<label className="flex items-center justify-between text-sm cursor-pointer">
<span>Auto-Sync Immediately When Save Files Change</span>
<input
type="checkbox"
checked={settings.autoSyncOnChange}
onChange={(e) => setSettings({ ...settings, autoSyncOnChange: e.target.checked })}
/>
</label>
<label className="flex items-center justify-between text-sm cursor-pointer">
<span>Minimize to System Tray on Window Close</span>
<input
type="checkbox"
checked={settings.minimizeToTray}
onChange={(e) => setSettings({ ...settings, minimizeToTray: e.target.checked })}
/>
</label>
</div>
<div className="grid grid-cols-2 gap-4 pt-2 border-t border-slate-800">
<div>
<label className="block text-xs text-slate-400 mb-1">
Watcher Debounce (seconds)
</label>
<input
type="number"
min={1}
max={60}
value={settings.debounceSeconds}
onChange={(e) =>
setSettings({ ...settings, debounceSeconds: Number(e.target.value) || 5 })
}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">
Max Local Backups per ROM
</label>
<input
type="number"
min={1}
max={100}
value={settings.maxBackupsPerSave}
onChange={(e) =>
setSettings({ ...settings, maxBackupsPerSave: Number(e.target.value) || 10 })
}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
</div>
<div className="pt-2 border-t border-slate-800">
<label className="block text-xs text-slate-400 mb-1">
Default ROM Download Folder (optional)
</label>
<div className="flex gap-2">
<input
value={settings.defaultRomDownloadDir || ""}
onChange={(e) =>
setSettings({ ...settings, defaultRomDownloadDir: e.target.value || null })
}
placeholder="Ask every time"
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
type="button"
onClick={async () => {
const dir = await api.pickFolder("Select Default ROM Download Folder");
if (dir) setSettings({ ...settings, defaultRomDownloadDir: dir });
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs flex items-center gap-1 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Browse
</button>
</div>
</div>
<div className="flex items-center justify-between pt-3">
<button
type="submit"
className="px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium flex items-center gap-2 cursor-pointer"
>
<Save className="w-4 h-4" /> Save Settings
</button>
{savedMsg && <span className="text-xs text-emerald-400">Saved!</span>}
</div>
</form>
<div className="p-5 rounded-2xl bg-rose-950/20 border border-rose-500/30 flex items-center justify-between">
<div>
<div className="text-sm font-semibold text-rose-200">Disconnect from RomM</div>
<div className="text-xs text-slate-400">
Clears the saved auth token from this machine. Local emulator rules are kept.
</div>
</div>
<button
onClick={onDisconnect}
className="px-3.5 py-2 rounded-lg bg-rose-600 hover:bg-rose-500 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<LogOut className="w-3.5 h-3.5" /> Disconnect
</button>
</div>
</div>
);
};
+24
View File
@@ -0,0 +1,24 @@
@import "tailwindcss";
@layer base {
body {
font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, sans-serif;
background-color: #020617;
color: #f1f5f9;
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #0f172a;
}
::-webkit-scrollbar-thumb {
background: #334155;
border-radius: 9999px;
}
::-webkit-scrollbar-thumb:hover {
background: #475569;
}
}
+137
View File
@@ -0,0 +1,137 @@
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { openUrl } from "@tauri-apps/plugin-opener";
import type {
AppStateSnapshot,
BackupEntry,
DetectedNextUiVolume,
DeviceAuthInitResponse,
DiscoveredSaveItem,
EmulatorPresetInfo,
EmulatorRule,
LocalRomScanResult,
NextUiCardInspection,
PlatformSchema,
RemoteSavesAndStates,
RomPageResponse,
SyncRunSummary,
UserSchema,
WatcherSettings,
} from "./types";
export const api = {
getAppState: () => invoke<AppStateSnapshot>("get_app_state"),
testServer: (serverUrl: string) => invoke<unknown>("test_server", { serverUrl }),
startDeviceAuth: (serverUrl: string, deviceName: string) =>
invoke<DeviceAuthInitResponse>("start_device_auth", { serverUrl, deviceName }),
pollDeviceAuth: (serverUrl: string, deviceCode: string) =>
invoke<UserSchema | null>("poll_device_auth", { serverUrl, deviceCode }),
exchangePairCode: (serverUrl: string, code: string) =>
invoke<UserSchema>("exchange_pair_code", { serverUrl, code }),
connectWithToken: (serverUrl: string, token: string) =>
invoke<UserSchema>("connect_with_token", { serverUrl, token }),
loginWithPassword: (serverUrl: string, username: string, password: string) =>
invoke<UserSchema>("login_with_password", { serverUrl, username, password }),
disconnect: () => invoke<AppStateSnapshot>("disconnect"),
getEmulatorPresets: () => invoke<EmulatorPresetInfo[]>("get_emulator_presets"),
autoPopulateDetectedEmulators: () =>
invoke<AppStateSnapshot>("auto_populate_detected_emulators"),
upsertEmulatorRule: (rule: EmulatorRule) =>
invoke<AppStateSnapshot>("upsert_emulator_rule", { rule }),
deleteEmulatorRule: (emulatorId: string) =>
invoke<AppStateSnapshot>("delete_emulator_rule", { emulatorId }),
fetchPlatforms: () => invoke<PlatformSchema[]>("fetch_platforms"),
fetchRoms: (params: {
platformId?: number | null;
searchTerm?: string | null;
limit?: number;
offset?: number;
}) => invoke<RomPageResponse>("fetch_roms", params),
refreshRomCache: () => invoke<number>("refresh_rom_cache"),
scanLocalRomFolder: (folderPath: string, useHashLookup: boolean) =>
invoke<LocalRomScanResult[]>("scan_local_rom_folder", { folderPath, useHashLookup }),
downloadRomToFolder: (params: {
romId: number;
fileName: string;
destFolder?: string | null;
platformSlug?: string | null;
platformFsSlug?: string | null;
}) => invoke<string>("download_rom_to_folder", params),
fetchRemoteSavesAndStates: (romId?: number | null) =>
invoke<RemoteSavesAndStates>("fetch_remote_saves_and_states", { romId: romId ?? null }),
downloadSingleSave: (params: {
saveId: number;
romId: number;
fileName: string;
platformSlug: string;
platformFsSlug?: string | null;
emulatorHint?: string | null;
destOverride?: string | null;
}) => invoke<string>("download_single_save", params),
downloadSingleState: (params: {
stateId: number;
romId: number;
fileName: string;
platformSlug: string;
platformFsSlug?: string | null;
emulatorHint?: string | null;
destOverride?: string | null;
}) => invoke<string>("download_single_state", params),
uploadSingleSave: (params: {
localPath: string;
fileName: string;
romId: number;
emulatorId: string;
slot: string;
isDirectory: boolean;
isState: boolean;
}) => invoke<void>("upload_single_save", params),
discoverLocalSaves: () => invoke<DiscoveredSaveItem[]>("discover_local_saves"),
linkSaveToRom: (params: {
localPath: string;
romId: number;
romName: string;
emulatorId: string;
slot: string;
isState: boolean;
}) => invoke<void>("link_save_to_rom", params),
unlinkSave: (localPath: string) => invoke<void>("unlink_save", { localPath }),
runFullSync: () => invoke<SyncRunSummary>("run_full_sync"),
resolveSyncConflict: (conflictId: string, resolution: "keep_local" | "keep_server") =>
invoke<void>("resolve_sync_conflict", { conflictId, resolution }),
listBackups: () => invoke<BackupEntry[]>("list_backups"),
restoreBackup: (backupPath: string, targetPath: string, isDirectory: boolean) =>
invoke<void>("restore_backup", { backupPath, targetPath, isDirectory }),
saveSettings: (settings: WatcherSettings, deviceName?: string) =>
invoke<AppStateSnapshot>("save_settings", { settings, deviceName }),
clearSyncLogs: () => invoke<void>("clear_sync_logs"),
restartWatcher: () => invoke<AppStateSnapshot>("restart_watcher"),
detectNextUiVolumes: () => invoke<DetectedNextUiVolume[]>("detect_nextui_volumes"),
inspectNextUiCard: (sdRoot: string) =>
invoke<NextUiCardInspection>("inspect_nextui_card", { sdRoot }),
renameNextUiHandheld: (sdRoot: string, deviceName: string) =>
invoke<void>("rename_nextui_handheld", { sdRoot, deviceName }),
syncNextUiCard: (sdRoot: string, syncStates: boolean) =>
invoke<SyncRunSummary>("sync_nextui_card", { sdRoot, syncStates }),
downloadRomToNextUi: (params: {
sdRoot: string;
romId: number;
fileName: string;
platformSlug: string;
platformDisplayName: string;
}) => invoke<string>("download_rom_to_nextui", params),
pickFolder: async (title = "Select Folder"): Promise<string | null> => {
const selected = await open({ directory: true, multiple: false, title });
return typeof selected === "string" ? selected : null;
},
openExternalUrl: (url: string) => openUrl(url),
};
+253
View File
@@ -0,0 +1,253 @@
export type SaveStructure = "file_per_game" | "folder_per_game" | "memory_card";
export interface EmulatorRule {
id: string;
name: string;
platformSlugs: string[];
saveDir: string;
stateDir: string | null;
romDir: string | null;
saveExtensions: string[];
stateExtensions: string[];
structure: SaveStructure;
folderDepth: number;
enabled: boolean;
isCustom: boolean;
syncStates: boolean;
defaultSlot: string;
}
export interface EmulatorPresetInfo {
id: string;
name: string;
category: "console" | "handheld";
platformSlugs: string[];
detected: boolean;
detectedSaveDir: string | null;
detectedStateDir: string | null;
defaultSaveDir: string;
defaultStateDir: string | null;
saveExtensions: string[];
stateExtensions: string[];
structure: SaveStructure;
folderDepth: number;
notes: string;
}
export interface WatcherSettings {
enabled: boolean;
debounceSeconds: number;
autoSyncOnChange: boolean;
maxBackupsPerSave: number;
minimizeToTray: boolean;
defaultRomDownloadDir: string | null;
}
export interface SyncConflictItem {
id: string;
romId: number;
romName: string;
saveId: number | null;
localPath: string;
fileName: string;
isDirectory: boolean;
emulatorId: string;
slot: string;
localUpdatedAt: string;
serverUpdatedAt: string | null;
reason: string;
}
export interface SyncLogEntry {
id: string;
timestamp: string;
level: "info" | "success" | "warning" | "error";
action: string;
message: string;
romId: number | null;
filePath: string | null;
}
export interface AppStateSnapshot {
connected: boolean;
serverUrl: string;
username: string | null;
deviceId: string | null;
deviceName: string;
emulators: EmulatorRule[];
settings: WatcherSettings;
watcherActive: boolean;
watchedPaths: string[];
cachedRomCount: number;
conflicts: SyncConflictItem[];
logs: SyncLogEntry[];
}
export interface DeviceAuthInitResponse {
device_code: string;
user_code: string;
verification_path: string;
verification_path_complete: string;
expires_in: number;
interval: number;
}
export interface UserSchema {
id: number;
username: string;
email: string | null;
}
export interface PlatformSchema {
id: number;
slug: string;
fs_slug: string;
name: string;
display_name: string;
rom_count: number;
url_logo: string | null;
}
export interface SimpleRomSchema {
id: number;
platform_id: number;
platform_slug: string;
platform_fs_slug: string;
platform_display_name: string;
fs_name: string;
fs_name_no_tags: string;
fs_name_no_ext: string;
fs_extension: string;
fs_size_bytes: number;
name: string | null;
url_cover: string | null;
path_cover_small: string | null;
crc_hash: string | null;
md5_hash: string | null;
sha1_hash: string | null;
regions: string[];
}
export interface RomPageResponse {
items: SimpleRomSchema[];
total: number;
limit: number;
offset: number;
}
export interface DiscoveredSaveItem {
localPath: string;
fileName: string;
emulatorId: string;
emulatorName: string;
isDirectory: boolean;
isState: boolean;
sizeBytes: number;
updatedAt: string;
slot: string;
matchedRomId: number | null;
matchedRomName: string | null;
matchedPlatform: string | null;
matchConfidence: number;
matchSource: "manual" | "exact" | "fuzzy" | "unmatched";
}
export interface LocalRomScanResult {
localPath: string;
fileName: string;
sizeBytes: number;
crc32: string | null;
md5: string | null;
sha1: string | null;
matchedRomId: number | null;
matchedRomName: string | null;
matchedPlatform: string | null;
matchSource: "hash" | "filename" | "unmatched";
}
export interface SyncRunSummary {
sessionId: number | null;
uploadedSaves: number;
downloadedSaves: number;
uploadedStates: number;
upToDate: number;
conflicts: SyncConflictItem[];
errors: string[];
}
export interface BackupEntry {
backupPath: string;
romId: string;
fileName: string;
createdAt: string;
sizeBytes: number;
}
export interface RemoteSaveSchema {
id: number;
rom_id: number;
file_name: string;
file_size_bytes: number;
created_at: string;
updated_at: string;
emulator: string | null;
slot: string | null;
content_hash: string | null;
}
export interface RemoteStateSchema {
id: number;
rom_id: number;
file_name: string;
file_size_bytes: number;
created_at: string;
updated_at: string;
emulator: string | null;
}
export interface RemoteSavesAndStates {
saves: RemoteSaveSchema[];
states: RemoteStateSchema[];
}
export interface DetectedNextUiVolume {
path: string;
label: string;
detectedPlatform: string;
deviceLabel: string;
systemTags: string[];
hasSaves: boolean;
hasRoms: boolean;
}
export interface NextUiSdSaveItem {
localPath: string;
fileName: string;
systemTag: string;
isDirectory: boolean;
isState: boolean;
sizeBytes: number;
updatedAt: string;
slot: string;
matchedRomId: number | null;
matchedRomName: string | null;
matchedPlatform: string | null;
matchConfidence: number;
matchSource: "manual" | "exact" | "fuzzy" | "unmatched";
}
export interface NextUiCardInspection {
sdRoot: string;
detectedPlatform: string;
deviceName: string;
handheldDeviceId: string | null;
systemTags: string[];
saves: NextUiSdSaveItem[];
}
export function formatBytes(bytes: number): string {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
return `${(bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
}
+10
View File
@@ -0,0 +1,10 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2021",
"useDefineForClassFields": true,
"lib": ["ES2021", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+25
View File
@@ -0,0 +1,25 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
const host = process.env.TAURI_DEV_HOST;
export default defineConfig({
plugins: [react(), tailwindcss()],
clearScreen: false,
server: {
port: 1420,
strictPort: true,
host: host || false,
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
ignored: ["**/src-tauri/**"],
},
},
});