//! Linux platform effects. Environment-dependent trash tests run in isolated children.
use crate::{Result, download};
use std::{
fs,
io::{BufRead, BufReader, Read},
path::Path,
};
pub fn factorio_running_in(proc_root: &Path) -> bool {
let entries = match fs::read_dir(proc_root) {
Ok(entries) => entries,
Err(e) => {
eprintln!(
"Warning: cannot inspect {}: {e}; treating Factorio as not running",
proc_root.display()
);
return false;
}
};
let matches = |name: &[u8]| {
name.eq_ignore_ascii_case(b"factorio") || name.eq_ignore_ascii_case(b"factorio.exe")
};
let mut readable = false;
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(e) => {
eprintln!("Warning: process listing failed: {e}; treating Factorio as not running");
return false;
}
};
if !entry
.file_name()
.as_encoded_bytes()
.iter()
.all(u8::is_ascii_digit)
{
continue;
}
if let Ok(comm) = fs::read_to_string(entry.path().join("comm")) {
readable = true;
if matches(comm.trim().as_bytes()) {
return true;
}
}
// Read only argv0, never process environments or later arguments.
if let Ok(file) = fs::File::open(entry.path().join("cmdline")) {
let mut argv0 = Vec::new();
if BufReader::new(file)
.take(4096)
.read_until(0, &mut argv0)
.is_ok()
{
readable = true;
if argv0.last() == Some(&0) {
argv0.pop();
}
if matches(argv0.rsplit(|b| *b == b'/').next().unwrap_or_default()) {
return true;
}
}
}
}
if !readable {
eprintln!(
"Warning: process table has no readable processes; treating Factorio as not running"
);
}
false
}
pub fn trash(path: &Path) -> Result<()> {
download::ordinary(path)?;
if let Some(base) = std::env::var_os("XDG_DATA_HOME").filter(|s| !s.is_empty())
&& !Path::new(&base).is_absolute()
{
return Err("XDG_DATA_HOME must be absolute for desktop Trash".into());
}
// The pinned backend chooses home or per-volume Trash. Its sole local patch
// refuses EXDEV instead of copying and deleting a source (vendor/trash).
trash::delete(path)?;
Ok(())
}
/// Synchronous worker-side opener with an injected process launcher for tests.
pub fn open_browser_with(
url: &str,
launch: impl FnOnce(&str, &[&str]) -> Result<()>,
) -> Result<()> {
if !crate::markdown::browser_url(url) {
return Err("Only HTTP(S) browser URLs are supported".into());
}
launch("xdg-open", &[url])
}
pub fn open_browser(url: &str) -> Result<()> {
open_browser_with(url, |program, args| {
let status = std::process::Command::new(program).args(args).status()?;
if !status.success() {
return Err(format!("xdg-open failed: {status}").into());
}
Ok(())
})
}