feat(modpacks): refresh managed instances safely
This commit is contained in:
1 parent
bbf0317775
commit
e09e5a0168
15 files changed
+840
-29
No files matched your search
@@ -54,6 +54,7 @@ pub struct App {
|
||||
pub(super) content_update_snapshot:
|
||||
Option<(String, crate::instance::content::updates::UpdateSnapshot)>,
|
||||
pub(super) content_update_popup: Option<widgets::content::update::State>,
|
||||
pub(super) modpack_update_popup: Option<widgets::popups::modpack_update::State>,
|
||||
pub(super) provider_conflict: Option<ProviderConflictState>,
|
||||
pub(super) dismissed_provider_conflicts: HashSet<PathBuf>,
|
||||
}
|
||||
@@ -184,6 +185,7 @@ impl App {
|
||||
content_manifest: None,
|
||||
content_update_snapshot: None,
|
||||
content_update_popup: None,
|
||||
modpack_update_popup: None,
|
||||
provider_conflict: None,
|
||||
dismissed_provider_conflicts: HashSet::new(),
|
||||
}
|
||||
|
||||
@@ -48,6 +48,21 @@ impl App {
|
||||
self.content_update_popup = None;
|
||||
}
|
||||
}
|
||||
let completed_modpack = self.modpack_update_popup.as_mut().and_then(|update| {
|
||||
update.drain();
|
||||
update.completed.take()
|
||||
});
|
||||
if let Some(instance) = completed_modpack {
|
||||
let name = instance.name.clone();
|
||||
self.instances_state
|
||||
.replace_instance(&name, instance.clone());
|
||||
self.instances_state.modpack_updates.remove(&name);
|
||||
widgets::instances::spawn_modpack_update_check(&instance);
|
||||
self.modpack_update_popup = None;
|
||||
self.reconciliation_for = None;
|
||||
self.content_manifest = None;
|
||||
self.content_update_snapshot = None;
|
||||
}
|
||||
let mut local_streamed = false;
|
||||
let mut content_changed = false;
|
||||
let mut toggles = Vec::new();
|
||||
@@ -183,6 +198,7 @@ impl App {
|
||||
+ usize::from(self.focused == super::app::FocusedArea::ConfirmDelete)
|
||||
+ usize::from(self.provider_conflict.is_some())
|
||||
+ usize::from(self.content_update_popup.is_some())
|
||||
+ usize::from(self.modpack_update_popup.is_some())
|
||||
+ usize::from(!matches!(
|
||||
&self.account_state.add_mode,
|
||||
widgets::account::AddMode::None
|
||||
|
||||
@@ -64,6 +64,10 @@ impl App {
|
||||
self.handle_content_update_key(key_event);
|
||||
return Ok(());
|
||||
}
|
||||
if self.modpack_update_popup.is_some() {
|
||||
self.handle_modpack_update_key(key_event);
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(conflict) = self.provider_conflict.as_mut() {
|
||||
match key_event.code {
|
||||
KeyCode::Char('j') | KeyCode::Down => {
|
||||
@@ -755,6 +759,12 @@ impl App {
|
||||
self.spawn_launch(instance, None);
|
||||
}
|
||||
}
|
||||
KeyCode::Char('u')
|
||||
if self.focused == FocusedArea::Instances
|
||||
&& !self.instances_state.search.active =>
|
||||
{
|
||||
self.spawn_modpack_update();
|
||||
}
|
||||
KeyCode::Char('r')
|
||||
if self.focused == FocusedArea::Instances
|
||||
&& !self.instances_state.search.active =>
|
||||
@@ -799,6 +809,110 @@ impl App {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spawn_modpack_update(&mut self) {
|
||||
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(target) = self.instances_state.selected_modpack_update() else {
|
||||
return;
|
||||
};
|
||||
let state = widgets::popups::modpack_update::State::preparing();
|
||||
let pending = state.pending.clone();
|
||||
self.modpack_update_popup = Some(state);
|
||||
let instances_dir = self.instance_manager.instances_dir.clone();
|
||||
let meta_dir = self.instance_manager.meta_dir.clone();
|
||||
tokio::spawn(async move {
|
||||
let progress = crate::feedback::progress::ProgressTask::start(format!(
|
||||
"Preparing modpack update for {}",
|
||||
instance.name
|
||||
));
|
||||
let manager = crate::instance::InstanceManager::new(instances_dir, meta_dir);
|
||||
let result =
|
||||
crate::instance::import::refresh::prepare(&manager, &instance, target).await;
|
||||
if let Err(error) = &result {
|
||||
progress.fail(error);
|
||||
} else {
|
||||
progress.finish();
|
||||
}
|
||||
if let Ok(mut pending) = pending.lock() {
|
||||
pending.push(widgets::popups::modpack_update::PendingResult::Prepared(
|
||||
Box::new(result),
|
||||
));
|
||||
crate::feedback::request_redraw();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn handle_modpack_update_key(&mut self, key_event: KeyEvent) {
|
||||
let Some(state) = self.modpack_update_popup.as_mut() else {
|
||||
return;
|
||||
};
|
||||
match (state.phase, key_event.code) {
|
||||
(widgets::popups::modpack_update::Phase::Preparing, KeyCode::Esc)
|
||||
| (widgets::popups::modpack_update::Phase::Conflicts, KeyCode::Esc)
|
||||
| (widgets::popups::modpack_update::Phase::Review, KeyCode::Esc) => {
|
||||
self.modpack_update_popup = None;
|
||||
}
|
||||
(
|
||||
widgets::popups::modpack_update::Phase::Conflicts,
|
||||
KeyCode::Char('j') | KeyCode::Down,
|
||||
) => {
|
||||
let count = state.plan.as_ref().map_or(0, |plan| plan.conflicts.len());
|
||||
state.selected = (state.selected + 1).min(count.saturating_sub(1));
|
||||
}
|
||||
(
|
||||
widgets::popups::modpack_update::Phase::Conflicts,
|
||||
KeyCode::Char('k') | KeyCode::Up,
|
||||
) => state.selected = state.selected.saturating_sub(1),
|
||||
(widgets::popups::modpack_update::Phase::Conflicts, KeyCode::Char(' ')) => {
|
||||
if let Some(replace) = state.replace.get_mut(state.selected) {
|
||||
*replace = !*replace;
|
||||
}
|
||||
}
|
||||
(widgets::popups::modpack_update::Phase::Conflicts, KeyCode::Enter) => {
|
||||
state.phase = widgets::popups::modpack_update::Phase::Review;
|
||||
}
|
||||
(widgets::popups::modpack_update::Phase::Review, KeyCode::Enter)
|
||||
if state.plan.is_some() =>
|
||||
{
|
||||
self.spawn_modpack_update_apply();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_modpack_update_apply(&mut self) {
|
||||
let Some(state) = self.modpack_update_popup.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let replacements = state.replacements();
|
||||
let Some(plan) = state.plan.take() else {
|
||||
return;
|
||||
};
|
||||
state.phase = widgets::popups::modpack_update::Phase::Applying;
|
||||
let pending = state.pending.clone();
|
||||
tokio::spawn(async move {
|
||||
let progress = crate::feedback::progress::ProgressTask::start("Updating modpack");
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
crate::instance::import::refresh::apply(plan, &replacements)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|result| result);
|
||||
if let Err(error) = &result {
|
||||
progress.fail(error);
|
||||
} else {
|
||||
progress.finish();
|
||||
}
|
||||
if let Ok(mut pending) = pending.lock() {
|
||||
pending.push(widgets::popups::modpack_update::PendingResult::Applied(
|
||||
Box::new(result),
|
||||
));
|
||||
crate::feedback::request_redraw();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn ensure_active_discovery_loaded(&mut self) {
|
||||
if self.content_mode != widgets::content::ContentMode::Discover {
|
||||
return;
|
||||
|
||||
@@ -182,6 +182,10 @@ impl App {
|
||||
if let Some(update) = &self.content_update_popup {
|
||||
widgets::content::update::render(frame, update);
|
||||
}
|
||||
|
||||
if let Some(update) = &self.modpack_update_popup {
|
||||
widgets::popups::modpack_update::render(frame, update);
|
||||
}
|
||||
}
|
||||
|
||||
// full-screen log viewer with search highlighting and auto-scroll.
|
||||
|
||||
@@ -94,6 +94,7 @@ impl UiHarness {
|
||||
content_manifest: None,
|
||||
content_update_snapshot: None,
|
||||
content_update_popup: None,
|
||||
modpack_update_popup: None,
|
||||
provider_conflict: None,
|
||||
dismissed_provider_conflicts: HashSet::new(),
|
||||
};
|
||||
|
||||
@@ -83,7 +83,21 @@ fn instances_list_renders_empty() {
|
||||
#[test]
|
||||
fn managed_modpack_update_is_badged_in_the_instance_list() {
|
||||
let mut state = State::with_instances(vec![synthetic_instance("Managed Pack")]);
|
||||
state.modpack_updates.insert("Managed Pack".to_owned());
|
||||
state.modpack_updates.insert(
|
||||
"Managed Pack".to_owned(),
|
||||
crate::net::modrinth::VersionInfo {
|
||||
id: "new".to_owned(),
|
||||
project_id: "pack".to_owned(),
|
||||
name: "New".to_owned(),
|
||||
version_number: "2.0".to_owned(),
|
||||
game_versions: Vec::new(),
|
||||
loaders: Vec::new(),
|
||||
version_type: crate::net::modrinth::VersionType::Release,
|
||||
dependencies: Vec::new(),
|
||||
date_published: String::new(),
|
||||
files: Vec::new(),
|
||||
},
|
||||
);
|
||||
let backend = TestBackend::new(40, 5);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
|
||||
|
||||
@@ -405,6 +405,7 @@ pub fn render(
|
||||
("Esc", " kill"),
|
||||
("a", " add"),
|
||||
("m", " modpacks"),
|
||||
("u", " update"),
|
||||
("d", " delete"),
|
||||
("r", " rename"),
|
||||
("/", " search"),
|
||||
|
||||
@@ -11,7 +11,7 @@ use ratatui::{
|
||||
text::{Line, Span, Text},
|
||||
widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
||||
};
|
||||
use std::collections::HashSet;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||
|
||||
@@ -22,9 +22,13 @@ use crate::tui::app::FocusedArea;
|
||||
|
||||
use super::{WidgetKey, search::SearchState, styled_title};
|
||||
|
||||
static PENDING_MODPACK_UPDATES: LazyLock<
|
||||
Mutex<Vec<(String, crate::instance::ProviderProject, bool)>>,
|
||||
> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
type PendingModpackUpdate = (
|
||||
String,
|
||||
crate::instance::ProviderProject,
|
||||
Option<crate::net::modrinth::VersionInfo>,
|
||||
);
|
||||
static PENDING_MODPACK_UPDATES: LazyLock<Mutex<Vec<PendingModpackUpdate>>> =
|
||||
LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
static MODPACK_UPDATE_SLOTS: LazyLock<Arc<tokio::sync::Semaphore>> =
|
||||
LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(4)));
|
||||
|
||||
@@ -43,27 +47,15 @@ pub fn spawn_modpack_update_check(instance: &InstanceConfig) {
|
||||
let Ok(_permit) = MODPACK_UPDATE_SLOTS.clone().acquire_owned().await else {
|
||||
return;
|
||||
};
|
||||
let registry = crate::instance::content::provider::ProviderRegistry::configured(
|
||||
crate::net::HttpClient::new(),
|
||||
);
|
||||
let Some(provider) = registry.get(&source.provider) else {
|
||||
let Ok(versions) = crate::instance::import::provider_versions(&source).await else {
|
||||
return;
|
||||
};
|
||||
let Ok(versions) = provider
|
||||
.compatible_versions(
|
||||
&source.project_id,
|
||||
crate::instance::ContentKind::Mod,
|
||||
&instance.game_version,
|
||||
instance.loader,
|
||||
let update = versions.first().cloned().filter(|_| {
|
||||
crate::instance::content::provider::has_newer_compatible_version(
|
||||
&versions,
|
||||
&source.version_id,
|
||||
)
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let update = crate::instance::content::provider::has_newer_compatible_version(
|
||||
&versions,
|
||||
&source.version_id,
|
||||
);
|
||||
});
|
||||
if let Ok(mut pending) = PENDING_MODPACK_UPDATES.lock() {
|
||||
pending.push((instance.name, source, update));
|
||||
crate::feedback::request_redraw();
|
||||
@@ -80,7 +72,7 @@ pub struct State {
|
||||
pub show_import_popup: bool,
|
||||
pub search: SearchState,
|
||||
pub renaming: Option<String>,
|
||||
pub(crate) modpack_updates: HashSet<String>,
|
||||
pub(crate) modpack_updates: HashMap<String, crate::net::modrinth::VersionInfo>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
@@ -94,7 +86,7 @@ impl State {
|
||||
show_import_popup: false,
|
||||
search: SearchState::default(),
|
||||
renaming: None,
|
||||
modpack_updates: HashSet::new(),
|
||||
modpack_updates: HashMap::new(),
|
||||
};
|
||||
if count > 0 {
|
||||
s.list_state.selected = Some(0);
|
||||
@@ -184,7 +176,7 @@ impl State {
|
||||
let Ok(mut pending) = PENDING_MODPACK_UPDATES.lock() else {
|
||||
return;
|
||||
};
|
||||
for (name, source, available) in pending.drain(..) {
|
||||
for (name, source, update) in pending.drain(..) {
|
||||
if self
|
||||
.instances
|
||||
.iter()
|
||||
@@ -194,8 +186,8 @@ impl State {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if available {
|
||||
self.modpack_updates.insert(name);
|
||||
if let Some(update) = update {
|
||||
self.modpack_updates.insert(name, update);
|
||||
} else {
|
||||
self.modpack_updates.remove(&name);
|
||||
}
|
||||
@@ -208,6 +200,12 @@ impl State {
|
||||
self.update_scrollbar();
|
||||
}
|
||||
|
||||
pub fn selected_modpack_update(&self) -> Option<crate::net::modrinth::VersionInfo> {
|
||||
self.selected_instance()
|
||||
.and_then(|instance| self.modpack_updates.get(&instance.name))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub fn replace_instance(&mut self, old_name: &str, instance: InstanceConfig) {
|
||||
if let Some(existing) = self
|
||||
.instances
|
||||
@@ -351,7 +349,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
||||
} else {
|
||||
let mut spans = vec![selector.clone()];
|
||||
spans.extend(state.search.highlight_spans(&instance.name, name_style));
|
||||
if state.modpack_updates.contains(&instance.name) {
|
||||
if state.modpack_updates.contains_key(&instance.name) {
|
||||
spans.extend([
|
||||
Span::raw(" "),
|
||||
Span::styled(
|
||||
|
||||
@@ -6,6 +6,7 @@ pub mod confirm;
|
||||
pub mod error;
|
||||
pub mod import_modpack;
|
||||
mod load_state;
|
||||
pub mod modpack_update;
|
||||
pub mod new_instance;
|
||||
|
||||
pub use load_state::LoadState;
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::{Constraint, Flex, Layout},
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph},
|
||||
};
|
||||
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crate::instance::import::refresh::RefreshPlan;
|
||||
|
||||
pub enum PendingResult {
|
||||
Prepared(Box<Result<RefreshPlan, String>>),
|
||||
Applied(Box<Result<crate::instance::InstanceConfig, String>>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
Preparing,
|
||||
Conflicts,
|
||||
Review,
|
||||
Applying,
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
pub phase: Phase,
|
||||
pub plan: Option<RefreshPlan>,
|
||||
pub selected: usize,
|
||||
pub replace: Vec<bool>,
|
||||
pub error: Option<String>,
|
||||
pub pending: Arc<Mutex<Vec<PendingResult>>>,
|
||||
pub completed: Option<crate::instance::InstanceConfig>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn preparing() -> Self {
|
||||
Self {
|
||||
phase: Phase::Preparing,
|
||||
plan: None,
|
||||
selected: 0,
|
||||
replace: Vec::new(),
|
||||
error: None,
|
||||
pending: Arc::new(Mutex::new(Vec::new())),
|
||||
completed: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn drain(&mut self) {
|
||||
let pending = match self.pending.lock() {
|
||||
Ok(mut pending) => pending.drain(..).collect::<Vec<_>>(),
|
||||
Err(_) => return,
|
||||
};
|
||||
for result in pending {
|
||||
match result {
|
||||
PendingResult::Prepared(result) => match *result {
|
||||
Ok(plan) => {
|
||||
self.replace = vec![false; plan.conflicts.len()];
|
||||
self.phase = if plan.conflicts.is_empty() {
|
||||
Phase::Review
|
||||
} else {
|
||||
Phase::Conflicts
|
||||
};
|
||||
self.plan = Some(plan);
|
||||
self.error = None;
|
||||
}
|
||||
Err(error) => {
|
||||
self.phase = Phase::Review;
|
||||
self.error = Some(error);
|
||||
}
|
||||
},
|
||||
PendingResult::Applied(result) => match *result {
|
||||
Ok(instance) => self.completed = Some(instance),
|
||||
Err(error) => {
|
||||
self.phase = Phase::Review;
|
||||
self.error = Some(error);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn replacements(&self) -> HashSet<PathBuf> {
|
||||
self.plan
|
||||
.as_ref()
|
||||
.into_iter()
|
||||
.flat_map(|plan| plan.conflicts.iter())
|
||||
.enumerate()
|
||||
.filter(|(index, _)| self.replace.get(*index) == Some(&true))
|
||||
.map(|(_, path)| path.clone())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(frame: &mut Frame, state: &State) {
|
||||
let theme = THEME.as_ref();
|
||||
let count = state
|
||||
.plan
|
||||
.as_ref()
|
||||
.map_or(1, |plan| plan.conflicts.len().max(5));
|
||||
let [area] = Layout::vertical([Constraint::Length((count as u16 + 5).clamp(8, 20))])
|
||||
.flex(Flex::Center)
|
||||
.areas(frame.area());
|
||||
let [area] = Layout::horizontal([Constraint::Percentage(62)])
|
||||
.flex(Flex::Center)
|
||||
.areas(area);
|
||||
frame.render_widget(Clear, area);
|
||||
let (title, footer) = match state.phase {
|
||||
Phase::Preparing => (" Prepare modpack update ", " [Esc] cancel "),
|
||||
Phase::Conflicts => (
|
||||
" Resolve modpack conflicts ",
|
||||
" [j/k] select [Space] keep/replace [Enter] continue [Esc] cancel ",
|
||||
),
|
||||
Phase::Review => (" Update modpack ", " [Enter] update [Esc] cancel "),
|
||||
Phase::Applying => (" Updating modpack ", " Please wait "),
|
||||
};
|
||||
let block = Block::default()
|
||||
.title(title)
|
||||
.title_bottom(Line::from(footer).centered())
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BORDER_STYLE.to_border_type())
|
||||
.border_style(Style::default().fg(theme.accent()))
|
||||
.style(Style::default().fg(theme.text()).bg(theme.surface()));
|
||||
match state.phase {
|
||||
Phase::Preparing => frame.render_widget(
|
||||
Paragraph::new("Downloading and validating the target pack…").block(block),
|
||||
area,
|
||||
),
|
||||
Phase::Applying => frame.render_widget(
|
||||
Paragraph::new("Preserving user files and activating the staged pack…").block(block),
|
||||
area,
|
||||
),
|
||||
Phase::Conflicts => {
|
||||
let items = state
|
||||
.plan
|
||||
.as_ref()
|
||||
.into_iter()
|
||||
.flat_map(|plan| plan.conflicts.iter())
|
||||
.enumerate()
|
||||
.map(|(index, path)| {
|
||||
let action = if state.replace.get(index) == Some(&true) {
|
||||
"Replace"
|
||||
} else {
|
||||
"Keep"
|
||||
};
|
||||
ListItem::new(Line::from(vec![
|
||||
Span::raw(format!("• {} ", path.display())),
|
||||
Span::styled(action, Style::default().fg(theme.accent())),
|
||||
]))
|
||||
});
|
||||
let mut selected = ListState::default().with_selected(Some(state.selected));
|
||||
frame.render_stateful_widget(
|
||||
List::new(items)
|
||||
.block(block)
|
||||
.highlight_symbol("▌")
|
||||
.highlight_style(Style::default().bg(theme.stripe())),
|
||||
area,
|
||||
&mut selected,
|
||||
);
|
||||
}
|
||||
Phase::Review => {
|
||||
let mut lines = state.plan.as_ref().map_or_else(Vec::new, |plan| {
|
||||
vec![
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
plan.summary.name.clone(),
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::raw(format!(
|
||||
" {} → {}",
|
||||
plan.current_version, plan.target_version
|
||||
)),
|
||||
]),
|
||||
Line::from(format!("Minecraft: {}", plan.summary.game_version)),
|
||||
Line::from(format!(
|
||||
"Loader: {} {}",
|
||||
plan.summary.loader,
|
||||
plan.summary.loader_version.as_deref().unwrap_or("")
|
||||
)),
|
||||
Line::from(format!("Pack files: {}", plan.summary.mod_count)),
|
||||
Line::from(format!("Overrides: {}", plan.summary.override_count)),
|
||||
]
|
||||
});
|
||||
if let Some(error) = &state.error {
|
||||
lines.push(Line::from(error.clone()).style(Style::default().fg(theme.error())));
|
||||
}
|
||||
frame.render_widget(Paragraph::new(lines).block(block), area);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user