454 lines
19 KiB
Rust
454 lines
19 KiB
Rust
use crate::{
|
|
engine::{self, Event, Outcome},
|
|
model::{FORMATS, Options},
|
|
};
|
|
use eframe::egui::{self, Color32, RichText};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::{
|
|
path::PathBuf,
|
|
sync::{
|
|
Arc,
|
|
atomic::{AtomicBool, Ordering},
|
|
mpsc::{self, Receiver},
|
|
},
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
#[derive(Default, Clone, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct Preferences {
|
|
pub options: Options,
|
|
pub recent: Vec<PathBuf>,
|
|
}
|
|
impl Preferences {
|
|
pub fn remember(&mut self, path: PathBuf) {
|
|
self.recent.retain(|p| p != &path);
|
|
self.recent.insert(0, path);
|
|
self.recent.truncate(8);
|
|
}
|
|
}
|
|
fn config_path() -> Option<PathBuf> {
|
|
directories::ProjectDirs::from("com", "beffroi", "pptx-reporter")
|
|
.map(|d| d.config_dir().join("settings.json"))
|
|
}
|
|
pub fn accept_drop(paths: impl IntoIterator<Item = PathBuf>) -> Result<PathBuf, String> {
|
|
let paths: Vec<_> = paths.into_iter().collect();
|
|
if paths.len() != 1 {
|
|
return Err("Drop one PPTX presentation at a time.".into());
|
|
}
|
|
let path = paths.into_iter().next().unwrap();
|
|
if !path.is_file()
|
|
|| !path
|
|
.extension()
|
|
.is_some_and(|e| e.eq_ignore_ascii_case("pptx"))
|
|
{
|
|
return Err("Choose a .pptx presentation.".into());
|
|
}
|
|
Ok(path)
|
|
}
|
|
enum Update {
|
|
Progress(Event),
|
|
Finished(Result<Outcome, String>),
|
|
}
|
|
struct App {
|
|
preferences: Preferences,
|
|
source: String,
|
|
output: String,
|
|
ffprobe: String,
|
|
rx: Option<Receiver<Update>>,
|
|
cancel: Arc<AtomicBool>,
|
|
status: Event,
|
|
started: Instant,
|
|
phase: Instant,
|
|
log: Vec<(String, bool)>,
|
|
paths: Vec<PathBuf>,
|
|
error: Option<String>,
|
|
completed_output: Option<PathBuf>,
|
|
}
|
|
impl App {
|
|
fn new() -> Self {
|
|
let preferences: Preferences = config_path()
|
|
.and_then(|p| std::fs::read(p).ok())
|
|
.and_then(|b| serde_json::from_slice(&b).ok())
|
|
.unwrap_or_default();
|
|
Self::from_preferences(preferences)
|
|
}
|
|
fn from_preferences(preferences: Preferences) -> Self {
|
|
Self {
|
|
source: preferences.options.source.display().to_string(),
|
|
output: preferences
|
|
.options
|
|
.output
|
|
.as_ref()
|
|
.map(|p| p.display().to_string())
|
|
.unwrap_or_default(),
|
|
ffprobe: preferences
|
|
.options
|
|
.ffprobe
|
|
.as_ref()
|
|
.map(|p| p.display().to_string())
|
|
.unwrap_or_default(),
|
|
preferences,
|
|
rx: None,
|
|
cancel: Arc::new(AtomicBool::new(false)),
|
|
status: Event::step("Ready", 0, 0),
|
|
started: Instant::now(),
|
|
phase: Instant::now(),
|
|
log: vec![],
|
|
paths: vec![],
|
|
error: None,
|
|
completed_output: None,
|
|
}
|
|
}
|
|
fn save(&mut self) {
|
|
if let Some(path) = config_path() {
|
|
let result = (|| -> anyhow::Result<()> {
|
|
let parent = path.parent().unwrap();
|
|
std::fs::create_dir_all(parent)?;
|
|
let temp = tempfile::NamedTempFile::new_in(parent)?;
|
|
std::fs::write(temp.path(), serde_json::to_vec_pretty(&self.preferences)?)?;
|
|
temp.persist(path).map_err(|e| e.error)?;
|
|
Ok(())
|
|
})();
|
|
if let Err(e) = result {
|
|
self.log
|
|
.push((format!("Could not save settings: {e}"), true));
|
|
}
|
|
}
|
|
}
|
|
fn start(&mut self) {
|
|
let options = &mut self.preferences.options;
|
|
options.source = PathBuf::from(&self.source);
|
|
options.output = (!self.output.trim().is_empty()).then(|| PathBuf::from(&self.output));
|
|
options.ffprobe = (!self.ffprobe.trim().is_empty()).then(|| PathBuf::from(&self.ffprobe));
|
|
if let Err(error) = options.validate() {
|
|
self.error = Some(error.to_string());
|
|
return;
|
|
}
|
|
let options = options.clone();
|
|
self.preferences.remember(options.source.clone());
|
|
self.log.clear();
|
|
self.error = None;
|
|
self.paths.clear();
|
|
self.completed_output = None;
|
|
self.save();
|
|
self.started = Instant::now();
|
|
self.phase = self.started;
|
|
self.status = Event::step("Starting", 0, 0);
|
|
self.cancel = Arc::new(AtomicBool::new(false));
|
|
let cancel = self.cancel.clone();
|
|
let (tx, rx) = mpsc::channel();
|
|
self.rx = Some(rx);
|
|
std::thread::spawn(move || {
|
|
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
|
engine::run(&options, &cancel, |event| {
|
|
let _ = tx.send(Update::Progress(event));
|
|
})
|
|
}))
|
|
.map_err(|_| "Reporter worker stopped unexpectedly.".to_string())
|
|
.and_then(|r| r.map_err(|e| format!("{e:#}")));
|
|
let _ = tx.send(Update::Finished(result));
|
|
});
|
|
}
|
|
fn receive(&mut self) {
|
|
let updates: Vec<_> = self
|
|
.rx
|
|
.as_ref()
|
|
.map(|r| r.try_iter().collect())
|
|
.unwrap_or_default();
|
|
for update in updates {
|
|
match update {
|
|
Update::Progress(event) => {
|
|
if event.total != self.status.total || event.done < self.status.done {
|
|
self.phase = Instant::now();
|
|
}
|
|
self.log.push((event.message.clone(), event.warning));
|
|
if self.log.len() > 500 {
|
|
self.log.remove(0);
|
|
}
|
|
self.status = event;
|
|
}
|
|
Update::Finished(result) => {
|
|
self.rx = None;
|
|
match result {
|
|
Ok(outcome) => {
|
|
self.status = Event::step(
|
|
if outcome.paths.is_empty() {
|
|
"No embedded videos found."
|
|
} else {
|
|
"Reports ready"
|
|
},
|
|
0,
|
|
0,
|
|
);
|
|
if !outcome.paths.is_empty() {
|
|
self.completed_output = Some(outcome.output);
|
|
}
|
|
self.paths = outcome.paths;
|
|
}
|
|
Err(error) => {
|
|
self.status = Event::step("Stopped", 0, 0);
|
|
self.error = Some(error);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fn open(&mut self, path: &std::path::Path) {
|
|
if let Err(e) = open::that(path) {
|
|
self.error = Some(format!("Could not open {}: {e}", path.display()));
|
|
}
|
|
}
|
|
}
|
|
impl Drop for App {
|
|
fn drop(&mut self) {
|
|
self.cancel.store(true, Ordering::Relaxed);
|
|
}
|
|
}
|
|
impl eframe::App for App {
|
|
fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
|
|
self.draw(ctx);
|
|
}
|
|
}
|
|
impl App {
|
|
fn draw(&mut self, ctx: &egui::Context) {
|
|
self.receive();
|
|
if self.rx.is_some() {
|
|
ctx.request_repaint_after(Duration::from_millis(100));
|
|
}
|
|
let drops = ctx.input(|i| {
|
|
i.raw
|
|
.dropped_files
|
|
.iter()
|
|
.filter_map(|f| f.path.clone())
|
|
.collect::<Vec<_>>()
|
|
});
|
|
if !drops.is_empty() {
|
|
if self.rx.is_some() {
|
|
self.error = Some(
|
|
"Wait for the current report or cancel it before dropping another file.".into(),
|
|
);
|
|
} else {
|
|
match accept_drop(drops) {
|
|
Ok(path) => {
|
|
self.source = path.display().to_string();
|
|
self.error = None;
|
|
}
|
|
Err(e) => self.error = Some(e),
|
|
}
|
|
}
|
|
}
|
|
egui::CentralPanel::default().show(ctx, |ui| {
|
|
egui::ScrollArea::vertical().show(ui, |ui| {
|
|
ui.add_space(12.0);
|
|
ui.label(RichText::new("PRESENTATION MEDIA").color(Color32::from_rgb(117,100,230)).strong());
|
|
ui.heading(RichText::new("PPTX Reporter").size(32.0));
|
|
ui.label("Video timings, beautifully documented.");
|
|
ui.add_space(18.0);
|
|
ui.add_enabled_ui(self.rx.is_none(), |ui| {
|
|
egui::Frame::group(ui.style()).inner_margin(20.0).show(ui, |ui| {
|
|
ui.set_min_width(ui.available_width());
|
|
ui.label(RichText::new("Drop a PPTX here").size(22.0).strong());
|
|
ui.label("Or choose a presentation to get started.");
|
|
if ui.button("Choose presentation…").clicked()
|
|
&& let Some(file) = rfd::FileDialog::new().add_filter("PowerPoint",&["pptx"]).pick_file() {
|
|
self.source = file.display().to_string();
|
|
}
|
|
ui.add(egui::TextEdit::singleline(&mut self.source).desired_width(f32::INFINITY).hint_text("Presentation path"));
|
|
if !self.preferences.recent.is_empty() {
|
|
egui::ComboBox::from_label("Recent presentations").selected_text("Choose…").show_ui(ui, |ui| {
|
|
for path in &self.preferences.recent {
|
|
if ui.selectable_label(false,path.display().to_string()).clicked() { self.source = path.display().to_string(); }
|
|
}
|
|
});
|
|
}
|
|
});
|
|
ui.add_space(12.0);
|
|
ui.horizontal(|ui| {
|
|
ui.label("Output folder");
|
|
if ui.button("Choose…").clicked()
|
|
&& let Some(path) = rfd::FileDialog::new().pick_folder() {
|
|
self.output = path.display().to_string();
|
|
}
|
|
if ui.button("Use default").clicked() { self.output.clear(); }
|
|
});
|
|
ui.add(egui::TextEdit::singleline(&mut self.output).desired_width(f32::INFINITY).hint_text("Default: <presentation>_videos"));
|
|
let options = &mut self.preferences.options;
|
|
let mut mode = if options.extract_only { 2 } else if options.timings_only { 1 } else { 0 };
|
|
ui.horizontal_wrapped(|ui| {
|
|
ui.selectable_value(&mut mode,0,"Extract + reports");
|
|
ui.selectable_value(&mut mode,1,"Reports only");
|
|
ui.selectable_value(&mut mode,2,"Extract only");
|
|
});
|
|
options.extract_only = mode == 2; options.timings_only = mode == 1;
|
|
ui.add_enabled_ui(!options.extract_only,|ui| {
|
|
ui.horizontal_wrapped(|ui| {
|
|
for format in FORMATS {
|
|
let mut selected = options.formats.iter().any(|f| f == format);
|
|
if ui.checkbox(&mut selected,*format).changed() {
|
|
options.formats.retain(|f| f != format);
|
|
if selected { options.formats.push((*format).into()); }
|
|
}
|
|
}
|
|
if ui.small_button("All").clicked() { options.formats = FORMATS.iter().map(|s| (*s).into()).collect(); }
|
|
});
|
|
});
|
|
ui.collapsing("Advanced",|ui| {
|
|
ui.checkbox(&mut options.overwrite,"Replace existing extracted videos");
|
|
ui.label("Existing report files are regenerated. Videos are kept unless replacement is enabled.");
|
|
ui.horizontal(|ui| {
|
|
ui.label("FFprobe");
|
|
if ui.button("Locate…").clicked()
|
|
&& let Some(path) = rfd::FileDialog::new().pick_file() {
|
|
self.ffprobe = path.display().to_string();
|
|
}
|
|
});
|
|
ui.add(egui::TextEdit::singleline(&mut self.ffprobe).desired_width(f32::INFINITY).hint_text("Automatic: beside app, bin/, or PATH"));
|
|
ui.label("PDF generation is built in. FFprobe comes from FFmpeg; no PowerPoint installation is needed.");
|
|
});
|
|
ui.add_space(10.0);
|
|
if ui.add_sized([180.0,38.0],egui::Button::new("Generate")).clicked() { self.start(); }
|
|
});
|
|
ui.add_space(14.0);
|
|
if self.rx.is_some() {
|
|
ui.horizontal(|ui| {
|
|
ui.spinner(); ui.label(&self.status.message);
|
|
if ui.button("Cancel").clicked() { self.cancel.store(true,Ordering::Relaxed); }
|
|
});
|
|
let e = &self.status;
|
|
if e.total > 0 { ui.add(egui::ProgressBar::new(e.done as f32/e.total as f32).show_percentage()); }
|
|
let eta = if e.done > 0 && e.done < e.total {
|
|
format!(" · about {:.0}s remaining in this phase",self.phase.elapsed().as_secs_f64()/e.done as f64*(e.total-e.done) as f64)
|
|
} else { String::new() };
|
|
ui.label(format!("{:.0}s elapsed{eta}",self.started.elapsed().as_secs_f64()));
|
|
} else { ui.label(&self.status.message); }
|
|
if let Some(error) = &self.error { ui.colored_label(Color32::from_rgb(255,150,120),error); }
|
|
if let Some(dir) = self.completed_output.clone() {
|
|
ui.add_space(12.0);
|
|
if ui.button("Open output folder").clicked() { self.open(&dir); }
|
|
}
|
|
for path in self.paths.clone() {
|
|
ui.horizontal(|ui| {
|
|
ui.label(RichText::new(path.file_name().unwrap_or_default().to_string_lossy()).strong());
|
|
if ui.button("Open").clicked() { self.open(&path); }
|
|
if ui.button("Copy path").clicked() { ctx.copy_text(path.display().to_string()); }
|
|
});
|
|
}
|
|
ui.collapsing("Activity",|ui| {
|
|
egui::ScrollArea::vertical().max_height(180.0).stick_to_bottom(true).show(ui,|ui| {
|
|
for (line, warning) in &self.log { ui.colored_label(if *warning {Color32::from_rgb(236,185,86)} else {Color32::from_rgb(160,175,195)},line); }
|
|
});
|
|
});
|
|
});
|
|
});
|
|
if ctx.input(|i| !i.raw.hovered_files.is_empty()) {
|
|
let painter = ctx.layer_painter(egui::LayerId::new(
|
|
egui::Order::Foreground,
|
|
egui::Id::new("drop"),
|
|
));
|
|
painter.rect_filled(ctx.screen_rect(), 0.0, Color32::from_black_alpha(210));
|
|
painter.text(
|
|
ctx.screen_rect().center(),
|
|
egui::Align2::CENTER_CENTER,
|
|
"Drop your PPTX presentation",
|
|
egui::FontId::proportional(28.0),
|
|
Color32::WHITE,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn launch() -> anyhow::Result<()> {
|
|
let icon = eframe::icon_data::from_png_bytes(include_bytes!("../assets/rust-report-icon.png"))?;
|
|
let options = eframe::NativeOptions {
|
|
viewport: egui::ViewportBuilder::default()
|
|
.with_icon(icon)
|
|
.with_inner_size([860.0, 760.0])
|
|
.with_min_inner_size([620.0, 500.0])
|
|
.with_drag_and_drop(true),
|
|
..Default::default()
|
|
};
|
|
eframe::run_native(
|
|
"PPTX Reporter",
|
|
options,
|
|
Box::new(|cc| {
|
|
cc.egui_ctx.set_visuals(egui::Visuals::dark());
|
|
let mut style = (*cc.egui_ctx.style()).clone();
|
|
style.spacing.item_spacing = egui::vec2(10.0, 10.0);
|
|
style.visuals.selection.bg_fill = Color32::from_rgb(87, 68, 181);
|
|
cc.egui_ctx.set_style(style);
|
|
Ok(Box::new(App::new()))
|
|
}),
|
|
)
|
|
.map_err(|e| anyhow::anyhow!("{e}"))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn frame(app: &mut App, input: egui::RawInput) {
|
|
let ctx = egui::Context::default();
|
|
let output = ctx.run(input, |ctx| app.draw(ctx));
|
|
assert!(!output.shapes.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn renders_drop_validation_and_running_state_without_display() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let path = dir.path().join("Présentation.pptx");
|
|
std::fs::write(&path, b"fixture").unwrap();
|
|
let mut app = App::from_preferences(Preferences::default());
|
|
let input = egui::RawInput {
|
|
dropped_files: vec![egui::DroppedFile {
|
|
path: Some(path.clone()),
|
|
..Default::default()
|
|
}],
|
|
..Default::default()
|
|
};
|
|
frame(&mut app, input.clone());
|
|
assert_eq!(app.source, path.display().to_string());
|
|
assert!(app.error.is_none());
|
|
let (tx, rx) = mpsc::channel();
|
|
app.rx = Some(rx);
|
|
tx.send(Update::Progress(Event::step("Probing", 1, 3)))
|
|
.unwrap();
|
|
frame(&mut app, input);
|
|
assert!(app.error.as_ref().unwrap().contains("current report"));
|
|
assert_eq!(app.status.done, 1);
|
|
assert_eq!(app.log.len(), 1);
|
|
tx.send(Update::Finished(Err("Cancelled".into()))).unwrap();
|
|
frame(&mut app, egui::RawInput::default());
|
|
assert!(app.rx.is_none());
|
|
assert_eq!(app.error.as_deref(), Some("Cancelled"));
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_start_and_successful_completion_show_actionable_state() {
|
|
let mut app = App::from_preferences(Preferences::default());
|
|
app.start();
|
|
assert!(app.error.is_some());
|
|
assert!(app.rx.is_none());
|
|
let (tx, rx) = mpsc::channel();
|
|
app.rx = Some(rx);
|
|
for i in 0..505 {
|
|
tx.send(Update::Progress(Event::step("Working", i, 505)))
|
|
.unwrap();
|
|
}
|
|
tx.send(Update::Finished(Ok(Outcome {
|
|
report: None,
|
|
paths: vec!["reports/timings.html".into()],
|
|
output: "reports".into(),
|
|
})))
|
|
.unwrap();
|
|
frame(&mut app, egui::RawInput::default());
|
|
assert_eq!(app.log.len(), 500);
|
|
assert_eq!(app.paths.len(), 1);
|
|
assert_eq!(app.completed_output, Some("reports".into()));
|
|
let cancellation = app.cancel.clone();
|
|
drop(app);
|
|
assert!(cancellation.load(Ordering::Relaxed));
|
|
}
|
|
}
|