use fmm_core::changelog::Changelog;
use fmm_core::{
local_mods::{LocalMod, ModSource, builtin_rank, compatible_with_game},
store::Snapshot,
version::{DependencyKind, compare_versions, game_line, satisfies},
};
use serde::Deserialize;
pub use fmm_core::enable::{Pending, Pins};
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default)]
pub struct Row {
pub name: String,
pub title: String,
pub version: String,
pub checked: bool,
pub locked: bool,
pub dimmed: bool,
pub pending: bool,
pub selected: bool,
/// Shipped with the game: sorts keep these in their own group above the rest.
pub builtin: bool,
/// Ticked with a required dependency that is not active.
pub red: bool,
pub tooltip: String,
pub download: bool,
pub failed: bool,
pub placeholder: bool,
pub fraction: f32,
pub progress_label: String,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Info {
pub key: String,
pub value: String,
pub link: bool,
pub dependency: bool,
/// Drawn in the game's red label colour (an incompatible Factorio version).
pub red: bool,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct DependencyRow {
pub installed: bool,
pub name: String,
pub text: String,
pub optional: bool,
pub incompatible: bool,
/// Drawn red: a required dependency that is not active, or an incompatible mod that is.
pub red: bool,
pub tooltip: String,
}
// Game strings, core/locale/en/core.cfg [gui-mod-info].
pub const TIP_REQUIRED: &str = "This mod is required, but is not active.";
pub const TIP_OPTIONAL: &str = "This mod is not required, and is not active.";
pub const TIP_INCOMPATIBLE: &str = "This mod is incompatible with these mods.";
pub const INCOMPATIBLE_VERSION: &str = "Incompatible with current version of the game";
#[derive(Clone, Debug, Deserialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct ManageModel {
pub rows: Vec<Row>,
#[serde(rename = "detail-title")]
pub title: String,
pub description: String,
pub thumbnail: String,
pub missing: bool,
pub info: Vec<Info>,
pub dependencies: Vec<DependencyRow>,
pub pending_count: i32,
pub issue: String,
pub install_missing: bool,
pub versions: Vec<String>,
pub version_choice: i32,
pub notice: String,
pub changelog: Changelog,
#[serde(flatten)]
pub view: ViewState,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct ViewState {
pub sort_column: i32,
pub ascending: bool,
pub search_open: bool,
pub search_text: String,
pub show_changelog: bool,
pub changelog_version: usize,
pub changelog_subversion: usize,
pub changelog_category: usize,
}
impl Default for ViewState {
fn default() -> Self {
Self {
sort_column: 0,
ascending: true,
search_open: false,
search_text: String::new(),
show_changelog: false,
changelog_version: 0,
changelog_subversion: 0,
changelog_category: 3,
}
}
}
pub const CHANGELOG_CATEGORIES: [&str; 4] = ["Features", "Changes", "Bugfixes", "All"];
/// Operates on rows only: selection and pending edits stay keyed by internal mod name.
pub fn filter_and_sort(rows: &mut Vec<Row>, view: &ViewState) {
if view.search_open {
let query = view.search_text.to_lowercase();
rows.retain(|r| {
r.title.to_lowercase().contains(&query) || r.name.to_lowercase().contains(&query)
});
}
if matches!(view.sort_column, 0..=2) {
rows.sort_by(|a, b| {
b.builtin.cmp(&a.builtin).then_with(|| {
let by_name = fmm_core::text::compare_english(&a.title, &b.title, true);
let by_id = || fmm_core::text::compare_english(&a.name, &b.name, false);
if view.sort_column == 2 {
// Enabled first when ascending; ties stay in name order either way.
let order = b.checked.cmp(&a.checked);
let order = if view.ascending {
order
} else {
order.reverse()
};
return order.then(by_name).then_with(by_id);
}
let order = if view.sort_column == 1 {
compare_versions(&a.version, &b.version)
} else {
by_name
}
.then_with(by_id);
if view.ascending {
order
} else {
order.reverse()
}
})
});
}
}
/// Header click: ascending, then descending, then back to the default order (column -1).
pub fn next_sort(column: i32, ascending: bool, clicked: i32) -> (i32, bool) {
if column != clicked {
(clicked, true)
} else if ascending {
(clicked, false)
} else {
(-1, true)
}
}
impl Default for ManageModel {
fn default() -> Self {
Self {
rows: Vec::new(),
title: String::new(),
description: String::new(),
thumbnail: String::new(),
missing: true,
info: Vec::new(),
dependencies: Vec::new(),
pending_count: 0,
issue: String::new(),
install_missing: false,
versions: vec![],
version_choice: 0,
notice: String::new(),
changelog: Changelog::default(),
view: ViewState::default(),
}
}
}
pub fn ordered_mods(snapshot: &Snapshot) -> Vec<&LocalMod> {
let mut unique = fmm_core::enable::loaded_mods(snapshot, &vec![]);
for local in snapshot.builtin.iter().chain(&snapshot.mods) {
if let Some(existing) = unique.iter_mut().find(|m| m.name == local.name) {
let pin = snapshot
.mod_list
.mods
.iter()
.find(|e| e.name == local.name)
.and_then(|e| e.version.as_deref());
if pin.is_some_and(|pin| {
!snapshot
.mods
.iter()
.chain(&snapshot.builtin)
.any(|m| m.name == local.name && m.version == pin)
}) && compare_versions(&local.version, &existing.version).is_gt()
{
*existing = local;
}
} else {
unique.push(local);
}
}
unique.sort_by(|a, b| {
match (
a.source == ModSource::Builtin,
b.source == ModSource::Builtin,
) {
(true, true) => builtin_rank(&a.name)
.cmp(&builtin_rank(&b.name))
.then_with(|| fmm_core::text::compare_english(&a.name, &b.name, false)),
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
_ => fmm_core::text::compare_english(&a.title, &b.title, true)
.then_with(|| fmm_core::text::compare_english(&a.name, &b.name, false)),
}
});
unique
}
pub fn enabled(snapshot: &Snapshot, pending: &Pending, name: &str) -> bool {
fmm_core::enable::enabled(snapshot, pending, name)
}
#[cfg(test)]
pub fn toggle_pending(snapshot: &Snapshot, pending: &Pending, name: &str, value: bool) -> Pending {
fmm_core::enable::set_pending(snapshot, pending, name, value)
}
pub fn manage_model(
snapshot: &Snapshot,
pending: &Pending,
selection: Option<&str>,
) -> ManageModel {
let mods = ordered_mods(snapshot);
let loaded = fmm_core::enable::loaded_mods(snapshot, &vec![]);
let issues = fmm_core::enable::diagnose(snapshot, pending, &vec![]);
let selected = mods.iter().find(|m| Some(m.name.as_str()) == selection);
let mut model = ManageModel {
rows: mods
.iter()
.map(|m| {
let checked = enabled(snapshot, pending, &m.name);
let diagnostic = issues.get(&m.name);
let messages = diagnostic
.map(|d| {
d.missing
.iter()
.map(|dep| format!("Missing: {}", dependency_text(dep)))
.chain(d.incompatible.iter().map(|n| format!("Incompatible: {n}")))
.collect::<Vec<_>>()
})
.unwrap_or_default();
let tooltip = messages.join("\n");
Row {
red: !messages.is_empty(),
tooltip,
name: m.name.clone(),
title: if m.name == "base" {
"Base mod".into()
} else {
m.title.clone()
},
version: m.version.clone(),
checked,
locked: m.name == "base",
dimmed: !checked,
pending: pending.iter().any(|(name, _)| name == &m.name)
|| !snapshot
.mod_list
.mods
.iter()
.any(|entry| entry.name == m.name),
builtin: m.source == ModSource::Builtin,
selected: Some(m.name.as_str()) == selection,
..Default::default()
}
})
.collect(),
pending_count: pending.len() as i32,
..Default::default()
};
model.pending_count = model.rows.iter().filter(|row| row.pending).count() as i32;
let Some(selected) = selected else {
return model;
};
if let Some(d) = issues.get(&selected.name) {
model.issue = d
.missing
.iter()
.map(|dep| format!("Missing: {}", dependency_text(dep)))
.chain(d.incompatible.iter().map(|n| format!("Incompatible: {n}")))
.collect::<Vec<_>>()
.join("\n");
model.install_missing = !d.install_missing.is_empty();
}
let versions = fmm_core::enable::installed_versions(snapshot, &selected.name);
if versions.len() > 1 {
model.versions = std::iter::once("Latest".into()).chain(versions).collect();
model.version_choice = snapshot
.mod_list
.mods
.iter()
.find(|m| m.name == selected.name)
.and_then(|m| m.version.as_ref())
.and_then(|p| model.versions.iter().position(|v| v == p))
.unwrap_or(0) as i32;
}
model.title = if selected.name == "base" {
"Base mod".into()
} else {
selected.title.clone()
};
model.description = selected.description.clone();
model.thumbnail = selected
.thumbnail
.as_ref()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default();
model.missing = model.thumbnail.is_empty();
model.dependencies = selected
.dependencies
.iter()
.filter(|d| d.kind != DependencyKind::HiddenOptional)
.map(|d| {
let mut text = d.name.clone();
if let Some(cmp) = d.comparator {
text.push_str(&format!(
" {cmp} {}",
d.version.as_deref().unwrap_or_default()
));
}
let optional = d.kind == DependencyKind::Optional;
let incompatible = d.kind == DependencyKind::Incompatible;
// Active: installed and enabled in the current view state (pending, else mod-list.json).
let active = loaded
.iter()
.any(|m| m.name == d.name && satisfies(&m.version, d))
&& enabled(snapshot, pending, &d.name);
let (red, tooltip) = match (optional, incompatible, active) {
(false, false, false) => (true, TIP_REQUIRED),
(true, _, false) => (false, TIP_OPTIONAL),
(_, true, true) => (true, TIP_INCOMPATIBLE),
_ => (false, ""),
};
if optional {
text.push_str(" (optional)");
} else if incompatible {
text.push_str(" (incompatible)");
}
DependencyRow {
installed: snapshot
.mods
.iter()
.chain(&snapshot.builtin)
.any(|m| m.name == d.name),
name: d.name.clone(),
text,
optional,
incompatible,
red,
tooltip: tooltip.into(),
}
})
.collect();
let field = |key: &str, value: String, link, dependency| Info {
key: key.into(),
value,
link,
dependency,
red: false,
};
model.info = vec![
field(
"Status",
if enabled(snapshot, pending, &selected.name) {
"Enabled"
} else {
"Disabled"
}
.into(),
false,
false,
),
field("Version", selected.version.clone(), false, false),
field("Author", selected.author.clone(), false, false),
];
if selected.source != ModSource::Builtin {
model.info.push(field(
"Mod portal",
format!("https://mods.factorio.com/mod/{}", selected.name),
true,
false,
));
}
let version = if selected.name == "base" {
game_line(&snapshot.paths.game_version)
} else {
selected.factorio_version.clone()
};
let compatible = compatible_with_game(selected, &snapshot.paths.game_version);
model.info.push(Info {
red: !compatible,
..field(
"Factorio version",
if compatible {
version
} else {
format!("{version} - {INCOMPATIBLE_VERSION}")
},
false,
false,
)
});
model.info.push(field(
"Dependencies",
model
.dependencies
.first()
.map(|d| d.text.clone())
.unwrap_or_else(|| "None".into()),
false,
!model.dependencies.is_empty(),
));
model
}
fn dependency_text(d: &fmm_core::version::Dependency) -> String {
let mut text = d.name.clone();
if let Some(cmp) = d.comparator {
text.push_str(&format!(
" {cmp} {}",
d.version.as_deref().unwrap_or_default()
));
}
text
}