Compare commits
12 Commits
gui-testin
...
efbea10532
| Author | SHA1 | Date | |
|---|---|---|---|
| efbea10532 | |||
| 3669f54936 | |||
| 2fb9908329 | |||
| 0acab0413c | |||
| 8f16741705 | |||
| a663de3ca0 | |||
| 61575fbf65 | |||
|
579aace306
|
|||
| fe0b9d049e | |||
| c59febd924 | |||
|
276508713f
|
|||
| 3a2f058456 |
1959
Cargo.lock
generated
1959
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
22
Cargo.toml
22
Cargo.toml
@ -12,22 +12,25 @@ targets = ["x86_64-unknown-linux-gnu", "wasm32-unknown-unknown"]
|
|||||||
pinenote = []
|
pinenote = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
egui = "0.31"
|
egui = "0.32"
|
||||||
egui_extras = { version = "0.31", features = ["svg"] }
|
egui_extras = { version = "0.32", features = ["svg"] }
|
||||||
eframe = { version = "0.31", default-features = false, features = [
|
egui_glow = "0.32"
|
||||||
|
eframe = { version = "0.32", default-features = false, features = [
|
||||||
"glow", # alt: "wgpu".
|
"glow", # alt: "wgpu".
|
||||||
"persistence",
|
"persistence",
|
||||||
"wayland",
|
"wayland",
|
||||||
] }
|
] }
|
||||||
log = "0.4.27"
|
log = "0.4.27"
|
||||||
serde = { version = "1.0.219", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
egui_glow = "0.31.1"
|
|
||||||
rfd = { version = "0.15.3", default-features = false, features = ["gtk3"] }
|
rfd = { version = "0.15.3", default-features = false, features = ["gtk3"] }
|
||||||
rand = "0.9.1"
|
rand = "0.9.1"
|
||||||
eyre = "0.6.12"
|
eyre = "0.6.12"
|
||||||
half = "2.6.0"
|
half = "2.6.0"
|
||||||
zerocopy = { version = "0.8.25", features = ["derive", "std"] }
|
zerocopy = { version = "0.8.25", features = ["derive", "std"] }
|
||||||
base64 = "0.22.1"
|
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]
|
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||||
env_logger = "0.11.8"
|
env_logger = "0.11.8"
|
||||||
@ -39,15 +42,14 @@ 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 = { path = "../egui/crates/egui" }
|
||||||
eframe = { git = "https://github.com/emilk/egui", rev = "f2ce6424f3a32f47308fb9871d540c01377b2cd9" }
|
# eframe = { path = "../egui/crates/eframe" }
|
||||||
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" }
|
[lints.clippy]
|
||||||
# eframe = { path = "../egui/crates/eframe" }
|
unnecessary_lazy_evaluations = "allow"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
opt-level = 2 # fast and small wasm
|
opt-level = 2 # fast and small wasm
|
||||||
|
|||||||
120
src/app.rs
120
src/app.rs
@ -1,16 +1,24 @@
|
|||||||
use std::{
|
use std::{
|
||||||
fs,
|
fs,
|
||||||
|
io::Read,
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::{Arc, mpsc},
|
sync::{Arc, mpsc},
|
||||||
thread::JoinHandle,
|
thread::JoinHandle,
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{file_editor::FileEditor, folder::Folder, preferences::Preferences, util::GuiSender};
|
use crate::{
|
||||||
use egui::{
|
file_editor::{FileEditor, SaveStatus},
|
||||||
Align, Button, Context, FontData, FontDefinitions, Image, Key, Modifiers, PointerButton,
|
folder::Folder,
|
||||||
RichText, ScrollArea, Widget, include_image,
|
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, Image, Key, Modifiers,
|
||||||
|
PointerButton, RichText, ScrollArea, Theme, Widget, include_image,
|
||||||
|
};
|
||||||
|
use eyre::eyre;
|
||||||
|
|
||||||
#[derive(serde::Deserialize, serde::Serialize)]
|
#[derive(serde::Deserialize, serde::Serialize)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@ -40,7 +48,7 @@ pub struct Jobs {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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 ctx = ctx.clone();
|
||||||
let actions_tx = self.actions_tx.clone();
|
let actions_tx = self.actions_tx.clone();
|
||||||
self.handles.push(std::thread::spawn(move || {
|
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 {
|
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))))
|
.map(|(name, data)| (name.to_string(), Arc::new(FontData::from_static(data))))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
fonts.families.insert(
|
fonts
|
||||||
egui::FontFamily::Proportional,
|
.families
|
||||||
vec!["IosevkaAile-Regular".into()],
|
.insert(FontFamily::Proportional, vec!["IosevkaAile-Regular".into()]);
|
||||||
);
|
|
||||||
|
|
||||||
fonts
|
fonts
|
||||||
.families
|
.families
|
||||||
.insert(egui::FontFamily::Monospace, vec!["Iosevka-Thin".into()]);
|
.insert(FontFamily::Monospace, vec!["Iosevka-Thin".into()]);
|
||||||
|
|
||||||
cc.egui_ctx.set_fonts(fonts);
|
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
|
// 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);
|
||||||
|
|
||||||
@ -253,7 +295,7 @@ impl eframe::App for App {
|
|||||||
});
|
});
|
||||||
|
|
||||||
egui::TopBottomPanel::top("top_panel").show(ctx, |ui| {
|
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!
|
// NOTE: no File->Quit on web pages!
|
||||||
ui.menu_button("Menu ⚙", |ui| {
|
ui.menu_button("Menu ⚙", |ui| {
|
||||||
ui.label(RichText::new("Action").weak());
|
ui.label(RichText::new("Action").weak());
|
||||||
@ -268,11 +310,18 @@ impl eframe::App for App {
|
|||||||
self.jobs.start(ui.ctx(), move || {
|
self.jobs.start(ui.ctx(), move || {
|
||||||
let file_path = rfd::FileDialog::new().pick_file()?;
|
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}"))
|
.inspect_err(|e| log::error!("Failed to read {file_path:?}: {e}"))
|
||||||
.ok()?;
|
.ok()?;
|
||||||
|
|
||||||
let editor = FileEditor::from_file(file_path, &text);
|
let editor = FileEditor::from_file(file_path, &text, mtime);
|
||||||
Some(Action::OpenFile(editor))
|
Some(Action::OpenFile(editor))
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -364,8 +413,8 @@ impl eframe::App for App {
|
|||||||
let selected = self.open_tab_index == Some(i);
|
let selected = self.open_tab_index == Some(i);
|
||||||
let mut button = Button::new(tab.title()).selected(selected);
|
let mut button = Button::new(tab.title()).selected(selected);
|
||||||
|
|
||||||
if tab.is_dirty() {
|
if let Some(symbol) = tab.notice_symbol() {
|
||||||
button = button.right_text(RichText::new("*").strong())
|
button = button.right_text(RichText::new(symbol).strong())
|
||||||
}
|
}
|
||||||
|
|
||||||
let response = ui.add(button);
|
let response = ui.add(button);
|
||||||
@ -396,13 +445,22 @@ impl eframe::App for App {
|
|||||||
if let Some(file_path) = response.open_file {
|
if let Some(file_path) = response.open_file {
|
||||||
let file_path = file_path.to_owned();
|
let file_path = file_path.to_owned();
|
||||||
self.jobs.start(ui.ctx(), move || {
|
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| {
|
.inspect_err(|e| {
|
||||||
log::error!("Failed to read {file_path:?}: {e}")
|
log::error!("Failed to read {file_path:?}: {e}")
|
||||||
})
|
})
|
||||||
.ok()?;
|
.ok()?;
|
||||||
|
|
||||||
let editor = FileEditor::from_file(file_path, &text);
|
let editor = FileEditor::from_file(file_path, &text, mtime);
|
||||||
Some(Action::OpenFile(editor))
|
Some(Action::OpenFile(editor))
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -448,29 +506,13 @@ impl App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn save_active_tab(&mut self, ctx: &Context) {
|
fn save_active_tab(&mut self, ctx: &Context) {
|
||||||
let open_file = self
|
let open_tab = self
|
||||||
.open_tab_index
|
.open_tab_index
|
||||||
.and_then(|i| self.tabs.get_mut(i))
|
.and_then(|i| self.tabs.get_mut(i))
|
||||||
.map(|(id, tab)| match tab {
|
.map(|(_id, tab)| tab);
|
||||||
Tab::File(file_editor) => (*id, file_editor),
|
|
||||||
})
|
|
||||||
.and_then(|(_, file_editor)| {
|
|
||||||
file_editor
|
|
||||||
.path()
|
|
||||||
.map(ToOwned::to_owned)
|
|
||||||
.zip(Some(file_editor))
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Some((file_path, file_editor)) = open_file {
|
if let Some(open_tab) = open_tab {
|
||||||
file_editor.is_dirty = false;
|
open_tab.save(ctx, &mut self.jobs);
|
||||||
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
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,57 +1,116 @@
|
|||||||
use std::{
|
use std::{
|
||||||
cmp::Ordering,
|
cmp::Ordering,
|
||||||
fmt::{self, Display},
|
fmt::{self, Display},
|
||||||
|
fs::{self, File},
|
||||||
|
io::Write,
|
||||||
ops::{Div as _, Sub as _},
|
ops::{Div as _, Sub as _},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
|
sync::mpsc,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use chrono::{DateTime, Local};
|
||||||
use egui::{
|
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::{
|
use crate::{
|
||||||
|
app::Jobs,
|
||||||
custom_code_block::{MdItem, iter_lines_and_code_blocks},
|
custom_code_block::{MdItem, iter_lines_and_code_blocks},
|
||||||
handwriting::{self, Handwriting, HandwritingStyle},
|
handwriting::{self, Handwriting, HandwritingStyle},
|
||||||
preferences::Preferences,
|
preferences::Preferences,
|
||||||
text_editor::MdTextEdit,
|
text_editor::MdTextEdit,
|
||||||
|
util::{file_mtime, log_error},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(serde::Deserialize, serde::Serialize)]
|
#[derive(serde::Deserialize, serde::Serialize)]
|
||||||
pub struct FileEditor {
|
pub struct FileEditor {
|
||||||
title: String,
|
title: String,
|
||||||
pub path: Option<PathBuf>,
|
|
||||||
|
path: Option<PathBuf>,
|
||||||
pub buffer: Vec<BufferItem>,
|
pub buffer: Vec<BufferItem>,
|
||||||
|
|
||||||
/// Whether the file has been edited since it was laste saved to disk.
|
pub file_mtime: Option<DateTime<Local>>,
|
||||||
pub is_dirty: bool,
|
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)]
|
#[derive(serde::Deserialize, serde::Serialize)]
|
||||||
pub enum BufferItem {
|
pub enum BufferItem {
|
||||||
Text(MdTextEdit),
|
Text(Box<MdTextEdit>),
|
||||||
Handwriting(Box<Handwriting>),
|
Handwriting(Box<Handwriting>),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FileEditor {
|
impl FileEditor {
|
||||||
pub fn new(title: impl Into<String>) -> Self {
|
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 {
|
Self {
|
||||||
title: title.into(),
|
title: title.into(),
|
||||||
path: None,
|
path: None,
|
||||||
buffer,
|
buffer,
|
||||||
|
file_mtime: None,
|
||||||
|
buffer_mtime: Local::now(),
|
||||||
|
scroll_delta: 0.0,
|
||||||
is_dirty: false,
|
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
|
let file_title = file_path
|
||||||
.file_name()
|
.file_name()
|
||||||
.map(|name| name.to_string_lossy().to_string())
|
.map(|name| name.to_string_lossy().to_string())
|
||||||
.unwrap_or_else(|| String::from("untitled.md"));
|
.unwrap_or_else(|| String::from("untitled.md"));
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
title: file_title,
|
title: file_title,
|
||||||
path: Some(file_path),
|
path: Some(file_path),
|
||||||
|
file_mtime: Some(mtime),
|
||||||
|
buffer_mtime: mtime,
|
||||||
..FileEditor::from(contents)
|
..FileEditor::from(contents)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -64,12 +123,63 @@ impl FileEditor {
|
|||||||
self.path.as_deref()
|
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) {
|
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.vertical_centered_justified(|ui| {
|
||||||
ui.heading(&self.title);
|
ui.heading(&self.title);
|
||||||
|
|
||||||
const MAX_NOTE_WIDTH: f32 = 600.0;
|
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.horizontal(|ui| {
|
||||||
ui.label("new");
|
ui.label("new");
|
||||||
if ui.button(" text ").clicked() {
|
if ui.button(" text ").clicked() {
|
||||||
@ -81,9 +191,23 @@ impl FileEditor {
|
|||||||
self.buffer
|
self.buffer
|
||||||
.push(BufferItem::Handwriting(Default::default()));
|
.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| {
|
ui.horizontal(|ui| {
|
||||||
let side_padding = ui.available_width().sub(MAX_NOTE_WIDTH).max(0.0).div(2.0);
|
let side_padding = ui.available_width().sub(MAX_NOTE_WIDTH).max(0.0).div(2.0);
|
||||||
ui.add_space(side_padding);
|
ui.add_space(side_padding);
|
||||||
@ -94,6 +218,8 @@ impl FileEditor {
|
|||||||
ui.add_space(side_padding);
|
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;
|
let mut retain = true;
|
||||||
|
|
||||||
if is_dragging {
|
// Createa horizontal area to draw the buffer item. The three things drawn here are:
|
||||||
let (_, drop) = ui.dnd_drop_zone::<DraggingItem, _>(Frame::NONE, |ui| {
|
// - The controls that exist at the left-size of the buffer item, i.e. "up"/"down".
|
||||||
ui.set_min_size(vec2(ui.available_width(), drag_zone_height));
|
// - The buffer item.
|
||||||
});
|
// - The controls that exist at the right-size of the buffer item, i.e. "delete".
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
// We don't know how tall the buffer item will be, so we'll reserve
|
// 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 dragger
|
// some horizontal space here and come back to drawing the controls later.
|
||||||
// later.
|
let (_id, mut left_controls_rect) = ui.allocate_space(Vec2::new(20.0, 1.0));
|
||||||
let (dragger_id, mut dragger_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 w = ui.available_width();
|
||||||
let item_size = Vec2::new(w - 20.0, 0.0);
|
let item_size = Vec2::new(w - 20.0, 0.0);
|
||||||
|
|
||||||
@ -161,18 +278,17 @@ impl FileEditor {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Delete-button
|
// Delete-button
|
||||||
if ui.button("x").clicked() {
|
if ui.button("⌫").clicked() {
|
||||||
retain = false;
|
retain = false;
|
||||||
ui.ctx().request_repaint();
|
ui.ctx().request_repaint();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Draw the dragger using the height from the buffer item
|
left_controls_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.scope_builder(
|
ui.scope_builder(
|
||||||
UiBuilder::new()
|
UiBuilder::new()
|
||||||
.max_rect(dragger_rect)
|
.max_rect(left_controls_rect)
|
||||||
.layout(Layout::top_down(Align::Center)),
|
.layout(Layout::top_down(Align::Center)),
|
||||||
|ui| {
|
|ui| {
|
||||||
let up_button_response = ui.add_enabled(!is_first, Button::new("⇡"));
|
let up_button_response = ui.add_enabled(!is_first, Button::new("⇡"));
|
||||||
@ -180,17 +296,12 @@ impl FileEditor {
|
|||||||
drop_from_to = Some((i, i - 1));
|
drop_from_to = Some((i, i - 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
ui.dnd_drag_source(dragger_id, DraggingItem { index: i }, |ui| {
|
// Add some space so that the next button is drawn
|
||||||
Button::new("≡")
|
// at the bottom of the buffer item.
|
||||||
.min_size(
|
ui.add_space(
|
||||||
// Use all available height, save for the height taken up by
|
left_controls_rect.height()
|
||||||
// the up/down buttons + padding. Assume down-button is the
|
- (up_button_response.rect.height() * 2.0 + 4.0),
|
||||||
// equally tall as the up-button.
|
);
|
||||||
dragger_rect.size()
|
|
||||||
- Vec2::Y * (up_button_response.rect.height() * 2.0 + 4.0),
|
|
||||||
)
|
|
||||||
.ui(ui);
|
|
||||||
});
|
|
||||||
|
|
||||||
if ui.add_enabled(!is_last, Button::new("⇣")).clicked() {
|
if ui.add_enabled(!is_last, Button::new("⇣")).clicked() {
|
||||||
drop_from_to = Some((i, i + 2));
|
drop_from_to = Some((i, i + 2));
|
||||||
@ -243,6 +354,38 @@ impl FileEditor {
|
|||||||
self.title = title.to_string_lossy().to_string();
|
self.title = title.to_string_lossy().to_string();
|
||||||
self.path = Some(new_path);
|
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 {
|
impl Display for BufferItem {
|
||||||
@ -280,7 +423,7 @@ impl From<&str> for FileEditor {
|
|||||||
_ => {
|
_ => {
|
||||||
let mut text_edit = MdTextEdit::new();
|
let mut text_edit = MdTextEdit::new();
|
||||||
text_edit.text.push_str(text);
|
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)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
|
|
||||||
|
|||||||
@ -42,7 +42,7 @@ impl Tile {
|
|||||||
|
|
||||||
Self {
|
Self {
|
||||||
bounding_box,
|
bounding_box,
|
||||||
image: ColorImage::new([CHUNK_SIZE, CHUNK_SIZE], Color32::TRANSPARENT),
|
image: ColorImage::filled([CHUNK_SIZE, CHUNK_SIZE], Color32::TRANSPARENT),
|
||||||
texture: None,
|
texture: None,
|
||||||
texture_is_dirty: false,
|
texture_is_dirty: false,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,6 +8,7 @@ use std::{
|
|||||||
sync::Arc,
|
sync::Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use arboard::Clipboard;
|
||||||
use base64::{Engine, prelude::BASE64_STANDARD};
|
use base64::{Engine, prelude::BASE64_STANDARD};
|
||||||
use canvas_rasterizer::CanvasRasterizer;
|
use canvas_rasterizer::CanvasRasterizer;
|
||||||
use disk_format::{DiskFormat, RawStroke, RawStrokeHeader, f16_le};
|
use disk_format::{DiskFormat, RawStroke, RawStrokeHeader, f16_le};
|
||||||
@ -77,10 +78,15 @@ struct Ephemeral {
|
|||||||
|
|
||||||
canvas_rasterizer: CanvasRasterizer,
|
canvas_rasterizer: CanvasRasterizer,
|
||||||
|
|
||||||
|
/// Whether the handwriting element is being interacted with.
|
||||||
|
is_focused: bool,
|
||||||
|
|
||||||
/// The stroke that is currently being drawed.
|
/// The stroke that is currently being drawed.
|
||||||
current_stroke: Vec<Pos2>,
|
current_stroke: Vec<Pos2>,
|
||||||
|
|
||||||
/// The lines that have not been blitted to `texture` yet.
|
/// 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]>,
|
unblitted_lines: Vec<[Pos2; 2]>,
|
||||||
|
|
||||||
tessellator: Option<Tessellator>,
|
tessellator: Option<Tessellator>,
|
||||||
@ -125,6 +131,7 @@ impl Default for Ephemeral {
|
|||||||
Self {
|
Self {
|
||||||
id: random_id(),
|
id: random_id(),
|
||||||
canvas_rasterizer: Default::default(),
|
canvas_rasterizer: Default::default(),
|
||||||
|
is_focused: false,
|
||||||
current_stroke: Default::default(),
|
current_stroke: Default::default(),
|
||||||
tessellator: None,
|
tessellator: None,
|
||||||
mesh: Default::default(),
|
mesh: Default::default(),
|
||||||
@ -163,6 +170,12 @@ 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 vertex_count: usize = self.e.mesh.indices.len() / 3;
|
let vertex_count: usize = self.e.mesh.indices.len() / 3;
|
||||||
ui.label(format!("vertices: {vertex_count}"));
|
ui.label(format!("vertices: {vertex_count}"));
|
||||||
})
|
})
|
||||||
@ -205,9 +218,16 @@ impl Handwriting {
|
|||||||
// Was the user in the process of drawing a stroke last frame?
|
// Was the user in the process of drawing a stroke last frame?
|
||||||
let was_drawing = !self.e.current_stroke.is_empty();
|
let was_drawing = !self.e.current_stroke.is_empty();
|
||||||
|
|
||||||
// Is the user in the process of drawing a stroke now?
|
// Is the user in the process of drawing a stroke now?;
|
||||||
let is_drawing = response.interact_pointer_pos().is_some();
|
let is_drawing = response.interact_pointer_pos().is_some();
|
||||||
|
|
||||||
|
if is_drawing {
|
||||||
|
self.e.is_focused = true;
|
||||||
|
} else if ui.ctx().input(|i| i.pointer.any_down()) {
|
||||||
|
// if the user starts interactive with something else, unfocus the handwriting area.
|
||||||
|
self.e.is_focused = false;
|
||||||
|
}
|
||||||
|
|
||||||
if !is_drawing {
|
if !is_drawing {
|
||||||
if was_drawing {
|
if was_drawing {
|
||||||
// commit current line
|
// commit current line
|
||||||
@ -215,12 +235,18 @@ impl Handwriting {
|
|||||||
response.mark_changed();
|
response.mark_changed();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let padding = if self.e.is_focused {
|
||||||
|
HANDWRITING_BOTTOM_PADDING
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
|
||||||
// recalculate how tall the widget should be
|
// recalculate how tall the widget should be
|
||||||
let lines_max_y = self
|
let lines_max_y = self
|
||||||
.strokes
|
.strokes
|
||||||
.iter()
|
.iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.map(|p| p.y + HANDWRITING_BOTTOM_PADDING)
|
.map(|p| p.y + padding)
|
||||||
.fold(HANDWRITING_MIN_HEIGHT, |max, y| max.max(y));
|
.fold(HANDWRITING_MIN_HEIGHT, |max, y| max.max(y));
|
||||||
|
|
||||||
// Change the height of the handwriting item.
|
// Change the height of the handwriting item.
|
||||||
@ -418,7 +444,7 @@ impl Handwriting {
|
|||||||
last_mesh_ctx,
|
last_mesh_ctx,
|
||||||
..
|
..
|
||||||
} = &mut self.e;
|
} = &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);
|
*last_mesh_ctx = Some(mesh_context);
|
||||||
|
|
||||||
@ -437,10 +463,7 @@ impl Handwriting {
|
|||||||
.iter()
|
.iter()
|
||||||
.chain([&*current_stroke])
|
.chain([&*current_stroke])
|
||||||
.filter(|stroke| stroke.len() >= 2)
|
.filter(|stroke| stroke.len() >= 2)
|
||||||
.map(|stroke| {
|
.map(|stroke| egui::Shape::line(stroke.clone(), style.stroke))
|
||||||
//let points: Vec<Pos2> = stroke.iter().map(|&p| to_screen * p).collect();
|
|
||||||
egui::Shape::line(stroke.clone(), style.stroke)
|
|
||||||
})
|
|
||||||
.for_each(|shape| {
|
.for_each(|shape| {
|
||||||
tessellator.tessellate_shape(shape, mesh);
|
tessellator.tessellate_shape(shape, mesh);
|
||||||
});
|
});
|
||||||
@ -473,7 +496,6 @@ impl Handwriting {
|
|||||||
ui.vertical_centered_justified(|ui| {
|
ui.vertical_centered_justified(|ui| {
|
||||||
self.ui_control(None, ui, &mut response);
|
self.ui_control(None, ui, &mut response);
|
||||||
|
|
||||||
//ui.label("Paint with your mouse/touch!");
|
|
||||||
Frame::canvas(ui.style())
|
Frame::canvas(ui.style())
|
||||||
.corner_radius(20.0)
|
.corner_radius(20.0)
|
||||||
.stroke(Stroke::new(5.0, Color32::from_black_alpha(40)))
|
.stroke(Stroke::new(5.0, Color32::from_black_alpha(40)))
|
||||||
|
|||||||
@ -1,5 +1,3 @@
|
|||||||
#![warn(clippy::all, rust_2018_idioms)]
|
|
||||||
|
|
||||||
pub mod app;
|
pub mod app;
|
||||||
pub mod constants;
|
pub mod constants;
|
||||||
pub mod custom_code_block;
|
pub mod custom_code_block;
|
||||||
@ -10,6 +8,7 @@ pub mod markdown;
|
|||||||
pub mod preferences;
|
pub mod preferences;
|
||||||
pub mod rasterizer;
|
pub mod rasterizer;
|
||||||
pub mod text_editor;
|
pub mod text_editor;
|
||||||
|
pub mod text_styles;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|
||||||
pub use app::App;
|
pub use app::App;
|
||||||
|
|||||||
@ -1,5 +1,10 @@
|
|||||||
use egui::text::{CCursorRange, LayoutJob};
|
use egui::text::{CCursorRange, LayoutJob};
|
||||||
|
|
||||||
|
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};
|
use super::{Item, Style, parse};
|
||||||
|
|
||||||
/// Highlight markdown, caching previous output to save CPU.
|
/// Highlight markdown, caching previous output to save CPU.
|
||||||
@ -34,7 +39,6 @@ pub fn highlight_markdown(
|
|||||||
_cursor: Option<CCursorRange>,
|
_cursor: Option<CCursorRange>,
|
||||||
) -> LayoutJob {
|
) -> LayoutJob {
|
||||||
let mut job = LayoutJob::default();
|
let mut job = LayoutJob::default();
|
||||||
|
|
||||||
let code_style = Style {
|
let code_style = Style {
|
||||||
code: true,
|
code: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@ -71,8 +75,24 @@ fn format_from_style(egui_style: &egui::Style, style: &Style) -> egui::text::Tex
|
|||||||
egui_style.visuals.text_color()
|
egui_style.visuals.text_color()
|
||||||
};
|
};
|
||||||
|
|
||||||
let text_style = if style.heading.is_some() {
|
let text_style = if let Some(heading) = style.heading {
|
||||||
TextStyle::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 {
|
} else if style.code {
|
||||||
TextStyle::Monospace
|
TextStyle::Monospace
|
||||||
} else if style.small | style.raised {
|
} else if style.small | style.raised {
|
||||||
|
|||||||
@ -16,11 +16,6 @@ pub fn parse_tokens<'a>(mut tokens: &[Token<'a>]) -> Vec<Item<'a>> {
|
|||||||
|
|
||||||
let mut style = Style::default();
|
let mut style = Style::default();
|
||||||
|
|
||||||
let mono_style = Style {
|
|
||||||
code: true,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
iter::from_fn(move || {
|
iter::from_fn(move || {
|
||||||
if tokens.is_empty() {
|
if tokens.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
@ -73,7 +68,10 @@ pub fn parse_tokens<'a>(mut tokens: &[Token<'a>]) -> Vec<Item<'a>> {
|
|||||||
any_of([TokenKind::Mono, TokenKind::CodeBlock, TokenKind::Newline]),
|
any_of([TokenKind::Mono, TokenKind::CodeBlock, TokenKind::Newline]),
|
||||||
);
|
);
|
||||||
|
|
||||||
return Some(Item::Text { span, style: mono_style});
|
let mut style = style;
|
||||||
|
style.code = true;
|
||||||
|
|
||||||
|
return Some(Item::Text { span, style });
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: different heading strengths
|
// TODO: different heading strengths
|
||||||
|
|||||||
@ -31,7 +31,7 @@ pub enum TokenKind {
|
|||||||
Text,
|
Text,
|
||||||
}
|
}
|
||||||
|
|
||||||
const TOKENS: &[(&'static str, TokenKind)] = &[
|
const TOKENS: &[(&str, TokenKind)] = &[
|
||||||
("\n", TokenKind::Newline),
|
("\n", TokenKind::Newline),
|
||||||
("######", TokenKind::Heading(Heading::H6)),
|
("######", TokenKind::Heading(Heading::H6)),
|
||||||
("#####", TokenKind::Heading(Heading::H5)),
|
("#####", 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};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
@ -14,7 +14,7 @@ pub struct Preferences {
|
|||||||
pub hide_handwriting_cursor: bool,
|
pub hide_handwriting_cursor: bool,
|
||||||
|
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
has_applied_theme: bool,
|
has_applied_prefs: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Preferences {
|
impl Default for Preferences {
|
||||||
@ -22,7 +22,7 @@ impl Default for Preferences {
|
|||||||
Self {
|
Self {
|
||||||
animations: true,
|
animations: true,
|
||||||
high_contrast: false,
|
high_contrast: false,
|
||||||
has_applied_theme: false,
|
has_applied_prefs: false,
|
||||||
hide_handwriting_cursor: false,
|
hide_handwriting_cursor: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -31,8 +31,20 @@ impl Default for Preferences {
|
|||||||
impl Preferences {
|
impl Preferences {
|
||||||
/// Apply preferences, if they haven't already been applied.
|
/// Apply preferences, if they haven't already been applied.
|
||||||
pub fn apply(&mut self, ctx: &Context) {
|
pub fn apply(&mut self, ctx: &Context) {
|
||||||
if !self.has_applied_theme {
|
if !self.has_applied_prefs {
|
||||||
self.has_applied_theme = true;
|
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 dark_visuals = Visuals::dark();
|
||||||
let mut light_visuals = Visuals::light();
|
let mut light_visuals = Visuals::light();
|
||||||
@ -71,11 +83,15 @@ impl Preferences {
|
|||||||
pub fn show(&mut self, ui: &mut Ui) {
|
pub fn show(&mut self, ui: &mut Ui) {
|
||||||
ui.label(RichText::new("Prefs").weak());
|
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");
|
let high_contrast_toggle = ui.toggle_value(&mut self.high_contrast, "High Contrast");
|
||||||
if high_contrast_toggle.clicked() {
|
if high_contrast_toggle.clicked() {
|
||||||
self.has_applied_theme = false;
|
self.has_applied_prefs = false;
|
||||||
self.apply(ui.ctx());
|
self.apply(ui.ctx());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -22,7 +22,7 @@ pub fn rasterize<'a, Blend: BlendFn>(
|
|||||||
point_to_pixel: TSTransform,
|
point_to_pixel: TSTransform,
|
||||||
triangles: impl Iterator<Item = [&'a Vertex; 3]>,
|
triangles: impl Iterator<Item = [&'a Vertex; 3]>,
|
||||||
) -> ColorImage {
|
) -> 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);
|
rasterize_onto::<Blend>(&mut image, point_to_pixel, triangles);
|
||||||
image
|
image
|
||||||
}
|
}
|
||||||
@ -90,10 +90,10 @@ pub fn rasterize_onto<'a, Blend: BlendFn>(
|
|||||||
/// Rasterize a single triangles onto an image,
|
/// Rasterize a single triangles onto an image,
|
||||||
///
|
///
|
||||||
/// Triangle positions must be in image-local point-coords.
|
/// 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,
|
image: &mut ColorImage,
|
||||||
point_to_pixel: TSTransform,
|
point_to_pixel: TSTransform,
|
||||||
triangle: [&'a Vertex; 3],
|
triangle: [&Vertex; 3],
|
||||||
) {
|
) {
|
||||||
rasterize_onto::<Blend>(image, point_to_pixel, [triangle].into_iter());
|
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 {
|
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
|
|| self.y_from > other.y_to
|
||||||
|| other.x_from > self.x_to
|
|| other.x_from > self.x_to
|
||||||
|| other.y_from > self.y_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 egui::Id;
|
||||||
|
use eyre::{Context, ContextCompat};
|
||||||
use rand::{Rng, rng};
|
use rand::{Rng, rng};
|
||||||
|
|
||||||
pub fn random_id() -> Id {
|
pub fn random_id() -> Id {
|
||||||
@ -28,3 +30,27 @@ impl<T> GuiSender<T> {
|
|||||||
Ok(())
|
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