Compare commits
18 Commits
e0fd726f02
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| c63babb599 | |||
| fac896161e | |||
| 945bb4d9fe | |||
| 47b7feeab8 | |||
| b1eb5f91be | |||
| 3669f54936 | |||
| 2fb9908329 | |||
| 0acab0413c | |||
| 8f16741705 | |||
| a663de3ca0 | |||
| 61575fbf65 | |||
|
579aace306
|
|||
| fe0b9d049e | |||
| c59febd924 | |||
|
276508713f
|
|||
| 3a2f058456 | |||
|
38d26f0028
|
|||
|
462c27e111
|
1794
Cargo.lock
generated
1794
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
20
Cargo.toml
20
Cargo.toml
@ -12,22 +12,25 @@ targets = ["x86_64-unknown-linux-gnu", "wasm32-unknown-unknown"]
|
||||
pinenote = []
|
||||
|
||||
[dependencies]
|
||||
egui = "0.31"
|
||||
egui_extras = { version = "0.31", features = ["svg"] }
|
||||
eframe = { version = "0.31", default-features = false, features = [
|
||||
egui = "0.32"
|
||||
egui_extras = { version = "0.32", features = ["svg"] }
|
||||
egui_glow = "0.32"
|
||||
eframe = { version = "0.32", default-features = false, features = [
|
||||
"glow", # alt: "wgpu".
|
||||
"persistence",
|
||||
"wayland",
|
||||
] }
|
||||
log = "0.4.27"
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
egui_glow = "0.31.1"
|
||||
rfd = { version = "0.15.3", default-features = false, features = ["gtk3"] }
|
||||
rand = "0.9.1"
|
||||
eyre = "0.6.12"
|
||||
half = "2.6.0"
|
||||
zerocopy = { version = "0.8.25", features = ["derive", "std"] }
|
||||
base64 = "0.22.1"
|
||||
chrono = { version = "0.4.41", features = ["serde"] }
|
||||
notify = "8.1.0"
|
||||
arboard = "3.6.0"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
env_logger = "0.11.8"
|
||||
@ -39,13 +42,14 @@ wasm-bindgen-futures = "0.4.50"
|
||||
web-sys = "0.3.77"
|
||||
|
||||
[patch.crates-io]
|
||||
egui = { git = "https://github.com/emilk/egui", rev = "f2ce6424f3a32f47308fb9871d540c01377b2cd9" }
|
||||
eframe = { git = "https://github.com/emilk/egui", rev = "f2ce6424f3a32f47308fb9871d540c01377b2cd9" }
|
||||
# egui = { path = "../egui/crates/egui" }
|
||||
# eframe = { path = "../egui/crates/eframe" }
|
||||
|
||||
[dev-dependencies]
|
||||
insta = { version = "1.43.1", features = ["yaml"] }
|
||||
# egui = { path = "../egui/crates/egui" }
|
||||
# eframe = { path = "../egui/crates/eframe" }
|
||||
|
||||
[lints.clippy]
|
||||
unnecessary_lazy_evaluations = "allow"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 2 # fast and small wasm
|
||||
|
||||
147
src/app.rs
147
src/app.rs
@ -1,16 +1,24 @@
|
||||
use std::{
|
||||
fs,
|
||||
io::Read,
|
||||
path::PathBuf,
|
||||
sync::{Arc, mpsc},
|
||||
thread::JoinHandle,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crate::{file_editor::FileEditor, folder::Folder, preferences::Preferences, util::GuiSender};
|
||||
use egui::{
|
||||
Align, Button, Context, FontData, FontDefinitions, Image, Key, Modifiers, PointerButton,
|
||||
RichText, ScrollArea, Widget, include_image,
|
||||
use crate::{
|
||||
file_editor::{FileEditor, SaveStatus},
|
||||
folder::Folder,
|
||||
preferences::Preferences,
|
||||
text_styles::{H1, H1_MONO, H2, H2_MONO, H3, H3_MONO, H4, H4_MONO, H5, H5_MONO, H6, H6_MONO},
|
||||
util::{GuiSender, file_mtime, log_error},
|
||||
};
|
||||
use egui::{
|
||||
Align, Button, Context, FontData, FontDefinitions, FontFamily, FontId, Frame, Image, Key,
|
||||
Modifiers, PointerButton, RichText, ScrollArea, Theme, Widget, include_image,
|
||||
};
|
||||
use eyre::eyre;
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize)]
|
||||
#[serde(default)]
|
||||
@ -40,7 +48,7 @@ pub struct Jobs {
|
||||
}
|
||||
|
||||
impl Jobs {
|
||||
fn start(&mut self, ctx: &Context, job: impl FnOnce() -> Option<Action> + Send + 'static) {
|
||||
pub fn start(&mut self, ctx: &Context, job: impl FnOnce() -> Option<Action> + Send + 'static) {
|
||||
let ctx = ctx.clone();
|
||||
let actions_tx = self.actions_tx.clone();
|
||||
self.handles.push(std::thread::spawn(move || {
|
||||
@ -73,9 +81,21 @@ impl Tab {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
pub fn notice_symbol(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Tab::File(file_editor) => file_editor.is_dirty,
|
||||
Tab::File(file_editor) => match file_editor.save_status() {
|
||||
SaveStatus::Synced => None,
|
||||
SaveStatus::NoFile => Some("?"),
|
||||
SaveStatus::FileOutdated => Some("*"),
|
||||
SaveStatus::BufferOutdated => Some("!"),
|
||||
SaveStatus::Desynced => Some("!!"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&mut self, ctx: &Context, jobs: &mut Jobs) {
|
||||
match self {
|
||||
Tab::File(file_editor) => file_editor.save(ctx, jobs),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -171,17 +191,39 @@ impl App {
|
||||
.map(|(name, data)| (name.to_string(), Arc::new(FontData::from_static(data))))
|
||||
.collect();
|
||||
|
||||
fonts.families.insert(
|
||||
egui::FontFamily::Proportional,
|
||||
vec!["IosevkaAile-Regular".into()],
|
||||
);
|
||||
fonts
|
||||
.families
|
||||
.insert(FontFamily::Proportional, vec!["IosevkaAile-Regular".into()]);
|
||||
|
||||
fonts
|
||||
.families
|
||||
.insert(egui::FontFamily::Monospace, vec!["Iosevka-Thin".into()]);
|
||||
.insert(FontFamily::Monospace, vec!["Iosevka-Thin".into()]);
|
||||
|
||||
cc.egui_ctx.set_fonts(fonts);
|
||||
|
||||
// markdown font styles
|
||||
for theme in [Theme::Dark, Theme::Light] {
|
||||
cc.egui_ctx.style_mut_of(theme, |style| {
|
||||
for (name, size, family) in [
|
||||
(H1, 28.0, FontFamily::Proportional),
|
||||
(H2, 26.0, FontFamily::Proportional),
|
||||
(H3, 24.0, FontFamily::Proportional),
|
||||
(H4, 22.0, FontFamily::Proportional),
|
||||
(H5, 20.0, FontFamily::Proportional),
|
||||
(H6, 18.0, FontFamily::Proportional),
|
||||
(H1_MONO, 28.0, FontFamily::Monospace),
|
||||
(H2_MONO, 26.0, FontFamily::Monospace),
|
||||
(H3_MONO, 24.0, FontFamily::Monospace),
|
||||
(H4_MONO, 22.0, FontFamily::Monospace),
|
||||
(H5_MONO, 20.0, FontFamily::Monospace),
|
||||
(H6_MONO, 18.0, FontFamily::Monospace),
|
||||
] {
|
||||
let name = egui::TextStyle::Name(name.into());
|
||||
style.text_styles.insert(name, FontId { size, family });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// enable features on egui_extras to add more image types
|
||||
egui_extras::install_image_loaders(&cc.egui_ctx);
|
||||
|
||||
@ -253,7 +295,7 @@ impl eframe::App for App {
|
||||
});
|
||||
|
||||
egui::TopBottomPanel::top("top_panel").show(ctx, |ui| {
|
||||
egui::containers::menu::Bar::new().ui(ui, |ui| {
|
||||
egui::MenuBar::new().ui(ui, |ui| {
|
||||
// NOTE: no File->Quit on web pages!
|
||||
ui.menu_button("Menu ⚙", |ui| {
|
||||
ui.label(RichText::new("Action").weak());
|
||||
@ -268,11 +310,18 @@ impl eframe::App for App {
|
||||
self.jobs.start(ui.ctx(), move || {
|
||||
let file_path = rfd::FileDialog::new().pick_file()?;
|
||||
|
||||
let text = fs::read_to_string(&file_path)
|
||||
let mut file = fs::File::open(&file_path)
|
||||
.inspect_err(|e| log::error!("Failed to open {file_path:?}: {e}"))
|
||||
.ok()?;
|
||||
|
||||
let mtime = log_error(eyre!("file_path:?"), || file_mtime(&file))?;
|
||||
|
||||
let mut text = String::new();
|
||||
file.read_to_string(&mut text)
|
||||
.inspect_err(|e| log::error!("Failed to read {file_path:?}: {e}"))
|
||||
.ok()?;
|
||||
|
||||
let editor = FileEditor::from_file(file_path, &text);
|
||||
let editor = FileEditor::from_file(file_path, &text, mtime);
|
||||
Some(Action::OpenFile(editor))
|
||||
});
|
||||
}
|
||||
@ -364,8 +413,8 @@ impl eframe::App for App {
|
||||
let selected = self.open_tab_index == Some(i);
|
||||
let mut button = Button::new(tab.title()).selected(selected);
|
||||
|
||||
if tab.is_dirty() {
|
||||
button = button.right_text(RichText::new("*").strong())
|
||||
if let Some(symbol) = tab.notice_symbol() {
|
||||
button = button.right_text(RichText::new(symbol).strong())
|
||||
}
|
||||
|
||||
let response = ui.add(button);
|
||||
@ -396,13 +445,22 @@ impl eframe::App for App {
|
||||
if let Some(file_path) = response.open_file {
|
||||
let file_path = file_path.to_owned();
|
||||
self.jobs.start(ui.ctx(), move || {
|
||||
let text = fs::read_to_string(&file_path)
|
||||
let mut file = fs::File::open(&file_path)
|
||||
.inspect_err(|e| {
|
||||
log::error!("Failed to open {file_path:?}: {e}")
|
||||
})
|
||||
.ok()?;
|
||||
|
||||
let mtime = log_error(eyre!("file_path:?"), || file_mtime(&file))?;
|
||||
|
||||
let mut text = String::new();
|
||||
file.read_to_string(&mut text)
|
||||
.inspect_err(|e| {
|
||||
log::error!("Failed to read {file_path:?}: {e}")
|
||||
})
|
||||
.ok()?;
|
||||
|
||||
let editor = FileEditor::from_file(file_path, &text);
|
||||
let editor = FileEditor::from_file(file_path, &text, mtime);
|
||||
Some(Action::OpenFile(editor))
|
||||
});
|
||||
}
|
||||
@ -413,19 +471,24 @@ impl eframe::App for App {
|
||||
});
|
||||
});
|
||||
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
if let Some(Tab::File(file_editor)) = self
|
||||
.open_tab_index
|
||||
.and_then(|i| self.tabs.get_mut(i))
|
||||
.map(|(_tab_id, tab)| tab)
|
||||
{
|
||||
file_editor.show(ui, &self.preferences);
|
||||
}
|
||||
egui::CentralPanel::default()
|
||||
.frame(Frame {
|
||||
fill: ctx.style().visuals.window_fill(),
|
||||
..Frame::central_panel(&ctx.style())
|
||||
})
|
||||
.show(ctx, |ui| {
|
||||
if let Some(Tab::File(file_editor)) = self
|
||||
.open_tab_index
|
||||
.and_then(|i| self.tabs.get_mut(i))
|
||||
.map(|(_tab_id, tab)| tab)
|
||||
{
|
||||
file_editor.show(ui, &self.preferences);
|
||||
}
|
||||
|
||||
ui.with_layout(egui::Layout::bottom_up(Align::LEFT), |ui| {
|
||||
egui::warn_if_debug_build(ui);
|
||||
ui.with_layout(egui::Layout::bottom_up(Align::LEFT), |ui| {
|
||||
egui::warn_if_debug_build(ui);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -448,29 +511,13 @@ impl App {
|
||||
}
|
||||
|
||||
fn save_active_tab(&mut self, ctx: &Context) {
|
||||
let open_file = self
|
||||
let open_tab = self
|
||||
.open_tab_index
|
||||
.and_then(|i| self.tabs.get_mut(i))
|
||||
.map(|(id, tab)| match tab {
|
||||
Tab::File(file_editor) => (*id, file_editor),
|
||||
})
|
||||
.and_then(|(_, file_editor)| {
|
||||
file_editor
|
||||
.path()
|
||||
.map(ToOwned::to_owned)
|
||||
.zip(Some(file_editor))
|
||||
});
|
||||
.map(|(_id, tab)| tab);
|
||||
|
||||
if let Some((file_path, file_editor)) = open_file {
|
||||
file_editor.is_dirty = false;
|
||||
let text = file_editor.to_string();
|
||||
let file_path = file_path.to_owned();
|
||||
self.jobs.start(ctx, move || {
|
||||
if let Err(e) = fs::write(file_path, text.as_bytes()) {
|
||||
log::error!("{e}");
|
||||
};
|
||||
None
|
||||
});
|
||||
if let Some(open_tab) = open_tab {
|
||||
open_tab.save(ctx, &mut self.jobs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,245 +0,0 @@
|
||||
use egui::text::{CCursorRange, LayoutJob};
|
||||
|
||||
use crate::easy_mark::easy_mark_parser;
|
||||
|
||||
/// Highlight easymark, memoizing previous output to save CPU.
|
||||
///
|
||||
/// In practice, the highlighter is fast enough not to need any caching.
|
||||
#[derive(Default)]
|
||||
pub struct MemoizedHighlighter {
|
||||
style: egui::Style,
|
||||
code: String,
|
||||
output: LayoutJob,
|
||||
}
|
||||
|
||||
impl MemoizedHighlighter {
|
||||
pub fn highlight(
|
||||
&mut self,
|
||||
egui_style: &egui::Style,
|
||||
code: &str,
|
||||
cursor: Option<CCursorRange>,
|
||||
) -> LayoutJob {
|
||||
if (&self.style, self.code.as_str()) != (egui_style, code) {
|
||||
self.style = egui_style.clone();
|
||||
code.clone_into(&mut self.code);
|
||||
self.output = highlight_easymark(egui_style, code, cursor);
|
||||
}
|
||||
self.output.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn highlight_easymark(
|
||||
egui_style: &egui::Style,
|
||||
mut text: &str,
|
||||
|
||||
// TODO: hide special characters where cursor isn't
|
||||
_cursor: Option<CCursorRange>,
|
||||
) -> LayoutJob {
|
||||
let mut job = LayoutJob::default();
|
||||
let mut style = easy_mark_parser::Style::default();
|
||||
let mut start_of_line = true;
|
||||
|
||||
const CODE_INDENT: f32 = 10.0;
|
||||
|
||||
while !text.is_empty() {
|
||||
if start_of_line && text.starts_with("```") {
|
||||
let astyle = format_from_style(
|
||||
egui_style,
|
||||
&easy_mark_parser::Style {
|
||||
code: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
// Render the initial backticks as spaces
|
||||
text = &text[3..];
|
||||
job.append(" ", CODE_INDENT, astyle.clone());
|
||||
|
||||
match text.find("\n```") {
|
||||
Some(n) => {
|
||||
for line in text[..n + 1].lines() {
|
||||
job.append(line, CODE_INDENT, astyle.clone());
|
||||
job.append("\n", 0.0, astyle.clone());
|
||||
}
|
||||
// Render the final backticks as spaces
|
||||
job.append(" ", CODE_INDENT, astyle);
|
||||
text = &text[n + 4..];
|
||||
}
|
||||
None => {
|
||||
job.append(text, 0.0, astyle.clone());
|
||||
text = "";
|
||||
}
|
||||
};
|
||||
style = Default::default();
|
||||
continue;
|
||||
}
|
||||
|
||||
if text.starts_with('`') {
|
||||
style.code = true;
|
||||
let end = text[1..]
|
||||
.find(&['`', '\n'][..])
|
||||
.map_or_else(|| text.len(), |i| i + 2);
|
||||
job.append(&text[..end], 0.0, format_from_style(egui_style, &style));
|
||||
text = &text[end..];
|
||||
style.code = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
let skip;
|
||||
|
||||
// zero-width space
|
||||
let _zws = "\u{200b}";
|
||||
|
||||
let mut apply_basic_style =
|
||||
|text: &mut &str,
|
||||
style: &mut easy_mark_parser::Style,
|
||||
access: fn(&mut easy_mark_parser::Style) -> &mut bool| {
|
||||
let skip = if *access(style) {
|
||||
// Include the character that is ending this style:
|
||||
job.append(&text[..1], 0.0, format_from_style(egui_style, style));
|
||||
*text = &text[1..];
|
||||
0
|
||||
} else {
|
||||
1
|
||||
};
|
||||
*access(style) ^= true;
|
||||
skip
|
||||
};
|
||||
|
||||
if text.starts_with('*') {
|
||||
skip = apply_basic_style(&mut text, &mut style, |style| &mut style.strong);
|
||||
} else if text.starts_with('/') {
|
||||
skip = apply_basic_style(&mut text, &mut style, |style| &mut style.italics);
|
||||
} else if text.starts_with('_') {
|
||||
skip = apply_basic_style(&mut text, &mut style, |style| &mut style.underline);
|
||||
} else if text.starts_with('$') {
|
||||
skip = apply_basic_style(&mut text, &mut style, |style| &mut style.small);
|
||||
} else if text.starts_with('~') {
|
||||
skip = apply_basic_style(&mut text, &mut style, |style| &mut style.strikethrough);
|
||||
} else if text.starts_with('^') {
|
||||
skip = apply_basic_style(&mut text, &mut style, |style| &mut style.raised);
|
||||
} else if text.starts_with('\\') && text.len() >= 2 {
|
||||
skip = 2;
|
||||
} else if start_of_line && text.starts_with(' ') {
|
||||
// we don't preview indentation, because it is confusing
|
||||
skip = 1;
|
||||
} else if start_of_line && text.starts_with("###### ") {
|
||||
style.heading = true;
|
||||
skip = 7;
|
||||
} else if start_of_line && text.starts_with("##### ") {
|
||||
style.heading = true;
|
||||
skip = 6;
|
||||
} else if start_of_line && text.starts_with("#### ") {
|
||||
style.heading = true;
|
||||
skip = 5;
|
||||
} else if start_of_line && text.starts_with("### ") {
|
||||
style.heading = true;
|
||||
skip = 4;
|
||||
} else if start_of_line && text.starts_with("## ") {
|
||||
style.heading = true;
|
||||
skip = 3;
|
||||
} else if start_of_line && text.starts_with("# ") {
|
||||
style.heading = true;
|
||||
skip = 2;
|
||||
} else if start_of_line && text.starts_with("> ") {
|
||||
style.quoted = true;
|
||||
skip = 2;
|
||||
// we don't preview indentation, because it is confusing
|
||||
} else if start_of_line && text.trim_start().starts_with("- ") {
|
||||
job.append("• ", 0.0, format_from_style(egui_style, &style));
|
||||
text = &text[2..];
|
||||
skip = 0;
|
||||
// we don't preview indentation, because it is confusing
|
||||
} else {
|
||||
skip = 0;
|
||||
}
|
||||
// Note: we don't preview underline, strikethrough and italics because it confuses things.
|
||||
|
||||
// Swallow everything up to the next special character:
|
||||
let line_end = text[skip..]
|
||||
.find('\n')
|
||||
.map_or_else(|| text.len(), |i| (skip + i + 1));
|
||||
let end = text[skip..]
|
||||
.find(&['*', '`', '~', '_', '/', '$', '^', '\\', '<', '['][..])
|
||||
.map_or_else(|| text.len(), |i| (skip + i).max(1));
|
||||
|
||||
if line_end <= end {
|
||||
job.append(
|
||||
&text[..line_end],
|
||||
0.0,
|
||||
format_from_style(egui_style, &style),
|
||||
);
|
||||
text = &text[line_end..];
|
||||
start_of_line = true;
|
||||
style = Default::default();
|
||||
} else {
|
||||
job.append(&text[..end], 0.0, format_from_style(egui_style, &style));
|
||||
text = &text[end..];
|
||||
start_of_line = false;
|
||||
}
|
||||
}
|
||||
|
||||
job
|
||||
}
|
||||
|
||||
fn format_from_style(
|
||||
egui_style: &egui::Style,
|
||||
emark_style: &easy_mark_parser::Style,
|
||||
) -> egui::text::TextFormat {
|
||||
use egui::{Align, Color32, Stroke, TextStyle};
|
||||
|
||||
let color = if emark_style.code {
|
||||
egui_style.visuals.strong_text_color() * Color32::from_rgb(0x44, 0xff, 0x44)
|
||||
} else if emark_style.strong || emark_style.heading {
|
||||
egui_style.visuals.strong_text_color()
|
||||
} else if emark_style.quoted {
|
||||
egui_style.visuals.weak_text_color()
|
||||
} else {
|
||||
egui_style.visuals.text_color()
|
||||
};
|
||||
|
||||
let text_style = if emark_style.heading {
|
||||
TextStyle::Heading
|
||||
} else if emark_style.code {
|
||||
TextStyle::Monospace
|
||||
} else if emark_style.small | emark_style.raised {
|
||||
TextStyle::Small
|
||||
} else {
|
||||
TextStyle::Body
|
||||
};
|
||||
|
||||
let background = if emark_style.code {
|
||||
egui_style.visuals.code_bg_color
|
||||
} else {
|
||||
Color32::TRANSPARENT
|
||||
};
|
||||
|
||||
let underline = if emark_style.underline {
|
||||
Stroke::new(1.0, color)
|
||||
} else {
|
||||
Stroke::NONE
|
||||
};
|
||||
|
||||
let strikethrough = if emark_style.strikethrough {
|
||||
Stroke::new(1.0, color)
|
||||
} else {
|
||||
Stroke::NONE
|
||||
};
|
||||
|
||||
let valign = if emark_style.raised {
|
||||
Align::TOP
|
||||
} else {
|
||||
Align::BOTTOM
|
||||
};
|
||||
|
||||
egui::text::TextFormat {
|
||||
font_id: text_style.resolve(egui_style),
|
||||
color,
|
||||
background,
|
||||
italics: emark_style.italics,
|
||||
underline,
|
||||
strikethrough,
|
||||
valign,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@ -1,57 +1,116 @@
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
fmt::{self, Display},
|
||||
fs::{self, File},
|
||||
io::Write,
|
||||
ops::{Div as _, Sub as _},
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
sync::mpsc,
|
||||
};
|
||||
|
||||
use chrono::{DateTime, Local};
|
||||
use egui::{
|
||||
Align, Button, DragAndDrop, Frame, Layout, ScrollArea, Ui, UiBuilder, Vec2, Widget as _, vec2,
|
||||
Align, Button, Context, DragAndDrop, Frame, Layout, ScrollArea, Ui, UiBuilder, Vec2, vec2,
|
||||
};
|
||||
use eyre::eyre;
|
||||
use notify::{EventKind, Watcher};
|
||||
|
||||
use crate::{
|
||||
app::Jobs,
|
||||
custom_code_block::{MdItem, iter_lines_and_code_blocks},
|
||||
handwriting::{self, Handwriting, HandwritingStyle},
|
||||
preferences::Preferences,
|
||||
text_editor::MdTextEdit,
|
||||
util::{file_mtime, log_error},
|
||||
};
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize)]
|
||||
pub struct FileEditor {
|
||||
title: String,
|
||||
pub path: Option<PathBuf>,
|
||||
|
||||
path: Option<PathBuf>,
|
||||
pub buffer: Vec<BufferItem>,
|
||||
|
||||
/// Whether the file has been edited since it was laste saved to disk.
|
||||
pub is_dirty: bool,
|
||||
pub file_mtime: Option<DateTime<Local>>,
|
||||
pub buffer_mtime: DateTime<Local>,
|
||||
|
||||
// TODO: instantiate these on load
|
||||
#[serde(skip)]
|
||||
inner: Option<Inner>,
|
||||
|
||||
/// The distance to scroll when paging up or down.
|
||||
///
|
||||
/// This is calculated when the view is rendered.
|
||||
#[serde(skip)]
|
||||
scroll_delta: f32,
|
||||
|
||||
/// Whether the file has been edited since it was last saved to disk.
|
||||
is_dirty: bool,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
file_events: mpsc::Receiver<FileEvent>,
|
||||
file_events_tx: mpsc::Sender<FileEvent>,
|
||||
_file_watcher: notify::RecommendedWatcher,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SaveStatus {
|
||||
/// The contents of the buffer is the same as on disk.
|
||||
Synced,
|
||||
|
||||
/// The contents exits only in memory and has never been saved to disk.
|
||||
NoFile,
|
||||
|
||||
/// The buffer has been edited but not saved to disk.
|
||||
FileOutdated,
|
||||
|
||||
/// The contents on disk has changes that are newer than the buffer.
|
||||
BufferOutdated,
|
||||
|
||||
/// The contents on disk and in the buffer has diverged.
|
||||
Desynced,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum FileEvent {
|
||||
NewFileMTime(DateTime<Local>),
|
||||
NewBufferMTime(DateTime<Local>),
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize)]
|
||||
pub enum BufferItem {
|
||||
Text(MdTextEdit),
|
||||
Text(Box<MdTextEdit>),
|
||||
Handwriting(Box<Handwriting>),
|
||||
}
|
||||
|
||||
impl FileEditor {
|
||||
pub fn new(title: impl Into<String>) -> Self {
|
||||
let buffer = vec![BufferItem::Text(MdTextEdit::new())];
|
||||
let buffer = vec![BufferItem::Text(Box::new(MdTextEdit::new()))];
|
||||
Self {
|
||||
title: title.into(),
|
||||
path: None,
|
||||
buffer,
|
||||
file_mtime: None,
|
||||
buffer_mtime: Local::now(),
|
||||
scroll_delta: 0.0,
|
||||
is_dirty: false,
|
||||
inner: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_file(file_path: PathBuf, contents: &str) -> Self {
|
||||
pub fn from_file(file_path: PathBuf, contents: &str, mtime: DateTime<Local>) -> Self {
|
||||
let file_title = file_path
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| String::from("untitled.md"));
|
||||
|
||||
Self {
|
||||
title: file_title,
|
||||
path: Some(file_path),
|
||||
file_mtime: Some(mtime),
|
||||
buffer_mtime: mtime,
|
||||
..FileEditor::from(contents)
|
||||
}
|
||||
}
|
||||
@ -64,15 +123,66 @@ impl FileEditor {
|
||||
self.path.as_deref()
|
||||
}
|
||||
|
||||
pub fn save_status(&self) -> SaveStatus {
|
||||
let Some(file_mtime) = self.file_mtime else {
|
||||
return SaveStatus::NoFile;
|
||||
};
|
||||
|
||||
let buffer_is_newer = self.buffer_mtime > file_mtime;
|
||||
let file_is_newer = self.buffer_mtime < file_mtime;
|
||||
|
||||
if buffer_is_newer || (file_is_newer && self.is_dirty) {
|
||||
SaveStatus::Desynced
|
||||
} else if file_is_newer {
|
||||
SaveStatus::BufferOutdated
|
||||
} else if self.is_dirty {
|
||||
SaveStatus::FileOutdated
|
||||
} else {
|
||||
SaveStatus::Synced
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(&mut self, ui: &mut Ui, preferences: &Preferences) {
|
||||
if let Some(path) = &self.path
|
||||
&& self.inner.is_none()
|
||||
{
|
||||
self.inner = Some(spawn_file_watcher(path));
|
||||
}
|
||||
|
||||
if let Some(inner) = &mut self.inner {
|
||||
while let Ok(event) = inner.file_events.try_recv() {
|
||||
match event {
|
||||
FileEvent::NewFileMTime(mtime) => {
|
||||
self.file_mtime = Some(mtime);
|
||||
}
|
||||
FileEvent::NewBufferMTime(mtime) => {
|
||||
self.buffer_mtime = mtime;
|
||||
self.file_mtime = Some(mtime);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ui.vertical_centered_justified(|ui| {
|
||||
ui.heading(&self.title);
|
||||
|
||||
const MAX_NOTE_WIDTH: f32 = 600.0;
|
||||
|
||||
// distance to scroll when paging up or down.
|
||||
let mut scroll_delta = 0.0;
|
||||
|
||||
ui.input_mut(|input| {
|
||||
if input.consume_key(egui::Modifiers::NONE, egui::Key::PageUp) {
|
||||
scroll_delta += self.scroll_delta;
|
||||
}
|
||||
if input.consume_key(egui::Modifiers::NONE, egui::Key::PageDown) {
|
||||
scroll_delta -= self.scroll_delta;
|
||||
}
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("new");
|
||||
if ui.button("text").clicked() {
|
||||
if ui.button(" text ").clicked() {
|
||||
self.is_dirty = true;
|
||||
self.buffer.push(BufferItem::Text(Default::default()));
|
||||
}
|
||||
@ -81,9 +191,23 @@ impl FileEditor {
|
||||
self.buffer
|
||||
.push(BufferItem::Handwriting(Default::default()));
|
||||
}
|
||||
|
||||
ui.add_space(16.0);
|
||||
|
||||
ui.label("scroll");
|
||||
if ui.button(" up ").clicked() {
|
||||
scroll_delta += self.scroll_delta;
|
||||
}
|
||||
if ui.button("down").clicked() {
|
||||
scroll_delta -= self.scroll_delta;
|
||||
}
|
||||
});
|
||||
|
||||
ScrollArea::vertical().show(ui, |ui| {
|
||||
let scroll_area = ScrollArea::vertical().show(ui, |ui| {
|
||||
if scroll_delta != 0.0 {
|
||||
ui.scroll_with_delta(Vec2::new(0.0, scroll_delta));
|
||||
}
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
let side_padding = ui.available_width().sub(MAX_NOTE_WIDTH).max(0.0).div(2.0);
|
||||
ui.add_space(side_padding);
|
||||
@ -94,6 +218,8 @@ impl FileEditor {
|
||||
ui.add_space(side_padding);
|
||||
});
|
||||
});
|
||||
|
||||
self.scroll_delta = scroll_area.inner_rect.height() * 0.5;
|
||||
});
|
||||
}
|
||||
|
||||
@ -120,25 +246,16 @@ impl FileEditor {
|
||||
|
||||
let mut retain = true;
|
||||
|
||||
if is_dragging {
|
||||
let (_, drop) = ui.dnd_drop_zone::<DraggingItem, _>(Frame::NONE, |ui| {
|
||||
ui.set_min_size(vec2(ui.available_width(), drag_zone_height));
|
||||
});
|
||||
if let Some(drop) = drop {
|
||||
drop_from_to = Some((drop.index, i));
|
||||
}
|
||||
} else {
|
||||
// the dnd_drop_zone adds 3pts work of extra space
|
||||
ui.add_space(drag_zone_height + 3.0);
|
||||
}
|
||||
|
||||
// Createa horizontal area to draw the buffer item. The three things drawn here are:
|
||||
// - The controls that exist at the left-size of the buffer item, i.e. "up"/"down".
|
||||
// - The buffer item.
|
||||
// - The controls that exist at the right-size of the buffer item, i.e. "delete".
|
||||
ui.horizontal(|ui| {
|
||||
// We don't know how tall the buffer item will be, so we'll reserve
|
||||
// some horizontal space here and come back to drawing the dragger
|
||||
// later.
|
||||
let (dragger_id, mut dragger_rect) = ui.allocate_space(Vec2::new(20.0, 1.0));
|
||||
// At this point, we don't know how tall the buffer item will be, so we'll reserve
|
||||
// some horizontal space here and come back to drawing the controls later.
|
||||
let (_id, mut left_controls_rect) = ui.allocate_space(Vec2::new(20.0, 1.0));
|
||||
|
||||
// Leave some space at the end for the delete button..
|
||||
// Leave some space at the end for the delete button.
|
||||
let w = ui.available_width();
|
||||
let item_size = Vec2::new(w - 20.0, 0.0);
|
||||
|
||||
@ -161,18 +278,17 @@ impl FileEditor {
|
||||
});
|
||||
|
||||
// Delete-button
|
||||
if ui.button("x").clicked() {
|
||||
if ui.button("⌫").clicked() {
|
||||
retain = false;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
|
||||
// Draw the dragger using the height from the buffer item
|
||||
dragger_rect.set_height(item_response.response.rect.height());
|
||||
left_controls_rect.set_height(item_response.response.rect.height());
|
||||
|
||||
// Controls for moving the buffer item
|
||||
ui.allocate_new_ui(
|
||||
ui.scope_builder(
|
||||
UiBuilder::new()
|
||||
.max_rect(dragger_rect)
|
||||
.max_rect(left_controls_rect)
|
||||
.layout(Layout::top_down(Align::Center)),
|
||||
|ui| {
|
||||
let up_button_response = ui.add_enabled(!is_first, Button::new("⇡"));
|
||||
@ -180,17 +296,12 @@ impl FileEditor {
|
||||
drop_from_to = Some((i, i - 1));
|
||||
}
|
||||
|
||||
ui.dnd_drag_source(dragger_id, DraggingItem { index: i }, |ui| {
|
||||
Button::new("≡")
|
||||
.min_size(
|
||||
// Use all available height, save for the height taken up by
|
||||
// the up/down buttons + padding. Assume down-button is the
|
||||
// equally tall as the up-button.
|
||||
dragger_rect.size()
|
||||
- Vec2::Y * (up_button_response.rect.height() * 2.0 + 4.0),
|
||||
)
|
||||
.ui(ui);
|
||||
});
|
||||
// Add some space so that the next button is drawn
|
||||
// at the bottom of the buffer item.
|
||||
ui.add_space(
|
||||
left_controls_rect.height()
|
||||
- (up_button_response.rect.height() * 2.0 + 4.0),
|
||||
);
|
||||
|
||||
if ui.add_enabled(!is_last, Button::new("⇣")).clicked() {
|
||||
drop_from_to = Some((i, i + 2));
|
||||
@ -243,6 +354,38 @@ impl FileEditor {
|
||||
self.title = title.to_string_lossy().to_string();
|
||||
self.path = Some(new_path);
|
||||
}
|
||||
|
||||
pub fn set_dirty(&mut self, value: bool) {
|
||||
self.is_dirty = value;
|
||||
}
|
||||
|
||||
pub fn save(&mut self, ctx: &Context, jobs: &mut Jobs) {
|
||||
let Some(file_path) = self.path.clone() else {
|
||||
log::info!("Can't save {}, no path set.", self.title);
|
||||
return;
|
||||
};
|
||||
|
||||
self.is_dirty = false;
|
||||
let text = self.to_string();
|
||||
let inner = self
|
||||
.inner
|
||||
.get_or_insert_with(|| spawn_file_watcher(&file_path));
|
||||
let file_event_tx = inner.file_events_tx.clone();
|
||||
|
||||
jobs.start(ctx, move || {
|
||||
log_error(eyre!("Failed to save file {file_path:?}"), || {
|
||||
let mut file = fs::File::create(file_path)?;
|
||||
file.write_all(text.as_bytes())?;
|
||||
let mtime = file_mtime(&file)?;
|
||||
|
||||
let _ = file_event_tx.send(FileEvent::NewBufferMTime(mtime));
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
None
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for BufferItem {
|
||||
@ -280,7 +423,7 @@ impl From<&str> for FileEditor {
|
||||
_ => {
|
||||
let mut text_edit = MdTextEdit::new();
|
||||
text_edit.text.push_str(text);
|
||||
buffer.push(BufferItem::Text(text_edit));
|
||||
buffer.push(BufferItem::Text(Box::new(text_edit)));
|
||||
}
|
||||
};
|
||||
|
||||
@ -314,6 +457,40 @@ impl From<&str> for FileEditor {
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_file_watcher(p: &Path) -> Inner {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
let path = p.to_owned();
|
||||
let events_tx = tx.clone();
|
||||
let mut watcher = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
|
||||
log_error(eyre!("watch {path:?} error"), || {
|
||||
match event?.kind {
|
||||
EventKind::Create(..) | EventKind::Modify(..) | EventKind::Remove(..) => {}
|
||||
|
||||
EventKind::Access(..) | EventKind::Any | EventKind::Other => return Ok(()),
|
||||
}
|
||||
|
||||
let file = File::open(&path)?;
|
||||
let mtime = file_mtime(&file)?;
|
||||
|
||||
let _ = events_tx.send(FileEvent::NewFileMTime(mtime));
|
||||
|
||||
Ok(())
|
||||
});
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
if let Err(e) = watcher.watch(p, notify::RecursiveMode::NonRecursive) {
|
||||
log::error!("Failed to watch {p:?}: {e}");
|
||||
};
|
||||
|
||||
Inner {
|
||||
file_events: rx,
|
||||
file_events_tx: tx,
|
||||
_file_watcher: watcher,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
|
||||
|
||||
@ -7,7 +7,7 @@ use std::{
|
||||
thread,
|
||||
};
|
||||
|
||||
use egui::{Response, Ui};
|
||||
use egui::{Button, Color32, Response, Stroke, TextWrapMode, Ui, Vec2, Widget};
|
||||
use eyre::{Context, OptionExt, eyre};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@ -52,20 +52,59 @@ impl Deref for FolderResponse<'_> {
|
||||
impl LoadedFolder {
|
||||
pub fn show<'a>(&'a mut self, ui: &mut Ui) -> FolderResponse<'a> {
|
||||
let mut open_file = None;
|
||||
|
||||
let draw_highlight = |ui: &mut Ui, rect| {
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
2.0,
|
||||
if ui.visuals().dark_mode {
|
||||
Color32::from_white_alpha(16)
|
||||
} else {
|
||||
Color32::from_black_alpha(16)
|
||||
},
|
||||
Stroke::NONE,
|
||||
egui::StrokeKind::Outside,
|
||||
);
|
||||
};
|
||||
|
||||
let inner = ui
|
||||
.collapsing(&self.name, |ui| {
|
||||
for folder in &mut self.child_folders {
|
||||
open_file = open_file.or(folder.show(ui).open_file);
|
||||
}
|
||||
|
||||
let w = ui.available_width();
|
||||
|
||||
let mut first = true;
|
||||
|
||||
for file in &mut self.child_files {
|
||||
if ui.button(&file.name).clicked() {
|
||||
if !first {
|
||||
ui.add_space(2.0);
|
||||
}
|
||||
first = false;
|
||||
|
||||
let button = Button::new(&file.name)
|
||||
.min_size(Vec2::new(w, 0.0))
|
||||
.wrap_mode(TextWrapMode::Truncate)
|
||||
.frame(false)
|
||||
.corner_radius(0.0)
|
||||
.ui(ui);
|
||||
|
||||
if button.hovered() {
|
||||
draw_highlight(ui, button.rect);
|
||||
}
|
||||
|
||||
if button.clicked() {
|
||||
open_file = Some(file.path.as_path())
|
||||
};
|
||||
}
|
||||
})
|
||||
.header_response;
|
||||
|
||||
if inner.hovered() {
|
||||
draw_highlight(ui, inner.rect);
|
||||
}
|
||||
|
||||
FolderResponse { inner, open_file }
|
||||
}
|
||||
|
||||
@ -94,12 +133,19 @@ impl LoadedFolder {
|
||||
log::error!("Symlinks not yet supported, skipping {path:?}");
|
||||
continue;
|
||||
} else if file_type.is_file() {
|
||||
child_files.push(File { name, path });
|
||||
if filter_file(&name) {
|
||||
child_files.push(File { name, path });
|
||||
}
|
||||
} else if file_type.is_dir() {
|
||||
child_folders.push(Folder::NotLoaded { name, path });
|
||||
if filter_folder(&name) {
|
||||
child_folders.push(Folder::NotLoaded { name, path });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
child_folders.sort_by_key(|folder| folder.name().to_owned());
|
||||
child_files.sort_by_key(|file| (!file.name.ends_with(".md"), file.name.clone()));
|
||||
|
||||
let folder = LoadedFolder {
|
||||
name,
|
||||
path,
|
||||
@ -216,3 +262,11 @@ impl<'de> Deserialize<'de> for Folder {
|
||||
Ok(Folder::NotLoaded { name, path })
|
||||
}
|
||||
}
|
||||
|
||||
fn filter_folder(_folder_name: &str) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn filter_file(file_name: &str) -> bool {
|
||||
file_name != ".DS_Store"
|
||||
}
|
||||
|
||||
@ -42,7 +42,7 @@ impl Tile {
|
||||
|
||||
Self {
|
||||
bounding_box,
|
||||
image: ColorImage::new([CHUNK_SIZE, CHUNK_SIZE], Color32::TRANSPARENT),
|
||||
image: ColorImage::filled([CHUNK_SIZE, CHUNK_SIZE], Color32::TRANSPARENT),
|
||||
texture: None,
|
||||
texture_is_dirty: false,
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
mod canvas_rasterizer;
|
||||
mod disk_format;
|
||||
mod tool;
|
||||
|
||||
use std::{
|
||||
fmt::{self, Display},
|
||||
@ -8,13 +9,14 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use arboard::Clipboard;
|
||||
use base64::{Engine, prelude::BASE64_STANDARD};
|
||||
use canvas_rasterizer::CanvasRasterizer;
|
||||
use disk_format::{DiskFormat, RawStroke, RawStrokeHeader, f16_le};
|
||||
use egui::{
|
||||
Color32, Event, Frame, Id, Mesh, PointerButton, Pos2, Rect, Sense, Shape, Stroke, Theme, Ui,
|
||||
Vec2,
|
||||
emath::{self, TSTransform},
|
||||
emath::{self, RectTransform, TSTransform},
|
||||
epaint::{TessellationOptions, Tessellator, Vertex},
|
||||
};
|
||||
use eyre::{Context, bail};
|
||||
@ -25,6 +27,8 @@ use zerocopy::{FromBytes, IntoBytes};
|
||||
use crate::{custom_code_block::try_from_custom_code_block, rasterizer};
|
||||
use crate::{custom_code_block::write_custom_code_block, util::random_id};
|
||||
|
||||
use self::tool::{Tool, ToolEvent};
|
||||
|
||||
const HANDWRITING_MIN_HEIGHT: f32 = 100.0;
|
||||
const HANDWRITING_BOTTOM_PADDING: f32 = 80.0;
|
||||
const HANDWRITING_MARGIN: f32 = 0.05;
|
||||
@ -77,10 +81,20 @@ struct Ephemeral {
|
||||
|
||||
canvas_rasterizer: CanvasRasterizer,
|
||||
|
||||
tool: Tool,
|
||||
|
||||
/// Tool position in canvas space.
|
||||
tool_position: Option<Pos2>,
|
||||
|
||||
/// Tool position last frame, in canvas space.
|
||||
last_tool_position: Option<Pos2>,
|
||||
|
||||
/// The stroke that is currently being drawed.
|
||||
current_stroke: Vec<Pos2>,
|
||||
|
||||
/// The lines that have not been blitted to `texture` yet.
|
||||
///
|
||||
/// Each pair of [Pos2]s is the start and end of one line.
|
||||
unblitted_lines: Vec<[Pos2; 2]>,
|
||||
|
||||
tessellator: Option<Tessellator>,
|
||||
@ -125,6 +139,9 @@ impl Default for Ephemeral {
|
||||
Self {
|
||||
id: random_id(),
|
||||
canvas_rasterizer: Default::default(),
|
||||
tool: Tool::Pencil,
|
||||
tool_position: None,
|
||||
last_tool_position: None,
|
||||
current_stroke: Default::default(),
|
||||
tessellator: None,
|
||||
mesh: Default::default(),
|
||||
@ -163,6 +180,20 @@ impl Handwriting {
|
||||
}
|
||||
});
|
||||
|
||||
if ui.button("copy").clicked() {
|
||||
let text = self.to_string();
|
||||
// TODO: move to a job
|
||||
let _ = Clipboard::new().unwrap().set_text(text);
|
||||
}
|
||||
|
||||
let (label, switch_to_tool) = match self.e.tool {
|
||||
Tool::Pencil => ("eraser", Tool::Eraser),
|
||||
Tool::Eraser => ("pencil", Tool::Pencil),
|
||||
};
|
||||
if ui.button(label).clicked() {
|
||||
self.e.tool = switch_to_tool;
|
||||
}
|
||||
|
||||
let vertex_count: usize = self.e.mesh.indices.len() / 3;
|
||||
ui.label(format!("vertices: {vertex_count}"));
|
||||
})
|
||||
@ -202,6 +233,8 @@ impl Handwriting {
|
||||
emath::RectTransform::from_to(Rect::from_min_size(Pos2::ZERO, size), response.rect);
|
||||
let from_screen = to_screen.inverse();
|
||||
|
||||
self.e.last_tool_position = self.e.tool_position;
|
||||
|
||||
// Was the user in the process of drawing a stroke last frame?
|
||||
let was_drawing = !self.e.current_stroke.is_empty();
|
||||
|
||||
@ -261,88 +294,21 @@ impl Handwriting {
|
||||
|
||||
// Process input events and turn them into strokes
|
||||
for event in events {
|
||||
let last_canvas_pos = self.e.current_stroke.last();
|
||||
|
||||
match event {
|
||||
Event::PointerMoved(new_position) => {
|
||||
let new_canvas_pos = from_screen * new_position;
|
||||
if let Some(&last_canvas_pos) = last_canvas_pos {
|
||||
if last_canvas_pos != new_canvas_pos {
|
||||
self.push_to_stroke(new_canvas_pos);
|
||||
response.mark_changed();
|
||||
let mut last_tool_position = self.e.last_tool_position;
|
||||
process_event(&mut last_tool_position, from_screen, &event, |tool_event| {
|
||||
self.e.tool_position = tool_event.position();
|
||||
match self.e.tool {
|
||||
Tool::Pencil => {
|
||||
hw_response.changed |= tool::pencil::on_tool_event(self, tool_event);
|
||||
}
|
||||
Tool::Eraser => {
|
||||
if tool::eraser::on_tool_event(self, tool_event) {
|
||||
self.e.refresh_texture = true;
|
||||
hw_response.changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Event::MouseMoved(mut delta) => {
|
||||
if delta.length() == 0.0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
// FIXME: pinenote: MouseMovement delta does *not* take into account screen
|
||||
// scaling and rotation, so unless you've scaling=1 and no rotation, the
|
||||
// MouseMoved values will be all wrong.
|
||||
if cfg!(feature = "pinenote") {
|
||||
delta /= 1.8;
|
||||
delta = -delta.rot90();
|
||||
}
|
||||
|
||||
if let Some(&last_canvas_pos) = last_canvas_pos {
|
||||
self.push_to_stroke(last_canvas_pos + delta);
|
||||
response.mark_changed();
|
||||
} else {
|
||||
println!("Got `MouseMoved`, but have no previous pos");
|
||||
}
|
||||
}
|
||||
|
||||
Event::PointerButton {
|
||||
pos,
|
||||
button,
|
||||
pressed,
|
||||
modifiers: _,
|
||||
} => match (button, pressed) {
|
||||
(PointerButton::Primary, true) => {
|
||||
if last_canvas_pos.is_none() {
|
||||
self.e.current_stroke.push(from_screen * pos);
|
||||
}
|
||||
}
|
||||
(PointerButton::Primary, false) => {
|
||||
if last_canvas_pos.is_some() {
|
||||
self.push_to_stroke(from_screen * pos);
|
||||
self.commit_current_line(hw_response);
|
||||
response.mark_changed();
|
||||
}
|
||||
|
||||
// Stop reading events.
|
||||
// TODO: In theory, we can get multiple press->draw->release series
|
||||
// in the same frame. Should handle this.
|
||||
break;
|
||||
}
|
||||
(_, _) => continue,
|
||||
},
|
||||
|
||||
// Stop drawing after pointer disappears or the window is unfocused
|
||||
// TODO: In theory, we can get multiple press->draw->release series
|
||||
// in the same frame. Should handle this.
|
||||
Event::PointerGone | Event::WindowFocused(false) => {
|
||||
if !self.e.current_stroke.is_empty() {
|
||||
self.commit_current_line(hw_response);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Event::WindowFocused(true)
|
||||
| Event::Copy
|
||||
| Event::Cut
|
||||
| Event::Paste(..)
|
||||
| Event::Text(..)
|
||||
| Event::Key { .. }
|
||||
| Event::Zoom(..)
|
||||
| Event::Ime(..)
|
||||
| Event::Touch { .. }
|
||||
| Event::MouseWheel { .. }
|
||||
| Event::Screenshot { .. } => continue,
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -399,6 +365,14 @@ impl Handwriting {
|
||||
// Draw the texture
|
||||
self.e.canvas_rasterizer.show(ui.ctx(), &painter, mesh_rect);
|
||||
|
||||
if let Some(tool_position) = self.e.tool_position
|
||||
&& let Tool::Eraser = self.e.tool
|
||||
{
|
||||
let pos = to_screen * tool_position;
|
||||
let shape = Shape::circle_stroke(pos, tool::eraser::RADIUS, style.stroke);
|
||||
painter.add(shape);
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
@ -418,7 +392,7 @@ impl Handwriting {
|
||||
last_mesh_ctx,
|
||||
..
|
||||
} = &mut self.e;
|
||||
// TODO: don't tessellate and rasterize on the GUI thread
|
||||
// TODO: avoid tessellating and rasterizing on the GUI thread
|
||||
|
||||
*last_mesh_ctx = Some(mesh_context);
|
||||
|
||||
@ -437,10 +411,7 @@ impl Handwriting {
|
||||
.iter()
|
||||
.chain([&*current_stroke])
|
||||
.filter(|stroke| stroke.len() >= 2)
|
||||
.map(|stroke| {
|
||||
//let points: Vec<Pos2> = stroke.iter().map(|&p| to_screen * p).collect();
|
||||
egui::Shape::line(stroke.clone(), style.stroke)
|
||||
})
|
||||
.map(|stroke| egui::Shape::line(stroke.clone(), style.stroke))
|
||||
.for_each(|shape| {
|
||||
tessellator.tessellate_shape(shape, mesh);
|
||||
});
|
||||
@ -473,7 +444,6 @@ impl Handwriting {
|
||||
ui.vertical_centered_justified(|ui| {
|
||||
self.ui_control(None, ui, &mut response);
|
||||
|
||||
//ui.label("Paint with your mouse/touch!");
|
||||
Frame::canvas(ui.style())
|
||||
.corner_radius(20.0)
|
||||
.stroke(Stroke::new(5.0, Color32::from_black_alpha(40)))
|
||||
@ -584,6 +554,87 @@ impl Handwriting {
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert [egui::Event]s to [ToolEvent]s.
|
||||
fn process_event(
|
||||
last_canvas_pos: &mut Option<Pos2>,
|
||||
from_screen: RectTransform,
|
||||
event: &Event,
|
||||
mut on_tool_event: impl FnMut(ToolEvent),
|
||||
) {
|
||||
match event {
|
||||
&Event::PointerMoved(new_position) => {
|
||||
let new_canvas_pos = from_screen * new_position;
|
||||
if last_canvas_pos.is_some() && *last_canvas_pos != Some(new_canvas_pos) {
|
||||
*last_canvas_pos = Some(new_canvas_pos);
|
||||
on_tool_event(ToolEvent::Move { to: new_canvas_pos });
|
||||
}
|
||||
}
|
||||
|
||||
&Event::MouseMoved(mut delta) => {
|
||||
if delta.length() == 0.0 {
|
||||
return;
|
||||
}
|
||||
|
||||
// FIXME: pinenote: MouseMovement delta does *not* take into account screen
|
||||
// scaling and rotation, so unless you've scaling=1 and no rotation, the
|
||||
// MouseMoved values will be all wrong.
|
||||
if cfg!(feature = "pinenote") {
|
||||
delta /= 1.8;
|
||||
delta = -delta.rot90();
|
||||
}
|
||||
|
||||
if let Some(pos) = last_canvas_pos {
|
||||
*pos += delta;
|
||||
on_tool_event(ToolEvent::Move { to: *pos });
|
||||
} else {
|
||||
println!("Got `MouseMoved`, but have no previous pos");
|
||||
}
|
||||
}
|
||||
|
||||
&Event::PointerButton {
|
||||
pos,
|
||||
button,
|
||||
pressed,
|
||||
modifiers: _,
|
||||
} => match (button, pressed) {
|
||||
(PointerButton::Primary, true) => {
|
||||
if last_canvas_pos.is_none() {
|
||||
let pos = from_screen * pos;
|
||||
*last_canvas_pos = Some(pos);
|
||||
on_tool_event(ToolEvent::Press { at: pos });
|
||||
}
|
||||
}
|
||||
(PointerButton::Primary, false) => {
|
||||
if last_canvas_pos.take().is_some() {
|
||||
let pos = from_screen * pos;
|
||||
on_tool_event(ToolEvent::Move { to: pos });
|
||||
on_tool_event(ToolEvent::Release {});
|
||||
}
|
||||
}
|
||||
(_, _) => {}
|
||||
},
|
||||
|
||||
// Stop drawing after pointer disappears or the window is unfocused
|
||||
Event::PointerGone | Event::WindowFocused(false) => {
|
||||
if last_canvas_pos.take().is_some() {
|
||||
on_tool_event(ToolEvent::Release {});
|
||||
}
|
||||
}
|
||||
|
||||
Event::WindowFocused(true)
|
||||
| Event::Copy
|
||||
| Event::Cut
|
||||
| Event::Paste(..)
|
||||
| Event::Text(..)
|
||||
| Event::Key { .. }
|
||||
| Event::Zoom(..)
|
||||
| Event::Ime(..)
|
||||
| Event::Touch { .. }
|
||||
| Event::MouseWheel { .. }
|
||||
| Event::Screenshot { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn new_tessellator(pixels_per_point: f32) -> Tessellator {
|
||||
Tessellator::new(
|
||||
pixels_per_point,
|
||||
@ -727,7 +778,9 @@ fn mesh_triangles(mesh: &Mesh) -> impl Iterator<Item = [&Vertex; 3]> + Clone {
|
||||
mod test {
|
||||
use std::str::FromStr;
|
||||
|
||||
use super::Handwriting;
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, Rect, emath::RectTransform};
|
||||
|
||||
use super::{Handwriting, process_event};
|
||||
|
||||
#[test]
|
||||
fn serialize_handwriting() {
|
||||
@ -741,4 +794,194 @@ mod test {
|
||||
Handwriting::from_str(&serialized).expect("Handwriting must de/serialize correctly");
|
||||
insta::assert_debug_snapshot!("deserialized handwriting", deserialized.strokes);
|
||||
}
|
||||
|
||||
const TEST_EVENTS: &[Event] = &[
|
||||
Event::PointerMoved(Pos2::new(749.9, 225.6)),
|
||||
Event::PointerButton {
|
||||
pos: Pos2::new(749.9, 225.6),
|
||||
button: PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: Modifiers::NONE,
|
||||
},
|
||||
Event::PointerMoved(Pos2::new(749.9, 225.7)),
|
||||
Event::PointerMoved(Pos2::new(749.9, 226.4)),
|
||||
Event::PointerMoved(Pos2::new(750.2, 228.4)),
|
||||
Event::PointerMoved(Pos2::new(751.0, 231.3)),
|
||||
Event::PointerMoved(Pos2::new(752.6, 234.4)),
|
||||
Event::PointerMoved(Pos2::new(754.1, 237.7)),
|
||||
Event::PointerMoved(Pos2::new(755.8, 241.1)),
|
||||
Event::PointerMoved(Pos2::new(757.7, 244.4)),
|
||||
Event::PointerMoved(Pos2::new(759.3, 247.4)),
|
||||
Event::PointerMoved(Pos2::new(760.8, 250.2)),
|
||||
Event::PointerMoved(Pos2::new(762.8, 253.4)),
|
||||
Event::PointerMoved(Pos2::new(765.1, 256.8)),
|
||||
Event::PointerMoved(Pos2::new(767.7, 260.2)),
|
||||
Event::PointerMoved(Pos2::new(771.2, 264.3)),
|
||||
Event::PointerMoved(Pos2::new(774.6, 267.9)),
|
||||
Event::PointerMoved(Pos2::new(778.2, 271.2)),
|
||||
Event::PointerMoved(Pos2::new(782.7, 275.2)),
|
||||
Event::PointerMoved(Pos2::new(786.7, 278.5)),
|
||||
Event::PointerMoved(Pos2::new(790.4, 280.8)),
|
||||
Event::PointerMoved(Pos2::new(794.1, 282.6)),
|
||||
Event::PointerMoved(Pos2::new(797.9, 283.9)),
|
||||
Event::PointerMoved(Pos2::new(801.9, 284.8)),
|
||||
Event::PointerMoved(Pos2::new(805.9, 285.5)),
|
||||
Event::PointerMoved(Pos2::new(810.2, 285.8)),
|
||||
Event::PointerMoved(Pos2::new(814.5, 285.8)),
|
||||
Event::PointerMoved(Pos2::new(818.2, 285.6)),
|
||||
Event::PointerMoved(Pos2::new(821.6, 284.5)),
|
||||
Event::PointerMoved(Pos2::new(824.7, 283.0)),
|
||||
Event::PointerMoved(Pos2::new(827.5, 281.4)),
|
||||
Event::PointerMoved(Pos2::new(830.4, 279.6)),
|
||||
Event::PointerMoved(Pos2::new(833.4, 277.7)),
|
||||
Event::PointerMoved(Pos2::new(836.1, 275.7)),
|
||||
Event::PointerMoved(Pos2::new(838.6, 273.6)),
|
||||
Event::PointerMoved(Pos2::new(840.9, 271.7)),
|
||||
Event::PointerMoved(Pos2::new(843.0, 269.6)),
|
||||
Event::PointerMoved(Pos2::new(845.4, 267.2)),
|
||||
Event::PointerMoved(Pos2::new(847.7, 265.1)),
|
||||
Event::PointerMoved(Pos2::new(849.8, 262.7)),
|
||||
Event::PointerMoved(Pos2::new(852.0, 260.0)),
|
||||
Event::PointerMoved(Pos2::new(854.3, 256.8)),
|
||||
Event::PointerMoved(Pos2::new(856.3, 253.4)),
|
||||
Event::PointerMoved(Pos2::new(858.2, 250.1)),
|
||||
Event::PointerMoved(Pos2::new(860.0, 247.1)),
|
||||
Event::PointerMoved(Pos2::new(861.5, 244.3)),
|
||||
Event::PointerMoved(Pos2::new(862.8, 242.0)),
|
||||
Event::PointerMoved(Pos2::new(864.1, 240.1)),
|
||||
Event::PointerMoved(Pos2::new(865.0, 238.2)),
|
||||
Event::PointerMoved(Pos2::new(865.8, 236.6)),
|
||||
Event::PointerMoved(Pos2::new(866.5, 234.9)),
|
||||
Event::PointerMoved(Pos2::new(867.1, 233.1)),
|
||||
Event::PointerMoved(Pos2::new(867.8, 231.4)),
|
||||
Event::PointerMoved(Pos2::new(868.4, 229.8)),
|
||||
Event::PointerMoved(Pos2::new(868.7, 228.4)),
|
||||
Event::PointerMoved(Pos2::new(868.9, 227.2)),
|
||||
Event::PointerMoved(Pos2::new(869.1, 226.2)),
|
||||
Event::PointerMoved(Pos2::new(869.1, 225.1)),
|
||||
Event::PointerMoved(Pos2::new(869.1, 224.1)),
|
||||
Event::PointerMoved(Pos2::new(869.1, 223.4)),
|
||||
Event::PointerMoved(Pos2::new(869.1, 222.8)),
|
||||
Event::PointerMoved(Pos2::new(869.1, 222.4)),
|
||||
Event::PointerMoved(Pos2::new(869.1, 222.4)),
|
||||
// Event::PointerButton {
|
||||
// pos: Pos2::new(869.1, 222.4),
|
||||
// button: PointerButton::Primary,
|
||||
// pressed: false,
|
||||
// modifiers: Modifiers::NONE,
|
||||
// },
|
||||
Event::PointerGone,
|
||||
Event::PointerMoved(Pos2::new(779.3, 158.6)),
|
||||
// --
|
||||
// FIXME: This line looks weird. Probably because of a bug in the rasterizer when the X-coord is all the same.
|
||||
Event::PointerButton {
|
||||
pos: Pos2::new(779.3, 158.6),
|
||||
button: PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: Modifiers::NONE,
|
||||
},
|
||||
Event::PointerMoved(Pos2::new(779.3, 159.0)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 160.9)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 164.6)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 169.6)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 175.2)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 180.3)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 185.0)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 189.4)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 192.8)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 194.9)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 196.1)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 197.0)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 197.6)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 198.1)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 198.5)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 198.8)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 199.0)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 199.2)),
|
||||
Event::PointerMoved(Pos2::new(779.3, 199.2)),
|
||||
Event::PointerButton {
|
||||
pos: Pos2::new(779.3, 199.2),
|
||||
button: PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: Modifiers::NONE,
|
||||
},
|
||||
// --
|
||||
Event::PointerMoved(Pos2::new(841.5, 159.2)),
|
||||
Event::PointerButton {
|
||||
pos: Pos2::new(841.5, 159.2),
|
||||
button: PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: Modifiers::NONE,
|
||||
},
|
||||
Event::PointerMoved(Pos2::new(841.5, 159.3)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 159.7)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 160.5)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 162.4)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 165.1)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 168.4)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 171.6)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 174.4)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 177.1)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 179.3)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 180.9)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 182.4)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 183.5)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 184.5)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 185.6)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 187.0)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 188.6)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 190.3)),
|
||||
Event::PointerMoved(Pos2::new(841.5, 191.8)),
|
||||
Event::PointerMoved(Pos2::new(841.3, 192.7)),
|
||||
Event::PointerMoved(Pos2::new(841.0, 193.3)),
|
||||
Event::PointerMoved(Pos2::new(841.0, 193.7)),
|
||||
Event::PointerMoved(Pos2::new(841.1, 193.9)),
|
||||
Event::PointerMoved(Pos2::new(841.3, 193.9)),
|
||||
Event::PointerMoved(Pos2::new(841.4, 194.0)),
|
||||
Event::PointerMoved(Pos2::new(841.4, 194.2)),
|
||||
Event::PointerMoved(Pos2::new(841.4, 194.6)),
|
||||
Event::PointerMoved(Pos2::new(841.4, 194.9)),
|
||||
Event::PointerMoved(Pos2::new(841.4, 195.1)),
|
||||
Event::PointerMoved(Pos2::new(841.4, 195.1)),
|
||||
Event::PointerButton {
|
||||
pos: Pos2::new(841.4, 195.1),
|
||||
button: PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: Modifiers::NONE,
|
||||
},
|
||||
];
|
||||
|
||||
fn from_screen() -> RectTransform {
|
||||
RectTransform::from_to(
|
||||
Rect::from_two_pos(Pos2::new(570.0, 145.1), Pos2::new(1116.4, 245.1)),
|
||||
Rect::from_two_pos(Pos2::new(0.0, 0.0), Pos2::new(546.4, 100.0)),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_input() {
|
||||
let mut tool_events = vec![];
|
||||
let mut last_pos = None;
|
||||
let from_screen = from_screen();
|
||||
for event in TEST_EVENTS {
|
||||
process_event(&mut last_pos, from_screen, event, |tool_event| {
|
||||
tool_events.push(tool_event)
|
||||
});
|
||||
}
|
||||
insta::assert_yaml_snapshot!(tool_events);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_to_handwriting() {
|
||||
let mut handwriting = Handwriting::default();
|
||||
let mut last_pos = None;
|
||||
let from_screen = from_screen();
|
||||
for event in TEST_EVENTS {
|
||||
process_event(&mut last_pos, from_screen, event, |tool_event| {
|
||||
handwriting.on_tool_event(tool_event);
|
||||
});
|
||||
}
|
||||
let serialized = handwriting.to_string();
|
||||
insta::assert_snapshot!("input events to handwriting", serialized);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,455 @@
|
||||
---
|
||||
source: src/handwriting/mod.rs
|
||||
expression: tool_events
|
||||
---
|
||||
- Press:
|
||||
at:
|
||||
x: 179.90002
|
||||
y: 80.5
|
||||
- Move:
|
||||
to:
|
||||
x: 179.90002
|
||||
y: 80.59999
|
||||
- Move:
|
||||
to:
|
||||
x: 179.90002
|
||||
y: 81.29999
|
||||
- Move:
|
||||
to:
|
||||
x: 180.20001
|
||||
y: 83.29999
|
||||
- Move:
|
||||
to:
|
||||
x: 181
|
||||
y: 86.2
|
||||
- Move:
|
||||
to:
|
||||
x: 182.59998
|
||||
y: 89.29999
|
||||
- Move:
|
||||
to:
|
||||
x: 184.09998
|
||||
y: 92.59999
|
||||
- Move:
|
||||
to:
|
||||
x: 185.79999
|
||||
y: 96
|
||||
- Move:
|
||||
to:
|
||||
x: 187.70001
|
||||
y: 99.29999
|
||||
- Move:
|
||||
to:
|
||||
x: 189.3
|
||||
y: 102.29999
|
||||
- Move:
|
||||
to:
|
||||
x: 190.8
|
||||
y: 105.09999
|
||||
- Move:
|
||||
to:
|
||||
x: 192.79999
|
||||
y: 108.29998
|
||||
- Move:
|
||||
to:
|
||||
x: 195.09998
|
||||
y: 111.69999
|
||||
- Move:
|
||||
to:
|
||||
x: 197.70001
|
||||
y: 115.100006
|
||||
- Move:
|
||||
to:
|
||||
x: 201.20001
|
||||
y: 119.19998
|
||||
- Move:
|
||||
to:
|
||||
x: 204.59998
|
||||
y: 122.799995
|
||||
- Move:
|
||||
to:
|
||||
x: 208.20001
|
||||
y: 126.100006
|
||||
- Move:
|
||||
to:
|
||||
x: 212.70001
|
||||
y: 130.1
|
||||
- Move:
|
||||
to:
|
||||
x: 216.70001
|
||||
y: 133.4
|
||||
- Move:
|
||||
to:
|
||||
x: 220.40002
|
||||
y: 135.69998
|
||||
- Move:
|
||||
to:
|
||||
x: 224.09998
|
||||
y: 137.5
|
||||
- Move:
|
||||
to:
|
||||
x: 227.90002
|
||||
y: 138.79999
|
||||
- Move:
|
||||
to:
|
||||
x: 231.90002
|
||||
y: 139.69998
|
||||
- Move:
|
||||
to:
|
||||
x: 235.90002
|
||||
y: 140.4
|
||||
- Move:
|
||||
to:
|
||||
x: 240.20001
|
||||
y: 140.69998
|
||||
- Move:
|
||||
to:
|
||||
x: 244.5
|
||||
y: 140.69998
|
||||
- Move:
|
||||
to:
|
||||
x: 248.20001
|
||||
y: 140.5
|
||||
- Move:
|
||||
to:
|
||||
x: 251.59996
|
||||
y: 139.4
|
||||
- Move:
|
||||
to:
|
||||
x: 254.70001
|
||||
y: 137.9
|
||||
- Move:
|
||||
to:
|
||||
x: 257.5
|
||||
y: 136.29999
|
||||
- Move:
|
||||
to:
|
||||
x: 260.40002
|
||||
y: 134.5
|
||||
- Move:
|
||||
to:
|
||||
x: 263.40002
|
||||
y: 132.6
|
||||
- Move:
|
||||
to:
|
||||
x: 266.09998
|
||||
y: 130.6
|
||||
- Move:
|
||||
to:
|
||||
x: 268.59998
|
||||
y: 128.5
|
||||
- Move:
|
||||
to:
|
||||
x: 270.90002
|
||||
y: 126.600006
|
||||
- Move:
|
||||
to:
|
||||
x: 273
|
||||
y: 124.5
|
||||
- Move:
|
||||
to:
|
||||
x: 275.40002
|
||||
y: 122.100006
|
||||
- Move:
|
||||
to:
|
||||
x: 277.70004
|
||||
y: 120.00001
|
||||
- Move:
|
||||
to:
|
||||
x: 279.8
|
||||
y: 117.60001
|
||||
- Move:
|
||||
to:
|
||||
x: 282
|
||||
y: 114.899994
|
||||
- Move:
|
||||
to:
|
||||
x: 284.3
|
||||
y: 111.69999
|
||||
- Move:
|
||||
to:
|
||||
x: 286.3
|
||||
y: 108.29998
|
||||
- Move:
|
||||
to:
|
||||
x: 288.2
|
||||
y: 104.99999
|
||||
- Move:
|
||||
to:
|
||||
x: 290
|
||||
y: 102
|
||||
- Move:
|
||||
to:
|
||||
x: 291.5
|
||||
y: 99.2
|
||||
- Move:
|
||||
to:
|
||||
x: 292.8
|
||||
y: 96.899994
|
||||
- Move:
|
||||
to:
|
||||
x: 294.09995
|
||||
y: 95
|
||||
- Move:
|
||||
to:
|
||||
x: 295
|
||||
y: 93.09999
|
||||
- Move:
|
||||
to:
|
||||
x: 295.8
|
||||
y: 91.5
|
||||
- Move:
|
||||
to:
|
||||
x: 296.5
|
||||
y: 89.79999
|
||||
- Move:
|
||||
to:
|
||||
x: 297.1
|
||||
y: 88
|
||||
- Move:
|
||||
to:
|
||||
x: 297.8
|
||||
y: 86.29999
|
||||
- Move:
|
||||
to:
|
||||
x: 298.40005
|
||||
y: 84.7
|
||||
- Move:
|
||||
to:
|
||||
x: 298.7
|
||||
y: 83.29999
|
||||
- Move:
|
||||
to:
|
||||
x: 298.90002
|
||||
y: 82.09999
|
||||
- Move:
|
||||
to:
|
||||
x: 299.1
|
||||
y: 81.09999
|
||||
- Move:
|
||||
to:
|
||||
x: 299.1
|
||||
y: 80
|
||||
- Move:
|
||||
to:
|
||||
x: 299.1
|
||||
y: 79
|
||||
- Move:
|
||||
to:
|
||||
x: 299.1
|
||||
y: 78.29999
|
||||
- Move:
|
||||
to:
|
||||
x: 299.1
|
||||
y: 77.7
|
||||
- Move:
|
||||
to:
|
||||
x: 299.1
|
||||
y: 77.29999
|
||||
- Release
|
||||
- Press:
|
||||
at:
|
||||
x: 209.29999
|
||||
y: 13.500001
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 13.899994
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 15.799988
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 19.5
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 24.5
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 30.09999
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 35.199997
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 39.899994
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 44.299988
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 47.699997
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 49.799988
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 51
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 51.899994
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 52.499996
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 52.999996
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 53.399994
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 53.699993
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 53.89999
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 54.09999
|
||||
- Move:
|
||||
to:
|
||||
x: 209.29999
|
||||
y: 54.09999
|
||||
- Release
|
||||
- Press:
|
||||
at:
|
||||
x: 271.5
|
||||
y: 14.099991
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 14.199998
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 14.599991
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 15.399994
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 17.299988
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 20
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 23.299988
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 26.499998
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 29.299986
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 32
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 34.199997
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 35.799988
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 37.299988
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 38.399994
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 39.399994
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 40.5
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 41.899994
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 43.5
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 45.199997
|
||||
- Move:
|
||||
to:
|
||||
x: 271.5
|
||||
y: 46.699997
|
||||
- Move:
|
||||
to:
|
||||
x: 271.3
|
||||
y: 47.59999
|
||||
- Move:
|
||||
to:
|
||||
x: 271
|
||||
y: 48.199997
|
||||
- Move:
|
||||
to:
|
||||
x: 271
|
||||
y: 48.59999
|
||||
- Move:
|
||||
to:
|
||||
x: 271.09998
|
||||
y: 48.799988
|
||||
- Move:
|
||||
to:
|
||||
x: 271.3
|
||||
y: 48.799988
|
||||
- Move:
|
||||
to:
|
||||
x: 271.40002
|
||||
y: 48.899994
|
||||
- Move:
|
||||
to:
|
||||
x: 271.40002
|
||||
y: 49.09999
|
||||
- Move:
|
||||
to:
|
||||
x: 271.40002
|
||||
y: 49.5
|
||||
- Move:
|
||||
to:
|
||||
x: 271.40002
|
||||
y: 49.799988
|
||||
- Move:
|
||||
to:
|
||||
x: 271.40002
|
||||
y: 50
|
||||
- Move:
|
||||
to:
|
||||
x: 271.40002
|
||||
y: 50
|
||||
- Release
|
||||
@ -0,0 +1,7 @@
|
||||
---
|
||||
source: src/handwriting/mod.rs
|
||||
expression: serialized
|
||||
---
|
||||
```handwriting
|
||||
AQA9AJ9ZCFWfWQpVn1kVVaJZNVWoWWNVtVmVVcFZylXOWQBW3lk1VupZZVb2WZJWBlrFVhla+1YuWjJXSlpzV2VarVeCWuJXploRWMZaK1jjWj5YAVtMWB9bVlg/W15YX1tjWIJbZlikW2ZYwltkWN1bW1j2W09YBlxCWBJcNFgeXCVYKFwVWDJcBFg8XOpXRFzIV05coldXXIBXX1xaV2hcLldxXPtWeVzFVoFckFaIXGBWjlwzVpNcDlaYXPBVnFzSVZ9cuFWiXJ1VpFyAVadcZVWqXEtVq1w1VaxcIlWsXBJVrFwAVaxc8FSsXOVUrFzbVKxc1VQTAIpawEqKWvNKilrmS4pa4EyKWiBOilqGT4paZlCKWv1QilqKUYpa9lGKWjpSilpgUopafVKKWpBSilqgUoparVKKWrZSilq9Uopaw1IeAD5cDUs+XBpLPlxNSz5cs0s+XFNMPlwATT5c000+XKBOPlxTTz5cAFA+XEZQPlx6UD5cqlA+XM1QPlztUD5cEFE+XD1RPlxwUT5cplE+XNZRPVzzUTxcBlI8XBNSPFwaUj1cGlI+XB1SPlwjUj5cMFI+XDpSPlxAUg==
|
||||
```
|
||||
32
src/handwriting/tool/eraser.rs
Normal file
32
src/handwriting/tool/eraser.rs
Normal file
@ -0,0 +1,32 @@
|
||||
use crate::handwriting::{Handwriting, ToolEvent};
|
||||
use egui::Pos2;
|
||||
|
||||
pub const RADIUS: f32 = 12.0;
|
||||
|
||||
/// Handle a [ToolEvent]. Returns true if a stroke was completed.
|
||||
pub fn on_tool_event(handwriting: &mut Handwriting, tool_event: ToolEvent) -> bool {
|
||||
match tool_event {
|
||||
ToolEvent::Press { at } => {
|
||||
erase(handwriting, at, RADIUS)
|
||||
}
|
||||
ToolEvent::Move { to } => {
|
||||
erase(handwriting, to, RADIUS)
|
||||
}
|
||||
ToolEvent::Release => {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fn erase(handwriting: &mut Handwriting, at: Pos2, radius: f32) -> bool {
|
||||
let strokes = handwriting.strokes.len();
|
||||
|
||||
handwriting.strokes.retain(|stroke| {
|
||||
stroke.iter().all(|&point| {
|
||||
(point - at).length() > radius
|
||||
})
|
||||
});
|
||||
|
||||
handwriting.strokes.len() < strokes
|
||||
}
|
||||
28
src/handwriting/tool/mod.rs
Normal file
28
src/handwriting/tool/mod.rs
Normal file
@ -0,0 +1,28 @@
|
||||
pub mod pencil;
|
||||
pub mod eraser;
|
||||
|
||||
use egui::Pos2;
|
||||
use serde::Serialize;
|
||||
|
||||
pub enum Tool {
|
||||
Pencil,
|
||||
Eraser,
|
||||
}
|
||||
|
||||
/// A simple event that can defines how a tool (e.g. the pen) is used on a [Handwriting].
|
||||
#[derive(Debug, Serialize, Copy, Clone)]
|
||||
pub enum ToolEvent {
|
||||
Press { at: Pos2 },
|
||||
Move { to: Pos2 },
|
||||
Release,
|
||||
}
|
||||
|
||||
impl ToolEvent {
|
||||
pub const fn position(&self) -> Option<Pos2> {
|
||||
match self {
|
||||
&ToolEvent::Press { at } => Some(at),
|
||||
&ToolEvent::Move { to } => Some(to),
|
||||
ToolEvent::Release => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
22
src/handwriting/tool/pencil.rs
Normal file
22
src/handwriting/tool/pencil.rs
Normal file
@ -0,0 +1,22 @@
|
||||
use crate::handwriting::{Handwriting, ToolEvent};
|
||||
use std::mem;
|
||||
|
||||
/// Handle a [ToolEvent]. Returns true if a stroke was completed.
|
||||
pub fn on_tool_event(handwriting: &mut Handwriting, tool_event: ToolEvent) -> bool {
|
||||
match tool_event {
|
||||
ToolEvent::Press { at } => {
|
||||
debug_assert!(handwriting.e.current_stroke.is_empty());
|
||||
handwriting.push_to_stroke(at);
|
||||
false
|
||||
}
|
||||
ToolEvent::Move { to } => {
|
||||
handwriting.push_to_stroke(to);
|
||||
false
|
||||
}
|
||||
ToolEvent::Release => {
|
||||
debug_assert!(!handwriting.e.current_stroke.is_empty());
|
||||
handwriting.strokes.push(mem::take(&mut handwriting.e.current_stroke));
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,3 @@
|
||||
#![warn(clippy::all, rust_2018_idioms)]
|
||||
|
||||
pub mod app;
|
||||
pub mod constants;
|
||||
pub mod custom_code_block;
|
||||
@ -10,6 +8,7 @@ pub mod markdown;
|
||||
pub mod preferences;
|
||||
pub mod rasterizer;
|
||||
pub mod text_editor;
|
||||
pub mod text_styles;
|
||||
pub mod util;
|
||||
|
||||
pub use app::App;
|
||||
|
||||
@ -40,7 +40,7 @@ pub struct Style {
|
||||
pub raised: bool,
|
||||
}
|
||||
|
||||
pub enum MarkdownItem<'a> {
|
||||
pub enum Item<'a> {
|
||||
Text {
|
||||
span: Span<'a>,
|
||||
style: Style,
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
use egui::text::{CCursorRange, LayoutJob};
|
||||
|
||||
use crate::markdown::{
|
||||
span::Span,
|
||||
tokenizer::{Heading, Token, TokenKind, tokenize},
|
||||
use crate::{
|
||||
markdown::Heading,
|
||||
text_styles::{H1, H1_MONO, H2, H2_MONO, H3, H3_MONO, H4, H4_MONO, H5, H5_MONO, H6, H6_MONO},
|
||||
};
|
||||
|
||||
use super::{Item, Style, parse};
|
||||
|
||||
/// Highlight markdown, caching previous output to save CPU.
|
||||
#[derive(Default)]
|
||||
pub struct MemoizedHighlighter {
|
||||
@ -13,36 +15,6 @@ pub struct MemoizedHighlighter {
|
||||
output: LayoutJob,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Style {
|
||||
/// # heading (large text)
|
||||
pub heading: Option<Heading>,
|
||||
|
||||
/// > quoted (slightly dimmer color or other font style)
|
||||
pub quoted: bool,
|
||||
|
||||
/// `code` (monospace, some other color)
|
||||
pub code: bool,
|
||||
|
||||
/// self.strong* (emphasized, e.g. bold)
|
||||
pub strong: bool,
|
||||
|
||||
/// _underline_
|
||||
pub underline: bool,
|
||||
|
||||
/// ~strikethrough~
|
||||
pub strikethrough: bool,
|
||||
|
||||
/// /italics/
|
||||
pub italics: bool,
|
||||
|
||||
/// $small$
|
||||
pub small: bool,
|
||||
|
||||
/// ^raised^
|
||||
pub raised: bool,
|
||||
}
|
||||
|
||||
impl MemoizedHighlighter {
|
||||
pub fn highlight(
|
||||
&mut self,
|
||||
@ -67,189 +39,87 @@ pub fn highlight_markdown(
|
||||
_cursor: Option<CCursorRange>,
|
||||
) -> LayoutJob {
|
||||
let mut job = LayoutJob::default();
|
||||
let mut style = Style::default();
|
||||
let code_style = Style {
|
||||
code: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut prev = TokenKind::Newline;
|
||||
|
||||
let tokens: Vec<_> = tokenize(text).collect();
|
||||
let mut tokens = &tokens[..];
|
||||
|
||||
const CODE_INDENT: f32 = 10.0;
|
||||
|
||||
while !tokens.is_empty() {
|
||||
let token = tokens.first().unwrap();
|
||||
tokens = &tokens[1..];
|
||||
|
||||
let start_of_line = prev == TokenKind::Newline;
|
||||
prev = token.kind;
|
||||
|
||||
let mut basic_style: Option<fn(&mut Style) -> &mut bool> = None;
|
||||
|
||||
match token.kind {
|
||||
TokenKind::CodeBlock if start_of_line => {
|
||||
let span = collect_until(
|
||||
token,
|
||||
&mut tokens,
|
||||
series([TokenKind::Newline, TokenKind::CodeBlock]),
|
||||
);
|
||||
|
||||
let code_style = format_from_style(
|
||||
egui_style,
|
||||
&Style {
|
||||
code: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
job.append(&*span, CODE_INDENT, code_style.clone());
|
||||
style = Default::default();
|
||||
continue;
|
||||
for item in parse(text) {
|
||||
match item {
|
||||
Item::Text { span, style } => {
|
||||
job.append(&span, 0.0, format_from_style(egui_style, &style));
|
||||
}
|
||||
|
||||
TokenKind::Newline => style = Style::default(),
|
||||
|
||||
TokenKind::Strong => basic_style = Some(|s| &mut s.strong),
|
||||
TokenKind::Italic => basic_style = Some(|s| &mut s.italics),
|
||||
TokenKind::Strikethrough => basic_style = Some(|s| &mut s.strikethrough),
|
||||
|
||||
TokenKind::CodeBlock | TokenKind::Mono => {
|
||||
style.code = true;
|
||||
let span = collect_until(
|
||||
token,
|
||||
&mut tokens,
|
||||
any_of([TokenKind::Mono, TokenKind::CodeBlock, TokenKind::Newline]),
|
||||
);
|
||||
job.append(&*span, 0.0, format_from_style(egui_style, &style));
|
||||
style.code = false;
|
||||
continue;
|
||||
Item::CodeBlock {
|
||||
all,
|
||||
language: _, // TODO
|
||||
code: _, // TODO
|
||||
} => {
|
||||
job.append(&all, 100.0, format_from_style(egui_style, &code_style));
|
||||
}
|
||||
|
||||
// TODO: different heading strengths
|
||||
TokenKind::Heading(h) if start_of_line => style.heading = Some(h),
|
||||
TokenKind::Quote if start_of_line => style.quoted = true,
|
||||
|
||||
// TODO: indented list entries
|
||||
TokenKind::ListEntry if start_of_line => {
|
||||
job.append("• ", 0.0, format_from_style(egui_style, &style));
|
||||
continue;
|
||||
}
|
||||
|
||||
TokenKind::Text
|
||||
// the following tokens are only richly rendered if encountered e.g. at start_of_line.
|
||||
| TokenKind::Indentation
|
||||
| TokenKind::ListEntry
|
||||
| TokenKind::Heading(..)
|
||||
| TokenKind::Quote => {}
|
||||
}
|
||||
|
||||
// if we encountered a marker for Bold, Italic, or Strikethrough, toggle that style and
|
||||
// render the token with the style enabled.
|
||||
if let Some(basic_style) = basic_style {
|
||||
let mut tmp_style = style;
|
||||
*basic_style(&mut tmp_style) = true;
|
||||
*basic_style(&mut style) ^= true; // toggle
|
||||
job.append(&token.span, 0.0, format_from_style(egui_style, &tmp_style));
|
||||
continue;
|
||||
}
|
||||
|
||||
job.append(&token.span, 0.0, format_from_style(egui_style, &style));
|
||||
}
|
||||
|
||||
job
|
||||
}
|
||||
|
||||
fn series<'a, const N: usize>(of: [TokenKind; N]) -> impl FnMut(&[Token<'a>; N]) -> bool {
|
||||
move |token| {
|
||||
of.iter()
|
||||
.zip(token)
|
||||
.all(|(kind, token)| kind == &token.kind)
|
||||
}
|
||||
}
|
||||
|
||||
fn any_of<'a, const N: usize>(these: [TokenKind; N]) -> impl FnMut(&[Token<'a>; 1]) -> bool {
|
||||
move |[token]| these.contains(&token.kind)
|
||||
}
|
||||
|
||||
/// Collect all tokens up to and including `pattern`, and merge them into a signle span.
|
||||
///
|
||||
/// `N` determines how many specific and consecutive tokens we are looking for.
|
||||
/// i.e. if we were looking for a [TokenKind::Newline] followed by a [TokenKind::Quote], `N`
|
||||
/// would equal `2`.
|
||||
///
|
||||
/// `pattern` is a function that accepts an array of `N` tokens and returns `true` if they match,
|
||||
/// i.e. if we should stop collecting. [any_of] and [series] can help to construct this function.
|
||||
///
|
||||
/// The collected tokens will be split off the head of the slice referred to by `tokens`.
|
||||
///
|
||||
/// # Panic
|
||||
/// Panics if `tokens` does not contain only consecutive adjacent spans.
|
||||
fn collect_until<'a, const N: usize>(
|
||||
token: &Token<'a>,
|
||||
tokens: &mut &[Token<'a>],
|
||||
pattern: impl FnMut(&[Token<'a>; N]) -> bool,
|
||||
) -> Span<'a>
|
||||
where
|
||||
for<'b> &'b [Token<'a>; N]: TryFrom<&'b [Token<'a>]>,
|
||||
{
|
||||
let mut windows = tokens
|
||||
.windows(N)
|
||||
.map(|slice| <&[Token<'a>; N]>::try_from(slice).ok().unwrap());
|
||||
|
||||
let split_at = match windows.position(pattern) {
|
||||
Some(i) => i + N,
|
||||
None => tokens.len(), // consume everything
|
||||
};
|
||||
|
||||
let (consume, keep) = tokens.split_at(split_at);
|
||||
*tokens = keep;
|
||||
|
||||
consume
|
||||
.iter()
|
||||
.fold(token.span.clone(), |span: Span<'_>, token| {
|
||||
span.try_merge(&token.span).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
fn format_from_style(egui_style: &egui::Style, emark_style: &Style) -> egui::text::TextFormat {
|
||||
fn format_from_style(egui_style: &egui::Style, style: &Style) -> egui::text::TextFormat {
|
||||
use egui::{Align, Color32, Stroke, TextStyle};
|
||||
|
||||
let color = if emark_style.strong || emark_style.heading.is_some() {
|
||||
let color = if style.code {
|
||||
egui_style.visuals.strong_text_color() * Color32::GREEN
|
||||
} else if style.strong || style.heading.is_some() {
|
||||
egui_style.visuals.strong_text_color()
|
||||
} else if emark_style.quoted {
|
||||
} else if style.quoted {
|
||||
egui_style.visuals.weak_text_color()
|
||||
} else {
|
||||
egui_style.visuals.text_color()
|
||||
};
|
||||
|
||||
let text_style = if emark_style.heading.is_some() {
|
||||
TextStyle::Heading
|
||||
} else if emark_style.code {
|
||||
let text_style = if let Some(heading) = style.heading {
|
||||
let text_style = match (heading, style.code) {
|
||||
(Heading::H1, false) => H1,
|
||||
(Heading::H2, false) => H2,
|
||||
(Heading::H3, false) => H3,
|
||||
(Heading::H4, false) => H4,
|
||||
(Heading::H5, false) => H5,
|
||||
(Heading::H6, false) => H6,
|
||||
|
||||
(Heading::H1, true) => H1_MONO,
|
||||
(Heading::H2, true) => H2_MONO,
|
||||
(Heading::H3, true) => H3_MONO,
|
||||
(Heading::H4, true) => H4_MONO,
|
||||
(Heading::H5, true) => H5_MONO,
|
||||
(Heading::H6, true) => H6_MONO,
|
||||
};
|
||||
|
||||
TextStyle::Name(text_style.into())
|
||||
} else if style.code {
|
||||
TextStyle::Monospace
|
||||
} else if emark_style.small | emark_style.raised {
|
||||
} else if style.small | style.raised {
|
||||
TextStyle::Small
|
||||
} else {
|
||||
TextStyle::Body
|
||||
};
|
||||
|
||||
let background = if emark_style.code {
|
||||
let background = if style.code {
|
||||
egui_style.visuals.code_bg_color
|
||||
} else {
|
||||
Color32::TRANSPARENT
|
||||
};
|
||||
|
||||
let underline = if emark_style.underline {
|
||||
let underline = if style.underline {
|
||||
Stroke::new(1.0, color)
|
||||
} else {
|
||||
Stroke::NONE
|
||||
};
|
||||
|
||||
let strikethrough = if emark_style.strikethrough {
|
||||
let strikethrough = if style.strikethrough {
|
||||
Stroke::new(1.0, color)
|
||||
} else {
|
||||
Stroke::NONE
|
||||
};
|
||||
|
||||
let valign = if emark_style.raised {
|
||||
let valign = if style.raised {
|
||||
Align::TOP
|
||||
} else {
|
||||
Align::BOTTOM
|
||||
@ -259,7 +129,7 @@ fn format_from_style(egui_style: &egui::Style, emark_style: &Style) -> egui::tex
|
||||
font_id: text_style.resolve(egui_style),
|
||||
color,
|
||||
background,
|
||||
italics: emark_style.italics,
|
||||
italics: style.italics,
|
||||
underline,
|
||||
strikethrough,
|
||||
valign,
|
||||
|
||||
@ -1,7 +1,11 @@
|
||||
mod ast;
|
||||
mod highlighter;
|
||||
mod parser;
|
||||
mod span;
|
||||
mod tokenizer;
|
||||
|
||||
pub use ast::*;
|
||||
pub use highlighter::*;
|
||||
pub use parser::*;
|
||||
pub use span::*;
|
||||
pub use tokenizer::*;
|
||||
|
||||
170
src/markdown/parser.rs
Normal file
170
src/markdown/parser.rs
Normal file
@ -0,0 +1,170 @@
|
||||
use std::iter::{self, once};
|
||||
|
||||
use crate::markdown::Style;
|
||||
|
||||
use super::{Item, Span, Token, TokenKind, tokenize};
|
||||
|
||||
pub fn parse(text: &str) -> Vec<Item<'_>> {
|
||||
let tokens: Vec<_> = tokenize(text).collect();
|
||||
parse_tokens(&tokens)
|
||||
}
|
||||
|
||||
pub fn parse_tokens<'a>(mut tokens: &[Token<'a>]) -> Vec<Item<'a>> {
|
||||
// pretend that the first token was preceeded by a newline.
|
||||
// means we don't have to handle the first token as a special case.
|
||||
let mut prev = TokenKind::Newline;
|
||||
|
||||
let mut style = Style::default();
|
||||
|
||||
iter::from_fn(move || {
|
||||
if tokens.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let token = tokens.first().unwrap();
|
||||
tokens = &tokens[1..];
|
||||
|
||||
let start_of_line = prev == TokenKind::Newline;
|
||||
prev = token.kind;
|
||||
|
||||
let mut basic_style: Option<fn(&mut Style) -> &mut bool> = None;
|
||||
|
||||
match token.kind {
|
||||
TokenKind::CodeBlock if start_of_line => {
|
||||
let language = collect_until(
|
||||
None,
|
||||
&mut tokens,
|
||||
any_of([TokenKind::Newline]),
|
||||
);
|
||||
|
||||
let code = collect_until(
|
||||
None,
|
||||
&mut tokens,
|
||||
series([TokenKind::Newline, TokenKind::CodeBlock]),
|
||||
);
|
||||
|
||||
let all = [
|
||||
&token.span,
|
||||
&language,
|
||||
&code,
|
||||
].into_iter().fold(Span::empty(), |a, b| a.try_merge(b).unwrap());
|
||||
|
||||
let language = language.trim_end_matches("\n");
|
||||
let code = code.trim_end_matches("\n```");
|
||||
|
||||
return Some(Item::CodeBlock { all, language, code });
|
||||
}
|
||||
|
||||
TokenKind::Newline => style = Style::default(),
|
||||
|
||||
TokenKind::Strong => basic_style = Some(|s| &mut s.strong),
|
||||
TokenKind::Italic => basic_style = Some(|s| &mut s.italics),
|
||||
TokenKind::Strikethrough => basic_style = Some(|s| &mut s.strikethrough),
|
||||
|
||||
TokenKind::CodeBlock | TokenKind::Mono => {
|
||||
let span = collect_until(
|
||||
Some(token),
|
||||
&mut tokens,
|
||||
any_of([TokenKind::Mono, TokenKind::CodeBlock, TokenKind::Newline]),
|
||||
);
|
||||
|
||||
let mut style = style;
|
||||
style.code = true;
|
||||
|
||||
return Some(Item::Text { span, style });
|
||||
}
|
||||
|
||||
// TODO: different heading strengths
|
||||
TokenKind::Heading(h) if start_of_line => style.heading = Some(h),
|
||||
TokenKind::Quote if start_of_line => style.quoted = true,
|
||||
|
||||
// TODO: replace dashes with dots
|
||||
//// TODO: indented list entries
|
||||
//TokenKind::ListEntry if start_of_line => {
|
||||
// job.append("• ", 0.0, format_from_style(egui_style, &style));
|
||||
// continue;
|
||||
//}
|
||||
|
||||
TokenKind::Text
|
||||
// the following tokens are only richly rendered if encountered e.g. at start_of_line.
|
||||
| TokenKind::Indentation
|
||||
| TokenKind::ListEntry
|
||||
| TokenKind::Heading(..)
|
||||
| TokenKind::Quote => {}
|
||||
}
|
||||
|
||||
// if we encountered a marker for Bold, Italic, or Strikethrough, toggle that style and
|
||||
// render the token with the style enabled.
|
||||
if let Some(basic_style) = basic_style {
|
||||
let mut tmp_style = style;
|
||||
*basic_style(&mut tmp_style) = true;
|
||||
*basic_style(&mut style) ^= true; // toggle
|
||||
return Some(Item::Text {
|
||||
span: token.span.clone(),
|
||||
style: tmp_style,
|
||||
});
|
||||
}
|
||||
|
||||
Some(Item::Text {
|
||||
span: token.span.clone(),
|
||||
style,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn series<'a, const N: usize>(of: [TokenKind; N]) -> impl FnMut(&[Token<'a>; N]) -> bool {
|
||||
move |token| {
|
||||
of.iter()
|
||||
.zip(token)
|
||||
.all(|(kind, token)| kind == &token.kind)
|
||||
}
|
||||
}
|
||||
|
||||
fn any_of<'a, const N: usize>(these: [TokenKind; N]) -> impl FnMut(&[Token<'a>; 1]) -> bool {
|
||||
move |[token]| these.contains(&token.kind)
|
||||
}
|
||||
|
||||
/// Collect all tokens up to and including `pattern`, and merge them into a signle span.
|
||||
///
|
||||
/// `N` determines how many specific and consecutive tokens we are looking for.
|
||||
/// i.e. if we were looking for a [TokenKind::Newline] followed by a [TokenKind::Quote], `N`
|
||||
/// would equal `2`.
|
||||
///
|
||||
/// `pattern` is a function that accepts an array of `N` tokens and returns `true` if they match,
|
||||
/// i.e. if we should stop collecting. [any_of] and [series] can help to construct this function.
|
||||
///
|
||||
/// The collected tokens will be split off the head of the slice referred to by `tokens`.
|
||||
///
|
||||
/// # Panic
|
||||
/// Panics if `tokens` does not contain only consecutive adjacent spans.
|
||||
fn collect_until<'a, const N: usize>(
|
||||
first_token: Option<&Token<'a>>,
|
||||
tokens: &mut &[Token<'a>],
|
||||
pattern: impl FnMut(&[Token<'a>; N]) -> bool,
|
||||
) -> Span<'a>
|
||||
where
|
||||
// &[T; N]: TryFrom<&[T]>
|
||||
for<'b> &'b [Token<'a>; N]: TryFrom<&'b [Token<'a>]>,
|
||||
{
|
||||
let mut windows = tokens.windows(N).map(|slice| {
|
||||
<&[Token<'a>; N]>::try_from(slice)
|
||||
.ok()
|
||||
.expect("`windows` promises to return slices of length N")
|
||||
});
|
||||
|
||||
let split_at = match windows.position(pattern) {
|
||||
Some(i) => i + N,
|
||||
None => tokens.len(), // consume everything
|
||||
};
|
||||
|
||||
let (consume, keep) = tokens.split_at(split_at);
|
||||
*tokens = keep;
|
||||
|
||||
once(first_token)
|
||||
.flatten()
|
||||
.chain(consume)
|
||||
.fold(Span::empty(), |span: Span<'_>, token| {
|
||||
span.try_merge(&token.span).unwrap()
|
||||
})
|
||||
}
|
||||
@ -3,6 +3,8 @@ use std::{
|
||||
ops::{Deref, Range},
|
||||
};
|
||||
|
||||
use eyre::{bail, eyre};
|
||||
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
pub struct Span<'a> {
|
||||
complete_str: &'a str,
|
||||
@ -17,6 +19,13 @@ impl<'a> Span<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn empty() -> Self {
|
||||
Span {
|
||||
complete_str: "",
|
||||
range: 0..0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, slice: Range<usize>) -> Option<Self> {
|
||||
let start = self.range.start.checked_add(slice.start)?;
|
||||
let end = self.range.start.checked_add(slice.end)?;
|
||||
@ -41,26 +50,49 @@ impl<'a> Span<'a> {
|
||||
Some((head, tail))
|
||||
}
|
||||
|
||||
pub fn trim_end_matches(&self, p: &str) -> Self {
|
||||
if !self.ends_with(p) {
|
||||
return self.clone();
|
||||
}
|
||||
|
||||
Self {
|
||||
range: self.range.start..self.range.end - p.len(),
|
||||
complete_str: self.complete_str,
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to merge the spans.
|
||||
///
|
||||
/// If either spans is empty, this just returns the other one.
|
||||
/// This only works if spans are pointing into the same backing buffer, and are adjacent.
|
||||
pub fn try_merge(&self, other: &Self) -> Option<Self> {
|
||||
pub fn try_merge(&self, other: &Self) -> eyre::Result<Self> {
|
||||
if self.is_empty() {
|
||||
return Ok(other.clone());
|
||||
}
|
||||
|
||||
if other.is_empty() {
|
||||
return Ok(self.clone());
|
||||
}
|
||||
|
||||
if self.complete_str.as_ptr() != other.complete_str.as_ptr() {
|
||||
return None;
|
||||
bail!("Can't merge different strings");
|
||||
}
|
||||
|
||||
if self.range.end == other.range.start {
|
||||
Some(Self {
|
||||
Ok(Self {
|
||||
range: self.range.start..other.range.end,
|
||||
..*self
|
||||
})
|
||||
} else if self.range.start == other.range.end {
|
||||
Some(Self {
|
||||
Ok(Self {
|
||||
range: other.range.start..self.range.end,
|
||||
..*self
|
||||
})
|
||||
} else {
|
||||
None
|
||||
Err(eyre!("String: {:?}", self.complete_str)
|
||||
.wrap_err(eyre!("Span 2: {:?}", other.deref()))
|
||||
.wrap_err(eyre!("Span 1: {:?}", self.deref()))
|
||||
.wrap_err("Can't merge disjoint string spans"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,16 +1,6 @@
|
||||
use std::iter;
|
||||
|
||||
use super::span::Span;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Heading {
|
||||
H6,
|
||||
H5,
|
||||
H4,
|
||||
H3,
|
||||
H2,
|
||||
H1,
|
||||
}
|
||||
use super::{Heading, span::Span};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TokenKind {
|
||||
@ -41,7 +31,7 @@ pub enum TokenKind {
|
||||
Text,
|
||||
}
|
||||
|
||||
const TOKENS: &[(&'static str, TokenKind)] = &[
|
||||
const TOKENS: &[(&str, TokenKind)] = &[
|
||||
("\n", TokenKind::Newline),
|
||||
("######", TokenKind::Heading(Heading::H6)),
|
||||
("#####", TokenKind::Heading(Heading::H5)),
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
use egui::{Color32, Context, RichText, Theme, Ui, Visuals};
|
||||
use egui::{Color32, Context, RichText, Theme, Ui, Visuals, style::ScrollAnimation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@ -14,7 +14,7 @@ pub struct Preferences {
|
||||
pub hide_handwriting_cursor: bool,
|
||||
|
||||
#[serde(skip)]
|
||||
has_applied_theme: bool,
|
||||
has_applied_prefs: bool,
|
||||
}
|
||||
|
||||
impl Default for Preferences {
|
||||
@ -22,7 +22,7 @@ impl Default for Preferences {
|
||||
Self {
|
||||
animations: true,
|
||||
high_contrast: false,
|
||||
has_applied_theme: false,
|
||||
has_applied_prefs: false,
|
||||
hide_handwriting_cursor: false,
|
||||
}
|
||||
}
|
||||
@ -31,13 +31,30 @@ impl Default for Preferences {
|
||||
impl Preferences {
|
||||
/// Apply preferences, if they haven't already been applied.
|
||||
pub fn apply(&mut self, ctx: &Context) {
|
||||
if !self.has_applied_theme {
|
||||
self.has_applied_theme = true;
|
||||
if !self.has_applied_prefs {
|
||||
self.has_applied_prefs = true;
|
||||
|
||||
let scroll_animation = if self.animations {
|
||||
ScrollAnimation::default()
|
||||
} else {
|
||||
ScrollAnimation::none()
|
||||
};
|
||||
|
||||
for theme in [Theme::Dark, Theme::Light] {
|
||||
ctx.style_mut_of(theme, |style| {
|
||||
style.scroll_animation = scroll_animation;
|
||||
});
|
||||
}
|
||||
|
||||
let mut dark_visuals = Visuals::dark();
|
||||
let mut light_visuals = Visuals::light();
|
||||
|
||||
dark_visuals.code_bg_color = Color32::BLACK;
|
||||
dark_visuals.window_fill = Color32::from_rgb(0x1e, 0x1e, 0x1e);
|
||||
dark_visuals.panel_fill = Color32::from_rgb(0x26, 0x26, 0x26);
|
||||
|
||||
light_visuals.window_fill = Color32::WHITE;
|
||||
light_visuals.panel_fill = Color32::from_rgb(0xf6, 0xf6, 0xf6);
|
||||
|
||||
dark_visuals.code_bg_color = Color32::BLACK;
|
||||
light_visuals.code_bg_color = Color32::WHITE;
|
||||
|
||||
@ -71,11 +88,15 @@ impl Preferences {
|
||||
pub fn show(&mut self, ui: &mut Ui) {
|
||||
ui.label(RichText::new("Prefs").weak());
|
||||
|
||||
ui.toggle_value(&mut self.animations, "Animations");
|
||||
let animations_toggle = ui.toggle_value(&mut self.animations, "Animations");
|
||||
if animations_toggle.clicked() {
|
||||
self.has_applied_prefs = false;
|
||||
self.apply(ui.ctx());
|
||||
}
|
||||
|
||||
let high_contrast_toggle = ui.toggle_value(&mut self.high_contrast, "High Contrast");
|
||||
if high_contrast_toggle.clicked() {
|
||||
self.has_applied_theme = false;
|
||||
self.has_applied_prefs = false;
|
||||
self.apply(ui.ctx());
|
||||
}
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@ pub fn rasterize<'a, Blend: BlendFn>(
|
||||
point_to_pixel: TSTransform,
|
||||
triangles: impl Iterator<Item = [&'a Vertex; 3]>,
|
||||
) -> ColorImage {
|
||||
let mut image = ColorImage::new([width, height], Color32::TRANSPARENT);
|
||||
let mut image = ColorImage::filled([width, height], Color32::TRANSPARENT);
|
||||
rasterize_onto::<Blend>(&mut image, point_to_pixel, triangles);
|
||||
image
|
||||
}
|
||||
@ -90,10 +90,10 @@ pub fn rasterize_onto<'a, Blend: BlendFn>(
|
||||
/// Rasterize a single triangles onto an image,
|
||||
///
|
||||
/// Triangle positions must be in image-local point-coords.
|
||||
pub fn rasterize_triangle_onto<'a, Blend: BlendFn>(
|
||||
pub fn rasterize_triangle_onto<Blend: BlendFn>(
|
||||
image: &mut ColorImage,
|
||||
point_to_pixel: TSTransform,
|
||||
triangle: [&'a Vertex; 3],
|
||||
triangle: [&Vertex; 3],
|
||||
) {
|
||||
rasterize_onto::<Blend>(image, point_to_pixel, [triangle].into_iter());
|
||||
}
|
||||
@ -140,8 +140,7 @@ impl PxBoundingBox {
|
||||
}
|
||||
|
||||
pub fn is_disjoint_from(&self, other: &PxBoundingBox) -> bool {
|
||||
false
|
||||
|| self.x_from > other.x_to
|
||||
self.x_from > other.x_to
|
||||
|| self.y_from > other.y_to
|
||||
|| other.x_from > self.x_to
|
||||
|| other.y_from > self.y_to
|
||||
|
||||
14
src/text_styles.rs
Normal file
14
src/text_styles.rs
Normal file
@ -0,0 +1,14 @@
|
||||
//! Name of custom [egui::TextStyle]s
|
||||
|
||||
pub const H1: &str = "H1";
|
||||
pub const H2: &str = "H2";
|
||||
pub const H3: &str = "H3";
|
||||
pub const H4: &str = "H4";
|
||||
pub const H5: &str = "H5";
|
||||
pub const H6: &str = "H6";
|
||||
pub const H1_MONO: &str = "H1-mono";
|
||||
pub const H2_MONO: &str = "H2-mono";
|
||||
pub const H3_MONO: &str = "H3-mono";
|
||||
pub const H4_MONO: &str = "H4-mono";
|
||||
pub const H5_MONO: &str = "H5-mono";
|
||||
pub const H6_MONO: &str = "H6-mono";
|
||||
28
src/util.rs
28
src/util.rs
@ -1,6 +1,8 @@
|
||||
use std::sync::mpsc;
|
||||
use std::{fs::File, os::unix::fs::MetadataExt as _, sync::mpsc};
|
||||
|
||||
use chrono::{DateTime, Local};
|
||||
use egui::Id;
|
||||
use eyre::{Context, ContextCompat};
|
||||
use rand::{Rng, rng};
|
||||
|
||||
pub fn random_id() -> Id {
|
||||
@ -28,3 +30,27 @@ impl<T> GuiSender<T> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub fn log_error<T>(chain: eyre::Report, f: impl FnOnce() -> eyre::Result<T>) -> Option<T> {
|
||||
f().map_err(|e| e.wrap_err(chain))
|
||||
.inspect_err(|e| log::error!("{e}"))
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub fn file_mtime(file: &File) -> eyre::Result<DateTime<Local>> {
|
||||
(move || {
|
||||
let meta = file.metadata().wrap_err("Failed to stat file")?;
|
||||
|
||||
let sec = meta.mtime();
|
||||
let nsec = meta
|
||||
.mtime_nsec()
|
||||
.try_into()
|
||||
.wrap_err("Nanoseconds overflowed")?;
|
||||
|
||||
DateTime::from_timestamp(sec, nsec)
|
||||
.wrap_err("Bad timestamp")
|
||||
.map(Into::into)
|
||||
})()
|
||||
.wrap_err("Failed to get file mtime")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user