This commit is contained in:
2026-10-24 20:09:01 +02:00
parent db7f5703ca
commit 83ca065cde
4 changed files with 1156 additions and 39 deletions
Generated
+901 -12
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -5,6 +5,9 @@ edition = "2024"
[dependencies] [dependencies]
eframe = "0.37.0" eframe = "0.37.0"
egui_commonmark = "0.26.0"
image = "0.25.10"
pdfium-render = "0.9.4"
[llvm] [llvm]
+28 -26
View File
@@ -6,15 +6,10 @@ use std::collections::HashMap;
use eframe::egui::{self, Align2, Color32, FontId, Pos2, Sense, Stroke, Vec2}; use eframe::egui::{self, Align2, Color32, FontId, Pos2, Sense, Stroke, Vec2};
use std::f32::consts::PI; use std::f32::consts::PI;
use std::collections::BTreeMap; use std::collections::BTreeMap;
mod render;
use render::{view_pane, Viewers};
const SPLIT_MIN_WIDTH: f32 = 900.0; // AUTO splits when the center area is at least this wide const SPLIT_MIN_WIDTH: f32 = 900.0; // AUTO splits when the center area is at least this wide
/// the one place the rendered view is drawn; swap in PDF/markdown rendering here later
fn view_pane(ui: &mut egui::Ui, text: &str, selectable: bool) {
render_view(ui, text, selectable);
}
#[derive(Clone, Copy, PartialEq)] #[derive(Clone, Copy, PartialEq)]
enum Mode { enum Mode {
Edit, Edit,
@@ -22,20 +17,7 @@ enum Mode {
Viewer, Viewer,
} }
/// 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));
}
}
}
#[derive(Default)] #[derive(Default)]
struct Dir { struct Dir {
@@ -90,6 +72,8 @@ struct App {
mode: Mode, mode: Mode,
editing: bool, // only used in Auto mode editing: bool, // only used in Auto mode
last_open: Option<usize>, // detects when the open note changes last_open: Option<usize>, // detects when the open note changes
viewers: Viewers, // or render::Viewers if you didn't `use` it
root: PathBuf,
} }
@@ -170,7 +154,20 @@ impl App {
} }
fn editor_ui(&mut self, ui: &mut egui::Ui, i: usize) { fn editor_ui(&mut self, ui: &mut egui::Ui, i: usize) {
ui.horizontal(|ui| {
if ui.button("← Graph").clicked() {
self.open = None;
}
ui.heading(&self.vault.notes[i].title);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.selectable_value(&mut self.mode, Mode::Viewer, "VIEWER");
ui.selectable_value(&mut self.mode, Mode::Auto, "AUTO");
ui.selectable_value(&mut self.mode, Mode::Edit, "EDIT");
});
});
ui.separator();
let split = self.mode == Mode::Auto && ui.available_width() >= SPLIT_MIN_WIDTH; let split = self.mode == Mode::Auto && ui.available_width() >= SPLIT_MIN_WIDTH;
if split { if split {
@@ -189,7 +186,7 @@ impl App {
egui::ScrollArea::vertical() egui::ScrollArea::vertical()
.id_salt("view_pane") .id_salt("view_pane")
.show(&mut cols[1], |ui| { .show(&mut cols[1], |ui| {
view_pane(ui, &self.vault.notes[i].raw, true); view_pane(ui, &mut self.viewers, i, &self.vault.notes[i], &self.root, true);
}); });
}); });
return; return;
@@ -234,7 +231,7 @@ impl App {
let scope = ui.scope(|ui| { let scope = ui.scope(|ui| {
ui.set_min_height(ui.available_height().max(200.0)); ui.set_min_height(ui.available_height().max(200.0));
ui.set_min_width(ui.available_width()); ui.set_min_width(ui.available_width());
render_view(ui, &self.vault.notes[i].raw, selectable); view_pane(ui, &mut self.viewers, i, &self.vault.notes[i], &self.root, selectable);
}); });
if self.mode == Mode::Auto && scope.response.interact(Sense::click()).clicked() { if self.mode == Mode::Auto && scope.response.interact(Sense::click()).clicked() {
self.editing = true; self.editing = true;
@@ -244,8 +241,9 @@ impl App {
}); });
} }
fn new(vault: Vault) -> Self { fn new(vault: Vault, root: PathBuf) -> Self {
let root_buf = root.to_path_buf();
let n = vault.node_count(); let n = vault.node_count();
@@ -285,7 +283,10 @@ impl App {
mode: Mode::Auto, mode: Mode::Auto,
editing: false, editing: false,
last_open: None, last_open: None,
viewers: Viewers::new(),
root,
} }
} }
fn radius(&self, i: usize) -> f32 { fn radius(&self, i: usize) -> f32 {
@@ -664,12 +665,13 @@ fn main() -> io::Result<()> {
} }
let vault = scan_dir(root)?; let vault = scan_dir(root)?;
vault.links.print_links(); // optional console dump vault.links.print_links();
let root_buf = root.to_path_buf();
eframe::run_native( eframe::run_native(
"Vault", "Vault",
eframe::NativeOptions::default(), eframe::NativeOptions::default(),
Box::new(|_cc| Ok(Box::new(App::new(vault)))), Box::new(move |_cc| Ok(Box::new(App::new(vault, root_buf)))),
) )
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string())) .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))
} }
+223
View File
@@ -0,0 +1,223 @@
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, &note.raw, selectable),
NoteKind::Md => {
egui_commonmark::CommonMarkViewer::new().show(ui, &mut v.md, &note.raw);
}
NoteKind::Typ => {
v.typ.update(ui.ctx(), idx, &note.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()
}