PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Flatpak: a second launch hands its files to the running PhotoCraft over a Unix socket (#1540)
Diego Chagasf2a487b08845
diff --git a/apps/photocraft/src/single_instance.rs b/apps/photocraft/src/single_instance.rsindex d2cd65c67..4b57fa694 100644--- a/apps/photocraft/src/single_instance.rs+++ b/apps/photocraft/src/single_instance.rs@@ -3,8 +3,9 @@//! copy of the program.//!//! The first launch takes an exclusive OS lock on `instance.lock` in the settings directory (the OS-//! drops it when the process ends, crash included), listens on a loopback port and writes the port-//! plus a fresh 256-bit token to `instance.json`. A later launch that finds the lock taken sends its+//! drops it when the process ends, crash included), listens on a loopback port (inside a Flatpak+//! sandbox, on a Unix socket: see [`transport`]) and writes where it listens plus a fresh 256-bit+//! token to `instance.json`. A later launch that finds the lock taken sends its//! paths there; the primary queues them for the UI as [`OsEvent::Open`], which opens each one and//! brings the window forward. Explorer starts one process per file when several are opened at once;//! the lock decides the race, so they all end up as tabs in one window.@@ -26,7 +27,11 @@use std::fs::{File, OpenOptions};use std::io::{BufReader, Read, Write};use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};+#[cfg(unix)]+use std::os::unix::net::{UnixListener, UnixStream};use std::path::Path;+#[cfg(unix)]+use std::path::PathBuf;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::mpsc::{SyncSender, sync_channel};use std::sync::{Arc, Mutex, PoisonError};@@ -38,6 +43,9 @@ use serde_json::{Value, json};const LOCK_FILE: &str = "instance.lock";const INFO_FILE: &str = "instance.json";+/// The Unix socket a sandboxed primary listens on, in the app's runtime directory.+#[cfg(unix)]+const SOCKET_FILE: &str = "instance.sock";/// More paths than this in one request is not a file manager.const MAX_PATHS: usize = 4096;/// Launches served at once; a stalled client holds only its own slot, never the next launch.@@ -59,6 +67,45 @@ pub struct Timing {/// Generous enough for a primary that is still opening its window.pub const TIMING: Timing = Timing { handoff: Duration::from_secs(10), ack: Duration::from_secs(8), request: Duration::from_secs(5) };+/// How the primary listens for later launches.+#[derive(Clone, Debug, PartialEq)]+pub enum Transport {+ /// A loopback port (the default): private to the machine, reachable by every process on it.+ Loopback,+ /// A Unix socket at this path. Inside a Flatpak sandbox a loopback port is not enough: each+ /// `flatpak run` has its own network namespace, so the second sandbox's `127.0.0.1` never+ /// reaches the first (#1540). `$XDG_RUNTIME_DIR/app/<app id>/` is the same directory in every+ /// sandbox of the app, and the user's alone (0700).+ #[cfg(unix)]+ Socket(PathBuf),+}++/// The transport for this process: a Unix socket when running inside a Flatpak (`FLATPAK_ID` is+/// set and `XDG_RUNTIME_DIR` names the runtime directory), else a loopback port.+pub fn transport() -> Transport {+ #[cfg(unix)]+ if let Some(path) = sandbox_socket(std::env::var_os("FLATPAK_ID").as_deref(), std::env::var_os("XDG_RUNTIME_DIR").as_deref()) {+ return Transport::Socket(path);+ }+ Transport::Loopback+}++/// `$XDG_RUNTIME_DIR/app/<FLATPAK_ID>/instance.sock`, when both are set.+#[cfg(unix)]+fn sandbox_socket(flatpak_id: Option<&std::ffi::OsStr>, runtime_dir: Option<&std::ffi::OsStr>) -> Option<PathBuf> {+ let id = flatpak_id.filter(|v| !v.is_empty())?;+ let dir = runtime_dir.filter(|v| !v.is_empty())?;+ Some(Path::new(dir).join("app").join(id).join(SOCKET_FILE))+}++/// Where the running primary listens, as `instance.json` records it.+#[derive(Clone, Debug, PartialEq)]+enum Endpoint {+ Port(u16),+ #[cfg(unix)]+ Socket(PathBuf),+}+/// Outcome of [`claim`].pub enum Launch {/// This process is the running instance; keep [`Primary`] alive and attach it to the app.@@ -110,6 +157,10 @@ pub fn skip_reason(c: &LaunchContext) -> Option<String> {pub struct Primary {lock: Mutex<Option<File>>,shared: Arc<Shared>,+ /// The socket file to remove on the first shutdown (a Unix socket transport only); taken+ /// then, so the second call (`Drop`) can't remove the socket the next primary has bound.+ #[cfg(unix)]+ socket: Mutex<Option<PathBuf>>,}struct Shared {@@ -151,6 +202,10 @@ impl Primary {self.shared.closed.store(true, Ordering::Release);// Dropping the senders refuses every connection still waiting for the UI.self.shared.inbox.lock().unwrap_or_else(PoisonError::into_inner).pending.clear();+ #[cfg(unix)]+ if let Some(path) = self.socket.lock().unwrap_or_else(PoisonError::into_inner).take() {+ let _ = std::fs::remove_file(path);+ }drop(self.lock.lock().unwrap_or_else(PoisonError::into_inner).take());}}@@ -211,9 +266,15 @@ pub fn claim(dir: &Path, paths: &[String]) -> Launch {claim_with(dir, paths, TIMING)}-/// [`claim`] with explicit timeouts. Until `timing.handoff` runs out, each round tries the lock-/// (free once a quitting or crashed primary is gone) and then the running primary.+/// [`claim`] with explicit timeouts, over the transport this process would use ([`transport`]).pub fn claim_with(dir: &Path, paths: &[String], timing: Timing) -> Launch {+ claim_in(dir, paths, timing, &transport())+}++/// [`claim`] over `transport`. Until `timing.handoff` runs out, each round tries the lock (free+/// once a quitting or crashed primary is gone) and then the running primary, wherever+/// `instance.json` says it listens.+pub fn claim_in(dir: &Path, paths: &[String], timing: Timing, transport: &Transport) -> Launch {if let Err(e) = std::fs::create_dir_all(dir) {return Launch::Standalone(format!("{}: {e}", dir.display()));}@@ -227,7 +288,7 @@ pub fn claim_with(dir: &Path, paths: &[String], timing: Timing) -> Launch {loop {match lock.try_lock() {Ok(()) => {- return match serve(dir, lock, timing) {+ return match serve(dir, lock, timing, transport) {Ok(primary) => Launch::Primary(primary),Err(e) => Launch::Standalone(e),};@@ -235,8 +296,8 @@ pub fn claim_with(dir: &Path, paths: &[String], timing: Timing) -> Launch {Err(std::fs::TryLockError::WouldBlock) => {}Err(std::fs::TryLockError::Error(e)) => return Launch::Standalone(format!("{}: {e}", lock_path.display())),}- if let Some((port, token)) = read_info(dir) {- match send(port, &token, paths, deadline) {+ if let Some((endpoint, token)) = read_info(dir) {+ match send(&endpoint, &token, paths, deadline) {Ok(()) => return Launch::Forwarded,Err(e) => last = e,}@@ -248,11 +309,15 @@ pub fn claim_with(dir: &Path, paths: &[String], timing: Timing) -> Launch {}}-fn serve(dir: &Path, lock: File, timing: Timing) -> Result<Primary, String> {- let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|e| format!("loopback listener: {e}"))?;- let port = listener.local_addr().map_err(|e| format!("loopback listener: {e}"))?.port();+fn serve(dir: &Path, lock: File, timing: Timing, transport: &Transport) -> Result<Primary, String> {+ let (listener, endpoint) = Listener::bind(transport)?;let token = generate_token().map_err(|e| e.to_string())?;- write_info(dir, port, &token)?;+ write_info(dir, &endpoint, &token)?;+ #[cfg(unix)]+ let socket = match &endpoint {+ Endpoint::Socket(path) => Some(path.clone()),+ Endpoint::Port(_) => None,+ };let shared = Arc::new(Shared { inbox: Mutex::default(), closed: AtomicBool::new(false) });let listening = Arc::clone(&shared);let spawned = std::thread::Builder::new().name("single-instance".into()).spawn(move || {@@ -260,7 +325,7 @@ fn serve(dir: &Path, lock: File, timing: Timing) -> Result<Primary, String> {let clients = Arc::new(AtomicUsize::new(0));loop {let stream = match listener.accept() {- Ok((stream, _)) => stream,+ Ok(stream) => stream,// Back off instead of spinning when accept keeps failing (e.g. out of descriptors).Err(_) => {std::thread::sleep(Duration::from_millis(100));@@ -288,11 +353,117 @@ fn serve(dir: &Path, lock: File, timing: Timing) -> Result<Primary, String> {}});spawned.map_err(|e| format!("single-instance listener thread: {e}"))?;- Ok(Primary { lock: Mutex::new(Some(lock)), shared })+ Ok(Primary {+ lock: Mutex::new(Some(lock)),+ shared,+ #[cfg(unix)]+ socket: Mutex::new(socket),+ })+}++/// The primary's listener on either transport.+enum Listener {+ Tcp(TcpListener),+ #[cfg(unix)]+ Unix(UnixListener),+}++impl Listener {+ fn bind(transport: &Transport) -> Result<(Listener, Endpoint), String> {+ match transport {+ Transport::Loopback => {+ let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|e| format!("loopback listener: {e}"))?;+ let port = listener.local_addr().map_err(|e| format!("loopback listener: {e}"))?.port();+ Ok((Listener::Tcp(listener), Endpoint::Port(port)))+ }+ #[cfg(unix)]+ Transport::Socket(path) => {+ let at = |e: std::io::Error| format!("{}: {e}", path.display());+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).map_err(at)?;+ }+ // This process holds the lock, so a file already there is a crashed primary's.+ let _ = std::fs::remove_file(path);+ let listener = UnixListener::bind(path).map_err(at)?;+ // The runtime directory is the user's alone already; keep the socket so too.+ std::fs::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o600)).map_err(at)?;+ Ok((Listener::Unix(listener), Endpoint::Socket(path.clone())))+ }+ }+ }++ fn accept(&self) -> std::io::Result<Stream> {+ match self {+ Listener::Tcp(l) => l.accept().map(|(s, _)| Stream::Tcp(s)),+ #[cfg(unix)]+ Listener::Unix(l) => l.accept().map(|(s, _)| Stream::Unix(s)),+ }+ }+}++/// One connection, on either transport.+enum Stream {+ Tcp(TcpStream),+ #[cfg(unix)]+ Unix(UnixStream),+}++impl Stream {+ /// Connect to the primary; `timeout` bounds the loopback connect (a Unix connect is immediate).+ fn connect(endpoint: &Endpoint, timeout: Duration) -> std::io::Result<Stream> {+ match endpoint {+ Endpoint::Port(port) => TcpStream::connect_timeout(&SocketAddr::from((Ipv4Addr::LOCALHOST, *port)), timeout).map(Stream::Tcp),+ #[cfg(unix)]+ Endpoint::Socket(path) => UnixStream::connect(path).map(Stream::Unix),+ }+ }++ fn set_read_timeout(&self, dur: Option<Duration>) -> std::io::Result<()> {+ match self {+ Stream::Tcp(s) => s.set_read_timeout(dur),+ #[cfg(unix)]+ Stream::Unix(s) => s.set_read_timeout(dur),+ }+ }++ fn set_write_timeout(&self, dur: Option<Duration>) -> std::io::Result<()> {+ match self {+ Stream::Tcp(s) => s.set_write_timeout(dur),+ #[cfg(unix)]+ Stream::Unix(s) => s.set_write_timeout(dur),+ }+ }++ /// One read through a shared reference (both socket types read through `&self`).+ fn read_once(&self, buf: &mut [u8]) -> std::io::Result<usize> {+ match self {+ Stream::Tcp(s) => (&*s).read(buf),+ #[cfg(unix)]+ Stream::Unix(s) => (&*s).read(buf),+ }+ }+}++impl Write for Stream {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ match self {+ Stream::Tcp(s) => s.write(buf),+ #[cfg(unix)]+ Stream::Unix(s) => s.write(buf),+ }+ }++ fn flush(&mut self) -> std::io::Result<()> {+ match self {+ Stream::Tcp(s) => s.flush(),+ #[cfg(unix)]+ Stream::Unix(s) => s.flush(),+ }+ }}/// Read one request, hand its paths to the UI and answer `ok` only if the UI took them.-fn serve_client(stream: TcpStream, token: &str, shared: &Shared, timing: Timing) {+fn serve_client(stream: Stream, token: &str, shared: &Shared, timing: Timing) {let taken = match read_request(&stream, timing.request) {Some(line) => match parse_request(&line, token) {Some((paths, wait)) => shared.hand_over(paths, wait.min(timing.ack)),@@ -308,7 +479,7 @@ fn serve_client(stream: TcpStream, token: &str, shared: &Shared, timing: Timing)/// A reader that fails once `until` passes, however slowly the bytes trickle in.struct Deadline<'a> {- stream: &'a TcpStream,+ stream: &'a Stream,until: Instant,}@@ -317,25 +488,30 @@ impl Read for Deadline<'_> {let left = self.until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero());let left = left.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "request deadline passed"))?;self.stream.set_read_timeout(Some(left))?;- let mut stream = self.stream;- stream.read(buf)+ self.stream.read_once(buf)}}/// The request line, if it arrives complete within `total`.-fn read_request(stream: &TcpStream, total: Duration) -> Option<String> {+fn read_request(stream: &Stream, total: Duration) -> Option<String> {let mut reader = BufReader::new(Deadline { stream, until: Instant::now() + total });let mut line = String::new();matches!(read_bounded_line(&mut reader, &mut line), Ok(LineRead::Line)).then_some(line)}-/// Port and token, written to a temporary file and renamed so a reader never sees half of it.+/// Endpoint and token, written to a temporary file and renamed so a reader never sees half of it./// On Unix the file is the user's alone (0600): another local user who read the token could make/// this app open any path. (Windows keeps the per-user ACL of the settings folder.)-fn write_info(dir: &Path, port: u16, token: &str) -> Result<(), String> {+fn write_info(dir: &Path, endpoint: &Endpoint, token: &str) -> Result<(), String> {let path = dir.join(INFO_FILE);let tmp = dir.join(format!("{INFO_FILE}.{}.tmp", std::process::id()));- let body = json!({"port": port, "token": token, "pid": std::process::id()}).to_string();+ let mut body = json!({"token": token, "pid": std::process::id()});+ match endpoint {+ Endpoint::Port(port) => body["port"] = json!(port),+ #[cfg(unix)]+ Endpoint::Socket(socket) => body["socket"] = json!(socket.to_string_lossy()),+ }+ let body = body.to_string();// A leftover from a crash could carry wider permissions; the mode applies only on create.let _ = std::fs::remove_file(&tmp);let mut options = OpenOptions::new();@@ -349,10 +525,15 @@ fn write_info(dir: &Path, port: u16, token: &str) -> Result<(), String> {})}-fn read_info(dir: &Path) -> Option<(u16, String)> {+fn read_info(dir: &Path) -> Option<(Endpoint, String)> {let v: Value = serde_json::from_slice(&std::fs::read(dir.join(INFO_FILE)).ok()?).ok()?;+ let token = v.get("token")?.as_str()?.to_string();+ #[cfg(unix)]+ if let Some(socket) = v.get("socket").and_then(Value::as_str) {+ return Some((Endpoint::Socket(PathBuf::from(socket)), token));+ }let port = u16::try_from(v.get("port")?.as_u64()?).ok()?;- Some((port, v.get("token")?.as_str()?.to_string()))+ Some((Endpoint::Port(port), token))}/// `{"token":…,"open":[…],"wait_ms":…}`: the paths, and how long the sender will wait for the UI.@@ -370,11 +551,10 @@ fn parse_request(line: &str, token: &str) -> Option<(Vec<String>, Duration)> {Some((paths, wait))}-/// Offer `paths` to the primary on `port`; `Ok` once its UI has taken them.-fn send(port: u16, token: &str, paths: &[String], deadline: Instant) -> Result<(), String> {+/// Offer `paths` to the primary at `endpoint`; `Ok` once its UI has taken them.+fn send(endpoint: &Endpoint, token: &str, paths: &[String], deadline: Instant) -> Result<(), String> {let left = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or("out of time")?;- let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port));- let mut stream = TcpStream::connect_timeout(&addr, left).map_err(|e| e.to_string())?;+ let mut stream = Stream::connect(endpoint, left).map_err(|e| e.to_string())?;// The primary must answer before our deadline, so it waits a little less than we do.let wait_ms = u64::try_from(left.saturating_sub(REPLY_MARGIN).as_millis()).unwrap_or(u64::MAX);let request = json!({"token": token, "open": paths, "wait_ms": wait_ms});@@ -435,6 +615,21 @@ mod tests {}}+ /// A socket path short enough for every Unix (`sun_path` is about 100 bytes; macOS: 104).+ #[cfg(unix)]+ fn short_socket_path(tag: &str) -> PathBuf {+ std::env::temp_dir().join(format!("pc-si-{}-{tag}", std::process::id())).join(SOCKET_FILE)+ }++ /// The loopback port the primary under `dir` listens on.+ fn port_of(dir: &Path) -> u16 {+ match read_info(dir).unwrap().0 {+ Endpoint::Port(port) => port,+ #[cfg(unix)]+ Endpoint::Socket(path) => panic!("expected a loopback port, found {}", path.display()),+ }+ }+#[test]fn second_launch_hands_its_paths_to_the_first() {let dir = temp_dir("handoff");@@ -496,7 +691,7 @@ mod tests {// instance.json from a process that is gone; the lock is free.std::fs::write(dir.join(INFO_FILE), r#"{"port":1,"token":"x","pid":1}"#).unwrap();let primary = primary(&dir);- assert!(read_info(&dir).is_some_and(|(port, _)| port != 1));+ assert!(read_info(&dir).is_some_and(|(endpoint, _)| endpoint != Endpoint::Port(1)));drop(primary);// Released with the handle, as on process exit.assert!(matches!(claim_with(&dir, &[], FAST), Launch::Primary(_)));@@ -516,10 +711,10 @@ mod tests {primary.shutdown();assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary");// After shutdown new connections are refused too.- let (port, token) = read_info(&dir).unwrap();+ let (endpoint, token) = read_info(&dir).unwrap();drop(primary);let short = Instant::now() + Duration::from_millis(300);- assert!(send(port, &token, &["b.psd".into()], short).is_err());+ assert!(send(&endpoint, &token, &["b.psd".into()], short).is_err());let _ = std::fs::remove_dir_all(&dir);}@@ -557,7 +752,7 @@ mod tests {let dir = temp_dir("stalled");let primary = primary(&dir);let mut ui = primary.connect(&egui::Context::default());- let (port, _) = read_info(&dir).unwrap();+ let port = port_of(&dir);// Connects and never sends a line (each would otherwise hold the listener).let stalled: Vec<TcpStream> = (0..3).map(|_| TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap()).collect();let started = Instant::now();@@ -575,7 +770,7 @@ mod tests {fn a_trickling_client_is_cut_off_at_the_request_deadline() {let dir = temp_dir("trickle");let primary = primary(&dir);- let (port, _) = read_info(&dir).unwrap();+ let port = port_of(&dir);let mut slow = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap();let started = Instant::now();let mut cut_off = false;@@ -602,7 +797,7 @@ mod tests {let tmp = dir.join(format!("{INFO_FILE}.{}.tmp", std::process::id()));std::fs::write(&tmp, "{}").unwrap();std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644)).unwrap();- write_info(&dir, 1, &generate_token().unwrap()).unwrap();+ write_info(&dir, &Endpoint::Port(1), &generate_token().unwrap()).unwrap();let mode = std::fs::metadata(dir.join(INFO_FILE)).unwrap().permissions().mode() & 0o777;assert_eq!(mode, 0o600);let _ = std::fs::remove_dir_all(&dir);@@ -616,7 +811,7 @@ mod tests {let held = File::create(dir.join(LOCK_FILE)).unwrap();held.lock().unwrap();let closed = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port();- write_info(&dir, closed, &generate_token().unwrap()).unwrap();+ write_info(&dir, &Endpoint::Port(closed), &generate_token().unwrap()).unwrap();assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_)));drop(held);let _ = std::fs::remove_dir_all(&dir);@@ -645,4 +840,79 @@ mod tests {let reason = skip_reason(&LaunchContext { launch_options: &["--safe-gpu"], ..base });assert!(reason.is_some_and(|r| r.contains("--safe-gpu")));}++ /// #1540: inside a Flatpak sandbox the hand-off runs over a Unix socket in the app's runtime+ /// directory, which every sandbox of the app shares, with the same lock, token and reply.+ #[cfg(unix)]+ #[test]+ fn a_sandboxed_second_launch_hands_its_paths_over_a_unix_socket() {+ use std::os::unix::fs::PermissionsExt;+ let dir = temp_dir("socket");+ // Short: a Unix socket path is limited to about 100 bytes (macOS: 104).+ let socket = short_socket_path("a");+ let transport = Transport::Socket(socket.clone());+ let primary = match claim_in(&dir, &[], FAST, &transport) {+ Launch::Primary(p) => p,+ _ => panic!("first launch should be primary"),+ };+ assert_eq!(std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777, 0o600);+ let info: Value = serde_json::from_slice(&std::fs::read(dir.join(INFO_FILE)).unwrap()).unwrap();+ assert_eq!(info.get("socket").and_then(Value::as_str), Some(socket.to_str().unwrap()));+ assert!(info.get("port").is_none());+ let mut ui = primary.connect(&egui::Context::default());+ let paths = ["/home/a/one.psd".to_string()];+ let (d, p, t) = (dir.clone(), paths.clone(), transport.clone());+ let second = std::thread::spawn(move || claim_in(&d, &p, TIMING, &t));+ assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.to_vec())]);+ assert!(matches!(second.join().unwrap(), Launch::Forwarded));+ // The token still gates the socket.+ let (endpoint, _) = read_info(&dir).unwrap();+ assert!(send(&endpoint, "not the token", &["x.psd".into()], Instant::now() + FAST.handoff).is_err());+ primary.shutdown();+ assert!(!socket.exists(), "shutdown removes the socket file");+ // The next primary binds the same path; the old one's drop (a second shutdown) must leave it.+ let next = match claim_in(&dir, &[], FAST, &transport) {+ Launch::Primary(p) => p,+ _ => panic!("the lock is free again"),+ };+ drop(primary);+ assert!(socket.exists(), "a second shutdown doesn't remove the next primary's socket");+ drop(next);+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// A socket file left by a crashed primary (and a stale `instance.json` naming it) is replaced.+ #[cfg(unix)]+ #[test]+ fn a_crashed_primary_s_socket_file_does_not_block_the_next_one() {+ use std::os::unix::fs::FileTypeExt;+ let dir = temp_dir("stale-socket");+ let socket = short_socket_path("b");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::create_dir_all(socket.parent().unwrap()).unwrap();+ std::fs::write(&socket, b"not a socket").unwrap();+ write_info(&dir, &Endpoint::Socket(socket.clone()), &generate_token().unwrap()).unwrap();+ let primary = match claim_in(&dir, &["a.psd".into()], FAST, &Transport::Socket(socket.clone())) {+ Launch::Primary(p) => p,+ Launch::Forwarded => panic!("nothing was listening"),+ Launch::Standalone(e) => panic!("{e}"),+ };+ assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket());+ drop(primary);+ let _ = std::fs::remove_dir_all(&dir);+ let _ = std::fs::remove_dir_all(socket.parent().unwrap());+ }++ /// The socket transport is chosen only inside a Flatpak with a runtime directory.+ #[cfg(unix)]+ #[test]+ fn the_socket_transport_needs_a_flatpak_id_and_a_runtime_directory() {+ use std::ffi::OsStr;+ let (id, run) = (OsStr::new("ai.storyteller.photocraft"), OsStr::new("/run/user/1000"));+ assert_eq!(sandbox_socket(Some(id), Some(run)), Some(PathBuf::from("/run/user/1000/app/ai.storyteller.photocraft/instance.sock")));+ assert_eq!(sandbox_socket(None, Some(run)), None);+ assert_eq!(sandbox_socket(Some(id), None), None);+ assert_eq!(sandbox_socket(Some(OsStr::new("")), Some(run)), None);+ assert_eq!(sandbox_socket(Some(id), Some(OsStr::new(""))), None);+ }}diff --git a/docs/development.md b/docs/development.mdindex 6891e88a9..023fa49f6 100644--- a/docs/development.md+++ b/docs/development.md@@ -82,7 +82,7 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo test --workspace # runs the Japa## One instance per user-On Windows and Linux the first PhotoCraft holds an exclusive lock on `instance.lock` in the config directory and listens on a loopback port named in `instance.json` (with a fresh 256-bit token; the file is 0600 on Unix). A later launch hands its file arguments there and exits, so files opened from Explorer or a file manager become tabs in the running window (#3708). The primary answers `ok` only once its UI has taken the files; a launch that gets anything else (the primary is starting, hung or closing) keeps retrying the lock for up to 10 s, becoming the primary itself once the old one lets go, and then starts a separate instance, so a file is never acknowledged and lost. When the event loop ends (and before the CPU-compatibility relaunch) the primary refuses new files and frees the lock. It applies only with the per-user settings folder: a portable copy (`PhotoCraftData` beside the executable) or `PHOTOCRAFT_CONFIG_DIR` may be shared between users, so those launches run separately. So do `--new-instance` (or `PHOTOCRAFT_NEW_INSTANCE=1`), every `--control` launch, and launches given a per-process option (`--safe-gpu`, `--present-mode`, `--frame-latency`, `--stroke-trace`, `--in-window-menus`, `--automation-*-root`). A `cargo run` while an installed PhotoCraft is running forwards to it: pass `--new-instance` or set `PHOTOCRAFT_CONFIG_DIR`. macOS gets the same behaviour from LaunchServices (`apple_events.rs`). On native Wayland the running window can't bring itself forward (that takes the launcher's `XDG_ACTIVATION_TOKEN`, and winit 0.30 can't activate an existing window with one), so it asks for attention instead and the taskbar highlights it; X11, XWayland and Windows bring it to the front. Flatpak needs its own follow-up (#1540). Code: `apps/photocraft/src/single_instance.rs`.+On Windows and Linux the first PhotoCraft holds an exclusive lock on `instance.lock` in the config directory and listens on a loopback port named in `instance.json` (with a fresh 256-bit token; the file is 0600 on Unix). Inside a Flatpak it listens on a Unix socket instead, `$XDG_RUNTIME_DIR/app/<app id>/instance.sock` (0600), because Flatpak isolates each sandbox's network namespace, loopback included, unless the app is granted `--share=network`, while that runtime directory is shared by all sandboxes of the app (#1540); the lock, token and protocol are the same. A later launch hands its file arguments there and exits, so files opened from Explorer or a file manager become tabs in the running window (#3708). The primary answers `ok` only once its UI has taken the files; a launch that gets anything else (the primary is starting, hung or closing) keeps retrying the lock for up to 10 s, becoming the primary itself once the old one lets go, and then starts a separate instance, so a file is never acknowledged and lost. When the event loop ends (and before the CPU-compatibility relaunch) the primary refuses new files and frees the lock. It applies only with the per-user settings folder: a portable copy (`PhotoCraftData` beside the executable) or `PHOTOCRAFT_CONFIG_DIR` may be shared between users, so those launches run separately. So do `--new-instance` (or `PHOTOCRAFT_NEW_INSTANCE=1`), every `--control` launch, and launches given a per-process option (`--safe-gpu`, `--present-mode`, `--frame-latency`, `--stroke-trace`, `--in-window-menus`, `--automation-*-root`). A `cargo run` while an installed PhotoCraft is running forwards to it: pass `--new-instance` or set `PHOTOCRAFT_CONFIG_DIR`. macOS gets the same behaviour from LaunchServices (`apple_events.rs`). On native Wayland the running window can't bring itself forward (that takes the launcher's `XDG_ACTIVATION_TOKEN`, and winit 0.30 can't activate an existing window with one), so it asks for attention instead and the taskbar highlights it; X11, XWayland and Windows bring it to the front. Code: `apps/photocraft/src/single_instance.rs`.## Graphics startup and device loss