Add: windows mvp - transparent bugs not fixed

This commit is contained in:
DaZuo0122
2026-02-12 22:58:33 +08:00
commit 61825f647d
147 changed files with 28498 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
[package]
name = "sprimo-api"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tokio.workspace = true
sprimo-protocol = { path = "../sprimo-protocol" }
uuid.workspace = true
[dev-dependencies]
tower = "0.5.2"

View File

@@ -0,0 +1,405 @@
use axum::body::Bytes;
use axum::extract::{Json, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::Router;
use sprimo_protocol::v1::{
CommandEnvelope, ErrorResponse, FrontendStateSnapshot, HealthResponse,
};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};
use thiserror::Error;
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use uuid::Uuid;
#[derive(Debug, Clone)]
pub struct ApiConfig {
pub bind_addr: SocketAddr,
pub auth_token: String,
pub app_version: String,
pub app_build: String,
pub dedupe_capacity: usize,
pub dedupe_ttl: Duration,
}
impl ApiConfig {
#[must_use]
pub fn default_with_token(auth_token: String) -> Self {
Self {
bind_addr: SocketAddr::from(([127, 0, 0, 1], 32_145)),
auth_token,
app_version: env!("CARGO_PKG_VERSION").to_string(),
app_build: "dev".to_string(),
dedupe_capacity: 5_000,
dedupe_ttl: Duration::from_secs(600),
}
}
}
#[derive(Debug)]
pub struct ApiState {
start_at: Instant,
auth_token: String,
app_version: String,
app_build: String,
dedupe_capacity: usize,
dedupe_ttl: Duration,
recent_ids: Mutex<HashMap<Uuid, Instant>>,
snapshot: Arc<RwLock<FrontendStateSnapshot>>,
command_tx: mpsc::Sender<CommandEnvelope>,
}
impl ApiState {
#[must_use]
pub fn new(
config: ApiConfig,
snapshot: Arc<RwLock<FrontendStateSnapshot>>,
command_tx: mpsc::Sender<CommandEnvelope>,
) -> Self {
Self {
start_at: Instant::now(),
auth_token: config.auth_token,
app_version: config.app_version,
app_build: config.app_build,
dedupe_capacity: config.dedupe_capacity,
dedupe_ttl: config.dedupe_ttl,
recent_ids: Mutex::new(HashMap::new()),
snapshot,
command_tx,
}
}
}
#[derive(Debug, Error)]
pub enum ApiServerError {
#[error("bind failed: {0}")]
Bind(#[from] std::io::Error),
}
pub fn app_router(state: Arc<ApiState>) -> Router {
Router::new()
.route("/v1/health", get(handle_health))
.route("/v1/state", get(handle_state))
.route("/v1/command", post(handle_command))
.route("/v1/commands", post(handle_commands))
.with_state(state)
}
pub async fn run_server(config: ApiConfig, state: Arc<ApiState>) -> Result<(), ApiServerError> {
let listener = TcpListener::bind(config.bind_addr).await?;
axum::serve(listener, app_router(state))
.await
.map_err(ApiServerError::Bind)?;
Ok(())
}
async fn handle_health(State(state): State<Arc<ApiState>>) -> Json<HealthResponse> {
let snapshot = state
.snapshot
.read()
.expect("frontend snapshot lock poisoned");
Json(HealthResponse {
version: state.app_version.clone(),
build: state.app_build.clone(),
uptime_seconds: state.start_at.elapsed().as_secs(),
active_sprite_pack: snapshot.active_sprite_pack.clone(),
capabilities: snapshot.capabilities.clone(),
})
}
async fn handle_state(
State(state): State<Arc<ApiState>>,
headers: HeaderMap,
) -> Result<Json<FrontendStateSnapshot>, ApiError> {
require_auth(&headers, &state)?;
let snapshot = state
.snapshot
.read()
.map_err(|_| ApiError::Internal("snapshot lock poisoned".to_string()))?
.clone();
Ok(Json(snapshot))
}
async fn handle_command(
State(state): State<Arc<ApiState>>,
headers: HeaderMap,
body: Bytes,
) -> Result<StatusCode, ApiError> {
require_auth(&headers, &state)?;
let command: CommandEnvelope =
serde_json::from_slice(&body).map_err(|e| ApiError::BadJson(e.to_string()))?;
enqueue_if_new(&state, command).await?;
Ok(StatusCode::ACCEPTED)
}
async fn handle_commands(
State(state): State<Arc<ApiState>>,
headers: HeaderMap,
body: Bytes,
) -> Result<StatusCode, ApiError> {
require_auth(&headers, &state)?;
let commands: Vec<CommandEnvelope> =
serde_json::from_slice(&body).map_err(|e| ApiError::BadJson(e.to_string()))?;
for command in commands {
enqueue_if_new(&state, command).await?;
}
Ok(StatusCode::ACCEPTED)
}
async fn enqueue_if_new(state: &ApiState, command: CommandEnvelope) -> Result<(), ApiError> {
let now = Instant::now();
{
let mut ids = state
.recent_ids
.lock()
.map_err(|_| ApiError::Internal("dedupe lock poisoned".to_string()))?;
ids.retain(|_, seen_at| now.duration_since(*seen_at) < state.dedupe_ttl);
if ids.contains_key(&command.id) {
return Ok(());
}
if ids.len() >= state.dedupe_capacity {
let oldest = ids
.iter()
.min_by_key(|(_, seen_at)| *seen_at)
.map(|(id, _)| *id);
if let Some(oldest) = oldest {
ids.remove(&oldest);
}
}
ids.insert(command.id, now);
}
state
.command_tx
.send(command)
.await
.map_err(|_| ApiError::Internal("command receiver dropped".to_string()))
}
fn require_auth(headers: &HeaderMap, state: &ApiState) -> Result<(), ApiError> {
let raw = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.ok_or(ApiError::Unauthorized)?;
let expected = format!("Bearer {}", state.auth_token);
if raw == expected {
return Ok(());
}
Err(ApiError::Unauthorized)
}
enum ApiError {
Unauthorized,
BadJson(String),
Internal(String),
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
match self {
Self::Unauthorized => (
StatusCode::UNAUTHORIZED,
Json(ErrorResponse {
code: "unauthorized".to_string(),
message: "missing or invalid bearer token".to_string(),
}),
)
.into_response(),
Self::BadJson(message) => (
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
code: "bad_json".to_string(),
message,
}),
)
.into_response(),
Self::Internal(message) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
code: "internal".to_string(),
message,
}),
)
.into_response(),
}
}
}
#[cfg(test)]
mod tests {
use super::{app_router, ApiConfig, ApiState};
use axum::body::Body;
use axum::http::{Request, StatusCode};
use sprimo_protocol::v1::{
CapabilityFlags, CommandEnvelope, FrontendCommand, FrontendStateSnapshot,
};
use std::sync::{Arc, RwLock};
use tokio::sync::mpsc;
use tower::ServiceExt;
use uuid::Uuid;
fn build_state() -> (Arc<ApiState>, mpsc::Receiver<CommandEnvelope>) {
let snapshot =
FrontendStateSnapshot::idle(CapabilityFlags::default());
let snapshot = Arc::new(RwLock::new(snapshot));
let (tx, rx) = mpsc::channel(8);
(
Arc::new(ApiState::new(
ApiConfig::default_with_token("token".to_string()),
snapshot,
tx,
)),
rx,
)
}
#[tokio::test]
async fn health_does_not_require_auth() {
let (state, _) = build_state();
let app = app_router(state);
let response = app
.oneshot(
Request::builder()
.uri("/v1/health")
.body(Body::empty())
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn command_requires_auth() {
let (state, _) = build_state();
let app = app_router(state);
let command = CommandEnvelope {
id: Uuid::new_v4(),
ts_ms: 1,
command: FrontendCommand::Toast {
text: "hi".to_string(),
ttl_ms: None,
},
};
let body = serde_json::to_vec(&command).expect("json");
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/command")
.header("content-type", "application/json")
.body(Body::from(body))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn command_accepts_with_auth() {
let (state, mut rx) = build_state();
let app = app_router(state);
let command = CommandEnvelope {
id: Uuid::new_v4(),
ts_ms: 1,
command: FrontendCommand::Toast {
text: "hi".to_string(),
ttl_ms: None,
},
};
let body = serde_json::to_vec(&command).expect("json");
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/command")
.header("content-type", "application/json")
.header("authorization", "Bearer token")
.body(Body::from(body))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::ACCEPTED);
let received = rx.recv().await.expect("forwarded command");
assert_eq!(received.id, command.id);
}
#[tokio::test]
async fn malformed_json_returns_bad_request() {
let (state, _) = build_state();
let app = app_router(state);
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/command")
.header("content-type", "application/json")
.header("authorization", "Bearer token")
.body(Body::from("{ not-json }"))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn duplicate_command_is_deduped() {
let (state, mut rx) = build_state();
let app = app_router(state);
let command = CommandEnvelope {
id: Uuid::new_v4(),
ts_ms: 1,
command: FrontendCommand::Toast {
text: "hi".to_string(),
ttl_ms: None,
},
};
let body = serde_json::to_vec(&command).expect("json");
let first = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/command")
.header("content-type", "application/json")
.header("authorization", "Bearer token")
.body(Body::from(body.clone()))
.expect("request"),
)
.await
.expect("response");
assert_eq!(first.status(), StatusCode::ACCEPTED);
let second = app
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/command")
.header("content-type", "application/json")
.header("authorization", "Bearer token")
.body(Body::from(body))
.expect("request"),
)
.await
.expect("response");
assert_eq!(second.status(), StatusCode::ACCEPTED);
let one = rx.recv().await.expect("first command");
assert_eq!(one.id, command.id);
assert!(rx.try_recv().is_err());
}
}

View File

@@ -0,0 +1,29 @@
[package]
name = "sprimo-app"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
bevy.workspace = true
image = { version = "0.25.9", default-features = false, features = ["png"] }
raw-window-handle = "0.6.2"
sprimo-api = { path = "../sprimo-api" }
sprimo-config = { path = "../sprimo-config" }
sprimo-platform = { path = "../sprimo-platform" }
sprimo-protocol = { path = "../sprimo-protocol" }
sprimo-sprite = { path = "../sprimo-sprite" }
thiserror.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.58.0", features = [
"Win32_Foundation",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_WindowsAndMessaging",
] }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
[package]
name = "sprimo-config"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
directories.workspace = true
serde.workspace = true
thiserror.workspace = true
toml.workspace = true
uuid.workspace = true
[dev-dependencies]
tempfile = "3.18.0"

View File

@@ -0,0 +1,206 @@
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;
use uuid::Uuid;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("no supported configuration directory for this platform")]
MissingProjectDir,
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("invalid config file: {0}")]
Parse(#[from] toml::de::Error),
#[error("could not encode config: {0}")]
Encode(#[from] toml::ser::Error),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AppConfig {
pub window: WindowConfig,
pub animation: AnimationConfig,
pub sprite: SpriteConfig,
pub api: ApiConfig,
pub logging: LoggingConfig,
pub controls: ControlsConfig,
}
impl Default for AppConfig {
fn default() -> Self {
Self {
window: WindowConfig::default(),
animation: AnimationConfig::default(),
sprite: SpriteConfig::default(),
api: ApiConfig::default(),
logging: LoggingConfig::default(),
controls: ControlsConfig::default(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WindowConfig {
pub x: f32,
pub y: f32,
pub monitor_id: Option<String>,
pub scale: f32,
pub always_on_top: bool,
pub click_through: bool,
pub visible: bool,
}
impl Default for WindowConfig {
fn default() -> Self {
Self {
x: 200.0,
y: 200.0,
monitor_id: None,
scale: 1.0,
always_on_top: true,
click_through: false,
visible: true,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AnimationConfig {
pub fps: u16,
pub idle_timeout_ms: u64,
}
impl Default for AnimationConfig {
fn default() -> Self {
Self {
fps: 30,
idle_timeout_ms: 3_000,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SpriteConfig {
pub selected_pack: String,
pub sprite_packs_dir: String,
}
impl Default for SpriteConfig {
fn default() -> Self {
Self {
selected_pack: "default".to_string(),
sprite_packs_dir: "sprite-packs".to_string(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ApiConfig {
pub port: u16,
pub auth_token: String,
}
impl Default for ApiConfig {
fn default() -> Self {
Self {
port: 32_145,
auth_token: Uuid::new_v4().to_string(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LoggingConfig {
pub level: String,
}
impl Default for LoggingConfig {
fn default() -> Self {
Self {
level: "info".to_string(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ControlsConfig {
pub hotkey_enabled: bool,
pub recovery_hotkey: String,
}
impl Default for ControlsConfig {
fn default() -> Self {
Self {
hotkey_enabled: true,
recovery_hotkey: "Ctrl+Alt+P".to_string(),
}
}
}
#[must_use]
pub fn config_path(app_name: &str) -> Result<PathBuf, ConfigError> {
let dirs =
ProjectDirs::from("", "", app_name).ok_or(ConfigError::MissingProjectDir)?;
Ok(dirs.config_dir().join("config.toml"))
}
pub fn load_or_create(app_name: &str) -> Result<(PathBuf, AppConfig), ConfigError> {
let path = config_path(app_name)?;
load_or_create_at(&path)
}
pub fn load_or_create_at(path: &Path) -> Result<(PathBuf, AppConfig), ConfigError> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
if !path.exists() {
let cfg = AppConfig::default();
save(path, &cfg)?;
return Ok((path.to_path_buf(), cfg));
}
let raw = fs::read_to_string(path)?;
let cfg = toml::from_str::<AppConfig>(&raw)?;
Ok((path.to_path_buf(), cfg))
}
pub fn save(path: &Path, config: &AppConfig) -> Result<(), ConfigError> {
let encoded = toml::to_string_pretty(config)?;
fs::write(path, encoded)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::{load_or_create_at, save, AppConfig};
use tempfile::TempDir;
#[test]
fn bootstrap_writes_default_config() {
let temp = TempDir::new().expect("tempdir");
let path = temp.path().join("config.toml");
let (_, config) = load_or_create_at(&path).expect("load or create");
assert_eq!(config.api.port, 32_145);
}
#[test]
fn save_roundtrip() {
let temp = TempDir::new().expect("tempdir");
let path = temp.path().join("config.toml");
let mut config = AppConfig::default();
config.window.x = 42.0;
save(&path, &config).expect("save");
let (_, loaded) = load_or_create_at(&path).expect("reload");
assert!((loaded.window.x - 42.0).abs() < f32::EPSILON);
}
}

View File

@@ -0,0 +1,18 @@
[package]
name = "sprimo-platform"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
sprimo-protocol = { path = "../sprimo-protocol" }
thiserror.workspace = true
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.58.0", features = [
"Win32_Foundation",
"Win32_UI_WindowsAndMessaging",
] }

View File

@@ -0,0 +1,252 @@
use sprimo_protocol::v1::CapabilityFlags;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum PlatformError {
#[error("operation unsupported on this platform")]
Unsupported,
#[error("platform operation failed: {0}")]
Message(String),
}
pub trait PlatformAdapter: Send + Sync {
fn capabilities(&self) -> CapabilityFlags;
fn attach_window_handle(&self, handle: isize) -> Result<(), PlatformError>;
fn set_click_through(&self, enabled: bool) -> Result<(), PlatformError>;
fn set_always_on_top(&self, enabled: bool) -> Result<(), PlatformError>;
fn set_visible(&self, visible: bool) -> Result<(), PlatformError>;
fn set_window_position(&self, x: f32, y: f32) -> Result<(), PlatformError>;
}
pub fn create_adapter() -> Box<dyn PlatformAdapter> {
#[cfg(target_os = "windows")]
{
return Box::new(windows::WindowsAdapter::default());
}
#[cfg(not(target_os = "windows"))]
{
Box::new(NoopAdapter::default())
}
}
#[derive(Debug, Default)]
pub struct NoopAdapter {
_private: (),
}
impl PlatformAdapter for NoopAdapter {
fn capabilities(&self) -> CapabilityFlags {
CapabilityFlags::default()
}
fn attach_window_handle(&self, _handle: isize) -> Result<(), PlatformError> {
Ok(())
}
fn set_click_through(&self, _enabled: bool) -> Result<(), PlatformError> {
Err(PlatformError::Unsupported)
}
fn set_always_on_top(&self, _enabled: bool) -> Result<(), PlatformError> {
Ok(())
}
fn set_visible(&self, _visible: bool) -> Result<(), PlatformError> {
Ok(())
}
fn set_window_position(&self, _x: f32, _y: f32) -> Result<(), PlatformError> {
Ok(())
}
}
#[cfg(target_os = "windows")]
#[allow(unsafe_code)]
mod windows {
use crate::{PlatformAdapter, PlatformError};
use sprimo_protocol::v1::CapabilityFlags;
use std::ffi::c_void;
use std::sync::Mutex;
use windows::Win32::Foundation::{COLORREF, GetLastError, HWND};
use windows::Win32::UI::WindowsAndMessaging::{
GetWindowLongPtrW, SetLayeredWindowAttributes, SetWindowLongPtrW, SetWindowPos,
ShowWindow, GWL_EXSTYLE, HWND_NOTOPMOST, HWND_TOPMOST, LWA_COLORKEY, SW_HIDE, SW_SHOW,
SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WINDOW_EX_STYLE, WS_EX_LAYERED,
WS_EX_TRANSPARENT,
};
const COLOR_KEY_RGB: [u8; 3] = [255, 0, 255];
#[derive(Debug, Default)]
pub struct WindowsAdapter {
hwnd: Mutex<Option<isize>>,
}
impl WindowsAdapter {
fn enable_color_key_transparency(hwnd: HWND) -> Result<(), PlatformError> {
// SAFETY: `hwnd` comes from a real native window handle attached during startup.
let current_bits = unsafe { GetWindowLongPtrW(hwnd, GWL_EXSTYLE) };
let mut style = WINDOW_EX_STYLE(current_bits as u32);
style |= WS_EX_LAYERED;
// SAFETY: We pass the same valid window handle and write a computed style bitmask.
let previous = unsafe { SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style.0 as isize) };
if previous == 0 {
// SAFETY: Calling `GetLastError` immediately after failed Win32 API is valid.
let code = unsafe { GetLastError().0 };
if code != 0 {
return Err(PlatformError::Message(format!(
"SetWindowLongPtrW(layered) failed: {}",
code
)));
}
}
let key = COLORREF(
u32::from(COLOR_KEY_RGB[0])
| (u32::from(COLOR_KEY_RGB[1]) << 8)
| (u32::from(COLOR_KEY_RGB[2]) << 16),
);
// SAFETY: `hwnd` is valid and colorkey transparency is configured on a layered window.
let result = unsafe { SetLayeredWindowAttributes(hwnd, key, 0, LWA_COLORKEY) };
if let Err(err) = result {
// SAFETY: Calling `GetLastError` immediately after failed Win32 API is valid.
let code = unsafe { GetLastError().0 };
return Err(PlatformError::Message(format!(
"SetLayeredWindowAttributes(colorkey) failed: {} ({})",
code, err
)));
}
Ok(())
}
fn apply_click_through_style(
hwnd: HWND,
click_through: Option<bool>,
) -> Result<(), PlatformError> {
// SAFETY: `hwnd` comes from a real native window handle attached during startup.
let current_bits = unsafe { GetWindowLongPtrW(hwnd, GWL_EXSTYLE) };
let mut style = WINDOW_EX_STYLE(current_bits as u32);
if let Some(enabled) = click_through {
if enabled {
style |= WS_EX_TRANSPARENT;
} else {
style &= !WS_EX_TRANSPARENT;
}
}
// SAFETY: We pass the same valid window handle and write a computed style bitmask.
let previous = unsafe { SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style.0 as isize) };
if previous == 0 {
// SAFETY: Calling `GetLastError` immediately after failed Win32 API is valid.
let code = unsafe { GetLastError().0 };
if code != 0 {
return Err(PlatformError::Message(format!(
"SetWindowLongPtrW failed: {}",
code
)));
}
}
Ok(())
}
fn with_hwnd<F>(&self, callback: F) -> Result<(), PlatformError>
where
F: FnOnce(HWND) -> Result<(), PlatformError>,
{
let guard = self
.hwnd
.lock()
.map_err(|_| PlatformError::Message("window handle lock poisoned".to_string()))?;
let hwnd = guard.ok_or_else(|| {
PlatformError::Message("window handle not attached".to_string())
})?;
callback(HWND(hwnd as *mut c_void))
}
}
impl PlatformAdapter for WindowsAdapter {
fn capabilities(&self) -> CapabilityFlags {
CapabilityFlags {
supports_click_through: true,
supports_transparency: true,
supports_tray: false,
supports_global_hotkey: true,
supports_skip_taskbar: true,
}
}
fn attach_window_handle(&self, handle: isize) -> Result<(), PlatformError> {
{
let mut guard = self.hwnd.lock().map_err(|_| {
PlatformError::Message("window handle lock poisoned".to_string())
})?;
*guard = Some(handle);
}
self.with_hwnd(Self::enable_color_key_transparency)
}
fn set_click_through(&self, enabled: bool) -> Result<(), PlatformError> {
self.with_hwnd(|hwnd| Self::apply_click_through_style(hwnd, Some(enabled)))
}
fn set_always_on_top(&self, enabled: bool) -> Result<(), PlatformError> {
self.with_hwnd(|hwnd| {
let insert_after = if enabled { HWND_TOPMOST } else { HWND_NOTOPMOST };
// SAFETY: `hwnd` is valid and flags request only z-order update.
let result = unsafe {
SetWindowPos(hwnd, insert_after, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE)
};
if let Err(err) = result {
// SAFETY: Calling `GetLastError` immediately after failed Win32 API is valid.
let code = unsafe { GetLastError().0 };
return Err(PlatformError::Message(format!(
"SetWindowPos(topmost) failed: {} ({})",
code, err
)));
}
Ok(())
})
}
fn set_visible(&self, visible: bool) -> Result<(), PlatformError> {
self.with_hwnd(|hwnd| {
let command = if visible { SW_SHOW } else { SW_HIDE };
// SAFETY: `hwnd` is valid and `ShowWindow` is safe with these standard commands.
unsafe {
let _ = ShowWindow(hwnd, command);
}
Ok(())
})
}
fn set_window_position(&self, x: f32, y: f32) -> Result<(), PlatformError> {
self.with_hwnd(|hwnd| {
// SAFETY: `hwnd` is valid and this call updates only position.
let result = unsafe {
SetWindowPos(
hwnd,
HWND(std::ptr::null_mut()),
x.round() as i32,
y.round() as i32,
0,
0,
SWP_NOSIZE | SWP_NOZORDER,
)
};
if let Err(err) = result {
// SAFETY: Calling `GetLastError` immediately after failed Win32 API is valid.
let code = unsafe { GetLastError().0 };
return Err(PlatformError::Message(format!(
"SetWindowPos(move) failed: {} ({})",
code, err
)));
}
Ok(())
})
}
}
}

View File

@@ -0,0 +1,15 @@
[package]
name = "sprimo-protocol"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
serde.workspace = true
uuid.workspace = true
[dev-dependencies]
serde_json.workspace = true

View File

@@ -0,0 +1,173 @@
pub mod v1 {
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendState {
Idle,
Active,
Success,
Error,
Dragging,
Hidden,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct AnimationPriority(pub u8);
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CommandEnvelope {
pub id: Uuid,
pub ts_ms: i64,
pub command: FrontendCommand,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "payload", rename_all = "snake_case")]
pub enum FrontendCommand {
SetState {
state: FrontendState,
ttl_ms: Option<u64>,
},
PlayAnimation {
name: String,
priority: AnimationPriority,
duration_ms: Option<u64>,
interrupt: Option<bool>,
},
SetSpritePack {
pack_id_or_path: String,
},
SetTransform {
x: Option<f32>,
y: Option<f32>,
anchor: Option<String>,
scale: Option<f32>,
opacity: Option<f32>,
},
SetFlags {
click_through: Option<bool>,
always_on_top: Option<bool>,
visible: Option<bool>,
},
Toast {
text: String,
ttl_ms: Option<u64>,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CapabilityFlags {
pub supports_click_through: bool,
pub supports_transparency: bool,
pub supports_tray: bool,
pub supports_global_hotkey: bool,
pub supports_skip_taskbar: bool,
}
impl Default for CapabilityFlags {
fn default() -> Self {
Self {
supports_click_through: false,
supports_transparency: true,
supports_tray: false,
supports_global_hotkey: false,
supports_skip_taskbar: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OverlayFlags {
pub click_through: bool,
pub always_on_top: bool,
pub visible: bool,
}
impl Default for OverlayFlags {
fn default() -> Self {
Self {
click_through: false,
always_on_top: true,
visible: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FrontendStateSnapshot {
pub state: FrontendState,
pub current_animation: String,
pub flags: OverlayFlags,
pub x: f32,
pub y: f32,
pub scale: f32,
pub active_sprite_pack: String,
pub capabilities: CapabilityFlags,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_error: Option<String>,
}
impl FrontendStateSnapshot {
#[must_use]
pub fn idle(capabilities: CapabilityFlags) -> Self {
Self {
state: FrontendState::Idle,
current_animation: "idle".to_string(),
flags: OverlayFlags::default(),
x: 200.0,
y: 200.0,
scale: 1.0,
active_sprite_pack: "default".to_string(),
capabilities,
last_error: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HealthResponse {
pub version: String,
pub build: String,
pub uptime_seconds: u64,
pub active_sprite_pack: String,
pub capabilities: CapabilityFlags,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
pub code: String,
pub message: String,
}
}
#[cfg(test)]
mod tests {
use super::v1::{AnimationPriority, CommandEnvelope, FrontendCommand, FrontendState};
use uuid::Uuid;
#[test]
fn command_envelope_roundtrip() {
let payload = CommandEnvelope {
id: Uuid::nil(),
ts_ms: 1_737_000_000_000,
command: FrontendCommand::PlayAnimation {
name: "dance".to_string(),
priority: AnimationPriority(9),
duration_ms: Some(1_200),
interrupt: Some(true),
},
};
let encoded = serde_json::to_string(&payload).expect("serialize");
let decoded: CommandEnvelope = serde_json::from_str(&encoded).expect("deserialize");
assert_eq!(decoded, payload);
}
#[test]
fn state_serializes_as_snake_case() {
let encoded = serde_json::to_string(&FrontendState::Hidden).expect("serialize");
assert_eq!(encoded, "\"hidden\"");
}
}

View File

@@ -0,0 +1,16 @@
[package]
name = "sprimo-sprite"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
[dev-dependencies]
tempfile = "3.18.0"

View File

@@ -0,0 +1,123 @@
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;
const MANIFEST_FILE: &str = "manifest.json";
#[derive(Debug, Error)]
pub enum SpriteError {
#[error("sprite pack not found: {0}")]
PackNotFound(String),
#[error("manifest not found: {0}")]
ManifestNotFound(PathBuf),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("invalid manifest: {0}")]
Parse(#[from] serde_json::Error),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpritePackManifest {
pub id: String,
pub version: String,
pub image: String,
pub frame_width: u32,
pub frame_height: u32,
pub animations: Vec<AnimationDefinition>,
pub anchor: AnchorPoint,
#[serde(default)]
pub chroma_key_color: Option<String>,
#[serde(default)]
pub chroma_key_enabled: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnimationDefinition {
pub name: String,
pub fps: u16,
pub frames: Vec<u32>,
pub one_shot: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnchorPoint {
pub x: f32,
pub y: f32,
}
pub fn load_manifest(pack_dir: &Path) -> Result<SpritePackManifest, SpriteError> {
let manifest_path = pack_dir.join(MANIFEST_FILE);
if !manifest_path.exists() {
return Err(SpriteError::ManifestNotFound(manifest_path));
}
let raw = fs::read_to_string(&manifest_path)?;
let manifest = serde_json::from_str::<SpritePackManifest>(&raw)?;
Ok(manifest)
}
pub fn resolve_pack_path(root: &Path, pack_id_or_path: &str) -> Result<PathBuf, SpriteError> {
let direct = PathBuf::from(pack_id_or_path);
if direct.exists() {
return Ok(direct);
}
let candidate = root.join(pack_id_or_path);
if candidate.exists() {
return Ok(candidate);
}
Err(SpriteError::PackNotFound(pack_id_or_path.to_string()))
}
pub fn load_selected_or_default(
root: &Path,
selected_pack: &str,
default_pack: &str,
) -> Result<SpritePackManifest, SpriteError> {
let selected = resolve_pack_path(root, selected_pack)
.and_then(|path| load_manifest(&path));
if let Ok(manifest) = selected {
return Ok(manifest);
}
let fallback_path = resolve_pack_path(root, default_pack)?;
load_manifest(&fallback_path)
}
#[cfg(test)]
mod tests {
use super::{load_selected_or_default, SpritePackManifest};
use std::fs;
use tempfile::TempDir;
fn write_manifest(dir: &std::path::Path, id: &str) {
let manifest = SpritePackManifest {
id: id.to_string(),
version: "1".to_string(),
image: "atlas.png".to_string(),
frame_width: 64,
frame_height: 64,
animations: vec![],
anchor: super::AnchorPoint { x: 0.5, y: 1.0 },
chroma_key_color: None,
chroma_key_enabled: None,
};
let encoded = serde_json::to_string_pretty(&manifest).expect("manifest encode");
fs::write(dir.join("manifest.json"), encoded).expect("manifest write");
}
#[test]
fn fallback_to_default_pack() {
let temp = TempDir::new().expect("tempdir");
let root = temp.path();
let default_dir = root.join("default");
fs::create_dir_all(&default_dir).expect("mkdir");
write_manifest(&default_dir, "default");
let manifest =
load_selected_or_default(root, "missing", "default").expect("fallback");
assert_eq!(manifest.id, "default");
}
}