Nacre/src/instance.rs
astar76 d2bb67f4ea S001: first build compiles; fix 5 compile errors in place
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:27:07 -06:00

96 lines
3.7 KiB
Rust

//! Single instance per profile: a running Nacre listens on a loopback port; a second launch
//! hands its links to it and exits. The port and a random token are in the profile's data folder.
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use winit::event_loop::EventLoopProxy;
use crate::app::{App, AppEvent, Job, Launch};
use crate::paths::Paths;
use crate::util;
#[derive(Serialize, Deserialize, Default)]
struct InstanceFile {
port: u16,
token: String,
pid: u32,
}
#[derive(Serialize, Deserialize)]
struct Message {
token: String,
launch: Launch,
}
pub struct Server {
stop: Arc<AtomicBool>,
file: std::path::PathBuf,
}
impl Server {
pub fn start(paths: &Paths, jobs: Sender<Job>, proxy: EventLoopProxy<AppEvent>) -> Result<Server, String> {
if paths.incognito {
return Err("incognito windows are separate".into());
}
let listener = TcpListener::bind(("127.0.0.1", 0)).map_err(|e| e.to_string())?;
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
let token = util::random_hex(16);
let file = paths.instance_file();
util::save_json_private(&file, &InstanceFile { port, token: token.clone(), pid: std::process::id() }).map_err(|e| e.to_string())?;
let stop = Arc::new(AtomicBool::new(false));
let stopping = stop.clone();
std::thread::Builder::new()
.name("nacre-instance".into())
.spawn(move || {
for stream in listener.incoming() {
if stopping.load(Ordering::Relaxed) {
break;
}
let Ok(stream) = stream else { continue };
let _ = stream.set_read_timeout(Some(Duration::from_secs(3)));
let mut line = String::new();
if BufReader::new(&stream).take(1024 * 1024).read_line(&mut line).is_err() {
continue;
}
let Ok(message) = serde_json::from_str::<Message>(&line) else { continue };
if message.token != token {
continue;
}
let mut s = &stream;
let _ = s.write_all(b"ok\n");
let launch = message.launch;
let _ = jobs.send(Box::new(move |app: &mut App| app.pending_launches.push(launch)));
let _ = proxy.send_event(AppEvent::Wake);
}
})
.map_err(|e| e.to_string())?;
Ok(Server { stop, file })
}
pub fn stop(self) {
self.stop.store(true, Ordering::Relaxed);
let _ = std::fs::remove_file(&self.file);
}
}
/// Hand `launch` to a running Nacre for this profile. True if one took it.
pub fn hand_off(paths: &Paths, launch: &Launch) -> bool {
let info: InstanceFile = util::load_json(&paths.instance_file());
if info.port == 0 || info.token.is_empty() {
return false;
}
let Ok(mut stream) = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], info.port)), Duration::from_millis(500)) else { return false };
let _ = stream.set_read_timeout(Some(Duration::from_secs(3)));
let Ok(text) = serde_json::to_string(&Message { token: info.token, launch: launch.clone() }) else { return false };
if stream.write_all(format!("{text}\n").as_bytes()).is_err() {
return false;
}
let mut reply = String::new();
BufReader::new(&stream).read_line(&mut reply).is_ok() && reply.trim() == "ok"
}