//! Search and faceted counts over an immutable, pre-indexed local catalogue.
use crate::{
portal::PortalMod,
text::compare_english,
version::{DependencyKind, game_line, parse_dependency},
};
use std::cmp::Ordering;
pub const FILTERS: [&str; 28] = [
"space-age",
"content",
"overhaul",
"tweaks",
"utilities",
"scenarios",
"mod-packs",
"localizations",
"internal",
"no-category",
"planets",
"transportation",
"logistics",
"trains",
"combat",
"armor",
"character",
"enemies",
"environment",
"mining",
"fluids",
"logistic-network",
"circuit-network",
"manufacturing",
"power",
"storage",
"blueprints",
"cheats",
];
const GROUPS: [u32; 3] = [1, (1 << 10) - 2, ((1 << 28) - 1) ^ ((1 << 10) - 1)];
pub fn group(index: usize) -> usize {
if index == 0 {
0
} else if index < 10 {
1
} else {
2
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FilterMode {
#[default]
Off,
Include,
Exclude,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Sort {
#[default]
Relevance,
Downloads,
Updated,
Trending,
}
#[derive(Clone, Debug)]
pub struct ViewState {
pub search: String,
pub sort: Sort,
pub filters: [FilterMode; 28],
}
impl Default for ViewState {
fn default() -> Self {
let mut filters = [FilterMode::Off; 28];
filters[8] = FilterMode::Exclude;
Self {
search: String::new(),
sort: Sort::Relevance,
filters,
}
}
}
impl ViewState {
pub fn set_filter(&mut self, id: &str, mode: FilterMode) -> bool {
if let Some(i) = FILTERS.iter().position(|s| *s == id) {
self.filters[i] = mode;
true
} else {
false
}
}
pub fn toggle_filter(&mut self, id: &str, exclude: bool) {
if let Some(i) = FILTERS.iter().position(|s| *s == id) {
let mode = if exclude {
FilterMode::Exclude
} else {
FilterMode::Include
};
self.filters[i] = if self.filters[i] == mode {
FilterMode::Off
} else {
mode
};
}
}
}
struct Indexed {
name: String,
title: String,
owner: String,
summary: String,
mask: u32,
compatible: bool,
}
pub struct ExploreIndex {
pub mods: Vec<PortalMod>,
indexed: Vec<Indexed>,
/// Filters the data can answer. The bulk catalogue has no tags or dependencies, so those counts are unknown there.
known: u32,
}
#[derive(Debug)]
pub struct SearchResult {
pub rows: Vec<usize>,
pub counts: [usize; 28],
/// Bit i set: `counts[i]` is real. Unset: the data lacks the field, show no count.
pub known: u32,
}
impl ExploreIndex {
pub fn new(mods: Vec<PortalMod>, game_version: &str) -> Self {
let line = game_line(game_version);
let indexed = mods
.iter()
.map(|m| {
let mut mask = 0;
let category = m.category.as_deref().unwrap_or("no-category");
if let Some(i) = FILTERS[1..10].iter().position(|s| *s == category) {
mask |= 1 << (i + 1);
}
for tag in m.tags.as_deref().unwrap_or_default() {
if let Some(i) = FILTERS[10..].iter().position(|s| s == tag) {
mask |= 1 << (i + 10);
}
}
if let Some(release) = &m.latest_release
&& release
.info_json
.dependencies
.as_deref()
.unwrap_or_default()
.iter()
.any(|s| {
let d = parse_dependency(s);
d.is_some_and(|d| {
d.name == "space-age" && d.kind != DependencyKind::Incompatible
})
})
{
mask |= 1;
}
Indexed {
name: m.name.to_lowercase(),
title: m.title.to_lowercase(),
owner: m.owner.to_lowercase(),
summary: m.summary.to_lowercase(),
mask,
compatible: m
.latest_release
.as_ref()
.is_some_and(|r| r.info_json.factorio_version == line),
}
})
.collect();
// Categories are always known (a missing category is "no-category").
let mut known = 0b11_1111_1110u32;
if mods.iter().any(|m| m.tags.is_some()) {
known |= !0u32 << 10 & ((1 << 28) - 1);
}
if mods.iter().any(|m| {
m.latest_release
.as_ref()
.is_some_and(|r| r.info_json.dependencies.is_some())
}) {
known |= 1;
}
Self {
mods,
indexed,
known,
}
}
pub fn query(&self, state: &ViewState) -> SearchResult {
let query = state.search.to_lowercase();
let mut include = 0u32;
let mut exclude = 0u32;
for (i, mode) in state.filters.iter().enumerate() {
match mode {
FilterMode::Include => include |= 1 << i,
FilterMode::Exclude => exclude |= 1 << i,
FilterMode::Off => (),
}
}
let mut counts = [0; 28];
let mut rows = Vec::new();
for (i, m) in self.indexed.iter().enumerate() {
if !m.compatible
|| !(m.title.contains(&query)
|| m.name.contains(&query)
|| m.owner.contains(&query)
|| m.summary.contains(&query))
{
continue;
}
let passes = GROUPS.map(|g| {
(m.mask & exclude & g == 0) && (include & g == 0 || m.mask & include & g != 0)
});
if passes.iter().all(|p| *p) {
rows.push(i);
}
for (g, mask) in GROUPS.iter().enumerate() {
if (0..3).all(|other| other == g || passes[other]) {
let mut matching = m.mask & mask;
while matching != 0 {
counts[matching.trailing_zeros() as usize] += 1;
matching &= matching - 1;
}
}
}
}
rows.sort_unstable_by(|&a, &b| {
let (ma, mb) = (&self.mods[a], &self.mods[b]);
let downloads = || mb.downloads_count.cmp(&ma.downloads_count);
let order = match state.sort {
Sort::Relevance => self
.rank(a, &query)
.cmp(&self.rank(b, &query))
.then_with(downloads),
Sort::Downloads => downloads(),
Sort::Updated => mb
.latest_release
.as_ref()
.map(|r| &r.released_at)
.cmp(&ma.latest_release.as_ref().map(|r| &r.released_at)),
Sort::Trending => match (ma.score, mb.score) {
(Some(a), Some(b)) => b.total_cmp(&a),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
},
};
order.then_with(|| compare_english(&ma.name, &mb.name, false))
});
SearchResult {
rows,
counts,
known: self.known,
}
}
fn rank(&self, index: usize, query: &str) -> u8 {
let m = &self.indexed[index];
if query.is_empty() || m.name == query || m.title == query {
0
} else if m.title.starts_with(query) {
1
} else if m.title.contains(query) {
2
} else {
3
}
}
}