13 Commits

27 changed files with 1248 additions and 728 deletions

179
Cargo.lock generated
View File

@ -28,6 +28,22 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "accesskit"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e25ae84c0260bdf5df07796d7cc4882460de26a2b406ec0e6c42461a723b271b"
[[package]]
name = "accesskit_consumer"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bfae7c152994a31dc7d99b8eeac7784a919f71d1b306f4b83217e110fd3824c"
dependencies = [
"accesskit 0.19.0",
"hashbrown",
]
[[package]] [[package]]
name = "adler2" name = "adler2"
version = "2.0.0" version = "2.0.0"
@ -143,6 +159,12 @@ dependencies = [
"windows-sys 0.59.0", "windows-sys 0.59.0",
] ]
[[package]]
name = "anyhow"
version = "1.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487"
[[package]] [[package]]
name = "arboard" name = "arboard"
version = "3.5.0" version = "3.5.0"
@ -412,7 +434,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e"
dependencies = [ dependencies = [
"termcolor", "termcolor",
"unicode-width", "unicode-width 0.1.14",
] ]
[[package]] [[package]]
@ -421,6 +443,16 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
[[package]]
name = "colored"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
dependencies = [
"lazy_static",
"windows-sys 0.59.0",
]
[[package]] [[package]]
name = "combine" name = "combine"
version = "4.6.7" version = "4.6.7"
@ -511,6 +543,25 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "crossbeam-deque"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
dependencies = [
"crossbeam-utils",
]
[[package]] [[package]]
name = "crossbeam-utils" name = "crossbeam-utils"
version = "0.8.21" version = "0.8.21"
@ -535,6 +586,19 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c297a1c74b71ae29df00c3e22dd9534821d60eb9af5a0192823fa2acea70c2a" checksum = "5c297a1c74b71ae29df00c3e22dd9534821d60eb9af5a0192823fa2acea70c2a"
[[package]]
name = "dify"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11217d469eafa3b809ad84651eb9797ccbb440b4a916d5d85cb1b994e89787f6"
dependencies = [
"anyhow",
"colored",
"getopts",
"image",
"rayon",
]
[[package]] [[package]]
name = "dispatch" name = "dispatch"
version = "0.2.0" version = "0.2.0"
@ -638,6 +702,7 @@ dependencies = [
"objc2-foundation 0.2.2", "objc2-foundation 0.2.2",
"parking_lot", "parking_lot",
"percent-encoding", "percent-encoding",
"pollster",
"profiling", "profiling",
"raw-window-handle", "raw-window-handle",
"ron", "ron",
@ -647,6 +712,7 @@ dependencies = [
"wasm-bindgen-futures", "wasm-bindgen-futures",
"web-sys", "web-sys",
"web-time", "web-time",
"wgpu",
"winapi", "winapi",
"windows-sys 0.59.0", "windows-sys 0.59.0",
"winit", "winit",
@ -657,7 +723,7 @@ name = "egui"
version = "0.31.1" version = "0.31.1"
source = "git+https://github.com/emilk/egui?rev=f2ce6424f3a32f47308fb9871d540c01377b2cd9#f2ce6424f3a32f47308fb9871d540c01377b2cd9" source = "git+https://github.com/emilk/egui?rev=f2ce6424f3a32f47308fb9871d540c01377b2cd9#f2ce6424f3a32f47308fb9871d540c01377b2cd9"
dependencies = [ dependencies = [
"accesskit", "accesskit 0.18.0",
"ahash", "ahash",
"bitflags 2.9.0", "bitflags 2.9.0",
"emath", "emath",
@ -757,6 +823,27 @@ dependencies = [
"winit", "winit",
] ]
[[package]]
name = "egui_kittest"
version = "0.31.1"
source = "git+https://github.com/emilk/egui?rev=f2ce6424f3a32f47308fb9871d540c01377b2cd9#f2ce6424f3a32f47308fb9871d540c01377b2cd9"
dependencies = [
"dify",
"eframe",
"egui",
"egui-wgpu",
"image",
"kittest",
"pollster",
"wgpu",
]
[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]] [[package]]
name = "emath" name = "emath"
version = "0.31.1" version = "0.31.1"
@ -989,6 +1076,15 @@ dependencies = [
"windows-targets 0.48.5", "windows-targets 0.48.5",
] ]
[[package]]
name = "getopts"
version = "0.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba6ae63eb948698e300f645f87c70f76630d505f23b8907cf1e193ee85048c1"
dependencies = [
"unicode-width 0.2.1",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.2.16" version = "0.2.16"
@ -1144,6 +1240,18 @@ dependencies = [
"bitflags 2.9.0", "bitflags 2.9.0",
] ]
[[package]]
name = "gpu-allocator"
version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c151a2a5ef800297b4e79efa4f4bec035c5f51d5ae587287c9b952bdf734cacd"
dependencies = [
"log",
"presser",
"thiserror 1.0.69",
"windows",
]
[[package]] [[package]]
name = "gpu-descriptor" name = "gpu-descriptor"
version = "0.3.1" version = "0.3.1"
@ -1411,6 +1519,7 @@ dependencies = [
"egui", "egui",
"egui_extras", "egui_extras",
"egui_glow 0.31.1 (registry+https://github.com/rust-lang/crates.io-index)", "egui_glow 0.31.1 (registry+https://github.com/rust-lang/crates.io-index)",
"egui_kittest",
"env_logger", "env_logger",
"eyre", "eyre",
"getrandom 0.3.2", "getrandom 0.3.2",
@ -1532,6 +1641,16 @@ version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
[[package]]
name = "kittest"
version = "0.1.0"
source = "git+https://github.com/rerun-io/kittest?branch=main#91bf0fd98b5afe04427bb3aea4c68c6e0034b4bd"
dependencies = [
"accesskit 0.19.0",
"accesskit_consumer",
"parking_lot",
]
[[package]] [[package]]
name = "kurbo" name = "kurbo"
version = "0.9.5" version = "0.9.5"
@ -1541,6 +1660,12 @@ dependencies = [
"arrayvec", "arrayvec",
] ]
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.172" version = "0.2.172"
@ -2245,6 +2370,12 @@ dependencies = [
"windows-sys 0.59.0", "windows-sys 0.59.0",
] ]
[[package]]
name = "pollster"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
[[package]] [[package]]
name = "portable-atomic" name = "portable-atomic"
version = "1.11.0" version = "1.11.0"
@ -2269,6 +2400,12 @@ dependencies = [
"zerocopy 0.8.25", "zerocopy 0.8.25",
] ]
[[package]]
name = "presser"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
[[package]] [[package]]
name = "proc-macro-crate" name = "proc-macro-crate"
version = "3.3.0" version = "3.3.0"
@ -2361,12 +2498,38 @@ dependencies = [
"getrandom 0.3.2", "getrandom 0.3.2",
] ]
[[package]]
name = "range-alloc"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d6831663a5098ea164f89cff59c6284e95f4e3c76ce9848d4529f5ccca9bde"
[[package]] [[package]]
name = "raw-window-handle" name = "raw-window-handle"
version = "0.6.2" version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
[[package]]
name = "rayon"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]] [[package]]
name = "rctree" name = "rctree"
version = "0.5.0" version = "0.5.0"
@ -2962,6 +3125,12 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]]
name = "unicode-width"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a1a07cc7db3810833284e8d372ccdc6da29741639ecc70c9ec107df0fa6154c"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.6" version = "0.2.6"
@ -3313,6 +3482,7 @@ dependencies = [
"document-features", "document-features",
"js-sys", "js-sys",
"log", "log",
"naga",
"parking_lot", "parking_lot",
"profiling", "profiling",
"raw-window-handle", "raw-window-handle",
@ -3360,13 +3530,16 @@ dependencies = [
"android_system_properties", "android_system_properties",
"arrayvec", "arrayvec",
"ash", "ash",
"bit-set",
"bitflags 2.9.0", "bitflags 2.9.0",
"block",
"bytemuck", "bytemuck",
"cfg_aliases", "cfg_aliases",
"core-graphics-types", "core-graphics-types",
"glow", "glow",
"glutin_wgl_sys", "glutin_wgl_sys",
"gpu-alloc", "gpu-alloc",
"gpu-allocator",
"gpu-descriptor", "gpu-descriptor",
"js-sys", "js-sys",
"khronos-egl", "khronos-egl",
@ -3381,6 +3554,7 @@ dependencies = [
"ordered-float", "ordered-float",
"parking_lot", "parking_lot",
"profiling", "profiling",
"range-alloc",
"raw-window-handle", "raw-window-handle",
"renderdoc-sys", "renderdoc-sys",
"rustc-hash", "rustc-hash",
@ -3390,6 +3564,7 @@ dependencies = [
"web-sys", "web-sys",
"wgpu-types", "wgpu-types",
"windows", "windows",
"windows-core",
] ]
[[package]] [[package]]

View File

@ -39,11 +39,13 @@ wasm-bindgen-futures = "0.4.50"
web-sys = "0.3.77" web-sys = "0.3.77"
[patch.crates-io] [patch.crates-io]
egui = { git = "https://github.com/emilk/egui", rev = "f2ce6424f3a32f47308fb9871d540c01377b2cd9" } egui = { git = "https://github.com/emilk/egui", rev = "f2ce6424f3a32f47308fb9871d540c01377b2cd9" }
eframe = { git = "https://github.com/emilk/egui", rev = "f2ce6424f3a32f47308fb9871d540c01377b2cd9" } eframe = { git = "https://github.com/emilk/egui", rev = "f2ce6424f3a32f47308fb9871d540c01377b2cd9" }
egui_kittest = { git = "https://github.com/emilk/egui", rev = "f2ce6424f3a32f47308fb9871d540c01377b2cd9" }
[dev-dependencies] [dev-dependencies]
insta = { version = "1.43.1", features = ["yaml"] } insta = { version = "1.43.1", features = ["yaml"] }
egui_kittest = { version = "0.31", features = ["wgpu", "snapshot"] }
# egui = { path = "../egui/crates/egui" } # egui = { path = "../egui/crates/egui" }
# eframe = { path = "../egui/crates/eframe" } # eframe = { path = "../egui/crates/eframe" }

View File

@ -8,8 +8,8 @@ use std::{
use crate::{file_editor::FileEditor, folder::Folder, preferences::Preferences, util::GuiSender}; use crate::{file_editor::FileEditor, folder::Folder, preferences::Preferences, util::GuiSender};
use egui::{ use egui::{
Align, Button, Color32, Context, FontData, FontDefinitions, Image, Key, Modifiers, Align, Button, Context, FontData, FontDefinitions, Image, Key, Modifiers, PointerButton,
PointerButton, RichText, ScrollArea, Stroke, Widget, include_image, RichText, ScrollArea, Widget, include_image,
}; };
#[derive(serde::Deserialize, serde::Serialize)] #[derive(serde::Deserialize, serde::Serialize)]
@ -182,12 +182,6 @@ impl App {
cc.egui_ctx.set_fonts(fonts); cc.egui_ctx.set_fonts(fonts);
cc.egui_ctx.style_mut(|style| {
// TODO: change color of text in TextEdit
style.visuals.widgets.noninteractive.fg_stroke =
Stroke::new(1.0, Color32::from_rgb(200, 200, 200));
});
// enable features on egui_extras to add more image types // enable features on egui_extras to add more image types
egui_extras::install_image_loaders(&cc.egui_ctx); egui_extras::install_image_loaders(&cc.egui_ctx);

View File

@ -1,243 +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.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()
}
}

View File

@ -1,346 +0,0 @@
//! A parser for `EasyMark`: a very simple markup language.
//!
//! WARNING: `EasyMark` is subject to change.
//
//! # `EasyMark` design goals:
//! 1. easy to parse
//! 2. easy to learn
//! 3. similar to markdown
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Item<'a> {
/// `\n`
// TODO(emilk): add Style here so empty heading still uses up the right amount of space.
Newline,
/// Text
Text(Style, &'a str),
/// title, url
Hyperlink(Style, &'a str, &'a str),
/// leading space before e.g. a [`Self::BulletPoint`].
Indentation(usize),
/// >
QuoteIndent,
/// - a point well made.
BulletPoint,
/// 1. numbered list. The string is the number(s).
NumberedPoint(&'a str),
/// ---
Separator,
/// language, code
CodeBlock(&'a str, &'a str),
}
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Style {
/// # heading (large text)
pub heading: bool,
/// > 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,
}
/// Parser for the `EasyMark` markup language.
pub struct Parser<'a> {
/// The remainder of the input text
s: &'a str,
/// Are we at the start of a line?
start_of_line: bool,
/// Current self.style. Reset after a newline.
style: Style,
}
impl<'a> Parser<'a> {
pub fn new(s: &'a str) -> Self {
Self {
s,
start_of_line: true,
style: Style::default(),
}
}
/// `1. `, `42. ` etc.
fn numbered_list(&mut self) -> Option<Item<'a>> {
let n_digits = self.s.chars().take_while(|c| c.is_ascii_digit()).count();
if n_digits > 0 && self.s.chars().skip(n_digits).take(2).eq(". ".chars()) {
let number = &self.s[..n_digits];
self.s = &self.s[(n_digits + 2)..];
self.start_of_line = false;
return Some(Item::NumberedPoint(number));
}
None
}
// ```{language}\n{code}```
fn code_block(&mut self) -> Option<Item<'a>> {
if let Some(language_start) = self.s.strip_prefix("```") {
if let Some(newline) = language_start.find('\n') {
let language = &language_start[..newline];
let code_start = &language_start[newline + 1..];
if let Some(end) = code_start.find("\n```") {
let code = &code_start[..end].trim();
self.s = &code_start[end + 4..];
self.start_of_line = false;
return Some(Item::CodeBlock(language, code));
} else {
self.s = "";
return Some(Item::CodeBlock(language, code_start));
}
}
}
None
}
// `code`
fn inline_code(&mut self) -> Option<Item<'a>> {
if let Some(rest) = self.s.strip_prefix('`') {
self.s = rest;
self.start_of_line = false;
self.style.code = true;
let rest_of_line = &self.s[..self.s.find('\n').unwrap_or(self.s.len())];
if let Some(end) = rest_of_line.find('`') {
let item = Item::Text(self.style, &self.s[..end]);
self.s = &self.s[end + 1..];
self.style.code = false;
return Some(item);
} else {
let end = rest_of_line.len();
let item = Item::Text(self.style, rest_of_line);
self.s = &self.s[end..];
self.style.code = false;
return Some(item);
}
}
None
}
/// `<url>` or `[link](url)`
fn url(&mut self) -> Option<Item<'a>> {
if self.s.starts_with('<') {
let this_line = &self.s[..self.s.find('\n').unwrap_or(self.s.len())];
if let Some(url_end) = this_line.find('>') {
let url = &self.s[1..url_end];
self.s = &self.s[url_end + 1..];
self.start_of_line = false;
return Some(Item::Hyperlink(self.style, url, url));
}
}
// [text](url)
if self.s.starts_with('[') {
let this_line = &self.s[..self.s.find('\n').unwrap_or(self.s.len())];
if let Some(bracket_end) = this_line.find(']') {
let text = &this_line[1..bracket_end];
if this_line[bracket_end + 1..].starts_with('(') {
if let Some(parens_end) = this_line[bracket_end + 2..].find(')') {
let parens_end = bracket_end + 2 + parens_end;
let url = &self.s[bracket_end + 2..parens_end];
self.s = &self.s[parens_end + 1..];
self.start_of_line = false;
return Some(Item::Hyperlink(self.style, text, url));
}
}
}
}
None
}
}
impl<'a> Iterator for Parser<'a> {
type Item = Item<'a>;
fn next(&mut self) -> Option<Self::Item> {
loop {
if self.s.is_empty() {
return None;
}
// \n
if self.s.starts_with('\n') {
self.s = &self.s[1..];
self.start_of_line = true;
self.style = Style::default();
return Some(Item::Newline);
}
// Ignore line break (continue on the same line)
if self.s.starts_with("\\\n") && self.s.len() >= 2 {
self.s = &self.s[2..];
self.start_of_line = false;
continue;
}
// \ escape (to show e.g. a backtick)
if self.s.starts_with('\\') && self.s.len() >= 2 {
let text = &self.s[1..2];
self.s = &self.s[2..];
self.start_of_line = false;
return Some(Item::Text(self.style, text));
}
if self.start_of_line {
// leading space (indentation)
if self.s.starts_with(' ') {
let length = self.s.find(|c| c != ' ').unwrap_or(self.s.len());
self.s = &self.s[length..];
self.start_of_line = true; // indentation doesn't count
return Some(Item::Indentation(length));
}
// # Heading
if let Some(after) = self.s.strip_prefix("# ") {
self.s = after;
self.start_of_line = false;
self.style.heading = true;
continue;
}
// > quote
if let Some(after) = self.s.strip_prefix("> ") {
self.s = after;
self.start_of_line = true; // quote indentation doesn't count
self.style.quoted = true;
return Some(Item::QuoteIndent);
}
// - bullet point
if self.s.starts_with("- ") {
self.s = &self.s[2..];
self.start_of_line = false;
return Some(Item::BulletPoint);
}
// `1. `, `42. ` etc.
if let Some(item) = self.numbered_list() {
return Some(item);
}
// --- separator
if let Some(after) = self.s.strip_prefix("---") {
self.s = after.trim_start_matches('-'); // remove extra dashes
self.s = self.s.strip_prefix('\n').unwrap_or(self.s); // remove trailing newline
self.start_of_line = false;
return Some(Item::Separator);
}
// ```{language}\n{code}```
if let Some(item) = self.code_block() {
return Some(item);
}
}
// `code`
if let Some(item) = self.inline_code() {
return Some(item);
}
if let Some(rest) = self.s.strip_prefix('*') {
self.s = rest;
self.start_of_line = false;
self.style.strong = !self.style.strong;
continue;
}
if let Some(rest) = self.s.strip_prefix('_') {
self.s = rest;
self.start_of_line = false;
self.style.underline = !self.style.underline;
continue;
}
if let Some(rest) = self.s.strip_prefix('~') {
self.s = rest;
self.start_of_line = false;
self.style.strikethrough = !self.style.strikethrough;
continue;
}
if let Some(rest) = self.s.strip_prefix('/') {
self.s = rest;
self.start_of_line = false;
self.style.italics = !self.style.italics;
continue;
}
if let Some(rest) = self.s.strip_prefix('$') {
self.s = rest;
self.start_of_line = false;
self.style.small = !self.style.small;
continue;
}
if let Some(rest) = self.s.strip_prefix('^') {
self.s = rest;
self.start_of_line = false;
self.style.raised = !self.style.raised;
continue;
}
// `<url>` or `[link](url)`
if let Some(item) = self.url() {
return Some(item);
}
// Swallow everything up to the next special character:
let end = self
.s
.find(&['*', '`', '~', '_', '/', '$', '^', '\\', '<', '[', '\n'][..])
.map_or_else(|| self.s.len(), |special| special.max(1));
let item = Item::Text(self.style, &self.s[..end]);
self.s = &self.s[end..];
self.start_of_line = false;
return Some(item);
}
}
}
#[test]
fn test_easy_mark_parser() {
let items: Vec<_> = Parser::new("~strikethrough `code`~").collect();
assert_eq!(
items,
vec![
Item::Text(
Style {
strikethrough: true,
..Default::default()
},
"strikethrough "
),
Item::Text(
Style {
code: true,
strikethrough: true,
..Default::default()
},
"code"
),
]
);
}

View File

@ -1,7 +0,0 @@
//! Experimental markup language
mod easy_mark_highlighter;
pub mod easy_mark_parser;
pub use easy_mark_highlighter::{MemoizedHighlighter, highlight_easymark};
pub use easy_mark_parser as parser;

View File

@ -151,6 +151,7 @@ impl FileEditor {
BufferItem::Handwriting(handwriting) => { BufferItem::Handwriting(handwriting) => {
let style = HandwritingStyle { let style = HandwritingStyle {
animate: preferences.animations, animate: preferences.animations,
hide_cursor: preferences.hide_handwriting_cursor,
..HandwritingStyle::from_theme(ui.ctx().theme()) ..HandwritingStyle::from_theme(ui.ctx().theme())
}; };
if handwriting.ui(&style, ui).changed { if handwriting.ui(&style, ui).changed {
@ -169,7 +170,7 @@ impl FileEditor {
dragger_rect.set_height(item_response.response.rect.height()); dragger_rect.set_height(item_response.response.rect.height());
// Controls for moving the buffer item // Controls for moving the buffer item
ui.allocate_new_ui( ui.scope_builder(
UiBuilder::new() UiBuilder::new()
.max_rect(dragger_rect) .max_rect(dragger_rect)
.layout(Layout::top_down(Align::Center)), .layout(Layout::top_down(Align::Center)),

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,176 @@
use std::sync::Arc;
use egui::{
Color32, ColorImage, CornerRadius, Painter, Pos2, Rect, Stroke, StrokeKind, TextureHandle,
Vec2,
ahash::HashMap,
emath::TSTransform,
epaint::{Brush, RectShape, Vertex},
load::SizedTexture,
};
use crate::rasterizer::{PxBoundingBox, rasterize_triangle_onto, triangle_bounding_box};
use super::StrokeBlendMode;
const CHUNK_SIZE: usize = 64;
/// Rasterize onto a resizeable canvas.
#[derive(Default)]
pub struct CanvasRasterizer {
image_size: [usize; 2],
tiles: HashMap<[usize; 2], Tile>,
}
struct Tile {
bounding_box: PxBoundingBox,
image: ColorImage,
texture: Option<TextureHandle>,
texture_is_dirty: bool,
}
impl Tile {
fn new(xi: usize, yi: usize) -> Self {
let x_from = xi * CHUNK_SIZE;
let y_from = yi * CHUNK_SIZE;
let bounding_box = PxBoundingBox {
x_from,
y_from,
x_to: x_from + CHUNK_SIZE,
y_to: y_from + CHUNK_SIZE,
};
Self {
bounding_box,
image: ColorImage::new([CHUNK_SIZE, CHUNK_SIZE], Color32::TRANSPARENT),
texture: None,
texture_is_dirty: false,
}
}
}
impl CanvasRasterizer {
pub fn set_size(&mut self, width: usize, height: usize) {
self.image_size = [width, height];
self.populate_tiles();
}
pub fn clear(&mut self) {
log::debug!("clearing all tiles");
self.tiles.clear();
self.populate_tiles();
}
fn populate_tiles(&mut self) {
let [width, height] = self.image_size;
// discard tiles that are out of bounds
self.tiles.retain(|_, tile| {
tile.bounding_box.x_from <= width && tile.bounding_box.y_from <= height
});
let chunk = |max: usize| {
(0..)
.step_by(CHUNK_SIZE)
.take_while(move |n| n <= &max)
.enumerate()
};
// create new tiles where we need them
for (xi, _x) in chunk(width) {
for (yi, _y) in chunk(height) {
self.tiles
.entry([xi, yi])
.or_insert_with(|| Tile::new(xi, yi));
}
}
}
pub fn rasterize<'a>(
&mut self,
point_to_pixel: TSTransform,
triangles: impl Iterator<Item = [&'a Vertex; 3]> + Clone,
) {
for triangle in triangles {
let triangle_bounding_box = triangle_bounding_box(&triangle, point_to_pixel);
for chunk in chunks_from_bounding_box(triangle_bounding_box) {
let Some(tile) = self.tiles.get_mut(&chunk) else {
continue;
};
let mut point_to_tile_pixel = point_to_pixel;
point_to_tile_pixel.translation -= Vec2::new(
tile.bounding_box.x_from as f32,
tile.bounding_box.y_from as f32,
);
tile.texture_is_dirty = true;
rasterize_triangle_onto::<StrokeBlendMode>(
&mut tile.image,
point_to_tile_pixel,
triangle,
);
}
}
}
/// `at` defines the location in screen-coordinates where the canvas should be drawn.
pub fn show(&mut self, ctx: &egui::Context, painter: &Painter, at: Rect) {
let pixels_per_point = ctx.pixels_per_point();
let chunk_vec = Vec2::splat(CHUNK_SIZE as f32) / pixels_per_point;
for ([xi, yi], tile) in &mut self.tiles {
if tile.texture_is_dirty {
tile.texture_is_dirty = false;
if let Some(texture) = &mut tile.texture {
texture.set(tile.image.clone(), Default::default());
} else {
tile.texture = Some(ctx.load_texture(
"handwriting",
tile.image.clone(),
Default::default(),
));
}
}
if let Some(texture) = &mut tile.texture {
let texture = SizedTexture::new(texture.id(), texture.size_vec2());
let shape = RectShape {
rect: Rect::from_min_size(
at.min + Vec2::new(*xi as f32, *yi as f32) * chunk_vec,
chunk_vec,
),
corner_radius: CornerRadius::ZERO,
fill: Color32::WHITE,
stroke: Stroke::NONE,
stroke_kind: StrokeKind::Inside,
round_to_pixels: None,
blur_width: 0.0,
brush: Some(Arc::new(Brush {
fill_texture_id: texture.id,
uv: Rect {
min: Pos2::ZERO,
max: Pos2::new(1.0, 1.0),
},
})),
};
painter.add(shape);
}
}
}
}
/// Get all chunk indices that overlaps with a PxBoundingBox.
fn chunks_from_bounding_box(
triangle_bounding_box: PxBoundingBox,
) -> impl Iterator<Item = [usize; 2]> {
let x_from_chunk = triangle_bounding_box.x_from / CHUNK_SIZE;
let y_from_chunk = triangle_bounding_box.y_from / CHUNK_SIZE;
let x_to_chunk = triangle_bounding_box.x_to.saturating_sub(1) / CHUNK_SIZE;
let y_to_chunk = triangle_bounding_box.y_to.saturating_sub(1) / CHUNK_SIZE;
let xs = x_from_chunk..=x_to_chunk;
let ys = y_from_chunk..=y_to_chunk;
ys.flat_map(move |yi| xs.clone().map(move |xi| [xi, yi]))
}

View File

@ -1,3 +1,6 @@
mod canvas_rasterizer;
mod disk_format;
use std::{ use std::{
fmt::{self, Display}, fmt::{self, Display},
iter, mem, iter, mem,
@ -6,27 +9,22 @@ use std::{
}; };
use base64::{Engine, prelude::BASE64_STANDARD}; use base64::{Engine, prelude::BASE64_STANDARD};
use canvas_rasterizer::CanvasRasterizer;
use disk_format::{DiskFormat, RawStroke, RawStrokeHeader, f16_le}; use disk_format::{DiskFormat, RawStroke, RawStrokeHeader, f16_le};
use egui::{ use egui::{
Color32, ColorImage, CornerRadius, Event, Frame, Id, Mesh, PointerButton, Pos2, Rect, Sense, Color32, Event, Frame, Id, Mesh, PointerButton, Pos2, Rect, Sense, Shape, Stroke, Theme, Ui,
Shape, Stroke, TextureHandle, Theme, Ui, Vec2, Vec2,
emath::{self, TSTransform}, emath::{self, TSTransform},
epaint::{Brush, RectShape, TessellationOptions, Tessellator, Vertex}, epaint::{TessellationOptions, Tessellator, Vertex},
load::SizedTexture,
}; };
use eyre::{Context, bail}; use eyre::{Context, bail};
use eyre::{OptionExt, eyre}; use eyre::{OptionExt, eyre};
use half::f16; use half::f16;
use zerocopy::{FromBytes, IntoBytes}; use zerocopy::{FromBytes, IntoBytes};
use crate::{ use crate::{custom_code_block::try_from_custom_code_block, rasterizer};
custom_code_block::try_from_custom_code_block,
rasterizer::{self, rasterize, rasterize_onto},
};
use crate::{custom_code_block::write_custom_code_block, util::random_id}; use crate::{custom_code_block::write_custom_code_block, util::random_id};
mod disk_format;
const HANDWRITING_MIN_HEIGHT: f32 = 100.0; const HANDWRITING_MIN_HEIGHT: f32 = 100.0;
const HANDWRITING_BOTTOM_PADDING: f32 = 80.0; const HANDWRITING_BOTTOM_PADDING: f32 = 80.0;
const HANDWRITING_MARGIN: f32 = 0.05; const HANDWRITING_MARGIN: f32 = 0.05;
@ -58,6 +56,7 @@ pub struct HandwritingStyle {
pub bg_line_stroke: Stroke, pub bg_line_stroke: Stroke,
pub bg_color: Color32, pub bg_color: Color32,
pub animate: bool, pub animate: bool,
pub hide_cursor: bool,
} }
#[derive(serde::Deserialize, serde::Serialize)] #[derive(serde::Deserialize, serde::Serialize)]
@ -76,6 +75,8 @@ pub struct Handwriting {
struct Ephemeral { struct Ephemeral {
id: Id, id: Id,
canvas_rasterizer: CanvasRasterizer,
/// The stroke that is currently being drawed. /// The stroke that is currently being drawed.
current_stroke: Vec<Pos2>, current_stroke: Vec<Pos2>,
@ -87,10 +88,6 @@ struct Ephemeral {
/// Tessellated mesh of all strokes /// Tessellated mesh of all strokes
mesh: Arc<Mesh>, mesh: Arc<Mesh>,
texture: Option<TextureHandle>,
image: ColorImage,
refresh_texture: bool, refresh_texture: bool,
/// Context of the last mesh render. /// Context of the last mesh render.
@ -109,45 +106,9 @@ struct MeshContext {
pub pixels_per_point: f32, pub pixels_per_point: f32,
/// Canvas size in points
pub size: Vec2,
pub stroke: Stroke, pub stroke: Stroke,
} }
/// Get [Painting::texture], initializing it if necessary.
macro_rules! texture {
($self_:expr, $ui:expr, $mesh_context:expr) => {{
let ui: &Ui = $ui;
let mesh_context: &MeshContext = $mesh_context;
let image_size = mesh_context.pixel_size();
let new_image = || {
let image = ColorImage::new(image_size, Color32::TRANSPARENT);
ui.ctx()
.load_texture("handwriting", image, Default::default())
};
let texture = $self_.texture.get_or_insert_with(new_image);
if texture.size() != image_size {
$self_.refresh_texture = true;
// TODO: don't redraw the entire mesh, just blit the old texture onto the new one
*texture = new_image()
};
texture
}};
}
impl MeshContext {
/// Calculate canvas size in pixels
pub fn pixel_size(&self) -> [usize; 2] {
let Vec2 { x, y } = self.size * self.pixels_per_point;
[x, y].map(|f| f.ceil() as usize)
}
}
impl Default for Handwriting { impl Default for Handwriting {
fn default() -> Self { fn default() -> Self {
Self { Self {
@ -163,11 +124,10 @@ impl Default for Ephemeral {
fn default() -> Self { fn default() -> Self {
Self { Self {
id: random_id(), id: random_id(),
canvas_rasterizer: Default::default(),
current_stroke: Default::default(), current_stroke: Default::default(),
tessellator: None, tessellator: None,
mesh: Default::default(), mesh: Default::default(),
texture: None,
image: ColorImage::new([0, 0], Color32::WHITE),
refresh_texture: true, refresh_texture: true,
last_mesh_ctx: None, last_mesh_ctx: None,
unblitted_lines: Default::default(), unblitted_lines: Default::default(),
@ -226,12 +186,11 @@ impl Handwriting {
} }
let desired_size = Vec2::new(ui.available_width(), self.height); let desired_size = Vec2::new(ui.available_width(), self.height);
let (response, painter) = ui.allocate_painter(desired_size, Sense::drag()); let (mut response, painter) = ui.allocate_painter(desired_size, Sense::drag());
let mut response = response if style.hide_cursor {
//.on_hover_cursor(CursorIcon::Crosshair) response = response.on_hover_and_drag_cursor(egui::CursorIcon::None);
//.on_hover_and_drag_cursor(CursorIcon::None) }
;
let size = response.rect.size(); let size = response.rect.size();
@ -400,7 +359,7 @@ impl Handwriting {
painter.add(shape); painter.add(shape);
}); });
// Get the dimensions of the image // Get the position and dimensions of the image
let mesh_rect = response let mesh_rect = response
.rect .rect
.with_max_y(response.rect.min.y + self.desired_height); .with_max_y(response.rect.min.y + self.desired_height);
@ -409,7 +368,6 @@ impl Handwriting {
let new_context = MeshContext { let new_context = MeshContext {
ui_theme: ui.ctx().theme(), ui_theme: ui.ctx().theme(),
pixels_per_point: ui.pixels_per_point(), pixels_per_point: ui.pixels_per_point(),
size: mesh_rect.size(),
stroke: style.stroke, stroke: style.stroke,
}; };
@ -418,40 +376,28 @@ impl Handwriting {
self.e.refresh_texture = true; self.e.refresh_texture = true;
} }
let [px_width, px_height] = {
let Vec2 { x, y } = mesh_rect.size() * new_context.pixels_per_point;
[x, y].map(|f| f.ceil() as usize)
};
self.e.canvas_rasterizer.set_size(px_width, px_height);
if self.e.refresh_texture { if self.e.refresh_texture {
// ...if we do, rasterize the entire texture from scratch // ...if we do, rasterize the entire texture from scratch
self.refresh_texture(style, new_context, ui); self.refresh_texture(style, new_context);
self.e.unblitted_lines.clear(); self.e.unblitted_lines.clear();
} else if !self.e.unblitted_lines.is_empty() { } else if !self.e.unblitted_lines.is_empty() {
// ...if we don't, we can get away with only rasterizing the *new* lines onto the // ...if we don't, we can get away with only rasterizing the *new* lines onto the
// existing texture. // existing texture.
for [from, to] in std::mem::take(&mut self.e.unblitted_lines) { for [from, to] in std::mem::take(&mut self.e.unblitted_lines) {
self.draw_line_to_texture(from, to, &new_context, ui); self.draw_line_to_texture(from, to, &new_context);
} }
self.e.unblitted_lines.clear(); self.e.unblitted_lines.clear();
} }
// Draw the texture // Draw the texture
if let Some(texture) = &self.e.texture { self.e.canvas_rasterizer.show(ui.ctx(), &painter, mesh_rect);
let texture = SizedTexture::new(texture.id(), texture.size_vec2());
let shape = RectShape {
rect: mesh_rect,
corner_radius: CornerRadius::ZERO,
fill: Color32::WHITE,
stroke: Stroke::NONE,
stroke_kind: egui::StrokeKind::Inside,
round_to_pixels: None,
blur_width: 0.0,
brush: Some(Arc::new(Brush {
fill_texture_id: texture.id,
uv: Rect {
min: Pos2::ZERO,
max: Pos2::new(1.0, 1.0),
},
})),
};
painter.add(shape);
}
response response
} }
@ -463,12 +409,7 @@ impl Handwriting {
} }
/// Tessellate and rasterize the strokes into a new texture. /// Tessellate and rasterize the strokes into a new texture.
fn refresh_texture( fn refresh_texture(&mut self, style: &HandwritingStyle, mesh_context: MeshContext) {
&mut self,
style: &HandwritingStyle,
mesh_context: MeshContext,
ui: &mut Ui,
) {
let Ephemeral { let Ephemeral {
current_stroke, current_stroke,
tessellator, tessellator,
@ -511,13 +452,13 @@ impl Handwriting {
// debug_assert!(vertex.pos.y.is_finite(), "{} must be finite", vertex.pos.y); // debug_assert!(vertex.pos.y.is_finite(), "{} must be finite", vertex.pos.y);
//} //}
let texture = texture!(self.e, ui, &mesh_context); let point_to_pixel = TSTransform::from_scaling(mesh_context.pixels_per_point);
let triangles = mesh_triangles(&self.e.mesh); let triangles = mesh_triangles(&self.e.mesh);
let [px_x, px_y] = mesh_context.pixel_size(); self.e.canvas_rasterizer.clear();
let point_to_pixel = TSTransform::from_scaling(mesh_context.pixels_per_point); self.e
self.e.image = rasterize::<StrokeBlendMode>(px_x, px_y, point_to_pixel, triangles); .canvas_rasterizer
texture.set(self.e.image.clone(), Default::default()); .rasterize(point_to_pixel, triangles);
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
{ {
@ -563,13 +504,7 @@ impl Handwriting {
} }
/// Draw a single line onto the existing texture. /// Draw a single line onto the existing texture.
fn draw_line_to_texture( fn draw_line_to_texture(&mut self, from: Pos2, to: Pos2, mesh_context: &MeshContext) {
&mut self,
from: Pos2,
to: Pos2,
mesh_context: &MeshContext,
ui: &mut Ui,
) {
// INVARIANT: if this function was called, then pixels_per_point is the same as last frame, // INVARIANT: if this function was called, then pixels_per_point is the same as last frame,
// so there's no need to create a new tessellator. // so there's no need to create a new tessellator.
let tessellator = self let tessellator = self
@ -581,15 +516,16 @@ impl Handwriting {
let line = egui::Shape::line_segment([from, to], mesh_context.stroke); let line = egui::Shape::line_segment([from, to], mesh_context.stroke);
tessellator.tessellate_shape(line, &mut mesh); tessellator.tessellate_shape(line, &mut mesh);
self.draw_mesh_to_texture(&mesh, mesh_context, ui); self.draw_mesh_to_texture(&mesh, mesh_context);
} }
/// Draw a single mesh onto the existing texture. /// Draw a single mesh onto the existing texture.
fn draw_mesh_to_texture(&mut self, mesh: &Mesh, mesh_context: &MeshContext, ui: &mut Ui) { fn draw_mesh_to_texture(&mut self, mesh: &Mesh, mesh_context: &MeshContext) {
let triangles = mesh_triangles(mesh); let triangles = mesh_triangles(mesh);
let point_to_pixel = TSTransform::from_scaling(mesh_context.pixels_per_point); let point_to_pixel = TSTransform::from_scaling(mesh_context.pixels_per_point);
rasterize_onto::<StrokeBlendMode>(&mut self.e.image, point_to_pixel, triangles); self.e
texture!(self.e, ui, mesh_context).set(self.e.image.clone(), Default::default()); .canvas_rasterizer
.rasterize(point_to_pixel, triangles);
} }
pub fn strokes(&self) -> &[Vec<Pos2>] { pub fn strokes(&self) -> &[Vec<Pos2>] {
@ -771,16 +707,19 @@ impl HandwritingStyle {
} }
HandwritingStyle { HandwritingStyle {
stroke: Stroke::new(1.6, stroke_color), stroke: Stroke::new(1.0, stroke_color),
bg_color, bg_color,
bg_line_stroke: Stroke::new(0.5, line_color), bg_line_stroke: Stroke::new(0.5, line_color),
animate: true, animate: true,
hide_cursor: false,
} }
} }
} }
fn mesh_triangles(mesh: &Mesh) -> impl Iterator<Item = [&Vertex; 3]> { fn mesh_triangles(mesh: &Mesh) -> impl Iterator<Item = [&Vertex; 3]> + Clone {
mesh.triangles() mesh.indices
.chunks_exact(3)
.map(|chunk| [chunk[0], chunk[1], chunk[2]])
.map(|indices| indices.map(|i| &mesh.vertices[i as usize])) .map(|indices| indices.map(|i| &mesh.vertices[i as usize]))
} }

View File

@ -0,0 +1,19 @@
---
source: src/handwriting/mod.rs
expression: deserialized.strokes
---
[
[
[-1.0 1.0],
[3.0 1.0],
[3.0 3.0],
[1.5 2.0],
[0.0 0.0],
],
[
[3.0 3.0],
[-1.0 1.0],
[0.0 0.0],
[3.0 1.0],
],
]

View File

@ -0,0 +1,19 @@
---
source: src/handwriting/mod.rs
expression: handwriting.strokes
---
[
[
[-1.0 1.0],
[3.0 1.0],
[3.0 3.0],
[1.5 2.0],
[0.0 0.0],
],
[
[3.0 3.0],
[-1.0 1.0],
[0.0 0.0],
[3.0 1.0],
],
]

View File

@ -0,0 +1,7 @@
---
source: src/handwriting/mod.rs
expression: serialized
---
```handwriting
AQAFAAC8ADwAQgA8AEIAQgA+AEAAAAAABAAAQgBCALwAPAAAAAAAQgA8
```

View File

@ -3,10 +3,10 @@
pub mod app; pub mod app;
pub mod constants; pub mod constants;
pub mod custom_code_block; pub mod custom_code_block;
pub mod easy_mark;
pub mod file_editor; pub mod file_editor;
pub mod folder; pub mod folder;
pub mod handwriting; pub mod handwriting;
pub mod markdown;
pub mod preferences; pub mod preferences;
pub mod rasterizer; pub mod rasterizer;
pub mod text_editor; pub mod text_editor;

54
src/markdown/ast.rs Normal file
View File

@ -0,0 +1,54 @@
use super::span::Span;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Heading {
H1,
H2,
H3,
H4,
H5,
H6,
}
#[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,
}
pub enum Item<'a> {
Text {
span: Span<'a>,
style: Style,
},
CodeBlock {
all: Span<'a>,
language: Span<'a>,
code: Span<'a>,
},
}

View File

@ -0,0 +1,10 @@
use std::str::FromStr;
grammar;
pub Term: i32 = {
<n:Num> => n,
"(" <t:Term> ")" => t,
};
Num: i32 = <s:r"[0-9]+"> => i32::from_str(s).unwrap();

118
src/markdown/highlighter.rs Normal file
View File

@ -0,0 +1,118 @@
use egui::text::{CCursorRange, LayoutJob};
use super::{Item, Style, parse};
/// Highlight markdown, caching previous output to save CPU.
#[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_markdown(egui_style, code, cursor);
}
self.output.clone()
}
}
pub fn highlight_markdown(
egui_style: &egui::Style,
text: &str,
// TODO: hide special characters where cursor isn't
_cursor: Option<CCursorRange>,
) -> LayoutJob {
let mut job = LayoutJob::default();
let code_style = Style {
code: true,
..Default::default()
};
for item in parse(text) {
match item {
Item::Text { span, style } => {
job.append(&span, 0.0, format_from_style(egui_style, &style));
}
Item::CodeBlock {
all,
language: _, // TODO
code: _, // TODO
} => {
job.append(&all, 100.0, format_from_style(egui_style, &code_style));
}
}
}
job
}
fn format_from_style(egui_style: &egui::Style, style: &Style) -> egui::text::TextFormat {
use egui::{Align, Color32, Stroke, TextStyle};
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 style.quoted {
egui_style.visuals.weak_text_color()
} else {
egui_style.visuals.text_color()
};
let text_style = if style.heading.is_some() {
TextStyle::Heading
} else if style.code {
TextStyle::Monospace
} else if style.small | style.raised {
TextStyle::Small
} else {
TextStyle::Body
};
let background = if style.code {
egui_style.visuals.code_bg_color
} else {
Color32::TRANSPARENT
};
let underline = if style.underline {
Stroke::new(1.0, color)
} else {
Stroke::NONE
};
let strikethrough = if style.strikethrough {
Stroke::new(1.0, color)
} else {
Stroke::NONE
};
let valign = if style.raised {
Align::TOP
} else {
Align::BOTTOM
};
egui::text::TextFormat {
font_id: text_style.resolve(egui_style),
color,
background,
italics: style.italics,
underline,
strikethrough,
valign,
..Default::default()
}
}

11
src/markdown/mod.rs Normal file
View File

@ -0,0 +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::*;

172
src/markdown/parser.rs Normal file
View File

@ -0,0 +1,172 @@
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();
let mono_style = Style {
code: true,
..Default::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]),
);
return Some(Item::Text { span, style: mono_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()
})
}

View File

@ -0,0 +1,46 @@
---
source: src/markdown/tokenizer.rs
expression: examples
---
- string: "just some normal text :D"
tokens:
- "Token { span: Span(0..24, \"just some normal text :D\"), kind: Text }"
- string: normal *bold* normal
tokens:
- "Token { span: Span(0..7, \"normal \"), kind: Text }"
- "Token { span: Span(7..8, \"*\"), kind: Strong }"
- "Token { span: Span(8..12, \"bold\"), kind: Text }"
- "Token { span: Span(12..13, \"*\"), kind: Strong }"
- "Token { span: Span(13..20, \" normal\"), kind: Text }"
- string: normal * maybe bold? * normal
tokens:
- "Token { span: Span(0..7, \"normal \"), kind: Text }"
- "Token { span: Span(7..8, \"*\"), kind: Strong }"
- "Token { span: Span(8..21, \" maybe bold? \"), kind: Text }"
- "Token { span: Span(21..22, \"*\"), kind: Strong }"
- "Token { span: Span(22..29, \" normal\"), kind: Text }"
- string: "```lang\ncode code code\n```"
tokens:
- "Token { span: Span(0..3, \"```\"), kind: CodeBlock }"
- "Token { span: Span(3..7, \"lang\"), kind: Text }"
- "Token { span: Span(7..8, \"\\n\"), kind: Newline }"
- "Token { span: Span(8..22, \"code code code\"), kind: Text }"
- "Token { span: Span(22..23, \"\\n\"), kind: Newline }"
- "Token { span: Span(23..26, \"```\"), kind: CodeBlock }"
- string: "*_``_*"
tokens:
- "Token { span: Span(0..1, \"*\"), kind: Strong }"
- "Token { span: Span(1..2, \"_\"), kind: Italic }"
- "Token { span: Span(2..3, \"`\"), kind: Mono }"
- "Token { span: Span(3..4, \"`\"), kind: Mono }"
- "Token { span: Span(4..5, \"_\"), kind: Italic }"
- "Token { span: Span(5..6, \"*\"), kind: Strong }"
- string: "*_`*_*_"
tokens:
- "Token { span: Span(0..1, \"*\"), kind: Strong }"
- "Token { span: Span(1..2, \"_\"), kind: Italic }"
- "Token { span: Span(2..3, \"`\"), kind: Mono }"
- "Token { span: Span(3..4, \"*\"), kind: Strong }"
- "Token { span: Span(4..5, \"_\"), kind: Italic }"
- "Token { span: Span(5..6, \"*\"), kind: Strong }"
- "Token { span: Span(6..7, \"_\"), kind: Italic }"

115
src/markdown/span.rs Normal file
View File

@ -0,0 +1,115 @@
use std::{
fmt,
ops::{Deref, Range},
};
use eyre::{bail, eyre};
#[derive(Clone, Eq, PartialEq)]
pub struct Span<'a> {
complete_str: &'a str,
range: Range<usize>,
}
impl<'a> Span<'a> {
pub fn new(complete_str: &'a str) -> Self {
Self {
complete_str,
range: 0..complete_str.len(),
}
}
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)?;
if end > self.range.end || end < start {
return None;
}
Some(Self {
complete_str: self.complete_str,
range: Range { start, end },
})
}
pub fn complete_str(&self) -> Self {
Self::new(self.complete_str)
}
pub fn split_at(&self, i: usize) -> Option<(Self, Self)> {
let head = self.get(0..i)?;
let tail = self.get(i..self.range.len())?;
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) -> 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() {
bail!("Can't merge different strings");
}
if self.range.end == other.range.start {
Ok(Self {
range: self.range.start..other.range.end,
..*self
})
} else if self.range.start == other.range.end {
Ok(Self {
range: other.range.start..self.range.end,
..*self
})
} else {
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"))
}
}
}
impl Deref for Span<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.complete_str[self.range.clone()]
}
}
impl<'a> fmt::Debug for Span<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Span")
.field(&self.range)
.field(&self.deref())
.finish()
}
}

146
src/markdown/tokenizer.rs Normal file
View File

@ -0,0 +1,146 @@
use std::iter;
use super::{Heading, span::Span};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TokenKind {
/// A newline that isn't a codeblock
Newline,
/// "#" to "######"
Heading(Heading),
/// A newline followed by three `
CodeBlock,
Mono,
Strong,
Italic,
Strikethrough,
/// ">"
Quote,
/// Two spaces
Indentation,
/// "- "
ListEntry,
/// Normal text
Text,
}
const TOKENS: &[(&'static str, TokenKind)] = &[
("\n", TokenKind::Newline),
("######", TokenKind::Heading(Heading::H6)),
("#####", TokenKind::Heading(Heading::H5)),
("####", TokenKind::Heading(Heading::H4)),
("###", TokenKind::Heading(Heading::H3)),
("##", TokenKind::Heading(Heading::H2)),
("#", TokenKind::Heading(Heading::H1)),
("```", TokenKind::CodeBlock),
("`", TokenKind::Mono),
("*", TokenKind::Strong),
("_", TokenKind::Italic),
("~", TokenKind::Strikethrough),
(">", TokenKind::Quote),
(" ", TokenKind::Indentation),
("- ", TokenKind::ListEntry),
];
#[derive(Debug)]
pub struct Token<'a> {
pub span: Span<'a>,
pub kind: TokenKind,
}
pub fn tokenize<'a>(s: &'a str) -> impl Iterator<Item = Token<'a>> {
let mut s = Span::new(s);
let mut yield_n: usize = 0;
iter::from_fn(move || {
loop {
if s.is_empty() {
return None;
}
if yield_n == s.len() {
let (token, rest) = s.split_at(s.len()).unwrap();
let token = Token {
span: token,
kind: TokenKind::Text,
};
s = rest;
return Some(token);
}
let token = TOKENS.iter().find_map(|(token_str, token_kind)| {
s[yield_n..]
.starts_with(token_str)
.then(|| (*token_kind, token_str.len()))
});
let Some((kind, len)) = token else {
yield_n += s[yield_n..].chars().next().unwrap_or('\0').len_utf8();
continue;
};
if yield_n > 0 {
let (token, rest) = s.split_at(yield_n).unwrap();
let token = Token {
span: token,
kind: TokenKind::Text,
};
s = rest;
yield_n = 0;
return Some(token);
}
let (token, rest) = s.split_at(len).unwrap();
let token = Token { span: token, kind };
s = rest;
return Some(token);
}
})
}
#[cfg(test)]
mod tests {
use serde::Serialize;
use super::tokenize;
#[test]
fn test_tokenize() {
let examples = [
"just some normal text :D",
"normal *bold* normal",
"normal * maybe bold? * normal",
"```lang\ncode code code\n```",
"*_``_*",
"*_`*_*_",
];
#[derive(Serialize)]
struct Result {
pub string: &'static str,
/// Debug-printed tokens
pub tokens: Vec<String>,
}
let examples = examples
.into_iter()
.map(|string| {
let tokens = tokenize(string)
.map(|tokens| format!("{tokens:?}"))
.collect::<Vec<_>>();
Result { string, tokens }
})
.collect::<Vec<_>>();
insta::assert_yaml_snapshot!(examples);
}
}

View File

@ -10,6 +10,9 @@ pub struct Preferences {
/// Enable high-contrast theme /// Enable high-contrast theme
pub high_contrast: bool, pub high_contrast: bool,
/// Hide the cursor when handwriting
pub hide_handwriting_cursor: bool,
#[serde(skip)] #[serde(skip)]
has_applied_theme: bool, has_applied_theme: bool,
} }
@ -20,6 +23,7 @@ impl Default for Preferences {
animations: true, animations: true,
high_contrast: false, high_contrast: false,
has_applied_theme: false, has_applied_theme: false,
hide_handwriting_cursor: false,
} }
} }
} }
@ -30,13 +34,18 @@ impl Preferences {
if !self.has_applied_theme { if !self.has_applied_theme {
self.has_applied_theme = true; self.has_applied_theme = true;
let mut dark_visuals = Visuals::dark();
let mut light_visuals = Visuals::light();
dark_visuals.code_bg_color = Color32::BLACK;
dark_visuals.code_bg_color = Color32::BLACK;
light_visuals.code_bg_color = Color32::WHITE;
if self.high_contrast { if self.high_contrast {
// widgets.active: color of headers in textedit // widgets.active: color of headers in textedit
// widgets.inactive: color of button labels // widgets.inactive: color of button labels
// widgets.hovered: color of hovered button labels // widgets.hovered: color of hovered button labels
// widgets.noninteractive: color of labels and normal textedit text // widgets.noninteractive: color of labels and normal textedit text
let mut dark_visuals = Visuals::dark();
let mut light_visuals = Visuals::light();
dark_visuals.widgets.noninteractive.fg_stroke.color = Color32::WHITE; dark_visuals.widgets.noninteractive.fg_stroke.color = Color32::WHITE;
dark_visuals.widgets.inactive.fg_stroke.color = Color32::WHITE; dark_visuals.widgets.inactive.fg_stroke.color = Color32::WHITE;
@ -45,13 +54,16 @@ impl Preferences {
light_visuals.widgets.noninteractive.fg_stroke.color = Color32::BLACK; light_visuals.widgets.noninteractive.fg_stroke.color = Color32::BLACK;
light_visuals.widgets.inactive.fg_stroke.color = Color32::BLACK; light_visuals.widgets.inactive.fg_stroke.color = Color32::BLACK;
light_visuals.widgets.hovered.fg_stroke.color = Color32::BLACK; light_visuals.widgets.hovered.fg_stroke.color = Color32::BLACK;
ctx.set_visuals_of(Theme::Dark, dark_visuals);
ctx.set_visuals_of(Theme::Light, light_visuals);
} else { } else {
ctx.set_visuals_of(Theme::Dark, Visuals::dark()); dark_visuals.widgets.noninteractive.fg_stroke.color =
ctx.set_visuals_of(Theme::Light, Visuals::light()); Color32::from_rgb(0xaa, 0xaa, 0xaa);
light_visuals.widgets.noninteractive.fg_stroke.color =
Color32::from_rgb(0x11, 0x11, 0x11);
} }
ctx.set_visuals_of(Theme::Dark, dark_visuals);
ctx.set_visuals_of(Theme::Light, light_visuals);
} }
} }
@ -67,6 +79,8 @@ impl Preferences {
self.apply(ui.ctx()); self.apply(ui.ctx());
} }
ui.toggle_value(&mut self.hide_handwriting_cursor, "Hide Handwriting Cursor");
egui::widgets::global_theme_preference_buttons(ui); egui::widgets::global_theme_preference_buttons(ui);
} }
} }

View File

@ -1,5 +1,6 @@
use core::f32; use core::f32;
use egui::{Color32, ColorImage, Pos2, Rect, Vec2, emath::TSTransform, epaint::Vertex}; use egui::{Color32, ColorImage, Pos2, Rect, Vec2, emath::TSTransform, epaint::Vertex};
use std::ops::Range;
pub trait BlendFn { pub trait BlendFn {
fn blend(a: Color32, b: Color32) -> Color32; fn blend(a: Color32, b: Color32) -> Color32;
@ -86,9 +87,20 @@ 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>(
image: &mut ColorImage,
point_to_pixel: TSTransform,
triangle: [&'a Vertex; 3],
) {
rasterize_onto::<Blend>(image, point_to_pixel, [triangle].into_iter());
}
/// A bounding box, measured in pixels. /// A bounding box, measured in pixels.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
struct PxBoundingBox { pub struct PxBoundingBox {
pub x_from: usize, pub x_from: usize,
pub y_from: usize, pub y_from: usize,
pub x_to: usize, pub x_to: usize,
@ -104,9 +116,42 @@ impl PxBoundingBox {
y_to: self.y_to.min(other.y_to), y_to: self.y_to.min(other.y_to),
} }
} }
pub fn union(&self, other: &PxBoundingBox) -> PxBoundingBox {
PxBoundingBox {
x_from: self.x_from.min(other.x_from),
y_from: self.y_from.min(other.y_from),
x_to: self.x_to.max(other.x_to),
y_to: self.y_to.max(other.y_to),
}
}
pub fn x_range(&self) -> Range<usize> {
self.x_from..self.x_to
}
pub fn y_range(&self) -> Range<usize> {
self.y_from..self.y_to
}
/// Test whether two boxes do NOT overlap
pub fn overlaps_with(&self, other: &PxBoundingBox) -> bool {
!self.is_disjoint_from(other)
}
pub fn is_disjoint_from(&self, other: &PxBoundingBox) -> bool {
false
|| self.x_from > other.x_to
|| self.y_from > other.y_to
|| other.x_from > self.x_to
|| other.y_from > self.y_to
}
} }
fn triangle_bounding_box(triangle: &[&Vertex; 3], point_to_pixel: TSTransform) -> PxBoundingBox { pub fn triangle_bounding_box(
triangle: &[&Vertex; 3],
point_to_pixel: TSTransform,
) -> PxBoundingBox {
// calculate bounding box in point coords // calculate bounding box in point coords
let mut rect = Rect::NOTHING; let mut rect = Rect::NOTHING;
for vertex in triangle { for vertex in triangle {

View File

@ -0,0 +1,43 @@
---
source: src/custom_code_block.rs
expression: list
---
[
Line(
"\n",
),
Line(
"# Hello world\n",
),
Line(
"## Subheader\n",
),
Line(
"- 1\n",
),
CodeBlock {
key: "foo",
content: " whatever\n some code\n Hi mom!",
span: "```foo\n whatever\n some code\n Hi mom!\n```",
},
Line(
" \n",
),
Line(
"\n",
),
CodeBlock {
key: "` # wrong number of ticks, but that's ok",
content: " ``` # indented ticks",
span: "```` # wrong number of ticks, but that's ok\n ``` # indented ticks\n```\n",
},
Line(
"\n",
),
Line(
"``` # no closing ticks\n",
),
Line(
" ",
),
]

View File

@ -0,0 +1,7 @@
---
source: src/painting.rs
expression: serialized
---
```handwriting
BQAAvAA8AEIAPABCAEIAPgBAAAAAAAQAAEIAQgC8ADwAAAAAAEIAPA==
```

View File

@ -8,7 +8,7 @@ use egui::{
Color32, InputState, Key, Modifiers, TextBuffer, TextEdit, Ui, Vec2, text::CCursorRange, Color32, InputState, Key, Modifiers, TextBuffer, TextEdit, Ui, Vec2, text::CCursorRange,
}; };
use crate::easy_mark::MemoizedHighlighter; use crate::markdown::MemoizedHighlighter;
#[derive(Default, serde::Deserialize, serde::Serialize)] #[derive(Default, serde::Deserialize, serde::Serialize)]
pub struct MdTextEdit { pub struct MdTextEdit {
@ -50,8 +50,8 @@ impl MdTextEdit {
let w = ui.available_width(); let w = ui.available_width();
let mut layouter = |ui: &egui::Ui, easymark: &dyn TextBuffer, _wrap_width: f32| { let mut layouter = |ui: &egui::Ui, markdown: &dyn TextBuffer, _wrap_width: f32| {
let mut layout_job = highlighter.highlight(ui.style(), easymark.as_str(), *cursor); let mut layout_job = highlighter.highlight(ui.style(), markdown.as_str(), *cursor);
layout_job.wrap.max_width = w - 10.0; layout_job.wrap.max_width = w - 10.0;
ui.fonts(|f| f.layout_job(layout_job)) ui.fonts(|f| f.layout_job(layout_job))
}; };