223 lines
6.8 KiB
Rust
223 lines
6.8 KiB
Rust
use std::collections::hash_map::DefaultHasher;
|
|
use std::hash::{Hash, Hasher};
|
|
use std::io::Write;
|
|
use std::process::{Command, Stdio};
|
|
use std::sync::mpsc::{channel, Receiver, Sender};
|
|
use std::time::{Duration, Instant};
|
|
use eframe::egui::{self, Align2, Color32, FontId, Pos2, Sense, Stroke, Vec2};
|
|
use pdfium_render::prelude::*;
|
|
use std::path::Path;
|
|
use std::fs;
|
|
use std::path::PathBuf;
|
|
|
|
use crate::{Note, NoteKind}; // these live in main.rs
|
|
|
|
// ... Pages, hash_str, PageRender, compile_typst, render_view (private) ...
|
|
|
|
pub struct Viewers {
|
|
md: egui_commonmark::CommonMarkCache,
|
|
typ: PageRender,
|
|
}
|
|
|
|
impl Viewers {
|
|
pub fn new() -> Self {
|
|
Self { md: Default::default(), typ: PageRender::new() }
|
|
}
|
|
}
|
|
|
|
pub fn view_pane(
|
|
ui: &mut egui::Ui,
|
|
v: &mut Viewers,
|
|
idx: usize,
|
|
note: &Note,
|
|
root: &Path,
|
|
selectable: bool,
|
|
) {
|
|
match note.kind {
|
|
NoteKind::Txt => render_view(ui, ¬e.raw, selectable),
|
|
NoteKind::Md => {
|
|
egui_commonmark::CommonMarkViewer::new().show(ui, &mut v.md, ¬e.raw);
|
|
}
|
|
NoteKind::Typ => {
|
|
v.typ.update(ui.ctx(), idx, ¬e.raw, root);
|
|
v.typ.show(ui);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// minimal read-only rendering: "# " and "## " headings, blank lines, plain text
|
|
fn render_view(ui: &mut egui::Ui, text: &str, selectable: bool) {
|
|
for line in text.lines() {
|
|
if let Some(h) = line.strip_prefix("# ") {
|
|
ui.add(egui::Label::new(egui::RichText::new(h).heading()).selectable(selectable));
|
|
} else if let Some(h) = line.strip_prefix("## ") {
|
|
ui.add(egui::Label::new(egui::RichText::new(h).strong().size(17.0)).selectable(selectable));
|
|
} else if line.trim().is_empty() {
|
|
ui.add_space(6.0);
|
|
} else {
|
|
ui.add(egui::Label::new(line).selectable(selectable));
|
|
}
|
|
}
|
|
}
|
|
|
|
type Pages = Result<Vec<egui::ColorImage>, String>;
|
|
|
|
fn hash_str(s: &str) -> u64 {
|
|
let mut h = DefaultHasher::new();
|
|
s.hash(&mut h);
|
|
h.finish()
|
|
}
|
|
|
|
|
|
|
|
|
|
struct PageRender {
|
|
note: usize,
|
|
hash: u64, // hash of current text
|
|
requested: u64, // hash of the last compile we started
|
|
changed_at: Instant,
|
|
textures: Vec<egui::TextureHandle>,
|
|
error: Option<String>,
|
|
tx: Sender<(u64, Pages)>,
|
|
rx: Receiver<(u64, Pages)>,
|
|
}
|
|
|
|
impl PageRender {
|
|
fn new() -> Self {
|
|
let (tx, rx) = channel();
|
|
Self {
|
|
note: usize::MAX,
|
|
hash: 0,
|
|
requested: 0,
|
|
changed_at: Instant::now(),
|
|
textures: Vec::new(),
|
|
error: None,
|
|
tx,
|
|
rx,
|
|
}
|
|
}
|
|
|
|
/// call every frame; compiles in a thread once typing pauses
|
|
fn update(&mut self, ctx: &egui::Context, note: usize, text: &str, root: &Path) {
|
|
if note != self.note {
|
|
self.note = note;
|
|
self.textures.clear();
|
|
self.error = None;
|
|
self.hash = 0;
|
|
self.requested = 0;
|
|
self.changed_at = Instant::now() - Duration::from_secs(1);
|
|
}
|
|
|
|
let h = hash_str(text);
|
|
if h != self.hash {
|
|
self.hash = h;
|
|
self.changed_at = Instant::now();
|
|
}
|
|
|
|
if self.hash != self.requested {
|
|
if self.changed_at.elapsed() > Duration::from_millis(400) {
|
|
self.requested = self.hash;
|
|
let (tx, ctx2, src, root) =
|
|
(self.tx.clone(), ctx.clone(), text.to_string(), root.to_path_buf());
|
|
std::thread::spawn(move || {
|
|
let _ = tx.send((h, compile_typst(&src, &root, h)));
|
|
ctx2.request_repaint();
|
|
});
|
|
} else {
|
|
ctx.request_repaint_after(Duration::from_millis(100));
|
|
}
|
|
}
|
|
|
|
for (h, res) in self.rx.try_iter() {
|
|
if h != self.requested {
|
|
continue; // stale result
|
|
}
|
|
match res {
|
|
Ok(imgs) => {
|
|
self.textures = imgs
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(i, img)| ctx.load_texture(format!("page{i}"), img, Default::default()))
|
|
.collect();
|
|
self.error = None;
|
|
}
|
|
Err(e) => self.error = Some(e), // keep the last good pages on screen
|
|
}
|
|
}
|
|
}
|
|
|
|
fn show(&self, ui: &mut egui::Ui) {
|
|
if let Some(e) = &self.error {
|
|
ui.colored_label(Color32::LIGHT_RED, e);
|
|
ui.separator();
|
|
}
|
|
let w = ui.available_width();
|
|
for tex in &self.textures {
|
|
ui.add(egui::Image::new(tex).max_width(w));
|
|
ui.add_space(8.0);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn compile_typst(src: &str, root: &Path, id: u64) -> Pages {
|
|
let dir = std::env::temp_dir().join(format!("vault-typ-{}-{id}", std::process::id()));
|
|
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
|
|
|
let mut child = Command::new("typst")
|
|
.args(["compile", "--format", "png", "--ppi", "110", "--root"])
|
|
.arg(root)
|
|
.arg("-") // source from stdin
|
|
.arg(dir.join("p-{0p}.png"))
|
|
.stdin(Stdio::piped())
|
|
.stderr(Stdio::piped())
|
|
.spawn()
|
|
.map_err(|e| format!("cannot run `typst`: {e}"))?;
|
|
|
|
child.stdin.take().unwrap().write_all(src.as_bytes()).map_err(|e| e.to_string())?;
|
|
let out = child.wait_with_output().map_err(|e| e.to_string())?;
|
|
if !out.status.success() {
|
|
let _ = fs::remove_dir_all(&dir);
|
|
return Err(String::from_utf8_lossy(&out.stderr).into_owned());
|
|
}
|
|
|
|
let mut files: Vec<PathBuf> = fs::read_dir(&dir)
|
|
.map_err(|e| e.to_string())?
|
|
.flatten()
|
|
.map(|e| e.path())
|
|
.collect();
|
|
files.sort(); // zero-padded names sort correctly
|
|
|
|
let pages = files
|
|
.iter()
|
|
.map(|p| {
|
|
let img = image::open(p).map_err(|e| e.to_string())?.to_rgba8();
|
|
let size = [img.width() as usize, img.height() as usize];
|
|
Ok(egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()))
|
|
})
|
|
.collect();
|
|
let _ = fs::remove_dir_all(&dir);
|
|
pages
|
|
}
|
|
|
|
use pdfium_render::prelude::*;
|
|
|
|
fn render_pdf(path: &Path, width: u32) -> Pages {
|
|
let lib = Pdfium::bind_to_system_library().map_err(|e| e.to_string())?;
|
|
let pdfium = Pdfium::new(lib);
|
|
let doc = pdfium.load_pdf_from_file(path, None).map_err(|e| e.to_string())?;
|
|
let cfg = PdfRenderConfig::new().set_target_width(width as i32);
|
|
|
|
doc.pages()
|
|
.iter()
|
|
.map(|page| {
|
|
let img = page
|
|
.render_with_config(&cfg)
|
|
.map_err(|e| e.to_string())?
|
|
.as_image()
|
|
.map_err(|e| e.to_string())?
|
|
.to_rgba8();
|
|
let size = [img.width() as usize, img.height() as usize];
|
|
Ok(egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()))
|
|
})
|
|
.collect()
|
|
} |