diff --git a/src/app.rs b/src/app.rs index 96c4cee..41b13db 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,5 +1,4 @@ //! The application: state, layout and command handling. - use crate::config::{config_dir, Settings}; use crate::discord; use crate::git::{self, GitState}; @@ -31,6 +30,8 @@ pub enum Msg { Search(Vec<(PathBuf, usize, String)>), Git(Box), Note(&'static str, String), + /// A save through sudo finished; `version` is the text that was written. + Elevated { id: u64, version: u64, result: Result<(), String> }, } pub struct Pane { @@ -41,6 +42,8 @@ pub struct Pane { pub peek_from: Option, pub lens_line: f32, pub lens_y: f32, + /// Where in the viewport bubble the rail was grabbed, from its middle. + pub mini_grab: f32, pub tab_scroll: f32, pub reveal_tab: bool, pub tab_drag: Option<(usize, f32)>, @@ -49,7 +52,7 @@ pub struct Pane { impl Pane { fn new(seq: u64) -> Pane { - Pane { tabs: vec![], active: 0, mini: Mini::default(), dragging_mini: false, peek_from: None, lens_line: 0.0, lens_y: 0.0, tab_scroll: 0.0, reveal_tab: false, tab_drag: None, seq } + Pane { tabs: vec![], active: 0, mini: Mini::default(), dragging_mini: false, peek_from: None, lens_line: 0.0, lens_y: 0.0, mini_grab: 0.0, tab_scroll: 0.0, reveal_tab: false, tab_drag: None, seq } } } @@ -112,6 +115,8 @@ pub struct App { pub logo_clock: f32, pub theme_wave: Option<(Pos2, f64)>, pub git: GitState, + /// Files saved with changes since the app started; the tree marks them, and forgets on quit. + pub edited: std::collections::HashSet, pub diags: HashMap>, pub terms: Vec, pub term_cur: usize, @@ -180,7 +185,7 @@ impl App { palette: Palette::default(), find: Find::default(), menu: None, menu_seq: 0, dialog: None, toasts: vec![], toast_seq: 0, closed: vec![], zen: false, tx, rx, lsp_tx, lsp_rx, lsp: HashMap::new(), lsp_dead: Default::default(), complete_due: None, lsp_sent: HashMap::new(), complete: None, hover: None, complete_seq: 0, caret_pos: pos2(200.0, 200.0), hover_copied: f64::MIN, smoke_frames: 0, side_window: false, startup: vec![], window_title: String::new(), presence: discord::spawn(), presence_sent: None, last_time: None, last_poll: Instant::now(), last_guess: Instant::now(), last_session: Instant::now(), last_git: Instant::now() - Duration::from_secs(60), - last_stamp: theme::source_stamp(), saved_settings: s.clone(), s, quit_now: false, + last_stamp: theme::source_stamp(), saved_settings: s.clone(), s, quit_now: false, edited: Default::default(), }; a.apply_style(ctx); // a window opened from a taskbar action is a side window: the main session stays as it was @@ -403,21 +408,44 @@ impl App { let d = self.docs.get_mut(&id).unwrap(); if trim { d.buf.trim_trailing() } match d.save() { - Ok(()) => { - d.saved_at = ctx.input(|i| i.time); - let path = d.path.clone(); - for (i, _) in self.panes.iter().enumerate() { - motion::spring(format!("tabs/{i}/save"), 0.0, motion::FAST); - motion::kick(format!("tabs/{i}/save"), 16.0); - } - if let Some(p) = path { self.lsp_saved(&p) } - self.refresh_git(); - ctx.request_repaint(); + Ok(()) => self.saved(ctx, id), + // a protected file: ask for the password and save it through sudo + Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied && d.path.is_some() => { + let name = d.title(); + self.dialog = Some(Dialog::Sudo { id, name, password: String::new(), error: None, busy: false }); } Err(e) => self.toast("error", format!("Couldn't save: {e}")), } } + /// The tick on the tab, change bars and everyone else told, once a save has landed. + fn saved(&mut self, ctx: &egui::Context, id: u64) { + let Some(d) = self.docs.get_mut(&id) else { return }; + d.saved_at = ctx.input(|i| i.time); + d.refresh_marks(); + let path = d.path.clone(); + if let Some(p) = path.as_ref().filter(|_| !d.marks.is_empty()) { self.edited.insert(p.clone()); } + for (i, _) in self.panes.iter().enumerate() { + motion::spring(format!("tabs/{i}/save"), 0.0, motion::FAST); + motion::kick(format!("tabs/{i}/save"), 16.0); + } + if let Some(p) = path { self.lsp_saved(&p) } + self.refresh_git(); + ctx.request_repaint(); + } + + /// Writes a protected file through sudo, off the frame: a wrong password takes sudo a moment. + pub fn save_elevated(&mut self, ctx: &egui::Context, id: u64, password: String) { + let Some(d) = self.docs.get(&id) else { return }; + let Some(path) = d.path.clone() else { return }; + let (bytes, version, tx, ctx) = (d.bytes(), d.buf.version, self.tx.clone(), ctx.clone()); + std::thread::spawn(move || { + let result = crate::elevate::save_as_root(&path, &bytes, &password); + let _ = tx.send(Msg::Elevated { id, version, result }); + ctx.request_repaint(); + }); + } + pub fn toast(&mut self, ic: &'static str, text: String) { self.toast_seq += 1; self.toasts.push(Toast { ic, text, born: -1.0, seq: self.toast_seq }); @@ -823,11 +851,9 @@ impl App { let Some(d) = self.docs.get(&id) else { return vec![] }; let mut v = vec![]; if let Some(p) = &d.path { - if let Some(h) = self.git.marks.get(p) { - for (l, n, k) in h { - let c = [t.added, t.changed, t.removed][*k as usize]; - for i in (0..*n).step_by((*n / 8).max(1)) { v.push((l + i, c)) } - } + for (l, n, k) in &d.marks { + let c = [t.added, t.changed, t.removed][*k as usize]; + for i in (0..*n).step_by((*n / 8).max(1)) { v.push((l + i, c)) } } if let Some(ds) = self.diags.get(p) { for x in ds { v.push((x.line, if x.severity == 1 { t.error } else { t.syntax[crate::syntax::DefStyle::Warning as usize] })) } @@ -847,11 +873,9 @@ impl App { pub fn gutter_marks(&self, p: &egui::Painter, d: &Doc, line: usize, at: Pos2, lh: f32) { let t = &self.t; let Some(path) = &d.path else { return }; - if let Some(h) = self.git.marks.get(path) { - if let Some((_, _, k)) = h.iter().find(|(l, n, _)| line >= *l && line < *l + *n) { - let c = [t.added, t.changed, t.removed][*k as usize]; - p.rect_filled(Rect::from_min_size(at + vec2(0.0, 2.0), vec2(3.0, lh - 4.0)), cr(1.5), c); - } + if let Some((_, _, k)) = d.marks.iter().find(|(l, n, _)| line >= *l && line < *l + *n) { + let c = [t.added, t.changed, t.removed][*k as usize]; + p.rect_filled(Rect::from_min_size(at + vec2(0.0, 2.0), vec2(3.0, lh - 4.0)), cr(1.5), c); } if let Some(ds) = self.diags.get(path) { if let Some(x) = ds.iter().filter(|x| x.line == line).min_by_key(|x| x.severity) { @@ -1064,7 +1088,7 @@ impl App { self.refresh_theme(ctx); } Settings => self.settings_open = !self.settings_open, - About => self.toast("info", format!("Damson {}: {} syntax definitions loaded from Kate", env!("CARGO_PKG_VERSION"), self.reg.languages.len())), + About => self.toast("info", format!("Damson {}: {} languages", env!("CARGO_PKG_VERSION"), self.reg.languages.len())), NextTab | PrevTab => { let p = &mut self.panes[self.focus_pane]; let n = p.tabs.len(); @@ -1164,6 +1188,27 @@ impl App { } Msg::Git(g) => self.git = *g, Msg::Note(ic, t) => self.toast(ic, t), + Msg::Elevated { id, version, result } => match result { + Ok(()) => { + if let Some(d) = self.docs.get_mut(&id) { + // typing since the save began stays unsaved + if d.buf.version == version { d.saved() } else { d.mtime = d.path.as_ref().and_then(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok()) } + } + self.saved(ctx, id); + if matches!(self.dialog, Some(Dialog::Sudo { .. })) { + self.dialog = None; + motion::forget("dialog"); + } + } + Err(e) => match &mut self.dialog { + Some(Dialog::Sudo { error, busy, password, .. }) => { + *error = Some(e); + *busy = false; + password.clear(); + } + _ => self.toast("error", format!("Couldn't save: {e}")), + }, + }, } } self.pump_terminals(ctx); @@ -1175,6 +1220,7 @@ impl App { for d in self.docs.values_mut() { d.sync_edits(); d.detect(&mut self.reg); + d.refresh_marks(); } } diff --git a/src/elevate.rs b/src/elevate.rs new file mode 100644 index 0000000..45daeac --- /dev/null +++ b/src/elevate.rs @@ -0,0 +1,47 @@ +//! Saving a file you don't own: the bytes go to a private temporary file, then `sudo cp` puts +//! them in place, with the password handed to sudo on its stdin and never kept. + +use std::io::Write; +use std::os::unix::fs::OpenOptionsExt; +use std::path::Path; +use std::process::{Command, Stdio}; + +pub fn save_as_root(path: &Path, bytes: &[u8], password: &str) -> Result<(), String> { + let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let tmp = std::env::temp_dir().join(format!("damson-{}-{nanos}", std::process::id())); + let r = (|| { + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp).map_err(|e| e.to_string())?; + f.write_all(bytes).map_err(|e| e.to_string())?; + drop(f); + // copying over the file keeps its owner and mode; a new file gets the usual ones + let mut child = Command::new("sudo") + .args(["-S", "-k", "-p", "", "--", "cp", "--no-preserve=mode,ownership,timestamps", "--"]) + .arg(&tmp) + .arg(&target) + .env("LC_ALL", "C") + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("Couldn't run sudo: {e}"))?; + // one line only: a wrong password then meets end of input, not another try + if let Some(mut i) = child.stdin.take() { + let _ = i.write_all(format!("{password}\n").as_bytes()); + } + let out = child.wait_with_output().map_err(|e| e.to_string())?; + if out.status.success() { + return Ok(()); + } + let err = String::from_utf8_lossy(&out.stderr); + Err(if err.contains("incorrect password") || err.contains("Sorry, try again") || err.contains("no password was provided") { + "Wrong password, try again".to_string() + } else if err.contains("not in the sudoers") { + "Your account isn't allowed to use sudo".to_string() + } else { + err.lines().rfind(|l| !l.trim().is_empty()).unwrap_or("sudo failed").trim().to_string() + }) + })(); + let _ = std::fs::remove_file(&tmp); + r +} diff --git a/src/git.rs b/src/git.rs index dd905a7..24fe0bf 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,6 +1,5 @@ -//! Git, by running `git`: branch and file status for the panel, changed lines for the gutter. +//! Git, by running `git`: branch and file status for the panel. -use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::process::Command; @@ -11,8 +10,6 @@ pub struct GitState { pub ahead: String, /// (index status, worktree status, path relative to root) pub files: Vec<(char, char, String)>, - /// Per file: first line, line count, kind (0 add, 1 change, 2 delete). - pub marks: HashMap>, } fn git(dir: &Path, args: &[&str]) -> Option { @@ -25,29 +22,6 @@ pub fn run(dir: &Path, args: &[&str]) -> Result { if o.status.success() { Ok(String::from_utf8_lossy(&o.stdout).into_owned()) } else { Err(String::from_utf8_lossy(&o.stderr).trim().to_string()) } } -/// Reads hunks from `git diff -U0` output. -pub fn parse_hunks(diff: &str) -> Vec<(usize, usize, u8)> { - let mut v = vec![]; - for l in diff.lines() { - let Some(rest) = l.strip_prefix("@@ -") else { continue }; - let mut parts = rest.split(' '); - let (Some(old), Some(new)) = (parts.next(), parts.next()) else { continue }; - let num = |s: &str| -> (usize, usize) { - let mut it = s.trim_start_matches(['+', '-']).split(','); - let a = it.next().and_then(|x| x.parse().ok()).unwrap_or(0); - let b = it.next().and_then(|x| x.parse().ok()).unwrap_or(1); - (a, b) - }; - let ((_, oc), (ns, nc)) = (num(old), num(new)); - if nc == 0 { - v.push((ns, 1, 2)); - } else { - v.push((ns.saturating_sub(1), nc, if oc == 0 { 0 } else { 1 })); - } - } - v -} - pub fn scan(dir: &Path) -> GitState { let mut st = GitState::default(); let Some(root) = git(dir, &["rev-parse", "--show-toplevel"]) else { return st }; @@ -69,34 +43,6 @@ pub fn scan(dir: &Path) -> GitState { st.files.push((cs[0], cs[1], path)); } } - let diff = git(&root, &["diff", "-U0", "--no-color", "--no-ext-diff"]).unwrap_or_default(); - let mut cur: Option = None; - let mut chunk = String::new(); - let flush = |p: &Option, c: &mut String, m: &mut HashMap>| { - if let Some(p) = p { m.insert(p.clone(), parse_hunks(c)); } - c.clear(); - }; - for l in diff.lines() { - if let Some(f) = l.strip_prefix("+++ b/") { - flush(&cur, &mut chunk, &mut st.marks); - cur = Some(root.join(f)); - } else if l.starts_with("@@") { - chunk.push_str(l); - chunk.push('\n'); - } - } - flush(&cur, &mut chunk, &mut st.marks); st.root = Some(root); st } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn hunks_become_added_changed_and_deleted() { - let d = "@@ -3,0 +4,2 @@\n@@ -9 +11 @@\n@@ -20,2 +21,0 @@\n"; - assert_eq!(parse_hunks(d), vec![(3, 2, 0), (10, 1, 1), (21, 1, 2)]); - } -} diff --git a/src/lib.rs b/src/lib.rs index bc2b813..ae2e630 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ pub mod app; pub mod config; pub mod discord; +pub mod elevate; pub mod git; pub mod icondata; pub mod lsp; diff --git a/src/text/diff.rs b/src/text/diff.rs new file mode 100644 index 0000000..095b7ff --- /dev/null +++ b/src/text/diff.rs @@ -0,0 +1,125 @@ +//! Which lines changed since a file was opened, for the change bars. A Myers diff over line hashes, +//! so the bars only ever describe this session's edits. + +use ropey::Rope; +use std::hash::Hasher; + +/// One hash per line, without its line break. +pub fn line_hashes(rope: &Rope) -> Vec { + rope.lines().map(|l| { + let mut h = std::hash::DefaultHasher::new(); + for c in l.chunks() { h.write(c.trim_end_matches(['\n', '\r']).as_bytes()) } + h.finish() + }).collect() +} + +/// Hunks of `new` against `old`: (first line, line count, kind: 0 add, 1 change, 2 delete). +/// A deletion marks the line that now sits where the removed lines were. +pub fn hunks(old: &[u64], new: &[u64]) -> Vec<(usize, usize, u8)> { + let pre = old.iter().zip(new).take_while(|(a, b)| a == b).count(); + let suf = old[pre..].iter().rev().zip(new[pre..].iter().rev()).take_while(|(a, b)| a == b).count(); + let (a, b) = (&old[pre..old.len() - suf], &new[pre..new.len() - suf]); + if a.is_empty() && b.is_empty() { + return vec![]; + } + // scattered edits all over a huge file would cost too much: past a budget it's one hunk + let cap = (20_000_000 / (a.len() + b.len()).max(1)).clamp(16, 1000); + let same = myers(a, b, cap).unwrap_or_default(); + let mut v = vec![]; + let (mut i, mut j) = (0, 0); + for (mi, mj) in same.into_iter().chain([(a.len(), b.len())]) { + if mi > i || mj > j { + if mj > j { + v.push((pre + j, mj - j, if mi > i { 1 } else { 0 })); + } else { + v.push(((pre + j).min(new.len().saturating_sub(1)), 1, 2)); + } + } + (i, j) = (mi + 1, mj + 1); + } + v +} + +/// Matching line pairs, in order, or None past `cap` edits. +fn myers(a: &[u64], b: &[u64], cap: usize) -> Option> { + let (n, m) = (a.len() as isize, b.len() as isize); + let cap = cap.min((n + m) as usize) as isize; + let off = cap + 1; + let mut v = vec![0isize; 2 * cap as usize + 3]; + // the frontier before each round, k from -d to d + let mut trace: Vec> = vec![]; + for d in 0..=cap { + trace.push(v[(off - d) as usize..=(off + d) as usize].to_vec()); + let mut k = -d; + while k <= d { + let mut x = if k == -d || (k != d && v[(off + k - 1) as usize] < v[(off + k + 1) as usize]) { v[(off + k + 1) as usize] } else { v[(off + k - 1) as usize] + 1 }; + let mut y = x - k; + while x < n && y < m && a[x as usize] == b[y as usize] { x += 1; y += 1 } + v[(off + k) as usize] = x; + if x >= n && y >= m { + return Some(backtrack(&trace, n, m)); + } + k += 2; + } + } + None +} + +fn backtrack(trace: &[Vec], n: isize, m: isize) -> Vec<(usize, usize)> { + let mut pairs = vec![]; + let (mut x, mut y) = (n, m); + for d in (0..trace.len() as isize).rev() { + let v = &trace[d as usize]; + let at = |k: isize| v[(k + d) as usize]; + let k = x - y; + let (px, py) = if d == 0 { (0, 0) } else { + let pk = if k == -d || (k != d && at(k - 1) < at(k + 1)) { k + 1 } else { k - 1 }; + (at(pk), at(pk) - pk) + }; + // the snake back to where this round's edit landed + while x > px && y > py { + x -= 1; + y -= 1; + pairs.push((x as usize, y as usize)); + } + (x, y) = (px, py); + } + pairs.reverse(); + pairs +} + +#[cfg(test)] +mod tests { + use super::*; + + fn h(s: &str) -> Vec { + line_hashes(&Rope::from_str(s)) + } + + #[test] + fn nothing_changed_means_no_marks() { + assert!(hunks(&h("a\nb\nc"), &h("a\nb\nc")).is_empty()); + } + + #[test] + fn adds_changes_and_deletes_land_on_the_right_lines() { + let old = h("a\nb\nc\nd\ne\nf\ng"); + // b changed, an x added after d, f removed + let new = h("a\nB\nc\nd\nx\ne\ng"); + assert_eq!(hunks(&old, &new), vec![(1, 1, 1), (4, 1, 0), (6, 1, 2)]); + } + + #[test] + fn separate_edits_stay_separate_in_a_long_file() { + let old: Vec = (0..5000).collect(); + let mut new = old.clone(); + new[10] = 99_999; + new[4000] = 88_888; + assert_eq!(hunks(&old, &new), vec![(10, 1, 1), (4000, 1, 1)]); + } + + #[test] + fn deleting_the_last_lines_marks_the_new_last_line() { + assert_eq!(hunks(&h("a\nb\nc\n"), &h("a\n")), vec![(1, 1, 2)]); + } +} diff --git a/src/text/doc.rs b/src/text/doc.rs index 89089ca..0e964b4 100644 --- a/src/text/doc.rs +++ b/src/text/doc.rs @@ -55,6 +55,11 @@ pub struct Doc { /// Extension suggested for an unnamed file, from its language. pub auto_ext: Option, guessed_at: u64, + /// The text as it was opened, as line hashes: change bars describe this session only. + base: Vec, + /// Change bars against `base`: (first line, count, kind 0 add / 1 change / 2 delete). + pub marks: Vec<(usize, usize, u8)>, + marks_at: u64, } fn decode(bytes: &[u8]) -> (String, &'static encoding_rs::Encoding, bool) { @@ -80,7 +85,9 @@ impl Doc { encoding: encoding_rs::UTF_8, bom: false, eol, mtime: None, hl: vec![], start_state: None, dirty: None, folded: BTreeSet::new(), fold_ends: HashMap::new(), fold_version: u64::MAX, bookmarks: BTreeSet::new(), hl_version: 0, saved_at: f64::MIN, lang_locked: false, auto_ext: None, guessed_at: u64::MAX, + base: vec![], marks: vec![], marks_at: 0, }; + d.base = super::diff::line_hashes(&d.buf.rope); let lang = d.detect_by_name(reg).unwrap_or_else(|| "None".to_string()); d.set_language(&lang, reg); d.detect(reg); @@ -168,6 +175,9 @@ impl Doc { self.mtime = std::fs::metadata(&path).and_then(|m| m.modified()).ok(); // it matches the disk now, whatever it held before self.buf.mark_saved(); + self.base = super::diff::line_hashes(&self.buf.rope); + self.marks.clear(); + self.marks_at = self.buf.version; Ok(()) } @@ -194,10 +204,8 @@ impl Doc { self.fold_version = u64::MAX; } - pub fn save(&mut self) -> std::io::Result<()> { - let Some(path) = self.path.clone() else { - return Err(std::io::Error::other("no file name")); - }; + /// The text as it goes on disk: line endings, encoding and BOM as the file had them. + pub fn bytes(&self) -> Vec { let mut text = self.buf.rope.to_string(); if self.eol != Eol::Lf { text = text.replace('\n', self.eol.text()); @@ -208,21 +216,45 @@ impl Doc { bytes.extend_from_slice(&[0xEF, 0xBB, 0xBF]); } bytes.extend_from_slice(&enc); + bytes + } + + pub fn save(&mut self) -> std::io::Result<()> { + let Some(path) = self.path.clone() else { + return Err(std::io::Error::other("no file name")); + }; + let bytes = self.bytes(); // write beside the file, then swap, so a crash mid-save can't leave half a file // (a symlink stays a link: the swap happens at the file it points to) let target = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone()); let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + // a file we may not write stays protected, even in a folder we may: that's for sudo + if target.exists() { + std::fs::OpenOptions::new().write(true).open(&target)?; + } let tmp = target.with_file_name(format!(".{name}.damson-tmp")); std::fs::write(&tmp, &bytes)?; if let Ok(m) = std::fs::metadata(&target) { let _ = std::fs::set_permissions(&tmp, m.permissions()); } std::fs::rename(&tmp, &target)?; - self.mtime = std::fs::metadata(&path).and_then(|m| m.modified()).ok(); - self.buf.mark_saved(); + self.saved(); Ok(()) } + /// The text is on disk now, however it got there. + pub fn saved(&mut self) { + self.mtime = self.path.as_ref().and_then(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok()); + self.buf.mark_saved(); + } + + /// Recomputes the change bars if the text moved on since last time. + pub fn refresh_marks(&mut self) { + if self.marks_at == self.buf.version { return } + self.marks_at = self.buf.version; + self.marks = super::diff::hunks(&self.base, &super::diff::line_hashes(&self.buf.rope)); + } + /// Brings the line tables in step with edits made to the buffer. pub fn sync_edits(&mut self) { let changes: Vec = std::mem::take(&mut self.buf.changes); diff --git a/src/text/mod.rs b/src/text/mod.rs index 7f5a8c4..ca9d875 100644 --- a/src/text/mod.rs +++ b/src/text/mod.rs @@ -1,5 +1,6 @@ pub mod buffer; pub mod commands; +pub mod diff; pub mod doc; pub use buffer::{Buffer, EditKind, Sel}; diff --git a/src/ui/menu.rs b/src/ui/menu.rs index d61dcbe..685e24b 100644 --- a/src/ui/menu.rs +++ b/src/ui/menu.rs @@ -42,6 +42,8 @@ pub enum Dialog { Confirm { title: String, body: String, pane: usize, tab: usize }, ConfirmTrash(PathBuf), ConfirmQuit, + /// Saving a file only root may write: asks for the sudo password. + Sudo { id: u64, name: String, password: String, error: Option, busy: bool }, } fn item(cmd: Cmd) -> MenuItem { @@ -180,7 +182,7 @@ impl App { ui.allocate_rect(screen, Sense::click()); ui.painter().rect_filled(screen, cr(0.0), alpha(egui::Color32::BLACK, 0.4 * k.clamp(0.0, 1.0))); }); - let rect = Rect::from_center_size(screen.center(), vec2(420.0, 190.0)); + let rect = Rect::from_center_size(screen.center(), vec2(420.0, if matches!(dlg, Dialog::Sudo { .. }) { 212.0 } else { 190.0 })); let mut close = ctx.input(|i| i.key_pressed(Key::Escape)); let mut after: Option> = None; let area = Area::new(Id::unique("dlg")).order(Order::Tooltip).fixed_pos(rect.min).show(ctx, |ui: &mut Ui| { @@ -191,6 +193,7 @@ impl App { Dialog::Prompt { title, .. } | Dialog::Confirm { title, .. } => title.clone(), Dialog::ConfirmTrash(p) => format!("Move {} to the trash?", p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()), Dialog::ConfirmQuit => "Quit with unsaved changes?".to_string(), + Dialog::Sudo { name, .. } => format!("Save {name} as administrator"), }; ui.painter().text(rect.left_top() + vec2(26.0, 34.0), Align2::LEFT_CENTER, title, fonts::med(16.0), t.on_surface); let btn_y = rect.bottom() - 48.0; @@ -235,6 +238,26 @@ impl App { close = true; } } + Dialog::Sudo { id, password, error, busy, .. } => { + let (body, col) = match error { Some(e) => (e.as_str(), t.error), None => ("This file is protected. Enter your password to save it", t.on_variant) }; + ui.painter().text(rect.left_top() + vec2(26.0, 66.0), Align2::LEFT_CENTER, body, fonts::ui(14.0), col); + let field = Rect::from_min_size(rect.left_top() + vec2(24.0, 88.0), vec2(rect.width() - 48.0, 42.0)); + ui.painter().rect_filled(field, cr(16.0), t.highest); + if error.is_some() && !*busy { + ui.painter().rect_stroke(field, cr(16.0), egui::Stroke::new(1.5, t.error), egui::StrokeKind::Inside); + } + let te = ui.add_enabled_ui(!*busy, |ui| { + ui.put(field.shrink2(vec2(14.0, 10.0)), egui::TextEdit::singleline(password).password(true).frame(egui::Frame::NONE).font(fonts::ui(14.0)).text_color(t.on_surface).hint_text("Password")) + }).inner; + if !*busy { te.request_focus() } else { motion::keep_alive() } + let enter = ctx.input(|i| i.key_pressed(Key::Enter)); + let label = if *busy { "Saving…" } else { "Save" }; + if (pill(ui, &t, primary, "dlg/ok", "", label, Tone::Filled).clicked() || enter) && !*busy && !password.is_empty() { + *busy = true; + let (id, pw) = (*id, std::mem::take(password)); + after = Some(Box::new(move |app, ctx| app.save_elevated(ctx, id, pw))); + } + } Dialog::ConfirmQuit => { ui.painter().text(rect.left_top() + vec2(26.0, 72.0), Align2::LEFT_CENTER, if self.side_window { "This window isn't part of your session, so they'll be lost" } else { "They stay saved as recovery copies for next time" }, fonts::ui(14.0), t.on_variant); if pill(ui, &t, primary, "dlg/ok", "", "Quit", Tone::Filled).clicked() { diff --git a/src/ui/preview.rs b/src/ui/preview.rs index 9844898..69ee21f 100644 --- a/src/ui/preview.rs +++ b/src/ui/preview.rs @@ -177,11 +177,25 @@ impl App { let popped = pop.abs() > 0.004; let frame = Rect::from_min_max(pos2(rail.right() - rail.width() * visual - 2.0 * hov, rail.top()), rail.max); let lh = lerp(LINE_H.0, LINE_H.1, pop.clamp(0.0, 1.2)); - let visible = m.lh * count as f32; let total_h = lh * count as f32; - let max_scroll = (visible - rail.height()).max(1.0); - let frac = (scroll / max_scroll).clamp(0.0, 1.0); - let offset = if total_h > frame.height() { frac * (total_h - frame.height()) } else { 0.0 }; + // the rail slides in step with the view: by how far through the file the top line is, in + // lines, so wrapped and folded files map the same way + let first_line = { + let tb = &self.panes[pane].tabs[self.panes[pane].active]; + let row = (scroll / m.lh).max(0.0); + let (l, c) = tb.rows.row(row as usize); + (l.min(count) as f32 + if c == 0 { row.fract() } else { 0.0 }).min(count as f32) + }; + let view_lines = (rail.height() / m.lh).min(count as f32); + // the editor scrolls until the last line sits mid-view + let last_top = (count as f32 - rail.height() / m.lh * 0.5).max(1.0); + // where the bubble's middle sits on the rail for a given top line, worked out at rest; popping + // out zooms the lines around it but leaves it there, so a grab never jumps + let rest_h = LINE_H.0 * count as f32; + let slide = if rest_h > frame.height() { (rest_h - frame.height()) / last_top } else { 0.0 }; + let bubble_at = |top: f32| top * (LINE_H.0 - slide) + view_lines / 2.0 * LINE_H.0; + let top_now = first_line.clamp(0.0, last_top); + let offset = ((top_now + view_lines / 2.0) * lh - bubble_at(top_now)).clamp(0.0, (total_h - frame.height()).max(0.0)); // the picture: drawn by a worker, and only asked for again once the last one has landed { @@ -266,16 +280,13 @@ impl App { } // viewport bubble: squashes and stretches with speed - let first_line = { - let tb = &self.panes[pane].tabs[self.panes[pane].active]; - tb.rows.row((scroll / m.lh).max(0.0) as usize).0.min(count) as f32 - }; - let view_lines = (rail.height() / m.lh).min(count as f32); let y_a = map.y_of(first_line); let y_b = map.y_of(first_line + view_lines); let top = spring(format!("{key}/ta"), y_a, Preset { stiffness: 1500.0, damping: 0.74 }); let bot = spring(format!("{key}/tb"), y_b.max(y_a + 14.0), Preset { stiffness: 620.0, damping: 0.66 }); - let thumb = Rect::from_min_max(pos2(frame.left() + 3.0, top), pos2(frame.right() - 3.0, bot.max(top + 12.0))); + // kept inside the rail, so it sits flush at either end + let top = top.clamp(frame.top() + 3.0, frame.bottom() - 15.0); + let thumb = Rect::from_min_max(pos2(frame.left() + 3.0, top), pos2(frame.right() - 3.0, bot.max(top + 12.0).min(frame.bottom() - 3.0))); let thumb_alpha = 0.16 + 0.1 * hov + 0.06 * pop.clamp(0.0, 1.0); painter.rect_filled(thumb, cr(12.0), alpha(t.primary, thumb_alpha)); painter.rect_stroke(thumb, cr(12.0), egui::Stroke::new(1.0 + hov, alpha(t.primary, 0.3 + 0.4 * hov)), egui::StrokeKind::Inside); @@ -299,6 +310,9 @@ impl App { let pressed = resp.is_pointer_button_down_on(); if pressed && !self.panes[pane].dragging_mini { self.panes[pane].dragging_mini = true; + // grabbing the bubble holds it where it was taken; anywhere else centres it there + let mid = (y_a + y_b) / 2.0; + self.panes[pane].mini_grab = ptr.filter(|p| p.y >= y_a && p.y <= y_b).map_or(0.0, |p| p.y - mid); self.panes[pane].peek_from = ui.input(|i| i.modifiers.shift).then_some(scroll); motion::forget(format!("{key}/lens")); } @@ -315,16 +329,21 @@ impl App { } if pane_ref.dragging_mini { if let Some(p) = ptr { - let y = (p.y - frame.top()).clamp(0.0, frame.height()); - // the file maps onto the rail, whatever the scroll, so a drag can't feed back on itself - let line = if total_h > frame.height() { (y / frame.height()) * count as f32 } else { (y / lh).min(count as f32) }; - pane_ref.lens_line = line; - pane_ref.lens_y = p.y; + let y = (p.y - pane_ref.mini_grab - frame.top()).clamp(0.0, frame.height()); + // the top line that puts the bubble's middle under the pointer (`bubble_at` turned + // round), so it stays with the pointer all the way down and can't feed back on itself + let top = ((y - view_lines / 2.0 * LINE_H.0) / (LINE_H.0 - slide)).clamp(0.0, last_top); if pane_ref.peek_from.is_none() { + pane_ref.lens_line = (top + view_lines / 2.0).min(count as f32); let a = pane_ref.active; - let target = line * m.lh - rail.height() / 2.0; - pane_ref.tabs[a].scroll.target = target.clamp(0.0, (count as f32 * m.lh - rail.height() * 0.5).max(0.0)); + let tb = &mut pane_ref.tabs[a]; + let row = tb.rows.row_of(top as usize, 0) as f32 + top.fract(); + tb.scroll.target = (row * m.lh).clamp(0.0, (tb.rows.count(&self.docs[&doc_id]) as f32 * m.lh - rail.height() * 0.5).max(0.0)); + } else { + // peeking leaves the view alone: the card shows what's under the pointer + pane_ref.lens_line = ((p.y - frame.top()).clamp(0.0, frame.height()) + offset) / lh; } + pane_ref.lens_y = p.y; } if !ui.input(|i| i.pointer.primary_down()) { pane_ref.dragging_mini = false; diff --git a/src/ui/sidebar.rs b/src/ui/sidebar.rs index 8517c0b..132ebbd 100644 --- a/src/ui/sidebar.rs +++ b/src/ui/sidebar.rs @@ -193,8 +193,13 @@ impl App { let scroll = self.scrolled(ui, area, 0, rows.len() as f32 * row_h); let cur = self.cur_doc().and_then(|d| d.path.clone()); let first = (scroll / row_h) as usize; - let git_root = self.git.root.clone(); - let changed: HashMap = self.git.files.iter().filter_map(|f| git_root.as_ref().map(|r| (r.join(&f.2), if f.1 != ' ' { f.1 } else { f.0 }))).collect(); + // edited this session: open with changes, or saved with changes since the app started + let mut changed: HashMap = self.edited.iter().map(|p| (p.clone(), 'M')).collect(); + for d in self.docs.values() { + if let Some(p) = &d.path { + if d.buf.is_modified() || !d.marks.is_empty() { changed.insert(p.clone(), 'M'); } else { changed.remove(p); } + } + } for (i, (path, name, is_dir, depth)) in rows.iter().enumerate().skip(first).take((area.height() / row_h) as usize + 2) { let y = area.top() + i as f32 * row_h - scroll; let r = Rect::from_min_size(pos2(area.left() + *depth as f32 * 14.0, y), vec2(area.width() - *depth as f32 * 14.0 - 6.0, row_h - 2.0)); diff --git a/tests/features.rs b/tests/features.rs index b775338..f4c2b39 100644 --- a/tests/features.rs +++ b/tests/features.rs @@ -477,8 +477,8 @@ fn git_panel_on_a_real_repository() { h.state_mut().set_root(dir.clone()); wait(&mut h, 10, "status reads", |h| h.state().git.files.len() == 2); assert_eq!(h.state().git.branch, "main"); - let marks = h.state().git.marks.get(&std::fs::canonicalize(&f).unwrap()).cloned().unwrap_or_default(); - assert_eq!(marks, vec![(1, 1, 1), (3, 1, 0)], "changed line 2, added line 4"); + // change bars describe this session's edits, not what git holds + assert!(h.state().cur_doc().unwrap().marks.is_empty()); h.state_mut().git_stage("new.txt", false); wait(&mut h, 10, "staged", |h| h.state().git.files.iter().any(|x| x.0 == 'A')); h.state_mut().git_stage("new.txt", true); @@ -493,6 +493,109 @@ fn git_panel_on_a_real_repository() { std::fs::remove_dir_all(dir).ok(); } +#[test] +fn change_bars_last_one_session() { + let dir = tmp("marks"); + let f = write(&dir.join("a.txt"), "one\ntwo\nthree\n"); + let mut h = app(vec![f.clone()]); + caret(&mut h, 1, 0); + typed(&mut h, "2"); + caret(&mut h, 3, 0); + typed(&mut h, "four\n"); + // changed line 2, added line 4 + wait(&mut h, 5, "bars", |h| h.state().cur_doc().unwrap().marks == vec![(1, 1, 1), (3, 1, 0)]); + cmd(&mut h, Cmd::Save); + assert_eq!(h.state().cur_doc().unwrap().marks.len(), 2, "saving keeps them for the session"); + assert!(h.state().edited.contains(&std::fs::canonicalize(&f).unwrap())); + h.state().save_session(); + drop(h); + // a new run: the same file, nothing marked + let h = app(vec![f]); + assert!(h.state().cur_doc().unwrap().marks.is_empty()); + assert!(h.state().edited.is_empty()); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn rail_drag_follows_the_pointer_in_a_long_file() { + use eframe::egui::{pos2, PointerButton}; + let dir = tmp("rail"); + let body: String = (0..6000).map(|i| format!("line {i}\n")).collect(); + let f = write(&dir.join("long.txt"), &body); + let mut h = app(vec![f]); + settle(&mut h, 20); + let x = std::env::var("RAIL_X").ok().and_then(|v| v.parse().ok()).unwrap_or(1262.0); + let ev = |h: &mut H, e: Event| { h.input_mut().events.push(e); h.step(); std::thread::sleep(Duration::from_millis(16)) }; + let press = |p, down| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE }; + let scroll = |h: &H| h.state().panes[0].tabs[0].scroll.target; + ev(&mut h, Event::PointerMoved(pos2(x, 140.0))); + ev(&mut h, press(pos2(x, 140.0), true)); + assert!(h.state().panes[0].dragging_mini, "pressed the rail"); + let mut y = 140.0; + while y < 790.0 { + y += 25.0; + ev(&mut h, Event::PointerMoved(pos2(x, y))); + } + settle(&mut h, 40); + if let Ok(out) = std::env::var("DAMSON_SHOTS") { h.render().unwrap().save(format!("{out}/rail-drag.png")).unwrap() } + let bottom = scroll(&h); + println!(" dragged to y {y}: scroll {bottom}"); + ev(&mut h, press(pos2(x, y), false)); + settle(&mut h, 40); + // press again on the same spot: the view stays where it is + ev(&mut h, press(pos2(x, y), true)); + settle(&mut h, 10); + let again = scroll(&h); + println!(" pressed again: scroll {again}"); + ev(&mut h, press(pos2(x, y), false)); + assert!((again - bottom).abs() < 40.0, "jumped from {bottom} to {again}"); + // and the end of the file is reachable by dragging to the bottom + ev(&mut h, press(pos2(x, 400.0), true)); + for i in 0..30 { ev(&mut h, Event::PointerMoved(pos2(x, 400.0 + i as f32 * 20.0))) } + settle(&mut h, 20); + let end = scroll(&h); + ev(&mut h, press(pos2(x, 980.0), false)); + let m = h.state().s.font_size * 1.55; + let max = 6001.0 * m.round() - 400.0; + println!(" dragged past the bottom: scroll {end} (end about {max})"); + assert!(end > max * 0.97, "only reached {end} of {max}"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn protected_files_save_through_sudo() { + use std::os::unix::fs::PermissionsExt; + let dir = tmp("sudo"); + // a stand-in sudo: one password line on stdin, then the command, made able to write + let bin = dir.join("bin"); + write(&bin.join("sudo"), "#!/bin/sh\nread pw\n[ \"$pw\" = secret ] || { echo 'sudo: 1 incorrect password attempt' >&2; exit 1; }\nwhile [ \"$1\" != -- ]; do shift; done; shift\nfor a; do t=$a; done\nchmod u+w \"$t\"; \"$@\"; r=$?; chmod a-w \"$t\"; exit $r\n"); + std::fs::set_permissions(bin.join("sudo"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let f = write(&dir.join("conf.txt"), "old\n"); + std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o444)).unwrap(); + let path = std::env::var("PATH").unwrap(); + std::env::set_var("PATH", format!("{}:{path}", bin.display())); + let mut h = app(vec![f.clone()]); + caret(&mut h, 0, 0); + typed(&mut h, "new "); + cmd(&mut h, Cmd::Save); + assert!(matches!(h.state().dialog, Some(damson::ui::menu::Dialog::Sudo { .. })), "asks for the password"); + assert_eq!(std::fs::read_to_string(&f).unwrap(), "old\n"); + if let Ok(out) = std::env::var("DAMSON_SHOTS") { h.render().unwrap().save(format!("{out}/sudo-ask.png")).unwrap() } + typed(&mut h, "wrong"); + key(&mut h, Key::Enter, Modifiers::NONE); + wait(&mut h, 10, "wrong password told", |h| matches!(&h.state().dialog, Some(damson::ui::menu::Dialog::Sudo { error: Some(_), busy: false, .. }))); + if let Ok(out) = std::env::var("DAMSON_SHOTS") { settle(&mut h, 20); h.render().unwrap().save(format!("{out}/sudo-wrong.png")).unwrap() } + assert!(h.state().cur_doc().unwrap().buf.is_modified()); + typed(&mut h, "secret"); + key(&mut h, Key::Enter, Modifiers::NONE); + wait(&mut h, 10, "saved", |h| h.state().dialog.is_none() && !h.state().cur_doc().unwrap().buf.is_modified()); + std::env::set_var("PATH", path); + assert_eq!(std::fs::read_to_string(&f).unwrap(), "new old\n"); + assert_eq!(std::fs::metadata(&f).unwrap().permissions().mode() & 0o777, 0o444, "the file keeps its mode"); + std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o644)).unwrap(); + std::fs::remove_dir_all(dir).ok(); +} + #[test] fn search_outline_and_palette() { let dir = tmp("search");