//! Read-only Steam library and Factorio folder discovery.
use crate::{paths, settings::validate_data_dir};
use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
};
#[derive(Default)]
pub struct Folders {
pub installs: Vec<PathBuf>,
pub data: Vec<PathBuf>,
}
fn push_unique(paths: &mut Vec<PathBuf>, path: PathBuf) {
#[cfg(not(target_os = "linux"))]
let key = |p: &Path| p.to_string_lossy().replace('\\', "/").to_lowercase();
#[cfg(target_os = "linux")]
let key = |p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
if !paths.iter().any(|p| key(p) == key(&path)) {
paths.push(path);
}
}
/// VDF uses quoted strings and escaped backslashes; old Steam versions use numeric keys.
#[cfg(not(target_os = "linux"))]
pub fn library_paths(vdf: &str) -> Vec<PathBuf> {
let mut strings = Vec::new();
let mut chars = vdf.chars();
while let Some(c) = chars.next() {
if c != '"' {
continue;
}
let mut value = String::new();
while let Some(c) = chars.next() {
match c {
'"' => break,
'\\' => {
if let Some(c) = chars.next() {
value.push(c);
}
}
_ => value.push(c),
}
}
strings.push(value);
}
strings
.windows(2)
.filter(|p| {
(p[0] == "path" || p[0].bytes().all(|b| b.is_ascii_digit()))
&& Path::new(&p[1]).is_absolute()
})
.map(|p| PathBuf::from(&p[1]))
.collect()
}
pub fn detect_with_roots(env: &HashMap<String, String>, roots: &[PathBuf]) -> Folders {
let mut libraries = Vec::new();
for root in roots {
push_unique(&mut libraries, root.clone());
if let Ok(vdf) = fs::read_to_string(root.join("steamapps/libraryfolders.vdf")) {
for path in library_paths(&vdf) {
push_unique(&mut libraries, path);
}
}
}
let mut result = Folders::default();
let native = paths::default_user_dir(env);
if native.is_absolute() && validate_data_dir(&native).is_ok() {
push_unique(&mut result.data, native);
}
for library in &libraries {
let install = paths::game_dir(&library.join("steamapps/common/Factorio"));
if paths::read_game_version(&install).is_ok() {
push_unique(&mut result.installs, install);
}
let proton = library.join(
"steamapps/compatdata/427520/pfx/drive_c/users/steamuser/AppData/Roaming/Factorio",
);
if validate_data_dir(&proton).is_ok() {
push_unique(&mut result.data, proton);
}
}
for path in paths::DEFAULT_INSTALL_DIRS.iter().map(PathBuf::from) {
if paths::read_game_version(&path).is_ok() {
push_unique(&mut result.installs, path);
}
}
#[cfg(target_os = "linux")]
{
if let Some(home) = crate::app_dirs::absolute(env, "HOME") {
let standalone = home.join("factorio");
if paths::read_game_version(&standalone).is_ok() {
push_unique(&mut result.installs, standalone);
}
let flat_home = home.join(".var/app/com.valvesoftware.Steam");
let flat_data = flat_home.join(".factorio");
if validate_data_dir(&flat_data).is_ok() {
push_unique(&mut result.data, flat_data);
}
}
}
#[cfg(target_os = "macos")]
if let Some(home) = crate::app_dirs::absolute(env, "HOME") {
let standalone = home.join("Applications").join(paths::MACOS_BUNDLE_ROOT);
if paths::read_game_version(&standalone).is_ok() {
push_unique(&mut result.installs, standalone);
}
}
for install in &result.installs {
if let Ok(data) = paths::resolve_user_dir(install, env)
&& validate_data_dir(&data).is_ok()
{
push_unique(&mut result.data, data);
}
}
result
}
pub fn detect(env: &HashMap<String, String>) -> Folders {
let mut roots = Vec::new();
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
for (key, value) in [
(r"HKCU\Software\Valve\Steam", "SteamPath"),
(r"HKLM\SOFTWARE\WOW6432Node\Valve\Steam", "InstallPath"),
] {
if let Ok(output) = std::process::Command::new("reg.exe")
.args(["query", key, "/v", value])
.creation_flags(0x08000000)
.output()
{
for line in String::from_utf8_lossy(&output.stdout).lines() {
if let Some((_, path)) = line.split_once("REG_SZ") {
push_unique(&mut roots, PathBuf::from(path.trim()));
}
}
}
}
if let Some(programs) = env.get("ProgramFiles(x86)") {
push_unique(&mut roots, PathBuf::from(programs).join("Steam"));
}
}
#[cfg(target_os = "macos")]
if let Some(home) = crate::app_dirs::absolute(env, "HOME") {
push_unique(&mut roots, home.join("Library/Application Support/Steam"));
}
#[cfg(target_os = "linux")]
{
if let Some(home) = crate::app_dirs::absolute(env, "HOME") {
for suffix in [
".local/share/Steam",
".steam/steam",
".steam/root",
".var/app/com.valvesoftware.Steam/.local/share/Steam",
".var/app/com.valvesoftware.Steam/.steam/steam",
] {
push_unique(&mut roots, home.join(suffix));
}
}
if let Some(data) = crate::app_dirs::absolute(env, "XDG_DATA_HOME") {
push_unique(&mut roots, data.join("Steam"));
}
}
detect_with_roots(env, &roots)
}
/// Parse VDF structure so commented paths, app IDs and malformed strings aren't candidates.
#[cfg(target_os = "linux")]
pub fn library_paths(vdf: &str) -> Vec<PathBuf> {
#[derive(Clone)]
enum Token {
Text(String),
Open,
Close,
}
enum Value {
Text(String),
Object(Vec<(String, Value)>),
}
fn object(tokens: &[Token], i: &mut usize, nested: bool) -> Option<Vec<(String, Value)>> {
let mut pairs = Vec::new();
while let Some(token) = tokens.get(*i) {
if matches!(token, Token::Close) {
*i += 1;
return nested.then_some(pairs);
}
let Token::Text(key) = token else {
return None;
};
*i += 1;
let value = match tokens.get(*i)? {
Token::Text(s) => {
*i += 1;
Value::Text(s.clone())
}
Token::Open => {
*i += 1;
Value::Object(object(tokens, i, true)?)
}
Token::Close => return None,
};
pairs.push((key.clone(), value));
}
(!nested).then_some(pairs)
}
let mut chars = vdf.chars().peekable();
let mut tokens = Vec::new();
while let Some(c) = chars.next() {
match c {
c if c.is_whitespace() => {}
'/' if chars.peek() == Some(&'/') => {
for c in chars.by_ref() {
if c == '\n' {
break;
}
}
}
'{' => tokens.push(Token::Open),
'}' => tokens.push(Token::Close),
'"' => {
let mut s = String::new();
let mut closed = false;
while let Some(c) = chars.next() {
match c {
'"' => {
closed = true;
break;
}
'\\' => match chars.next() {
Some('n') => s.push('\n'),
Some('t') => s.push('\t'),
Some(c) => s.push(c),
None => return vec![],
},
c => s.push(c),
}
}
if !closed {
return vec![];
}
tokens.push(Token::Text(s));
}
_ => return vec![],
}
}
let Some(root) = object(&tokens, &mut 0, false) else {
return vec![];
};
let mut paths = Vec::new();
for (key, value) in root {
if !key.eq_ignore_ascii_case("libraryfolders") {
continue;
}
let Value::Object(libraries) = value else {
continue;
};
for (number, value) in libraries {
if number.is_empty() || !number.bytes().all(|b| b.is_ascii_digit()) {
continue;
}
let path = match value {
Value::Text(p) => Some(p),
Value::Object(fields) => fields.into_iter().find_map(|(k, v)| match v {
Value::Text(p) if k == "path" => Some(p),
_ => None,
}),
};
if let Some(path) = path.filter(|p| Path::new(p).is_absolute()) {
push_unique(&mut paths, path.into());
}
}
}
paths
}
/// A host manager must resolve a Flatpak Steam game's system-write macro in the
/// sandbox home, including games in additional libraries declared by that Steam.
#[cfg(target_os = "linux")]
pub fn install_home(install: &Path, env: &HashMap<String, String>) -> Option<PathBuf> {
let home = crate::app_dirs::absolute(env, "HOME")?;
let flat_home = home.join(".var/app/com.valvesoftware.Steam");
let flat_root = flat_home.join(".local/share/Steam");
let canonical = fs::canonicalize(install).unwrap_or_else(|_| install.to_path_buf());
let mut libraries = vec![flat_root.clone()];
if let Ok(vdf) = fs::read_to_string(flat_root.join("steamapps/libraryfolders.vdf")) {
libraries.extend(library_paths(&vdf));
}
let is_flatpak = libraries.iter().any(|root| {
let root = fs::canonicalize(root).unwrap_or_else(|_| root.clone());
canonical.starts_with(root.join("steamapps/common"))
});
Some(if is_flatpak { flat_home } else { home })
}