use crate::ModsWindow;
use fmm_core::Result;
use slint::{
ComponentHandle, PhysicalSize,
platform::{
Platform, PlatformError, WindowAdapter, WindowEvent,
software_renderer::{MinimalSoftwareWindow, RepaintBufferType},
},
};
use std::{fs, io::BufWriter, path::Path, rc::Rc};
struct HeadlessPlatform {
window: Rc<MinimalSoftwareWindow>,
}
impl Platform for HeadlessPlatform {
fn create_window_adapter(&self) -> std::result::Result<Rc<dyn WindowAdapter>, PlatformError> {
Ok(self.window.clone())
}
}
pub fn init(width: u32, height: u32) -> Result<()> {
let window = MinimalSoftwareWindow::new(RepaintBufferType::NewBuffer);
window.dispatch_event(WindowEvent::ScaleFactorChanged { scale_factor: 1.0 });
window.set_size(PhysicalSize::new(width, height));
slint::platform::set_platform(Box::new(HeadlessPlatform { window }))
.map_err(|e| e.to_string())?;
Ok(())
}
pub fn save(
app: &ModsWindow,
out: &Path,
width: u32,
height: u32,
started: std::time::Instant,
) -> Result<()> {
// This adapter has no native window. Showing it only initializes Slint layout.
app.show().map_err(|e| e.to_string())?;
let pixels = app.window().take_snapshot().map_err(|e| e.to_string())?;
eprintln!("Cached first snapshot: {:?}", started.elapsed());
if pixels.width() != width || pixels.height() != height {
return Err("Capture dimensions do not match --size".into());
}
if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
let mut encoder = png::Encoder::new(BufWriter::new(fs::File::create(out)?), width, height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()?
.write_image_data(pixels.as_bytes())?;
app.hide().map_err(|e| e.to_string())?;
Ok(())
}