Files
Marcos Paulo 2e23fd09a1 feat: paste images and files from the clipboard, more image formats, scripts without boxes, code font without ligatures
arboard (image-data) approved for clipboard paste: image bytes become a PNG attachment, copied files inside the vault are linked without copying, outside files are copied; works in Visual and Source. image crate gains jpeg, gif, webp, bmp decoders. Lazy system-font fallbacks for 28 scripts (Bengali, Indic, Thai, CJK, Khmer...) and the math font as last resort. JetBrains Mono copy with calt emptied (SIL OFL, renamed). Big embedded images are shrunk to the texture limit off the UI thread (fixes a crash).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 23:59:14 -03:00

186 lines
7.0 KiB
Rust

//! Paste from the clipboard into a note: the image lands in the note and in the vault, a file of the
//! vault is linked and never copied.
use std::path::{Path, PathBuf};
use egui::{Context, Event, Key, Modifiers, Pos2, RawInput};
use notescraft_engine::Session;
use notescraft_ui_egui::app::NotesApp;
use notescraft_ui_egui::attachment_drop::{Clipboard, ClipboardImage, ClipboardSource};
use notescraft_ui_egui::center::ViewMode;
/// A clipboard the test hands to the app.
struct FakeClipboard {
/// What the clipboard holds.
content: Clipboard,
}
impl ClipboardSource for FakeClipboard {
fn read(&self) -> Result<Clipboard, String> {
Ok(self.content.clone())
}
}
/// A clipboard image of `width` x `height` pixels.
fn image(width: usize, height: usize) -> ClipboardImage {
let mut bytes = Vec::with_capacity(width * height * 4);
for _ in 0..width * height {
bytes.extend_from_slice(&[10, 20, 30, 255]);
}
ClipboardImage { width, height, bytes }
}
/// The app over a fresh vault with one note, and the vault folder.
struct Driver {
/// The app under test.
app: NotesApp,
/// The egui context the app draws in.
ctx: Context,
/// The clock of the frames.
time: f64,
/// The vault folder.
root: PathBuf,
}
impl Driver {
/// One frame with the events it gets.
fn frame(&mut self, events: Vec<Event>) {
self.time += 0.05;
let input = RawInput {
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1440.0, 900.0))),
time: Some(self.time),
events,
..Default::default()
};
let app = &mut self.app;
let mut output = self.ctx.run_ui(input, |ui| app.ui(ui.ctx()));
output.textures_delta.clear();
}
/// The frames the app needs before it draws: the first one installs the fonts.
fn settle(&mut self) {
self.frame(Vec::new());
self.frame(Vec::new());
}
/// One frame with the paste shortcut, then the frames that carry the answer
/// of the clipboard read.
fn paste(&mut self) {
let event = Event::Key { key: Key::V, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND };
self.frame(vec![event]);
for _ in 0..20 {
std::thread::sleep(std::time::Duration::from_millis(5));
self.frame(Vec::new());
if self.text() != "Hello" {
break;
}
}
}
/// The text of a note.
fn text(&self) -> String {
self.app.session.buffer("note.md").map(notescraft_engine::Buffer::text).unwrap_or_default().to_owned()
}
/// The files of the attachment folder.
fn attachments(&self) -> Vec<String> {
files(&self.root.join("Attachments"))
}
}
/// The app over a fresh vault with one note.
fn driver(name: &str) -> Option<Driver> {
let root = std::env::temp_dir().join(format!("notescraft-paste-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).ok()?;
std::fs::write(root.join("note.md"), "Hello").ok()?;
let mut session = Session::open(&root).ok()?;
session.use_settings_dir(root.join("config"));
let theme = notescraft_themes::builtin("catppuccin-mocha")?;
let mut app = NotesApp::new(session, theme);
app.state.animations = false;
app.open_note("note.md");
Some(Driver { app, ctx: Context::default(), time: 1.0, root })
}
/// The files of a folder, sorted.
fn files(folder: &Path) -> Vec<String> {
let mut names: Vec<String> =
std::fs::read_dir(folder).map(|entries| entries.flatten().map(|entry| entry.file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default();
names.sort();
names
}
#[test]
fn a_pasted_image_lands_in_the_note_and_in_the_vault() {
let Some(mut driver) = driver("image") else { return };
driver.app.attachment_input.set_clipboard(std::sync::Arc::new(FakeClipboard { content: Clipboard::Image(image(2, 2)) }));
driver.settle();
driver.paste();
let note = driver.text();
assert!(note.contains("![[Pasted image "), "{note}");
assert!(note.contains(".png]]"), "{note}");
let saved = driver.attachments();
assert_eq!(saved.len(), 1, "{saved:?}");
let name = saved.first().cloned().unwrap_or_default();
assert!(name.starts_with("Pasted image "), "{name}");
assert!(Path::new(&name).extension().is_some_and(|extension| extension.eq_ignore_ascii_case("png")), "{name}");
let bytes = std::fs::read(driver.root.join("Attachments").join(name)).unwrap_or_default();
assert_eq!(bytes.get(..4), Some(&[0x89, b'P', b'N', b'G'][..]));
}
#[test]
fn a_pasted_image_lands_in_the_source_editor_too() {
let Some(mut driver) = driver("source") else { return };
if let Some(edit) = driver.app.editing.tabs.get_mut("note.md") {
edit.view = ViewMode::Markdown;
}
driver.app.attachment_input.set_clipboard(std::sync::Arc::new(FakeClipboard { content: Clipboard::Image(image(2, 2)) }));
driver.settle();
driver.paste();
let note = driver.text();
assert!(note.contains("![[Pasted image "), "{note}");
assert_eq!(driver.attachments().len(), 1);
}
#[test]
fn a_file_of_the_vault_is_linked_and_never_copied() {
let Some(mut driver) = driver("inside") else { return };
let folder = driver.root.join("Attachments");
std::fs::create_dir_all(&folder).ok();
std::fs::write(folder.join("pic.png"), b"picture").ok();
let inside = std::fs::canonicalize(&driver.root).unwrap_or_else(|_| driver.root.clone()).join("Attachments/pic.png");
driver.app.attachment_input.set_clipboard(std::sync::Arc::new(FakeClipboard { content: Clipboard::Files(vec![inside]) }));
driver.settle();
driver.paste();
let note = driver.text();
assert!(note.contains("![[Attachments/pic.png]]"), "{note}");
assert_eq!(files(&folder), vec!["pic.png".to_owned()]);
}
#[test]
fn a_file_outside_the_vault_is_copied_into_the_attachment_folder() {
let Some(mut driver) = driver("outside") else { return };
let folder = std::env::temp_dir().join(format!("notescraft-paste-outside-files-{}", std::process::id()));
std::fs::create_dir_all(&folder).ok();
let outside = folder.join("paper.png");
std::fs::write(&outside, b"picture").ok();
driver.app.attachment_input.set_clipboard(std::sync::Arc::new(FakeClipboard { content: Clipboard::Files(vec![outside.clone()]) }));
driver.settle();
driver.paste();
let note = driver.text();
assert!(note.contains("![[paper.png]]"), "{note}");
assert!(driver.root.join("Attachments/paper.png").exists(), "the file was not copied into the vault");
let _ = std::fs::remove_dir_all(&folder);
}
#[test]
fn a_text_only_clipboard_leaves_the_note_alone() {
let Some(mut driver) = driver("text") else { return };
driver.app.attachment_input.set_clipboard(std::sync::Arc::new(FakeClipboard { content: Clipboard::Empty }));
driver.settle();
driver.paste();
assert_eq!(driver.text(), "Hello");
assert!(!driver.root.join("Attachments").exists());
}