Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add detailed mod info view #84

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ egui_commonmark = "0.7.4"
egui_dnd = { git = "https://github.com/lucasmerlin/egui_dnd.git", rev = "e9043021e101fb42fc6ce70e508da857cb7ee263" }
futures = "0.3.28"
hex = "0.4.3"
image = { version = "0.24.7", default-features = false, features = ["png"] }
image = { version = "0.24.7", default-features = false, features = ["png", "jpeg"] }
indexmap = { version = "2.0.0", features = ["serde"] }
inventory = "0.3.11"
lazy_static = "1.4.0"
Expand Down
104 changes: 104 additions & 0 deletions src/gui/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub enum Message {
LintMods(LintMods),
SelfUpdate(SelfUpdate),
FetchSelfUpdateProgress(FetchSelfUpdateProgress),
FetchModDetails(FetchModDetails),
}

impl Message {
Expand All @@ -60,6 +61,7 @@ impl Message {
Self::LintMods(msg) => msg.receive(app),
Self::SelfUpdate(msg) => msg.receive(app),
Self::FetchSelfUpdateProgress(msg) => msg.receive(app),
Self::FetchModDetails(msg) => msg.receive(app),
}
}
}
Expand Down Expand Up @@ -748,3 +750,105 @@ async fn self_update_async(

Ok(original_exe_path)
}

#[derive(Debug)]
pub struct FetchModDetails {
rid: RequestID,
modio_id: u32,
result: Result<ModDetails>,
}

#[derive(Debug)]
pub struct ModDetails {
pub r#mod: modio::mods::Mod,
pub versions: Vec<modio::files::File>,
pub thumbnail: Vec<u8>,
}

impl FetchModDetails {
pub fn send(
rc: &mut RequestCounter,
ctx: &egui::Context,
tx: Sender<Message>,
oauth_token: &str,
modio_id: u32,
) -> MessageHandle<()> {
let rid = rc.next();
let ctx = ctx.clone();
let oauth_token = oauth_token.to_string();

MessageHandle {
rid,
handle: tokio::task::spawn(async move {
let result = fetch_modio_mod_details(oauth_token, modio_id).await;
tx.send(Message::FetchModDetails(FetchModDetails {
rid,
result,
modio_id,
}))
.await
.unwrap();
ctx.request_repaint();
}),
state: (),
}
}

fn receive(self, app: &mut App) {
let mut to_remove = None;

if let Some(req) = app.fetch_mod_details_rid.get(&self.modio_id)
&& req.rid == self.rid
{
match self.result {
Ok(mod_details) => {
info!("fetch mod details successful");
app.mod_details.insert(mod_details.r#mod.id, mod_details);
app.last_action_status =
LastActionStatus::Success("fetch mod details complete".to_string());
}
Err(e) => {
error!("fetch mod details failed");
error!("{:#?}", e);
to_remove = Some(self.modio_id);
app.last_action_status =
LastActionStatus::Failure("fetch mod details failed".to_string());
}
}
}

if let Some(id) = to_remove {
app.fetch_mod_details_rid.remove(&id);
}
}
}

async fn fetch_modio_mod_details(oauth_token: String, modio_id: u32) -> Result<ModDetails> {
use crate::providers::modio::{LoggingMiddleware, MODIO_DRG_ID};
use modio::{filter::prelude::*, Credentials, Modio};

let credentials = Credentials::with_token("", oauth_token);
let client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new())
.with::<LoggingMiddleware>(Default::default())
.build();
let modio = Modio::new(credentials, client.clone())?;
let mod_ref = modio.mod_(MODIO_DRG_ID, modio_id);
let r#mod = mod_ref.clone().get().await?;

let filter = with_limit(10).order_by(modio::user::filters::files::Version::desc());
let versions = mod_ref.clone().files().search(filter).first_page().await?;

let thumbnail = client
.get(r#mod.logo.thumb_320x180.clone())
.send()
.await?
.bytes()
.await?
.to_vec();

Ok(ModDetails {
r#mod,
versions,
thumbnail,
})
}
170 changes: 166 additions & 4 deletions src/gui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::{
};

use anyhow::{anyhow, Context, Result};
use eframe::egui::{Button, CollapsingHeader, RichText};
use eframe::egui::{Button, CollapsingHeader, Label, RichText};
use eframe::epaint::{Pos2, Vec2};
use eframe::{
egui::{self, FontSelection, Layout, TextFormat, Ui},
Expand Down Expand Up @@ -43,6 +43,7 @@ use find_string::FindString;
use message::MessageHandle;
use request_counter::{RequestCounter, RequestID};

use self::message::ModDetails;
use self::toggle_switch::toggle_switch;

pub fn gui(args: Option<Vec<String>>) -> Result<()> {
Expand Down Expand Up @@ -98,10 +99,14 @@ pub struct App {
lint_report: Option<LintReport>,
lints_toggle_window: Option<WindowLintsToggle>,
lint_options: LintOptions,
cache: CommonMarkCache,
update_cmark_cache: CommonMarkCache,
needs_restart: bool,
self_update_rid: Option<MessageHandle<SelfUpdateProgress>>,
original_exe_path: Option<PathBuf>,
detailed_mod_info_windows: HashMap<u32, WindowDetailedModInfo>,
mod_details: HashMap<u32, ModDetails>,
fetch_mod_details_rid: HashMap<u32, MessageHandle<()>>,
mod_details_thumbnail_texture_handle: HashMap<u32, egui::TextureHandle>,
}

#[derive(Default)]
Expand Down Expand Up @@ -157,10 +162,14 @@ impl App {
lint_report: None,
lints_toggle_window: None,
lint_options: LintOptions::default(),
cache: Default::default(),
update_cmark_cache: Default::default(),
needs_restart: false,
self_update_rid: None,
original_exe_path: None,
detailed_mod_info_windows: HashMap::default(),
mod_details: HashMap::default(),
fetch_mod_details_rid: HashMap::default(),
mod_details_thumbnail_texture_handle: HashMap::default(),
})
}

Expand Down Expand Up @@ -434,6 +443,24 @@ impl App {
ui.output_mut(|o| o.copied_text = mc.spec.url.to_owned());
}

if let Some(modio_id) = info.modio_id
&& let Some(modio_provider_params) = self.state.config.provider_parameters.get("modio")
&& let Some(oauth_token) = modio_provider_params.get("oauth")
&& ui
.button("ℹ")
.on_hover_text_at_pointer("View details")
.clicked()
{
self.detailed_mod_info_windows.insert(modio_id, WindowDetailedModInfo { info: info.clone() });
self.fetch_mod_details_rid.insert(modio_id, message::FetchModDetails::send(
&mut self.request_counter,
ui.ctx(),
self.tx.clone(),
oauth_token,
modio_id
));
}

if mc.enabled {
let is_duplicate = enabled_specs.iter().any(|(i, spec)| {
Some(state.index) != *i && info.spec.satisfies_dependency(spec)
Expand Down Expand Up @@ -730,7 +757,7 @@ impl App {
.show(ctx, |ui| {
CommonMarkViewer::new("available-update")
.max_image_width(Some(512))
.show(ui, &mut self.cache, &update.body);
.show(ui, &mut self.update_cmark_cache, &update.body);
ui.with_layout(egui::Layout::right_to_left(Align::TOP), |ui| {
if ui
.add(egui::Button::new("Install update"))
Expand Down Expand Up @@ -1400,6 +1427,125 @@ impl App {
}
}
}

fn show_detailed_mod_info(&mut self, ctx: &egui::Context, modio_id: u32) {
let mut to_remove = Vec::new();

if let Some(WindowDetailedModInfo { info }) = self.detailed_mod_info_windows.get(&modio_id)
{
let mut open = true;

egui::Window::new(&info.name)
.open(&mut open)
.collapsible(false)
.movable(true)
.resizable(true)
.show(ctx, |ui| self.show_detailed_mod_info_inner(ui, modio_id));

if !open {
to_remove.push(modio_id);
}
}

for id in to_remove {
self.detailed_mod_info_windows.remove(&id);
self.mod_details.remove(&id);
self.fetch_mod_details_rid.remove(&id);
self.mod_details_thumbnail_texture_handle.remove(&id);
}
}

fn show_detailed_mod_info_inner(&mut self, ui: &mut egui::Ui, modio_id: u32) {
if let Some(mod_details) = &self.mod_details.get(&modio_id) {
let scroll_area_height = (ui.available_height() - 60.0).clamp(0.0, f32::INFINITY);

egui::ScrollArea::vertical()
.max_height(scroll_area_height)
.max_width(f32::INFINITY)
.auto_shrink([false, false])
.stick_to_right(true)
.show(ui, |ui| {
let texture: &egui::TextureHandle = self
.mod_details_thumbnail_texture_handle
.entry(modio_id)
.or_insert_with(|| {
ui.ctx().load_texture(
format!("{} image", mod_details.r#mod.name),
{
let image =
image::load_from_memory(&mod_details.thumbnail).unwrap();
let size = [image.width() as _, image.height() as _];
let image_buffer = image.to_rgb8();
let pixels = image_buffer.as_flat_samples();
egui::ColorImage::from_rgb(size, pixels.as_slice())
},
Default::default(),
)
});
ui.vertical_centered(|ui| {
ui.image(texture, texture.size_vec2());
});

ui.heading("Uploader");
ui.label(&mod_details.r#mod.submitted_by.username);
ui.add_space(10.0);

ui.heading("Description");
if let Some(desc) = &mod_details.r#mod.description_plaintext {
ui.label(desc);
} else {
ui.label("No description provided.");
}
ui.add_space(10.0);

ui.heading("Versions and changelog");
ui.label(
RichText::new("Only the 10 most recent versions are shown.")
.color(Color32::GRAY)
.italics(),
);
egui::Grid::new("mod-details-available-versions")
.spacing(Vec2::new(3.0, 10.0))
.striped(true)
.num_columns(2)
.show(ui, |ui| {
mod_details.versions.iter().for_each(|file| {
if let Some(version) = &file.version {
ui.label(version);
} else {
ui.label("Unknown version");
}
if let Some(changelog) = &file.changelog {
ui.add(Label::new(changelog).wrap(true));
} else {
ui.label("N/A");
}
ui.end_row();
});
});
ui.add_space(10.0);

ui.heading("Files");
if let Some(file) = &mod_details.r#mod.modfile {
ui.horizontal(|ui| {
if let Some(version) = &file.version {
ui.label(version);
} else {
ui.label("Unknown version");
}
ui.hyperlink(&file.download.binary_url);
});
} else {
ui.label("No files provided.");
}
});
} else {
ui.horizontal(|ui| {
ui.spinner();
ui.label("Fetching mod details from mod.io...");
});
}
}
}

struct WindowProviderParameters {
Expand Down Expand Up @@ -1456,6 +1602,10 @@ struct WindowLintsToggle {
mods: Vec<ModSpecification>,
}

struct WindowDetailedModInfo {
info: ModInfo,
}

impl eframe::App for App {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
if self.needs_restart
Expand Down Expand Up @@ -1492,13 +1642,25 @@ impl eframe::App for App {
self.show_lints_toggle(ctx);
self.show_lint_report(ctx);

let modio_ids = self
.detailed_mod_info_windows
.keys()
.copied()
.collect::<Vec<_>>();

for modio_id in modio_ids {
self.show_detailed_mod_info(ctx, modio_id);
}

egui::TopBottomPanel::bottom("bottom_panel").show(ctx, |ui| {
ui.with_layout(egui::Layout::right_to_left(Align::TOP), |ui| {
ui.add_enabled_ui(
self.integrate_rid.is_none()
&& self.update_rid.is_none()
&& self.lint_rid.is_none()
&& self.self_update_rid.is_none()
&& self.detailed_mod_info_windows.is_empty()
&& self.fetch_mod_details_rid.is_empty()
&& self.state.config.drg_pak_path.is_some(),
|ui| {
if let Some(args) = &self.args {
Expand Down
Loading