Indicate when file has changed on disk
This commit is contained in:
79
src/app.rs
79
src/app.rs
@ -1,16 +1,23 @@
|
||||
use std::{
|
||||
fs,
|
||||
io::Read,
|
||||
path::PathBuf,
|
||||
sync::{Arc, mpsc},
|
||||
thread::JoinHandle,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crate::{file_editor::FileEditor, folder::Folder, preferences::Preferences, util::GuiSender};
|
||||
use crate::{
|
||||
file_editor::{FileEditor, SaveStatus},
|
||||
folder::Folder,
|
||||
preferences::Preferences,
|
||||
util::{GuiSender, file_mtime, log_error},
|
||||
};
|
||||
use egui::{
|
||||
Align, Button, Context, FontData, FontDefinitions, Image, Key, Modifiers, PointerButton,
|
||||
RichText, ScrollArea, Widget, include_image,
|
||||
};
|
||||
use eyre::eyre;
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize)]
|
||||
#[serde(default)]
|
||||
@ -40,7 +47,7 @@ pub struct Jobs {
|
||||
}
|
||||
|
||||
impl Jobs {
|
||||
fn start(&mut self, ctx: &Context, job: impl FnOnce() -> Option<Action> + Send + 'static) {
|
||||
pub fn start(&mut self, ctx: &Context, job: impl FnOnce() -> Option<Action> + Send + 'static) {
|
||||
let ctx = ctx.clone();
|
||||
let actions_tx = self.actions_tx.clone();
|
||||
self.handles.push(std::thread::spawn(move || {
|
||||
@ -73,9 +80,21 @@ impl Tab {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
pub fn notice_symbol(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Tab::File(file_editor) => file_editor.is_dirty,
|
||||
Tab::File(file_editor) => match file_editor.save_status() {
|
||||
SaveStatus::Synced => None,
|
||||
SaveStatus::NoFile => Some("?"),
|
||||
SaveStatus::FileOutdated => Some("*"),
|
||||
SaveStatus::BufferOutdated => Some("!"),
|
||||
SaveStatus::Desynced => Some("!!"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&mut self, ctx: &Context, jobs: &mut Jobs) {
|
||||
match self {
|
||||
Tab::File(file_editor) => file_editor.save(ctx, jobs),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -268,11 +287,18 @@ impl eframe::App for App {
|
||||
self.jobs.start(ui.ctx(), move || {
|
||||
let file_path = rfd::FileDialog::new().pick_file()?;
|
||||
|
||||
let text = fs::read_to_string(&file_path)
|
||||
let mut file = fs::File::open(&file_path)
|
||||
.inspect_err(|e| log::error!("Failed to open {file_path:?}: {e}"))
|
||||
.ok()?;
|
||||
|
||||
let mtime = log_error(eyre!("file_path:?"), || file_mtime(&file))?;
|
||||
|
||||
let mut text = String::new();
|
||||
file.read_to_string(&mut text)
|
||||
.inspect_err(|e| log::error!("Failed to read {file_path:?}: {e}"))
|
||||
.ok()?;
|
||||
|
||||
let editor = FileEditor::from_file(file_path, &text);
|
||||
let editor = FileEditor::from_file(file_path, &text, mtime);
|
||||
Some(Action::OpenFile(editor))
|
||||
});
|
||||
}
|
||||
@ -364,8 +390,8 @@ impl eframe::App for App {
|
||||
let selected = self.open_tab_index == Some(i);
|
||||
let mut button = Button::new(tab.title()).selected(selected);
|
||||
|
||||
if tab.is_dirty() {
|
||||
button = button.right_text(RichText::new("*").strong())
|
||||
if let Some(symbol) = tab.notice_symbol() {
|
||||
button = button.right_text(RichText::new(symbol).strong())
|
||||
}
|
||||
|
||||
let response = ui.add(button);
|
||||
@ -396,13 +422,22 @@ impl eframe::App for App {
|
||||
if let Some(file_path) = response.open_file {
|
||||
let file_path = file_path.to_owned();
|
||||
self.jobs.start(ui.ctx(), move || {
|
||||
let text = fs::read_to_string(&file_path)
|
||||
let mut file = fs::File::open(&file_path)
|
||||
.inspect_err(|e| {
|
||||
log::error!("Failed to open {file_path:?}: {e}")
|
||||
})
|
||||
.ok()?;
|
||||
|
||||
let mtime = log_error(eyre!("file_path:?"), || file_mtime(&file))?;
|
||||
|
||||
let mut text = String::new();
|
||||
file.read_to_string(&mut text)
|
||||
.inspect_err(|e| {
|
||||
log::error!("Failed to read {file_path:?}: {e}")
|
||||
})
|
||||
.ok()?;
|
||||
|
||||
let editor = FileEditor::from_file(file_path, &text);
|
||||
let editor = FileEditor::from_file(file_path, &text, mtime);
|
||||
Some(Action::OpenFile(editor))
|
||||
});
|
||||
}
|
||||
@ -448,29 +483,13 @@ impl App {
|
||||
}
|
||||
|
||||
fn save_active_tab(&mut self, ctx: &Context) {
|
||||
let open_file = self
|
||||
let open_tab = self
|
||||
.open_tab_index
|
||||
.and_then(|i| self.tabs.get_mut(i))
|
||||
.map(|(id, tab)| match tab {
|
||||
Tab::File(file_editor) => (*id, file_editor),
|
||||
})
|
||||
.and_then(|(_, file_editor)| {
|
||||
file_editor
|
||||
.path()
|
||||
.map(ToOwned::to_owned)
|
||||
.zip(Some(file_editor))
|
||||
});
|
||||
.map(|(_id, tab)| tab);
|
||||
|
||||
if let Some((file_path, file_editor)) = open_file {
|
||||
file_editor.is_dirty = false;
|
||||
let text = file_editor.to_string();
|
||||
let file_path = file_path.to_owned();
|
||||
self.jobs.start(ctx, move || {
|
||||
if let Err(e) = fs::write(file_path, text.as_bytes()) {
|
||||
log::error!("{e}");
|
||||
};
|
||||
None
|
||||
});
|
||||
if let Some(open_tab) = open_tab {
|
||||
open_tab.save(ctx, &mut self.jobs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,30 +1,77 @@
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
fmt::{self, Display},
|
||||
fs::{self, File},
|
||||
io::Write,
|
||||
ops::{Div as _, Sub as _},
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
sync::mpsc,
|
||||
};
|
||||
|
||||
use chrono::{DateTime, Local};
|
||||
use egui::{
|
||||
Align, Button, DragAndDrop, Frame, Layout, ScrollArea, Ui, UiBuilder, Vec2, Widget as _, vec2,
|
||||
Align, Button, Context, DragAndDrop, Frame, Layout, ScrollArea, Ui, UiBuilder, Vec2,
|
||||
Widget as _, vec2,
|
||||
};
|
||||
use eyre::eyre;
|
||||
use notify::{EventKind, Watcher};
|
||||
|
||||
use crate::{
|
||||
app::Jobs,
|
||||
custom_code_block::{MdItem, iter_lines_and_code_blocks},
|
||||
handwriting::{self, Handwriting, HandwritingStyle},
|
||||
preferences::Preferences,
|
||||
text_editor::MdTextEdit,
|
||||
util::{file_mtime, log_error},
|
||||
};
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize)]
|
||||
pub struct FileEditor {
|
||||
title: String,
|
||||
pub path: Option<PathBuf>,
|
||||
|
||||
path: Option<PathBuf>,
|
||||
pub buffer: Vec<BufferItem>,
|
||||
|
||||
/// Whether the file has been edited since it was laste saved to disk.
|
||||
pub is_dirty: bool,
|
||||
pub file_mtime: Option<DateTime<Local>>,
|
||||
pub buffer_mtime: DateTime<Local>,
|
||||
|
||||
// TODO: instantiate these on load
|
||||
#[serde(skip)]
|
||||
inner: Option<Inner>,
|
||||
|
||||
/// 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)]
|
||||
@ -40,18 +87,24 @@ impl FileEditor {
|
||||
title: title.into(),
|
||||
path: None,
|
||||
buffer,
|
||||
file_mtime: None,
|
||||
buffer_mtime: Local::now(),
|
||||
is_dirty: false,
|
||||
inner: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_file(file_path: PathBuf, contents: &str) -> Self {
|
||||
pub fn from_file(file_path: PathBuf, contents: &str, mtime: DateTime<Local>) -> Self {
|
||||
let file_title = file_path
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| String::from("untitled.md"));
|
||||
|
||||
Self {
|
||||
title: file_title,
|
||||
path: Some(file_path),
|
||||
file_mtime: Some(mtime),
|
||||
buffer_mtime: mtime,
|
||||
..FileEditor::from(contents)
|
||||
}
|
||||
}
|
||||
@ -64,7 +117,46 @@ impl FileEditor {
|
||||
self.path.as_deref()
|
||||
}
|
||||
|
||||
pub fn save_status(&self) -> SaveStatus {
|
||||
let Some(file_mtime) = self.file_mtime else {
|
||||
return SaveStatus::NoFile;
|
||||
};
|
||||
|
||||
let buffer_is_newer = self.buffer_mtime > file_mtime;
|
||||
let file_is_newer = self.buffer_mtime < file_mtime;
|
||||
|
||||
if buffer_is_newer || (file_is_newer && self.is_dirty) {
|
||||
SaveStatus::Desynced
|
||||
} else if file_is_newer {
|
||||
SaveStatus::BufferOutdated
|
||||
} else if self.is_dirty {
|
||||
SaveStatus::FileOutdated
|
||||
} else {
|
||||
SaveStatus::Synced
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(&mut self, ui: &mut Ui, preferences: &Preferences) {
|
||||
if let Some(path) = &self.path
|
||||
&& self.inner.is_none()
|
||||
{
|
||||
self.inner = Some(spawn_file_watcher(path));
|
||||
}
|
||||
|
||||
if let Some(inner) = &mut self.inner {
|
||||
while let Ok(event) = inner.file_events.try_recv() {
|
||||
match dbg!(event) {
|
||||
FileEvent::NewFileMTime(mtime) => {
|
||||
self.file_mtime = Some(mtime);
|
||||
}
|
||||
FileEvent::NewBufferMTime(mtime) => {
|
||||
self.buffer_mtime = mtime;
|
||||
self.file_mtime = Some(mtime);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ui.vertical_centered_justified(|ui| {
|
||||
ui.heading(&self.title);
|
||||
|
||||
@ -243,6 +335,38 @@ impl FileEditor {
|
||||
self.title = title.to_string_lossy().to_string();
|
||||
self.path = Some(new_path);
|
||||
}
|
||||
|
||||
pub fn set_dirty(&mut self, value: bool) {
|
||||
self.is_dirty = value;
|
||||
}
|
||||
|
||||
pub fn save(&mut self, ctx: &Context, jobs: &mut Jobs) {
|
||||
let Some(file_path) = self.path.clone() else {
|
||||
log::info!("Can't save {}, no path set.", self.title);
|
||||
return;
|
||||
};
|
||||
|
||||
self.is_dirty = false;
|
||||
let text = self.to_string();
|
||||
let inner = self
|
||||
.inner
|
||||
.get_or_insert_with(|| spawn_file_watcher(&file_path));
|
||||
let file_event_tx = inner.file_events_tx.clone();
|
||||
|
||||
jobs.start(ctx, move || {
|
||||
log_error(eyre!("Failed to save file {file_path:?}"), || {
|
||||
let mut file = fs::File::create(file_path)?;
|
||||
file.write_all(text.as_bytes())?;
|
||||
let mtime = file_mtime(&file)?;
|
||||
|
||||
let _ = file_event_tx.send(FileEvent::NewBufferMTime(mtime));
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
None
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for BufferItem {
|
||||
@ -314,6 +438,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.into()));
|
||||
|
||||
Ok(())
|
||||
});
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
if let Err(e) = watcher.watch(p, notify::RecursiveMode::NonRecursive) {
|
||||
log::error!("Failed to watch {p:?}: {e}");
|
||||
};
|
||||
|
||||
Inner {
|
||||
file_events: rx,
|
||||
file_events_tx: tx,
|
||||
_file_watcher: watcher,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
|
||||
|
||||
@ -8,6 +8,7 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use arboard::Clipboard;
|
||||
use base64::{Engine, prelude::BASE64_STANDARD};
|
||||
use canvas_rasterizer::CanvasRasterizer;
|
||||
use disk_format::{DiskFormat, RawStroke, RawStrokeHeader, f16_le};
|
||||
@ -163,6 +164,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;
|
||||
ui.label(format!("vertices: {vertex_count}"));
|
||||
})
|
||||
|
||||
@ -31,7 +31,7 @@ pub enum TokenKind {
|
||||
Text,
|
||||
}
|
||||
|
||||
const TOKENS: &[(&'static str, TokenKind)] = &[
|
||||
const TOKENS: &[(&str, TokenKind)] = &[
|
||||
("\n", TokenKind::Newline),
|
||||
("######", TokenKind::Heading(Heading::H6)),
|
||||
("#####", TokenKind::Heading(Heading::H5)),
|
||||
|
||||
@ -90,10 +90,10 @@ pub fn rasterize_onto<'a, Blend: BlendFn>(
|
||||
/// Rasterize a single triangles onto an image,
|
||||
///
|
||||
/// Triangle positions must be in image-local point-coords.
|
||||
pub fn rasterize_triangle_onto<'a, Blend: BlendFn>(
|
||||
pub fn rasterize_triangle_onto<Blend: BlendFn>(
|
||||
image: &mut ColorImage,
|
||||
point_to_pixel: TSTransform,
|
||||
triangle: [&'a Vertex; 3],
|
||||
triangle: [&Vertex; 3],
|
||||
) {
|
||||
rasterize_onto::<Blend>(image, point_to_pixel, [triangle].into_iter());
|
||||
}
|
||||
|
||||
28
src/util.rs
28
src/util.rs
@ -1,6 +1,8 @@
|
||||
use std::sync::mpsc;
|
||||
use std::{fs::File, os::unix::fs::MetadataExt as _, sync::mpsc};
|
||||
|
||||
use chrono::{DateTime, Local};
|
||||
use egui::Id;
|
||||
use eyre::{Context, ContextCompat};
|
||||
use rand::{Rng, rng};
|
||||
|
||||
pub fn random_id() -> Id {
|
||||
@ -28,3 +30,27 @@ impl<T> GuiSender<T> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub fn log_error<T>(chain: eyre::Report, f: impl FnOnce() -> eyre::Result<T>) -> Option<T> {
|
||||
f().map_err(|e| e.wrap_err(chain))
|
||||
.inspect_err(|e| log::error!("{e}"))
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub fn file_mtime(file: &File) -> eyre::Result<DateTime<Local>> {
|
||||
(move || {
|
||||
let meta = file.metadata().wrap_err("Failed to stat file")?;
|
||||
|
||||
let sec = meta.mtime();
|
||||
let nsec = meta
|
||||
.mtime_nsec()
|
||||
.try_into()
|
||||
.wrap_err("Nanoseconds overflowed")?;
|
||||
|
||||
DateTime::from_timestamp(sec, nsec)
|
||||
.wrap_err("Bad timestamp")
|
||||
.map(Into::into)
|
||||
})()
|
||||
.wrap_err("Failed to get file mtime")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user