use bezel::gpui::{App, hash};
use editor::Source;
use std::{
borrow::Cow,
path::{Path, PathBuf},
sync::Mutex,
};
const MARK: &str = "media-";
static TARGET: Mutex<Option<PathBuf>> = Mutex::new(None);
pub fn init(cx: &mut App) {
editor::set_image_store(cx, keep);
}
pub fn aim(content: Option<&Path>) {
if let Ok(mut target) = TARGET.lock() {
*target = content.and_then(Path::parent).map(Path::to_path_buf);
}
}
fn keep(source: Source) -> Option<String> {
let dir = TARGET.lock().ok()?.clone()?;
let (bytes, extension) = match source {
Source::Bytes(image) => (
Cow::Borrowed(image.bytes.as_slice()),
image.format.extension().to_owned(),
),
Source::File(path) => (
Cow::Owned(std::fs::read(path).ok()?),
path.extension()?.to_str()?.to_ascii_lowercase(),
),
};
let file = dir.join(format!("{MARK}{:x}.{extension}", hash(&bytes)));
if !file.is_file() && std::fs::write(&file, &bytes).is_err() {
return None;
}
Some(file.to_string_lossy().into_owned())
}