pub mod linux;
pub mod macos;
pub mod thunar;
pub mod windows;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use super::owner::{decide, Facts, Owner};
use super::registry::SharedRegistry;
use super::{State, OWNER_TAG};
use crate::open_in::Os;
pub use super::MARKER;
pub const ICON_NAME: &str = "gitpoulpi-folder";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Manager {
Explorer,
Nautilus,
Dolphin,
Nemo,
Thunar,
Caja,
PcManFm,
Finder,
}
impl Manager {
pub fn as_str(self) -> &'static str {
match self {
Manager::Explorer => "explorer",
Manager::Nautilus => "nautilus",
Manager::Dolphin => "dolphin",
Manager::Nemo => "nemo",
Manager::Thunar => "thunar",
Manager::Caja => "caja",
Manager::PcManFm => "pcmanfm",
Manager::Finder => "finder",
}
}
pub fn name(self) -> &'static str {
match self {
Manager::Explorer => "File Explorer",
Manager::Nautilus => "GNOME Files",
Manager::Dolphin => "Dolphin",
Manager::Nemo => "Nemo",
Manager::Thunar => "Thunar",
Manager::Caja => "Caja",
Manager::PcManFm => "PCManFM",
Manager::Finder => "Finder",
}
}
pub fn probes(self) -> &'static [&'static str] {
match self {
Manager::Nautilus => &["nautilus"],
Manager::Dolphin => &["dolphin"],
Manager::Nemo => &["nemo"],
Manager::Thunar => &["thunar"],
Manager::Caja => &["caja"],
Manager::PcManFm => &["pcmanfm", "pcmanfm-qt"],
Manager::Explorer | Manager::Finder => &[],
}
}
pub fn for_os(os: Os) -> &'static [Manager] {
match os {
Os::Windows => &[Manager::Explorer],
Os::Macos => &[Manager::Finder],
Os::Linux => &[
Manager::Nautilus,
Manager::Dolphin,
Manager::Nemo,
Manager::Thunar,
Manager::Caja,
Manager::PcManFm,
],
}
}
}
#[derive(Clone)]
pub struct Env {
pub os: Os,
pub data_home: PathBuf,
pub config_home: PathBuf,
pub home: PathBuf,
pub exe: PathBuf,
pub helper: Option<PathBuf>,
pub has: Arc<dyn Fn(&str) -> bool + Send + Sync>,
pub registry: SharedRegistry,
pub icon_png: Option<Vec<u8>>,
pub refresh_hooks: bool,
pub ctx: super::InstallCtx,
pub ico: Option<PathBuf>,
pub submenu: String,
}
impl Env {
pub fn discover(
os: Os,
env: &dyn Fn(&str) -> Option<String>,
home: &Path,
exe: &Path,
has: Arc<dyn Fn(&str) -> bool + Send + Sync>,
registry: SharedRegistry,
) -> Env {
let var = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
Env {
os,
data_home: var("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share")),
config_home: var("XDG_CONFIG_HOME").unwrap_or_else(|| home.join(".config")),
home: home.to_path_buf(),
exe: exe.to_path_buf(),
helper: super::terminals::folder_helper(os, exe, &|p| p.is_file()),
has,
registry,
icon_png: None,
refresh_hooks: false,
ctx: crate::desktop::InstallCtx::legacy(),
ico: None,
submenu: String::new(),
}
}
pub(crate) fn helper_path(&self) -> Result<&Path, String> {
self.helper
.as_deref()
.ok_or_else(|| "the gitpoulpi launcher is not next to GitPoulpi".to_string())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub manager: Manager,
pub detected: bool,
pub state: State,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unavailable {
NoHelper,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Status {
pub entries: Vec<Entry>,
pub unavailable: Option<Unavailable>,
pub error: Option<String>,
}
fn detected(env: &Env, m: Manager) -> bool {
match m {
Manager::Explorer | Manager::Finder => true,
_ => m.probes().iter().any(|p| (env.has)(p)),
}
}
pub(crate) fn follows_name(found: &str, name: &str) -> bool {
let name = name.trim();
if name.is_empty() {
return false;
}
let word = |c: char| c.is_alphanumeric() || c == '_';
found
.strip_suffix(name)
.is_some_and(|rest| !rest.chars().next_back().is_some_and(word))
|| found
.strip_prefix(name)
.is_some_and(|rest| !rest.chars().next().is_some_and(word))
}
pub(crate) fn label_current(found: &str, label: &str, name: &str) -> bool {
found == label || follows_name(found, name)
}
pub(crate) fn current_label(found: &str, label: &str, name: &str) -> String {
if label_current(found, label, name) {
found.to_string()
} else {
label.to_string()
}
}
fn state_of(env: &Env, label: &str, m: Manager) -> Result<State, String> {
match m {
Manager::Explorer => windows::state(env, label),
Manager::Finder => Ok(macos::state(env, label)),
_ => Ok(linux::state(env, label, m)),
}
}
pub fn status(env: &Env, label: &str) -> Status {
let mut error = None;
let entries = Manager::for_os(env.os)
.iter()
.map(|&manager| Entry {
manager,
detected: detected(env, manager),
state: state_of(env, label, manager).unwrap_or_else(|e| {
error.get_or_insert(e);
State::NotInstalled
}),
})
.collect();
Status {
entries,
unavailable: env.helper.is_none().then_some(Unavailable::NoHelper),
error,
}
}
pub fn has_any_ours(s: &Status) -> bool {
s.entries
.iter()
.any(|e| matches!(e.state, State::Installed | State::Outdated))
}
pub fn all_installed(s: &Status) -> bool {
let mut any = false;
for e in s.entries.iter().filter(|e| e.detected) {
match e.state {
State::Installed => any = true,
State::Foreign => {}
_ => return false,
}
}
any
}
fn write_one(env: &Env, label: &str, m: Manager) -> Result<(), String> {
match m {
Manager::Explorer => windows::install(env, label),
Manager::Finder => macos::install(env, label),
_ => linux::install(env, label, m),
}
}
fn remove_one(env: &Env, m: Manager) -> Result<bool, String> {
match m {
Manager::Explorer => windows::remove(env),
Manager::Finder => macos::remove(env),
_ => linux::remove(env, m),
}
}
pub fn install(env: &Env, label: &str) -> Result<Vec<Manager>, String> {
env.helper_path()?;
let mut done = Vec::new();
for &m in Manager::for_os(env.os) {
if !detected(env, m) {
continue;
}
if matches!(state_of(env, label, m)?, State::Installed | State::Foreign) {
continue;
}
write_one(env, label, m)?;
done.push(m);
}
if env.os == Os::Linux && !done.is_empty() {
linux::write_icon(env);
}
Ok(done)
}
pub fn sync(env: &Env, label: &str) -> Result<Vec<Manager>, String> {
if env.helper.is_none() {
return Ok(Vec::new());
}
let mut done = Vec::new();
for &m in Manager::for_os(env.os) {
if state_of(env, label, m)? == State::Outdated {
write_one(env, label, m)?;
done.push(m);
}
}
if env.os == Os::Linux && linux::sync_icon(env) && done.is_empty() {
done.extend(
Manager::for_os(env.os)
.iter()
.copied()
.filter(|&m| state_of(env, label, m).is_ok_and(|s| s == State::Installed)),
);
}
Ok(done)
}
pub fn remove(env: &Env) -> Result<Vec<Manager>, String> {
let mut done = Vec::new();
for &m in Manager::for_os(env.os) {
if remove_one(env, m)? {
done.push(m);
}
}
if env.os == Os::Linux {
linux::remove_icon_if_unused(env);
}
Ok(done)
}
pub fn demote(old: &Env) -> Result<Vec<Manager>, String> {
if old.os == Os::Windows {
return Ok(if windows::demote(old)? {
vec![Manager::Explorer]
} else {
Vec::new()
});
}
remove(old)
}
pub fn remove_replaced(old: &Env, new: &Env) -> Result<Vec<Manager>, String> {
if old.ctx.is_primary() == new.ctx.is_primary() {
return Ok(Vec::new());
}
let mut done = Vec::new();
for &m in Manager::for_os(old.os) {
if matches!(
m,
Manager::Explorer | Manager::Finder | Manager::Nautilus | Manager::Caja
) {
continue;
}
if remove_one(old, m)? {
done.push(m);
}
}
if old.os == Os::Linux {
linux::remove_icon_if_unused(old);
}
Ok(done)
}
pub fn names(managers: &[Manager]) -> String {
managers
.iter()
.map(|m| m.name())
.collect::<Vec<_>>()
.join(", ")
}
#[derive(Debug, Clone)]
pub(crate) struct Who {
pub id: String,
pub short: String,
pub primary: bool,
pub submenu: String,
}
impl Who {
pub(crate) fn of(env: &Env) -> Who {
Who {
id: env.ctx.id.clone(),
short: env.ctx.short.clone(),
primary: env.ctx.is_primary(),
submenu: env.submenu.trim().replace(|c: char| c.is_control(), " "),
}
}
pub(crate) fn suffix(&self) -> String {
if self.primary {
String::new()
} else {
format!("-{}", self.short)
}
}
pub(crate) fn icon_name(&self) -> String {
format!("{ICON_NAME}{}", self.suffix())
}
pub(crate) fn owner_lines(&self, prefix: &str) -> String {
let mut out = String::new();
if self.primary {
out.push_str(&format!("{prefix}{MARKER}\n"));
}
if !self.id.is_empty() {
out.push_str(&format!("{prefix}{OWNER_TAG}={}\n", self.id));
}
out
}
pub(crate) fn submenu_norm(&self) -> Option<String> {
Some(normalize(&self.submenu)).filter(|n| !n.is_empty())
}
}
pub(crate) fn normalize(name: &str) -> String {
name.trim().to_lowercase()
}
pub(crate) fn menu_hash(norm: &str) -> String {
format!(
"{:08x}",
crate::installation::fnv1a64(norm.as_bytes()) & 0xffff_ffff
)
}
pub(crate) fn facts_of(text: &str) -> Facts<'_> {
let mut facts = Facts::default();
let tag_prefix = format!("{OWNER_TAG}=");
for line in text.lines() {
let l = line.strip_prefix("# ").unwrap_or(line);
if l == MARKER {
facts.legacy_marker = true;
} else if let Some(t) = l.strip_prefix(&tag_prefix) {
facts.tag = Some(t);
}
}
facts
}
pub(crate) fn may_touch(env: &Env, facts: &Facts) -> bool {
matches!(decide(facts, &env.ctx), Owner::Mine | Owner::Adopt)
}
pub(crate) fn is_mine(env: &Env, text: &str) -> bool {
may_touch(env, &facts_of(text))
}
#[cfg(test)]
pub(crate) mod testing {
use super::super::{InstallCtx, KnownInstall};
pub const A: &str = "aaaaaaaa11111111";
pub const B: &str = "bbbbbbbb22222222";
pub fn ctx(id: &str, primary: Option<&str>) -> InstallCtx {
InstallCtx {
id: id.to_string(),
short: crate::installation::short_id(id),
name: format!("GitPoulpi {id}"),
primary: primary.map(str::to_string),
alias_claims: Vec::new(),
known: [A, B]
.iter()
.map(|k| KnownInstall {
id: k.to_string(),
exists: true,
})
.collect(),
}
}
}