From a pass with the taste skill's rules:
- File errors read as a person would say them ("Couldn't open x: it
isn't there") instead of raw OS text with "(os error 2)", and each
prompt says what it couldn't do.
- Segmented buttons tint on hover and squeeze when pressed, and switches
get a hover halo round the thumb, like the rest of the controls.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1676 lines
77 KiB
Rust
1676 lines
77 KiB
Rust
//! The application: state, layout and command handling.
|
|
use crate::config::{config_dir, Settings};
|
|
use crate::discord;
|
|
use crate::git::{self, GitState};
|
|
use crate::lsp::{self, Client, CompletionItem, Diag, LspEvent};
|
|
use crate::motion::{self, spring, Preset};
|
|
use crate::syntax::Registry;
|
|
use crate::text::commands::Prefs;
|
|
use crate::text::{Doc, EditKind, Sel};
|
|
use crate::theme::{self, alpha, Theme};
|
|
use crate::ui::commands::Cmd;
|
|
use crate::ui::editor::Tab;
|
|
use crate::ui::find::Find;
|
|
use crate::ui::menu::{Act, Dialog, Menu};
|
|
use crate::ui::palette::Palette;
|
|
use crate::ui::preview::Mini;
|
|
use crate::ui::sidebar::Side;
|
|
use crate::ui::terminal::Session;
|
|
use crate::ui::morph::{self, Morph};
|
|
use crate::ui::{fonts, icons, status::FAB_W, widgets::*};
|
|
use eframe::egui::{self, pos2, vec2, Align2, Color32, Id, Key, Modifiers, Pos2, Rect, Sense, Stroke, Ui, ViewportCommand};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::collections::HashMap;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::mpsc::{channel, Receiver, Sender};
|
|
use std::sync::Arc;
|
|
use std::time::{Duration, Instant, SystemTime};
|
|
|
|
/// A file error as a person would say it, for the end of a "Couldn't …" message.
|
|
pub fn why(e: &std::io::Error) -> String {
|
|
use std::io::ErrorKind::*;
|
|
match e.kind() {
|
|
NotFound => "it isn't there".into(),
|
|
PermissionDenied => "you don't have permission".into(),
|
|
AlreadyExists => "something with that name is already there".into(),
|
|
IsADirectory => "it's a folder".into(),
|
|
NotADirectory => "part of that path is a file, not a folder".into(),
|
|
DirectoryNotEmpty => "the folder isn't empty".into(),
|
|
StorageFull => "the disk is full".into(),
|
|
ReadOnlyFilesystem => "the drive is read-only".into(),
|
|
_ => {
|
|
// the system's wording, without "(os error 2)" and with a small first letter
|
|
let s = e.to_string();
|
|
let s = s.split(" (os error").next().unwrap_or(&s).trim().to_string();
|
|
let mut c = s.chars();
|
|
c.next().map_or(s.clone(), |f| f.to_lowercase().chain(c).collect())
|
|
}
|
|
}
|
|
}
|
|
|
|
pub enum Msg {
|
|
Search(Vec<(PathBuf, usize, String)>),
|
|
Git(Box<GitState>),
|
|
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 {
|
|
pub tabs: Vec<Tab>,
|
|
pub active: usize,
|
|
pub mini: Mini,
|
|
pub dragging_mini: bool,
|
|
pub peek_from: Option<f32>,
|
|
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)>,
|
|
pub seq: u64,
|
|
}
|
|
|
|
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, mini_grab: 0.0, tab_scroll: 0.0, reveal_tab: false, tab_drag: None, seq }
|
|
}
|
|
}
|
|
|
|
pub struct Toast {
|
|
pub ic: &'static str,
|
|
pub text: String,
|
|
pub born: f64,
|
|
pub seq: u64,
|
|
}
|
|
|
|
pub struct Completion {
|
|
pub items: Vec<CompletionItem>,
|
|
pub sel: usize,
|
|
pub start: usize,
|
|
pub seq: u64,
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize, Default)]
|
|
struct SessionFile {
|
|
root: Option<PathBuf>,
|
|
files: Vec<SavedFile>,
|
|
active: usize,
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
struct SavedFile {
|
|
path: Option<PathBuf>,
|
|
line: usize,
|
|
col: usize,
|
|
scroll: f32,
|
|
/// Recovery copy of unsaved text.
|
|
backup: Option<PathBuf>,
|
|
}
|
|
|
|
pub struct App {
|
|
pub s: Settings,
|
|
pub t: Arc<Theme>,
|
|
pub theme_stamp: u32,
|
|
pub reg: Registry,
|
|
pub docs: HashMap<u64, Doc>,
|
|
pub panes: Vec<Pane>,
|
|
pub focus_pane: usize,
|
|
pub split_vertical: bool,
|
|
pub split: f32,
|
|
next_id: u64,
|
|
pub root: Option<PathBuf>,
|
|
pub reveal: bool,
|
|
pub last_input: f64,
|
|
pub side: usize,
|
|
pub side_open: bool,
|
|
pub side_state: Side,
|
|
pub settings_open: bool,
|
|
pub settings_tab: usize,
|
|
pub settings_scroll: [f32; 6],
|
|
pub settings_height: [f32; 6],
|
|
pub shell_open: bool,
|
|
pub shells: Vec<String>,
|
|
pub toolbar_filter: String,
|
|
pub logo_spin: f32,
|
|
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<PathBuf>,
|
|
pub diags: HashMap<PathBuf, Vec<Diag>>,
|
|
pub terms: Vec<Session>,
|
|
pub term_cur: usize,
|
|
pub next_term: u64,
|
|
pub term_open: bool,
|
|
pub term_busy: bool,
|
|
pub term_want_focus: bool,
|
|
pub term_target: Rect,
|
|
pub term_height: f32,
|
|
pub fab_rect: Rect,
|
|
pub palette: Palette,
|
|
pub find: Find,
|
|
pub menu: Option<Menu>,
|
|
pub menu_seq: u64,
|
|
pub dialog: Option<Dialog>,
|
|
pub toasts: Vec<Toast>,
|
|
toast_seq: u64,
|
|
closed: Vec<PathBuf>,
|
|
zen: bool,
|
|
pub tx: Sender<Msg>,
|
|
rx: Receiver<Msg>,
|
|
lsp_tx: Sender<(String, serde_json::Value)>,
|
|
lsp_rx: Receiver<(String, serde_json::Value)>,
|
|
pub lsp: HashMap<String, Client>,
|
|
lsp_dead: std::collections::HashSet<String>,
|
|
complete_due: Option<Instant>,
|
|
lsp_sent: HashMap<u64, u64>,
|
|
pub complete: Option<Completion>,
|
|
pub hover: Option<(String, Pos2, u64)>,
|
|
complete_seq: u64,
|
|
pub caret_pos: Pos2,
|
|
hover_copied: f64,
|
|
smoke_frames: u64,
|
|
pub side_window: bool,
|
|
startup: Vec<Cmd>,
|
|
window_title: String,
|
|
presence: Sender<discord::Update>,
|
|
presence_sent: Option<(String, bool, bool, bool)>,
|
|
last_time: Option<Instant>,
|
|
last_poll: Instant,
|
|
last_guess: Instant,
|
|
last_session: Instant,
|
|
last_git: Instant,
|
|
last_stamp: Option<SystemTime>,
|
|
saved_settings: Settings,
|
|
pub quit_now: bool,
|
|
}
|
|
|
|
impl App {
|
|
pub fn new(cc: &eframe::CreationContext, files: Vec<String>) -> App {
|
|
Self::build(&cc.egui_ctx, files)
|
|
}
|
|
|
|
pub fn build(ctx: &egui::Context, args: Vec<String>) -> App {
|
|
let (flags, files): (Vec<String>, Vec<String>) = args.into_iter().partition(|a| a.starts_with("--"));
|
|
let s = Settings::load();
|
|
fonts::install(ctx, &s.mono_font);
|
|
let (tx, rx) = channel();
|
|
let (lsp_tx, lsp_rx) = channel();
|
|
let t = Arc::new(Theme::build(&s));
|
|
let mut a = App {
|
|
t, theme_stamp: 1, reg: Registry::scan(), docs: HashMap::new(), panes: vec![Pane::new(0)], focus_pane: 0, split_vertical: false,
|
|
split: 0.5, next_id: 1, root: None, reveal: false, last_input: 0.0, side: 0, side_open: false, side_state: Side::default(),
|
|
settings_open: false, settings_tab: 0, settings_scroll: [0.0; 6], settings_height: [0.0; 6], shell_open: false, shells: vec![], toolbar_filter: String::new(), logo_spin: 0.0, logo_clock: 0.0, theme_wave: None, git: GitState::default(), diags: HashMap::new(),
|
|
terms: vec![], term_cur: 0, next_term: 0, term_open: false, term_busy: false, term_want_focus: false, term_target: Rect::from_min_size(pos2(0.0, 0.0), vec2(900.0, 300.0)), term_height: 300.0, fab_rect: Rect::from_min_size(pos2(0.0, 0.0), vec2(FAB_W, 44.0)),
|
|
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, 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
|
|
a.side_window = !flags.is_empty();
|
|
for f in &flags {
|
|
match f.as_str() {
|
|
"--new-file" => a.startup.push(Cmd::New),
|
|
"--open-folder" => a.startup.push(Cmd::OpenFolder),
|
|
"--terminal" => a.startup.push(Cmd::ToggleTerminal),
|
|
_ => {}
|
|
}
|
|
}
|
|
if a.s.restore_session && files.is_empty() && !a.side_window {
|
|
a.restore_session(ctx);
|
|
}
|
|
for f in files {
|
|
let (path, line) = split_line(&f);
|
|
if path.is_dir() { a.set_root(path) } else { a.open_path(ctx, path, line) }
|
|
}
|
|
a
|
|
}
|
|
|
|
fn apply_style(&self, ctx: &egui::Context) {
|
|
let t = &self.t;
|
|
let mut v = if t.dark { egui::Visuals::dark() } else { egui::Visuals::light() };
|
|
v.panel_fill = Color32::TRANSPARENT;
|
|
v.window_fill = t.high;
|
|
v.override_text_color = Some(t.on_surface);
|
|
v.selection.bg_fill = alpha(t.primary, 0.32);
|
|
v.text_cursor.stroke = Stroke::new(2.0, t.primary);
|
|
v.widgets.noninteractive.bg_stroke = Stroke::NONE;
|
|
ctx.set_visuals(v);
|
|
ctx.global_style_mut(|s| s.interaction.tooltip_delay = 0.45);
|
|
}
|
|
|
|
pub fn refresh_theme(&mut self, ctx: &egui::Context) {
|
|
self.t = Arc::new(Theme::build(&self.s));
|
|
self.theme_stamp += 1;
|
|
self.apply_style(ctx);
|
|
}
|
|
|
|
pub fn settings_changed(&mut self, ctx: &egui::Context, old: &Settings) {
|
|
let s = &self.s;
|
|
if (&s.mode, &s.color_source, &s.scheme, &s.custom_color) != (&old.mode, &old.color_source, &old.scheme, &old.custom_color) {
|
|
self.refresh_theme(ctx);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- documents
|
|
|
|
pub fn pane_focus_id(&self, pane: usize) -> Id {
|
|
Id::unique(("editor", self.panes[pane].seq))
|
|
}
|
|
|
|
pub fn cur_doc_id(&self) -> Option<u64> {
|
|
let p = self.panes.get(self.focus_pane)?;
|
|
p.tabs.get(p.active).map(|t| t.doc)
|
|
}
|
|
|
|
pub fn cur_doc(&self) -> Option<&Doc> {
|
|
self.docs.get(&self.cur_doc_id()?)
|
|
}
|
|
|
|
pub fn cur_doc_mut(&mut self) -> Option<&mut Doc> {
|
|
let id = self.cur_doc_id()?;
|
|
self.docs.get_mut(&id)
|
|
}
|
|
|
|
pub fn focus_editor(&mut self, ctx: &egui::Context) {
|
|
let id = self.pane_focus_id(self.focus_pane.min(self.panes.len() - 1));
|
|
ctx.memory_mut(|m| m.request_focus(id));
|
|
}
|
|
|
|
fn add_doc(&mut self, ctx: &egui::Context, doc: Doc) {
|
|
let now = ctx.input(|i| i.time);
|
|
let (pane, id) = (self.focus_pane, doc.id);
|
|
self.docs.insert(id, doc);
|
|
self.lsp_open(id);
|
|
let p = &mut self.panes[pane];
|
|
p.tabs.push(Tab::new(id, now));
|
|
p.active = p.tabs.len() - 1;
|
|
p.reveal_tab = true;
|
|
self.focus_editor(ctx);
|
|
}
|
|
|
|
pub fn open_path(&mut self, ctx: &egui::Context, path: PathBuf, line: Option<usize>) {
|
|
let path = std::fs::canonicalize(&path).unwrap_or(path);
|
|
let found = self.panes[self.focus_pane].tabs.iter().position(|t| self.docs.get(&t.doc).is_some_and(|d| d.path.as_ref() == Some(&path)));
|
|
if let Some(i) = found {
|
|
let now = ctx.input(|i| i.time);
|
|
self.activate_tab(self.focus_pane, i, now);
|
|
} else {
|
|
// the same file open in another split shares its document
|
|
let shared = self.docs.values().find(|d| d.path.as_ref() == Some(&path)).map(|d| d.id);
|
|
if let Some(id) = shared {
|
|
let now = ctx.input(|i| i.time);
|
|
let p = &mut self.panes[self.focus_pane];
|
|
p.tabs.push(Tab::new(id, now));
|
|
p.active = p.tabs.len() - 1;
|
|
p.reveal_tab = true;
|
|
} else {
|
|
let id = self.next_id;
|
|
self.next_id += 1;
|
|
match Doc::open(id, path.clone(), &mut self.reg) {
|
|
Ok(d) => {
|
|
self.s.note_recent(&path.to_string_lossy());
|
|
if self.root.is_none() { self.adopt_root(&path) }
|
|
self.add_doc(ctx, d);
|
|
}
|
|
Err(e) => return self.toast("error", format!("Couldn't open {}: {}", path.display(), why(&e))),
|
|
}
|
|
}
|
|
}
|
|
if let Some(l) = line {
|
|
self.jump_to_line(ctx, l);
|
|
}
|
|
}
|
|
|
|
/// Takes the enclosing git repository, if any, as the project folder.
|
|
fn adopt_root(&mut self, file: &Path) {
|
|
if let Some(dir) = file.parent() {
|
|
if let Ok(out) = git::run(dir, &["rev-parse", "--show-toplevel"]) {
|
|
self.set_root(PathBuf::from(out.trim()));
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn set_root(&mut self, p: PathBuf) {
|
|
self.root = Some(p);
|
|
self.side_state.dirs.clear();
|
|
self.side_state.expanded.clear();
|
|
self.palette.files_root = None;
|
|
self.refresh_git();
|
|
}
|
|
|
|
pub fn jump_to_line(&mut self, ctx: &egui::Context, line: usize) {
|
|
let now = ctx.input(|i| i.time);
|
|
let m_h = (self.s.font_size * 1.55).round();
|
|
let pane = self.focus_pane;
|
|
let Some(id) = self.cur_doc_id() else { return };
|
|
let d = self.docs.get_mut(&id).unwrap();
|
|
let line = line.min(d.buf.lines() - 1);
|
|
d.sync_edits();
|
|
if d.buf.sels.iter().all(|s| d.buf.pos(s.head).0 != line) {
|
|
let at = d.buf.at(line, 0);
|
|
d.buf.set_cursor(at);
|
|
}
|
|
let p = &mut self.panes[pane];
|
|
let a = p.active;
|
|
let tb = &mut p.tabs[a];
|
|
let row = tb.rows.row_of(line, 0);
|
|
tb.scroll.target = (row as f32 * m_h - 240.0).max(0.0);
|
|
tb.beacon = Some((line, now));
|
|
self.focus_editor(ctx);
|
|
}
|
|
|
|
pub fn activate_tab(&mut self, pane: usize, i: usize, _now: f64) {
|
|
self.focus_pane = pane;
|
|
let p = &mut self.panes[pane];
|
|
if i < p.tabs.len() {
|
|
p.active = i;
|
|
p.reveal_tab = true;
|
|
}
|
|
}
|
|
|
|
pub fn close_tab(&mut self, pane: usize, i: usize) {
|
|
let Some(tab) = self.panes[pane].tabs.get(i) else { return };
|
|
let doc = tab.doc;
|
|
let shared = self.panes.iter().flat_map(|p| &p.tabs).filter(|t| t.doc == doc).count() > 1;
|
|
let d = &self.docs[&doc];
|
|
if d.buf.is_modified() && !shared && !d.buf.rope.len_chars().eq(&0) {
|
|
self.dialog = Some(Dialog::Confirm { title: format!("Save {}?", d.title()), body: "Your changes will be lost if you don't save them".into(), pane, tab: i });
|
|
return;
|
|
}
|
|
self.force_close(pane, i);
|
|
}
|
|
|
|
pub fn force_close(&mut self, pane: usize, i: usize) {
|
|
let p = &mut self.panes[pane];
|
|
if i >= p.tabs.len() { return }
|
|
let doc = p.tabs.remove(i).doc;
|
|
if p.active >= i && p.active > 0 { p.active -= 1 }
|
|
if p.tabs.is_empty() && self.panes.len() > 1 {
|
|
self.panes.remove(pane);
|
|
self.focus_pane = 0;
|
|
}
|
|
if !self.panes.iter().flat_map(|p| &p.tabs).any(|t| t.doc == doc) {
|
|
if let Some(d) = self.docs.remove(&doc) {
|
|
if let Some(path) = d.path {
|
|
self.lsp_close(&path);
|
|
self.closed.push(path);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The save dialog, already filled in with the file's name.
|
|
fn ask_save_path(&self, id: u64) -> Option<PathBuf> {
|
|
let d = self.docs.get(&id)?;
|
|
let mut dlg = rfd::FileDialog::new().set_file_name(d.title());
|
|
if let Some(dir) = d.path.as_ref().and_then(|p| p.parent()).or(self.root.as_deref()) {
|
|
dlg = dlg.set_directory(dir);
|
|
}
|
|
dlg.save_file()
|
|
}
|
|
|
|
fn name_doc(&mut self, id: u64, path: PathBuf) {
|
|
let d = self.docs.get_mut(&id).unwrap();
|
|
d.named(path.clone(), &mut self.reg);
|
|
self.s.note_recent(&path.to_string_lossy());
|
|
self.lsp_open(id);
|
|
}
|
|
|
|
fn save_doc(&mut self, ctx: &egui::Context, id: u64) {
|
|
if self.docs.get(&id).is_some_and(|d| d.path.is_none()) {
|
|
let Some(p) = self.ask_save_path(id) else { return };
|
|
self.name_doc(id, p);
|
|
}
|
|
let trim = self.s.trim_on_save;
|
|
let d = self.docs.get_mut(&id).unwrap();
|
|
if trim { d.buf.trim_trailing() }
|
|
match d.save() {
|
|
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: {}", why(&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 });
|
|
if self.toasts.len() > 3 { self.toasts.remove(0); }
|
|
}
|
|
|
|
pub fn trash(&mut self, p: &Path) {
|
|
let done = crate::trash::move_to_trash(p);
|
|
if done.is_ok() {
|
|
self.side_state.dirs.clear();
|
|
self.toast("delete", "Moved to the trash".to_string());
|
|
} else if let Err(e) = done {
|
|
self.toast("error", format!("Couldn't move it to the trash: {}", why(&e)));
|
|
}
|
|
}
|
|
|
|
pub fn prompt_done(&mut self, ctx: &egui::Context, act: Act, value: String) {
|
|
if value.trim().is_empty() { return }
|
|
let (what, res) = match act {
|
|
Act::NewFile(dir) => {
|
|
let p = dir.join(&value);
|
|
let r = std::fs::write(&p, "");
|
|
if r.is_ok() { self.open_path(ctx, p, None) }
|
|
("create the file", r)
|
|
}
|
|
Act::NewFolder(dir) => ("create the folder", std::fs::create_dir_all(dir.join(&value))),
|
|
Act::Rename(p) => {
|
|
let to = p.with_file_name(&value);
|
|
let r = std::fs::rename(&p, &to);
|
|
if r.is_ok() {
|
|
for d in self.docs.values_mut() {
|
|
if d.path.as_ref() == Some(&p) { d.path = Some(to.clone()) }
|
|
}
|
|
}
|
|
("rename it", r)
|
|
}
|
|
_ => ("", Ok(())),
|
|
};
|
|
if let Err(e) = res { self.toast("error", format!("Couldn't {what}: {}", why(&e))) }
|
|
self.side_state.dirs.clear();
|
|
}
|
|
|
|
pub fn act(&mut self, ctx: &egui::Context, a: Act) {
|
|
match a {
|
|
Act::Cmd(c) => self.run(ctx, c),
|
|
Act::CloseTabAt(p, i) => self.close_tab(p, i),
|
|
Act::CloseOthers(p, i) => {
|
|
let n = self.panes[p].tabs.len();
|
|
for j in (0..n).rev() {
|
|
if j != i && !self.docs[&self.panes[p].tabs[j].doc].buf.is_modified() { self.force_close(p, j) }
|
|
}
|
|
}
|
|
Act::NewFile(_) | Act::NewFolder(_) => {
|
|
let title = if matches!(a, Act::NewFile(_)) { "New file" } else { "New folder" };
|
|
self.dialog = Some(Dialog::Prompt { title: title.to_string(), value: String::new(), act: a });
|
|
}
|
|
Act::Rename(ref p) => {
|
|
let value = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
|
self.dialog = Some(Dialog::Prompt { title: "Rename".to_string(), value, act: a });
|
|
}
|
|
Act::Trash(p) => self.dialog = Some(Dialog::ConfirmTrash(p)),
|
|
Act::CopyPath(p) => ctx.copy_text(p.to_string_lossy().into_owned()),
|
|
Act::TerminalAt(d) => {
|
|
self.new_terminal(ctx, Some(d));
|
|
self.term_open = true;
|
|
self.term_want_focus = true;
|
|
}
|
|
Act::SetRoot(p) => self.set_root(p),
|
|
Act::OpenRecent(p) => self.open_path(ctx, p, None),
|
|
}
|
|
}
|
|
|
|
pub fn run_in_terminal(&mut self, ctx: &egui::Context, cmd: &str) {
|
|
if self.terms.is_empty() { self.new_terminal(ctx, None) }
|
|
self.term_open = true;
|
|
// the shell retitles the terminal when the command ends, which is how Stop turns back into Run
|
|
if let Some(s) = self.terms.get_mut(self.term_cur) {
|
|
s.running = true;
|
|
s.write(format!("{cmd}; printf '\\033]2;{}\\007'\r", crate::ui::terminal::RUN_DONE));
|
|
}
|
|
self.term_want_focus = true;
|
|
}
|
|
|
|
fn file_runner(d: &Doc) -> Option<String> {
|
|
let p = d.path.as_ref()?;
|
|
let q = format!("'{}'", p.to_string_lossy().replace('\'', r"'\''"));
|
|
Some(match d.language.as_str() {
|
|
"Python" => format!("python3 {q}"),
|
|
"Bash" | "Zsh" => format!("bash {q}"),
|
|
"Fish" => format!("fish {q}"),
|
|
"JavaScript" => format!("node {q}"),
|
|
"Lua" => format!("lua {q}"),
|
|
"Ruby" => format!("ruby {q}"),
|
|
"Perl" => format!("perl {q}"),
|
|
"PHP (HTML)" | "PHP/PHP" => format!("php {q}"),
|
|
"Go" => format!("go run {q}"),
|
|
"Rust" => "cargo run".to_string(),
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
// ---------------------------------------------------------------- git
|
|
|
|
pub fn refresh_git(&mut self) {
|
|
let Some(dir) = self.root.clone() else { return };
|
|
self.last_git = Instant::now();
|
|
let tx = self.tx.clone();
|
|
std::thread::spawn(move || { let _ = tx.send(Msg::Git(Box::new(git::scan(&dir)))); });
|
|
}
|
|
|
|
pub fn git_commit(&mut self) {
|
|
let msg = self.side_state.commit.trim().to_string();
|
|
let Some(root) = self.git.root.clone() else { return };
|
|
if msg.is_empty() { return self.toast("edit", "Write a commit message first".to_string()) }
|
|
match git::run(&root, &["commit", "-m", &msg]) {
|
|
Ok(_) => { self.side_state.commit.clear(); self.toast("commit", "Committed".to_string()) }
|
|
Err(e) => self.toast("error", e.lines().next().unwrap_or("Commit failed").to_string()),
|
|
}
|
|
self.refresh_git();
|
|
}
|
|
|
|
pub fn git_stage(&mut self, path: &str, staged: bool) {
|
|
let Some(root) = self.git.root.clone() else { return };
|
|
let r = if staged { git::run(&root, &["restore", "--staged", "--", path]) } else { git::run(&root, &["add", "--", path]) };
|
|
if let Err(e) = r { self.toast("error", e) }
|
|
self.refresh_git();
|
|
}
|
|
|
|
pub fn git_remote(&mut self, verb: &'static str) {
|
|
let Some(root) = self.git.root.clone() else { return };
|
|
self.toast("sync", format!("Running git {verb}…"));
|
|
let tx = self.tx.clone();
|
|
std::thread::spawn(move || {
|
|
let _ = tx.send(match git::run(&root, &[verb]) {
|
|
Ok(_) => Msg::Note("check_circle", format!("git {verb} finished")),
|
|
Err(e) => Msg::Note("error", e.lines().last().unwrap_or("Failed").to_string()),
|
|
});
|
|
});
|
|
}
|
|
|
|
pub fn open_diff(&mut self, ctx: &egui::Context, root: &Path, rel: &str) {
|
|
let text = git::run(root, &["diff", "HEAD", "--", rel]).unwrap_or_default();
|
|
let id = self.next_id;
|
|
self.next_id += 1;
|
|
let mut d = Doc::new(id, &text, None, &mut self.reg);
|
|
d.set_language("Diff", &mut self.reg);
|
|
self.add_doc(ctx, d);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- language servers
|
|
|
|
fn lsp_for(&mut self, id: u64) -> Option<(String, &'static str)> {
|
|
if !self.s.lsp { return None }
|
|
let d = self.docs.get(&id)?;
|
|
d.path.as_ref()?;
|
|
let (bin, args, lang) = lsp::server_for(&d.language)?;
|
|
if self.lsp_dead.contains(bin) {
|
|
return None;
|
|
}
|
|
if !self.lsp.contains_key(bin) {
|
|
let root = self.root.clone().or_else(|| d.path.as_ref()?.parent().map(PathBuf::from))?;
|
|
let c = Client::start(bin, args, &root, bin.to_string(), self.lsp_tx.clone())?;
|
|
self.lsp.insert(bin.to_string(), c);
|
|
}
|
|
Some((bin.to_string(), lang))
|
|
}
|
|
|
|
fn lsp_open(&mut self, id: u64) {
|
|
let Some((bin, lang)) = self.lsp_for(id) else { return };
|
|
let d = &self.docs[&id];
|
|
let (Some(p), v, text) = (d.path.clone(), d.buf.version as i64, d.buf.rope.to_string()) else { return };
|
|
if let Some(c) = self.lsp.get_mut(&bin) { c.did_open(&p, lang, v, &text) }
|
|
self.lsp_sent.insert(id, d.buf.version);
|
|
}
|
|
|
|
fn lsp_close(&mut self, p: &Path) {
|
|
self.diags.remove(p);
|
|
}
|
|
|
|
fn lsp_saved(&mut self, p: &Path) {
|
|
for c in self.lsp.values_mut() { c.did_save(p) }
|
|
}
|
|
|
|
fn lsp_sync(&mut self) {
|
|
let ids: Vec<u64> = self.docs.keys().copied().collect();
|
|
for id in ids {
|
|
let v = self.docs[&id].buf.version;
|
|
if self.lsp_sent.get(&id) == Some(&v) { continue }
|
|
let Some((bin, _)) = self.lsp_for(id) else { continue };
|
|
let d = &self.docs[&id];
|
|
let (Some(p), text) = (d.path.clone(), d.buf.rope.to_string()) else { continue };
|
|
if let Some(c) = self.lsp.get_mut(&bin) { c.did_change(&p, v as i64, &text) }
|
|
self.lsp_sent.insert(id, v);
|
|
}
|
|
}
|
|
|
|
fn lsp_at(&mut self, f: impl FnOnce(&mut Client, &Path, usize, usize)) -> bool {
|
|
let Some(id) = self.cur_doc_id() else { return false };
|
|
let Some((bin, _)) = self.lsp_for(id) else { return false };
|
|
self.lsp_sync();
|
|
let d = &self.docs[&id];
|
|
let (l, c) = d.buf.pos(d.buf.head());
|
|
let Some(p) = d.path.clone() else { return false };
|
|
match self.lsp.get_mut(&bin) {
|
|
Some(cl) => { f(cl, &p, l, c); true }
|
|
None => false,
|
|
}
|
|
}
|
|
|
|
fn pump_lsp(&mut self, ctx: &egui::Context) {
|
|
while let Ok((key, v)) = self.lsp_rx.try_recv() {
|
|
if v.get(lsp::SERVER_GONE).is_some() {
|
|
self.lsp.remove(&key);
|
|
self.lsp_dead.insert(key.clone());
|
|
self.toast("warning", format!("{key} isn't working, so completion is using words from your files"));
|
|
continue;
|
|
}
|
|
let Some(ev) = self.lsp.get_mut(&key).and_then(|c| c.handle(v)) else { continue };
|
|
match ev {
|
|
LspEvent::Diagnostics(p, d) => {
|
|
if d.is_empty() { self.diags.remove(&p); } else { self.diags.insert(p, d); }
|
|
}
|
|
LspEvent::Completion(items) => self.show_completion(items),
|
|
LspEvent::Hover(text) => {
|
|
self.complete_seq += 1;
|
|
self.hover = self.caret_screen().map(|p| (text, p, self.complete_seq));
|
|
}
|
|
LspEvent::Definition(p, l, _) => self.open_path(ctx, p, Some(l)),
|
|
LspEvent::Ready(_) => {}
|
|
}
|
|
ctx.request_repaint();
|
|
}
|
|
}
|
|
|
|
fn caret_screen(&self) -> Option<Pos2> {
|
|
Some(self.caret_pos)
|
|
}
|
|
|
|
fn show_completion(&mut self, mut items: Vec<CompletionItem>) {
|
|
let Some(d) = self.cur_doc() else { return };
|
|
let word = d.buf.word_at(d.buf.head());
|
|
let prefix = d.buf.text(word.start..d.buf.head()).to_lowercase();
|
|
items.retain(|i| i.filter.to_lowercase().starts_with(&prefix));
|
|
if items.is_empty() {
|
|
self.complete = None;
|
|
return;
|
|
}
|
|
// an open list keeps its place in the animation as it narrows
|
|
let seq = match &self.complete {
|
|
Some(c) => c.seq,
|
|
None => { self.complete_seq += 1; self.complete_seq }
|
|
};
|
|
self.complete = Some(Completion { items, sel: 0, start: word.start, seq });
|
|
}
|
|
|
|
/// Asks for completions a moment after typing, when what was typed calls for them.
|
|
fn typing_completion(&mut self, ctx: &egui::Context) {
|
|
let focused = ctx.memory(|m| m.focused()) == Some(self.pane_focus_id(self.focus_pane));
|
|
let typed = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_)) || matches!(e, egui::Event::Key { key: Key::Backspace, pressed: true, .. })));
|
|
if focused && typed {
|
|
self.complete_due = Some(Instant::now());
|
|
}
|
|
if self.complete_due.is_some_and(|t| t.elapsed() > Duration::from_millis(70)) {
|
|
self.complete_due = None;
|
|
let wanted = self.cur_doc().is_some_and(|d| {
|
|
let head = d.buf.head();
|
|
let word = d.buf.word_at(head);
|
|
let before = |n: usize| head.checked_sub(n).and_then(|i| d.buf.rope.get_char(i));
|
|
let member = before(1) == Some('.') || (before(1) == Some(':') && before(2) == Some(':')) || (before(1) == Some('>') && before(2) == Some('-'));
|
|
head - word.start >= 2 || member
|
|
});
|
|
if wanted && (self.s.auto_complete || self.complete.is_some()) {
|
|
self.run(ctx, Cmd::Complete);
|
|
} else {
|
|
self.complete = None;
|
|
}
|
|
}
|
|
// moving out of the word ends the list
|
|
if let (Some(c), Some(d)) = (&self.complete, self.cur_doc()) {
|
|
if d.buf.word_at(d.buf.head()).start != c.start {
|
|
self.complete = None;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Words already in the file, for when no language server is running.
|
|
fn word_completion(&mut self) {
|
|
let Some(d) = self.cur_doc() else { return };
|
|
let r = d.buf.word_at(d.buf.head());
|
|
let prefix = d.buf.text(r.start..d.buf.head());
|
|
if prefix.is_empty() { return }
|
|
let text = d.buf.rope.to_string();
|
|
let re = regex::Regex::new(r"[\p{L}_][\p{L}\p{N}_]+").unwrap();
|
|
let mut seen = std::collections::BTreeSet::new();
|
|
for m in re.find_iter(&text).take(200_000) {
|
|
if m.as_str().starts_with(&prefix) && m.as_str() != prefix { seen.insert(m.as_str().to_string()); }
|
|
}
|
|
let items = seen.into_iter().take(40).map(|w| CompletionItem { label: w.clone(), filter: w.clone(), insert: w, detail: String::new(), kind: 1 }).collect();
|
|
self.show_completion(items);
|
|
}
|
|
|
|
fn accept_completion(&mut self) {
|
|
let Some(c) = self.complete.take() else { return };
|
|
let Some(item) = c.items.get(c.sel) else { return };
|
|
let insert = item.insert.clone();
|
|
if let Some(d) = self.cur_doc_mut() {
|
|
let head = d.buf.head();
|
|
d.buf.apply(vec![(c.start..head, insert)], EditKind::Other, |_, st, n| Sel::cursor(st + n));
|
|
}
|
|
}
|
|
|
|
fn completion_ui(&mut self, ctx: &egui::Context) {
|
|
let t = self.t.clone();
|
|
if let Some(c) = &self.complete {
|
|
let key = format!("comp/{}", c.seq);
|
|
let k = motion::spring_from(&key, 0.0, 1.0, Preset { stiffness: 900.0, damping: 0.66 });
|
|
let row = 32.0;
|
|
let shown = c.items.len().min(8);
|
|
let sel = c.sel;
|
|
let first = sel.saturating_sub(shown - 1);
|
|
let w = 340.0;
|
|
let h = shown as f32 * row + 12.0;
|
|
let lh = (self.s.font_size * 1.55).round();
|
|
let mut pos = self.caret_pos + vec2(-8.0, lh + 4.0);
|
|
let screen = ctx.content_rect();
|
|
if pos.y + h > screen.bottom() - 8.0 { pos.y = self.caret_pos.y - h - 4.0 }
|
|
pos.x = pos.x.min(screen.right() - w - 8.0);
|
|
let rect = Rect::from_min_size(pos, vec2(w, h));
|
|
let visible: Vec<(String, String, u8)> = c.items.iter().skip(first).take(shown).map(|i| (i.label.clone(), i.detail.clone(), i.kind)).collect();
|
|
let mut clicked = None;
|
|
let area = egui::Area::new(Id::unique("completion")).order(egui::Order::Tooltip).fixed_pos(rect.min).show(ctx, |ui| {
|
|
ui.set_min_size(rect.size());
|
|
let p = ui.painter().clone();
|
|
shadow(&p, rect, 16.0, 0.9, t.dark);
|
|
p.rect_filled(rect, cr(16.0), t.high);
|
|
let sy = spring("comp/y", (sel - first) as f32 * row, Preset { stiffness: 1400.0, damping: 0.78 });
|
|
p.rect_filled(Rect::from_min_size(rect.min + vec2(6.0, 6.0 + sy), vec2(w - 12.0, row)), cr(12.0), t.secondary_container);
|
|
for (i, (label, detail, kind)) in visible.iter().enumerate() {
|
|
let r = Rect::from_min_size(rect.min + vec2(6.0, 6.0 + i as f32 * row), vec2(w - 12.0, row));
|
|
if ui.interact(r, Id::unique(("comp", i)), Sense::click()).clicked() { clicked = Some(first + i) }
|
|
let ic = match kind { 2 | 3 | 4 => "code", 5 | 10 => "tag", 7 | 8 | 22 => "data_object", _ => "text_fields" };
|
|
icons::paint(ctx, &p, r.left_center() + vec2(16.0, 0.0), 16.0, ic, t.on_variant);
|
|
p.with_clip_rect(r).text(r.left_center() + vec2(32.0, 0.0), Align2::LEFT_CENTER, label, fonts::mono(12.0), if first + i == sel { t.on_secondary_container } else { t.on_surface });
|
|
p.with_clip_rect(r).text(r.right_center() - vec2(10.0, 0.0), Align2::RIGHT_CENTER, detail.chars().take(26).collect::<String>(), fonts::ui(11.0), t.outline);
|
|
}
|
|
});
|
|
let a = pos;
|
|
let s = 0.8 + 0.2 * k;
|
|
ctx.set_transform_layer(area.response.layer_id, egui::emath::TSTransform::from_translation(a.to_vec2()) * egui::emath::TSTransform::from_scaling(s) * egui::emath::TSTransform::from_translation(-a.to_vec2()));
|
|
if let Some(i) = clicked {
|
|
if let Some(c) = self.complete.as_mut() { c.sel = i }
|
|
self.accept_completion();
|
|
}
|
|
}
|
|
if let Some((text, pos, seq)) = self.hover.clone() {
|
|
let k = motion::spring_from(format!("hover/{seq}"), 0.0, 1.0, motion::DEFAULT);
|
|
let screen = ctx.content_rect();
|
|
let lines: Vec<&str> = text.lines().take(14).collect();
|
|
let w = 520.0_f32.min(screen.width() - 40.0);
|
|
let h = lines.len() as f32 * 18.0 + 22.0;
|
|
let mut pp = pos + vec2(0.0, -h - 8.0);
|
|
if pp.y < 8.0 { pp.y = pos.y + 28.0 }
|
|
pp.x = pp.x.min(screen.right() - w - 8.0);
|
|
let rect = Rect::from_min_size(pp, vec2(w, h));
|
|
let area = egui::Area::new(Id::unique("hover")).order(egui::Order::Tooltip).fixed_pos(rect.min).show(ctx, |ui| {
|
|
ui.set_min_size(rect.size());
|
|
let p = ui.painter().clone();
|
|
shadow(&p, rect, 16.0, 0.9, t.dark);
|
|
p.rect_filled(rect, cr(16.0), t.high);
|
|
let pc = p.with_clip_rect(rect.shrink(8.0));
|
|
for (i, l) in lines.iter().enumerate() {
|
|
pc.text(rect.left_top() + vec2(14.0, 11.0 + i as f32 * 18.0), Align2::LEFT_TOP, *l, fonts::mono(12.0), t.on_surface);
|
|
}
|
|
let b = Rect::from_center_size(rect.right_top() + vec2(-20.0, 20.0), vec2(28.0, 28.0));
|
|
let done = ctx.input(|i| i.time) - self.hover_copied < 1.2;
|
|
if morph::button(ui, &t, b, "hover/copy", Morph::CopyCheck, done, "Copy", t.high).clicked() {
|
|
ctx.copy_text(text.clone());
|
|
self.hover_copied = ctx.input(|i| i.time);
|
|
}
|
|
if done { motion::keep_alive() }
|
|
});
|
|
let s = 0.86 + 0.14 * k;
|
|
ctx.set_transform_layer(area.response.layer_id, egui::emath::TSTransform::from_translation(pos.to_vec2()) * egui::emath::TSTransform::from_scaling(s) * egui::emath::TSTransform::from_translation(-pos.to_vec2()));
|
|
let away = ctx.input(|i| i.pointer.any_pressed() && !i.pointer.interact_pos().is_some_and(|p| rect.contains(p)));
|
|
if away || ctx.input(|i| i.key_pressed(Key::Escape) || i.events.iter().any(|e| matches!(e, egui::Event::Text(_)))) { self.hover = None }
|
|
}
|
|
}
|
|
|
|
pub fn problem_count(&self) -> usize {
|
|
self.diags.values().map(Vec::len).sum()
|
|
}
|
|
|
|
pub fn problem_totals(&self) -> (usize, usize) {
|
|
let mut e = (0, 0);
|
|
for d in self.diags.values().flatten() {
|
|
if d.severity == 1 { e.0 += 1 } else if d.severity == 2 { e.1 += 1 }
|
|
}
|
|
e
|
|
}
|
|
|
|
pub fn preview_marks(&self, id: u64) -> Vec<(usize, Color32)> {
|
|
let t = &self.t;
|
|
let Some(d) = self.docs.get(&id) else { return vec![] };
|
|
let mut v = vec![];
|
|
if let Some(p) = &d.path {
|
|
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] })) }
|
|
}
|
|
}
|
|
for b in &d.bookmarks { v.push((*b, t.tertiary)) }
|
|
if self.find.open {
|
|
let step = (self.find.hits.len() / 400).max(1);
|
|
for h in self.find.hits.iter().step_by(step) {
|
|
if h.0 <= d.buf.len() { v.push((d.buf.rope.char_to_line(h.0), t.tertiary)) }
|
|
}
|
|
}
|
|
v
|
|
}
|
|
|
|
/// Change bars and problem dots in the gutter.
|
|
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((_, _, 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) {
|
|
let c = if x.severity == 1 { t.error } else { t.syntax[crate::syntax::DefStyle::Warning as usize] };
|
|
p.circle_filled(at + vec2(-4.0, lh / 2.0 - 8.0), 2.5, c);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- commands
|
|
|
|
pub fn run(&mut self, ctx: &egui::Context, c: Cmd) {
|
|
use Cmd::*;
|
|
let prefs = Prefs { tab_width: self.s.tab_width, spaces: self.s.spaces, auto_close: self.s.auto_close };
|
|
// only commands that move or edit at the cursor scroll to it; view toggles leave you where you are
|
|
self.reveal = matches!(c, Undo | Redo | Cut | Paste | Comment | DuplicateLines | DeleteLines | MoveLinesUp | MoveLinesDown | JoinLines | Indent | Unindent | CursorAbove | CursorBelow | SelectNext);
|
|
match c {
|
|
New => {
|
|
let id = self.next_id;
|
|
self.next_id += 1;
|
|
let d = Doc::new(id, "", None, &mut self.reg);
|
|
self.add_doc(ctx, d);
|
|
}
|
|
Open => {
|
|
if let Some(files) = rfd::FileDialog::new().pick_files() {
|
|
for f in files { self.open_path(ctx, f, None) }
|
|
}
|
|
}
|
|
OpenFolder => {
|
|
if let Some(d) = rfd::FileDialog::new().pick_folder() {
|
|
self.set_root(d);
|
|
self.side = 0;
|
|
self.side_open = true;
|
|
}
|
|
}
|
|
Save => if let Some(id) = self.cur_doc_id() { self.save_doc(ctx, id) },
|
|
SaveAs => if let Some(id) = self.cur_doc_id() {
|
|
if let Some(p) = self.ask_save_path(id) {
|
|
self.name_doc(id, p);
|
|
self.save_doc(ctx, id);
|
|
}
|
|
},
|
|
SaveAll => {
|
|
let ids: Vec<u64> = self.docs.values().filter(|d| d.buf.is_modified() && d.path.is_some()).map(|d| d.id).collect();
|
|
for id in ids { self.save_doc(ctx, id) }
|
|
}
|
|
CloseTab => { let p = self.focus_pane; let a = self.panes[p].active; self.close_tab(p, a) }
|
|
ReopenClosed => if let Some(p) = self.closed.pop() { self.open_path(ctx, p, None) },
|
|
Reload => self.reload_current(),
|
|
Quit => self.request_quit(ctx),
|
|
Undo => if let Some(d) = self.cur_doc_mut() { d.buf.undo(); },
|
|
Redo => if let Some(d) = self.cur_doc_mut() { d.buf.redo(); },
|
|
Copy | Cut => if let Some(d) = self.cur_doc_mut() {
|
|
let t = d.buf.selected_text();
|
|
if !t.is_empty() {
|
|
ctx.copy_text(t);
|
|
if c == Cut { d.buf.insert("", EditKind::Other) }
|
|
}
|
|
},
|
|
Paste => ctx.send_viewport_cmd(ViewportCommand::RequestPaste),
|
|
SelectAll => if let Some(d) = self.cur_doc_mut() { d.buf.select_all() },
|
|
Comment => if let Some(d) = self.cur_doc_mut() {
|
|
let (l, b) = (d.meta.line_comment.clone(), d.meta.block_comment.clone());
|
|
d.buf.toggle_comment(l.as_deref(), b.as_ref().map(|x| (x.0.as_str(), x.1.as_str())));
|
|
},
|
|
DuplicateLines => if let Some(d) = self.cur_doc_mut() { d.buf.duplicate_lines() },
|
|
DeleteLines => if let Some(d) = self.cur_doc_mut() { d.buf.delete_lines() },
|
|
MoveLinesUp => if let Some(d) = self.cur_doc_mut() { d.buf.move_lines(true) },
|
|
MoveLinesDown => if let Some(d) = self.cur_doc_mut() { d.buf.move_lines(false) },
|
|
JoinLines => if let Some(d) = self.cur_doc_mut() { d.buf.join_lines() },
|
|
Indent => if let Some(d) = self.cur_doc_mut() { d.buf.indent(&prefs) },
|
|
Unindent => if let Some(d) = self.cur_doc_mut() { d.buf.unindent(&prefs) },
|
|
Upper => if let Some(d) = self.cur_doc_mut() { d.buf.transform(|s| s.to_uppercase()) },
|
|
Lower => if let Some(d) = self.cur_doc_mut() { d.buf.transform(|s| s.to_lowercase()) },
|
|
Capitalize => if let Some(d) = self.cur_doc_mut() {
|
|
d.buf.transform(|s| {
|
|
let mut c = s.chars();
|
|
c.next().map(|f| f.to_uppercase().chain(c.flat_map(char::to_lowercase)).collect()).unwrap_or_default()
|
|
})
|
|
},
|
|
SortLines => if let Some(d) = self.cur_doc_mut() { d.buf.sort_lines() },
|
|
TrimTrailing => if let Some(d) = self.cur_doc_mut() { d.buf.trim_trailing() },
|
|
CursorAbove => if let Some(d) = self.cur_doc_mut() { d.buf.add_cursor_vertical(false) },
|
|
CursorBelow => if let Some(d) = self.cur_doc_mut() { d.buf.add_cursor_vertical(true) },
|
|
SelectNext => if let Some(d) = self.cur_doc_mut() { d.buf.select_next() },
|
|
Find | Replace => {
|
|
self.find.open = true;
|
|
self.find.focus = true;
|
|
self.find.replace = c == Replace;
|
|
if let Some(d) = self.cur_doc() {
|
|
let s = d.buf.selected_text();
|
|
if !s.is_empty() && !s.contains('\n') { self.find.query = s }
|
|
}
|
|
}
|
|
FindInFiles => {
|
|
self.side = 1;
|
|
self.side_open = true;
|
|
self.side_state.search_focus = true;
|
|
if let Some(d) = self.cur_doc() {
|
|
let s = d.buf.selected_text();
|
|
if !s.is_empty() && !s.contains('\n') { self.side_state.search = s }
|
|
}
|
|
}
|
|
GotoLine => self.open_palette(ctx, ":", false),
|
|
Palette => self.open_palette(ctx, ">", false),
|
|
QuickOpen => self.open_palette(ctx, "", false),
|
|
Languages => self.open_palette(ctx, "", true),
|
|
Symbols => self.open_palette(ctx, "@", false),
|
|
ToggleTerminal => {
|
|
if self.terms.is_empty() { self.new_terminal(ctx, None) }
|
|
self.term_open = !self.term_open && !self.terms.is_empty();
|
|
if self.term_open { self.term_want_focus = true } else { self.focus_editor(ctx) }
|
|
}
|
|
NewTerminal => {
|
|
self.new_terminal(ctx, None);
|
|
self.term_open = !self.terms.is_empty();
|
|
self.term_want_focus = true;
|
|
}
|
|
RunFile => {
|
|
let id = self.cur_doc_id();
|
|
if let Some(id) = id { if self.docs[&id].buf.is_modified() { self.save_doc(ctx, id) } }
|
|
match self.cur_doc().and_then(Self::file_runner) {
|
|
Some(c) => self.run_in_terminal(ctx, &c),
|
|
None => self.toast("info", "No run command known for this language".to_string()),
|
|
}
|
|
}
|
|
TerminalHere => {
|
|
let dir = self.cur_doc().and_then(|d| d.path.as_ref()?.parent().map(PathBuf::from));
|
|
self.new_terminal(ctx, dir);
|
|
self.term_open = !self.terms.is_empty();
|
|
self.term_want_focus = true;
|
|
}
|
|
ToggleSidebar => self.side_open = !self.side_open,
|
|
Side(i) => {
|
|
if self.side == i && self.side_open { self.side_open = false }
|
|
else { self.side = i; self.side_open = true }
|
|
}
|
|
SplitRight | SplitDown => {
|
|
self.split_vertical = c == SplitDown;
|
|
self.split = 0.5;
|
|
if self.panes.len() < 2 {
|
|
let doc = self.cur_doc_id();
|
|
let seq = self.panes.iter().map(|p| p.seq).max().unwrap_or(0) + 1;
|
|
let mut p = Pane::new(seq);
|
|
if let Some(id) = doc {
|
|
p.tabs.push(Tab::new(id, ctx.input(|i| i.time)));
|
|
}
|
|
self.panes.push(p);
|
|
self.focus_pane = 1;
|
|
self.focus_editor(ctx);
|
|
}
|
|
}
|
|
CloseSplit => {
|
|
if self.panes.len() > 1 {
|
|
let p = self.focus_pane;
|
|
let n = self.panes[p].tabs.len();
|
|
if (0..n).all(|i| !self.docs[&self.panes[p].tabs[i].doc].buf.is_modified() || self.panes.iter().enumerate().any(|(j, o)| j != p && o.tabs.iter().any(|t| t.doc == self.panes[p].tabs[i].doc))) {
|
|
for j in (0..n).rev() { if self.panes.len() > 1 { self.force_close(p, j) } }
|
|
}
|
|
self.focus_pane = 0;
|
|
}
|
|
}
|
|
FocusNextPane => {
|
|
self.focus_pane = (self.focus_pane + 1) % self.panes.len();
|
|
self.focus_editor(ctx);
|
|
}
|
|
Zen => self.zen = !self.zen,
|
|
ToggleWrap => self.s.word_wrap ^= true,
|
|
ToggleWhitespace => self.s.show_whitespace ^= true,
|
|
ToggleNumbers => self.s.line_numbers ^= true,
|
|
TogglePreview => self.s.preview ^= true,
|
|
ToggleLens => self.s.lens ^= true,
|
|
ZoomIn => self.s.font_size = (self.s.font_size + 1.0).min(40.0),
|
|
ZoomOut => self.s.font_size = (self.s.font_size - 1.0).max(8.0),
|
|
ZoomReset => self.s.font_size = 14.0,
|
|
FoldHere => if let Some(d) = self.cur_doc_mut() {
|
|
let l = d.buf.pos(d.buf.head()).0;
|
|
let start = d.fold_ends.iter().filter(|(s, e)| **s <= l && l <= **e).map(|(s, _)| *s).max();
|
|
if let Some(s) = start { d.toggle_fold(s) }
|
|
},
|
|
FoldAll => if let Some(d) = self.cur_doc_mut() {
|
|
let v: Vec<usize> = d.fold_ends.keys().copied().collect();
|
|
d.folded.extend(v);
|
|
},
|
|
UnfoldAll => if let Some(d) = self.cur_doc_mut() { d.folded.clear() },
|
|
ToggleBookmark => if let Some(d) = self.cur_doc_mut() {
|
|
let l = d.buf.pos(d.buf.head()).0;
|
|
if !d.bookmarks.remove(&l) { d.bookmarks.insert(l); }
|
|
},
|
|
NextBookmark | PrevBookmark => {
|
|
let target = self.cur_doc().and_then(|d| {
|
|
let l = d.buf.pos(d.buf.head()).0;
|
|
if c == NextBookmark { d.bookmarks.range(l + 1..).next().or(d.bookmarks.iter().next()).copied() }
|
|
else { d.bookmarks.range(..l).next_back().or(d.bookmarks.iter().next_back()).copied() }
|
|
});
|
|
if let Some(l) = target { self.jump_to_line(ctx, l) }
|
|
}
|
|
GotoDefinition => { if !self.lsp_at(|c, p, l, col| c.definition(p, l, col)) { self.toast("info", "No language server for this file".to_string()) } }
|
|
Hover => { if !self.lsp_at(|c, p, l, col| c.hover(p, l, col)) { self.toast("info", "No language server for this file".to_string()) } }
|
|
Complete => { if !self.lsp_at(|c, p, l, col| c.completion(p, l, col)) { self.word_completion() } }
|
|
NextProblem => {
|
|
let list = self.cur_doc().and_then(|d| Some((d.buf.pos(d.buf.head()).0, self.diags.get(d.path.as_ref()?)?.clone())));
|
|
if let Some((l, mut ds)) = list {
|
|
ds.sort_by_key(|x| x.line);
|
|
if let Some(x) = ds.iter().find(|x| x.line > l).or(ds.first()) { self.jump_to_line(ctx, x.line) }
|
|
}
|
|
}
|
|
ToggleDark => {
|
|
self.s.mode = if self.t.dark { "light".into() } else { "dark".into() };
|
|
self.refresh_theme(ctx);
|
|
}
|
|
Settings => self.settings_open = !self.settings_open,
|
|
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();
|
|
if n > 0 {
|
|
p.active = if c == NextTab { (p.active + 1) % n } else { (p.active + n - 1) % n };
|
|
p.reveal_tab = true;
|
|
}
|
|
}
|
|
TabAt(i) => { let p = self.focus_pane; self.activate_tab(p, i, 0.0) }
|
|
GitRefresh => self.refresh_git(),
|
|
}
|
|
}
|
|
|
|
fn reload_current(&mut self) {
|
|
let Some(id) = self.cur_doc_id() else { return };
|
|
if let Err(e) = self.docs.get_mut(&id).unwrap().reload() {
|
|
self.toast("error", format!("Couldn't reload: {}", why(&e)));
|
|
}
|
|
}
|
|
|
|
fn request_quit(&mut self, ctx: &egui::Context) {
|
|
if self.docs.values().any(|d| d.buf.is_modified()) {
|
|
self.dialog = Some(Dialog::ConfirmQuit);
|
|
} else {
|
|
self.quit_now = true;
|
|
ctx.send_viewport_cmd(ViewportCommand::Close);
|
|
}
|
|
}
|
|
|
|
fn shortcuts(&mut self, ctx: &egui::Context) {
|
|
use Cmd::*;
|
|
const C: Modifiers = Modifiers::COMMAND;
|
|
const CS: Modifiers = Modifiers { shift: true, ..Modifiers::COMMAND };
|
|
const CA: Modifiers = Modifiers { alt: true, ..Modifiers::COMMAND };
|
|
const CAS: Modifiers = Modifiers { alt: true, shift: true, ..Modifiers::COMMAND };
|
|
const A: Modifiers = Modifiers::ALT;
|
|
const N: Modifiers = Modifiers::NONE;
|
|
|
|
// these work everywhere, even with the terminal focused
|
|
let global: &[(Modifiers, Key, Cmd)] = &[
|
|
(N, Key::F4, ToggleTerminal), (C, Key::Backtick, ToggleTerminal), (N, Key::F11, Zen), (CS, Key::P, Palette), (CS, Key::Backtick, NewTerminal),
|
|
];
|
|
let table: &[(Modifiers, Key, Cmd)] = &[
|
|
(C, Key::N, New), (C, Key::O, Open), (CS, Key::O, OpenFolder), (C, Key::S, Save), (CS, Key::S, SaveAs), (C, Key::L, SaveAll),
|
|
(C, Key::W, CloseTab), (CS, Key::T, ReopenClosed), (N, Key::F5, Reload), (C, Key::Q, Quit),
|
|
(C, Key::Z, Undo), (C, Key::Y, Redo), (CS, Key::Z, Redo), (C, Key::A, SelectAll),
|
|
(C, Key::Slash, Comment), (C, Key::D, Comment), (CAS, Key::ArrowDown, DuplicateLines), (C, Key::K, DeleteLines),
|
|
(CS, Key::ArrowUp, MoveLinesUp), (CS, Key::ArrowDown, MoveLinesDown), (C, Key::J, JoinLines),
|
|
(C, Key::U, Upper), (CS, Key::U, Lower), (CA, Key::U, Capitalize), (CA, Key::ArrowUp, CursorAbove), (CA, Key::ArrowDown, CursorBelow),
|
|
(A, Key::J, SelectNext), (C, Key::F, Find), (C, Key::R, Replace), (CS, Key::F, FindInFiles), (C, Key::G, GotoLine),
|
|
(C, Key::P, QuickOpen), (CS, Key::R, Symbols), (C, Key::F5, RunFile), (C, Key::B, ToggleSidebar),
|
|
(A, Key::Num1, Side(0)), (A, Key::Num2, Side(1)), (A, Key::Num3, Side(2)), (A, Key::Num4, Side(3)), (A, Key::Num5, Side(4)),
|
|
(CS, Key::L, SplitRight), (CA, Key::ArrowRight, FocusNextPane), (CS, Key::N, ToggleNumbers), (N, Key::F10, ToggleWrap), (C, Key::Equals, ZoomIn), (C, Key::Plus, ZoomIn), (C, Key::Minus, ZoomOut), (C, Key::Num0, ZoomReset),
|
|
(CS, Key::Minus, FoldHere), (CS, Key::OpenBracket, FoldAll), (CS, Key::CloseBracket, UnfoldAll),
|
|
(CS, Key::B, ToggleBookmark), (A, Key::PageDown, NextBookmark), (A, Key::PageUp, PrevBookmark),
|
|
(N, Key::F12, GotoDefinition), (C, Key::I, Hover), (C, Key::Space, Complete), (N, Key::F8, NextProblem), (C, Key::Comma, Settings),
|
|
(C, Key::Tab, NextTab), (CS, Key::Tab, PrevTab),
|
|
];
|
|
let term_focus = ctx.memory(|m| m.focused()) == Some(self.term_focus_id());
|
|
let mut hit = vec![];
|
|
ctx.input_mut(|i| {
|
|
for (m, k, c) in global {
|
|
if i.consume_key(*m, *k) { hit.push(c.clone()) }
|
|
}
|
|
if !term_focus {
|
|
// order the wider chords first, or Ctrl alone would swallow Ctrl+Shift
|
|
let mut sorted: Vec<&(Modifiers, Key, Cmd)> = table.iter().collect();
|
|
sorted.sort_by_key(|(m, _, _)| -(m.shift as i32 + m.alt as i32));
|
|
for (m, k, c) in sorted {
|
|
if i.consume_key(*m, *k) { hit.push(c.clone()) }
|
|
}
|
|
}
|
|
});
|
|
if !term_focus {
|
|
// the completion list takes the keys it needs before the editor sees them
|
|
if let Some(n) = self.complete.as_ref().map(|c| c.items.len()) {
|
|
let (up, down, accept, esc) = ctx.input_mut(|i| (i.consume_key(N, Key::ArrowUp), i.consume_key(N, Key::ArrowDown), i.consume_key(N, Key::Enter) || i.consume_key(N, Key::Tab), i.consume_key(N, Key::Escape)));
|
|
if let Some(c) = &mut self.complete {
|
|
if up { c.sel = (c.sel + n - 1) % n }
|
|
if down { c.sel = (c.sel + 1) % n }
|
|
}
|
|
if accept { self.accept_completion() }
|
|
if esc { self.complete = None }
|
|
}
|
|
}
|
|
for c in hit { self.run(ctx, c) }
|
|
}
|
|
|
|
// ---------------------------------------------------------------- housekeeping
|
|
|
|
fn background(&mut self, ctx: &egui::Context) {
|
|
while let Ok(m) = self.rx.try_recv() {
|
|
match m {
|
|
Msg::Search(r) => {
|
|
self.side_state.results = r;
|
|
self.side_state.searching = false;
|
|
}
|
|
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);
|
|
self.pump_lsp(ctx);
|
|
|
|
// unnamed files take their language from the text, a moment after it changes
|
|
if self.last_guess.elapsed() > Duration::from_millis(250) {
|
|
self.last_guess = Instant::now();
|
|
for d in self.docs.values_mut() {
|
|
d.sync_edits();
|
|
d.detect(&mut self.reg);
|
|
d.refresh_marks();
|
|
}
|
|
}
|
|
|
|
// colours for the rest of each file, a slice per frame
|
|
let start = Instant::now();
|
|
let ids: Vec<u64> = self.docs.keys().copied().collect();
|
|
for id in ids {
|
|
let d = self.docs.get_mut(&id).unwrap();
|
|
while d.highlight_pending() && start.elapsed() < Duration::from_millis(8) {
|
|
d.highlight(&self.reg, 0, 96);
|
|
}
|
|
if d.highlight_pending() { motion::keep_alive() }
|
|
}
|
|
|
|
let now = Instant::now();
|
|
if now - self.last_poll > Duration::from_millis(1500) {
|
|
self.last_poll = now;
|
|
self.lsp_sync();
|
|
self.check_external();
|
|
self.update_presence(ctx);
|
|
let st = theme::source_stamp();
|
|
if st != self.last_stamp {
|
|
self.last_stamp = st;
|
|
if self.s.color_source != "custom" { self.refresh_theme(ctx) }
|
|
}
|
|
if self.s != self.saved_settings {
|
|
self.s.save();
|
|
self.saved_settings = self.s.clone();
|
|
}
|
|
}
|
|
if now - self.last_git > Duration::from_secs(12) { self.refresh_git() }
|
|
if now - self.last_session > Duration::from_secs(8) {
|
|
self.last_session = now;
|
|
self.save_session();
|
|
}
|
|
}
|
|
|
|
fn update_presence(&mut self, ctx: &egui::Context) {
|
|
let id = if self.s.discord { self.s.discord_id.trim().to_string() } else { String::new() };
|
|
let _ = self.presence.send(discord::Update::Id(id));
|
|
let idle = ctx.input(|i| i.time) - self.last_input > discord::IDLE_AFTER;
|
|
let name = self.cur_doc().map(|d| d.title()).unwrap_or_default();
|
|
let key = (name.clone(), idle, self.s.discord_file, self.s.discord_project);
|
|
if self.presence_sent.as_ref() == Some(&key) {
|
|
return;
|
|
}
|
|
let project = self.root.as_ref().and_then(|r| r.file_name()).map(|n| n.to_string_lossy().into_owned());
|
|
let activity = match self.cur_doc() {
|
|
_ if idle => discord::Activity::idle(),
|
|
Some(d) => discord::Activity::editing(self.s.discord_file.then_some(name.as_str()), project.as_deref().filter(|_| self.s.discord_project), &name, &d.language),
|
|
None => discord::Activity { state: Some("Getting started".to_string()), ..discord::Activity::idle() },
|
|
};
|
|
let _ = self.presence.send(discord::Update::Show(Some(activity)));
|
|
self.presence_sent = Some(key);
|
|
}
|
|
|
|
/// Picks up files changed by something else; unsaved ones are left alone with a note.
|
|
fn check_external(&mut self) {
|
|
let mut reload = vec![];
|
|
for d in self.docs.values_mut() {
|
|
let (Some(p), Some(old)) = (&d.path, d.mtime) else { continue };
|
|
let Some(new) = std::fs::metadata(p).and_then(|m| m.modified()).ok() else { continue };
|
|
if new != old {
|
|
d.mtime = Some(new);
|
|
reload.push((d.id, d.buf.is_modified(), d.title()));
|
|
}
|
|
}
|
|
for (id, modified, name) in reload {
|
|
if modified {
|
|
self.toast("warning", format!("{name} changed on disk, reload with F5"));
|
|
} else {
|
|
let _ = self.docs.get_mut(&id).unwrap().reload();
|
|
}
|
|
}
|
|
}
|
|
|
|
fn session_path() -> PathBuf {
|
|
config_dir().join("session.json")
|
|
}
|
|
|
|
pub fn save_session(&self) {
|
|
if self.side_window {
|
|
return;
|
|
}
|
|
let dir = config_dir().join("recovery");
|
|
let _ = std::fs::create_dir_all(&dir);
|
|
let mut keep = vec![];
|
|
let pane = &self.panes[0];
|
|
let mut files = vec![];
|
|
let mut seen = std::collections::HashSet::new();
|
|
for tb in self.panes.iter().flat_map(|p| &p.tabs) {
|
|
if !seen.insert(tb.doc) { continue }
|
|
let Some(d) = self.docs.get(&tb.doc) else { continue };
|
|
let backup = d.buf.is_modified().then(|| {
|
|
let p = dir.join(format!("{}.txt", d.id));
|
|
let _ = std::fs::write(&p, d.buf.rope.to_string());
|
|
keep.push(p.clone());
|
|
p
|
|
});
|
|
if d.path.is_none() && backup.is_none() { continue }
|
|
let (line, col) = d.buf.pos(d.buf.head());
|
|
files.push(SavedFile { path: d.path.clone(), line, col, scroll: tb.scroll.x, backup });
|
|
}
|
|
if let Ok(rd) = std::fs::read_dir(&dir) {
|
|
for e in rd.flatten() {
|
|
if !keep.contains(&e.path()) { let _ = std::fs::remove_file(e.path()); }
|
|
}
|
|
}
|
|
let s = SessionFile { root: self.root.clone(), files, active: pane.active };
|
|
if let Ok(j) = serde_json::to_vec_pretty(&s) {
|
|
let _ = std::fs::create_dir_all(config_dir());
|
|
let _ = std::fs::write(Self::session_path(), j);
|
|
}
|
|
}
|
|
|
|
fn restore_session(&mut self, ctx: &egui::Context) {
|
|
let Some(s) = std::fs::read(Self::session_path()).ok().and_then(|b| serde_json::from_slice::<SessionFile>(&b).ok()) else { return };
|
|
if let Some(r) = s.root.filter(|r| r.is_dir()) { self.set_root(r) }
|
|
for f in s.files {
|
|
let backup = f.backup.as_ref().and_then(|p| std::fs::read_to_string(p).ok());
|
|
match (&f.path, backup) {
|
|
(Some(p), None) if p.is_file() => self.open_path(ctx, p.clone(), None),
|
|
(Some(p), Some(text)) => {
|
|
if p.is_file() { self.open_path(ctx, p.clone(), None) } else {
|
|
let id = self.next_id;
|
|
self.next_id += 1;
|
|
let d = Doc::new(id, "", Some(p.clone()), &mut self.reg);
|
|
self.add_doc(ctx, d);
|
|
}
|
|
if let Some(d) = self.cur_doc_mut() {
|
|
d.buf.select_all();
|
|
d.buf.insert(&text, EditKind::Other);
|
|
}
|
|
}
|
|
(None, Some(text)) => {
|
|
self.run(ctx, Cmd::New);
|
|
if let Some(d) = self.cur_doc_mut() { d.buf.insert(&text, EditKind::Other) }
|
|
}
|
|
_ => continue,
|
|
}
|
|
if let Some(d) = self.cur_doc_mut() {
|
|
let at = d.buf.at(f.line, f.col);
|
|
d.buf.set_cursor(at);
|
|
}
|
|
let p = &mut self.panes[0];
|
|
if let Some(tb) = p.tabs.last_mut() { tb.scroll.snap(f.scroll) }
|
|
}
|
|
let p = &mut self.panes[0];
|
|
p.active = s.active.min(p.tabs.len().saturating_sub(1));
|
|
}
|
|
|
|
// ---------------------------------------------------------------- the frame
|
|
|
|
pub fn ui(&mut self, ui: &mut Ui) {
|
|
let ctx = ui.ctx().clone();
|
|
let now = Instant::now();
|
|
let dt = self.last_time.map_or(1.0 / 60.0, |t| (now - t).as_secs_f32());
|
|
self.last_time = Some(now);
|
|
motion::begin_frame(dt, self.s.motion);
|
|
self.background(&ctx);
|
|
for c in std::mem::take(&mut self.startup) {
|
|
self.run(&ctx, c);
|
|
}
|
|
let title = self.cur_doc().map_or("Damson".to_string(), |d| format!("{}{} — Damson", if d.buf.is_modified() { "• " } else { "" }, d.title()));
|
|
if title != self.window_title {
|
|
ctx.send_viewport_cmd(ViewportCommand::Title(title.clone()));
|
|
self.window_title = title;
|
|
}
|
|
if ctx.memory(|m| m.focused()).is_none() && !self.palette.open && self.dialog.is_none() && !self.settings_open && !self.term_open {
|
|
self.focus_editor(&ctx);
|
|
}
|
|
self.shortcuts(&ctx);
|
|
if ctx.input(|i| i.viewport().close_requested()) && !self.quit_now {
|
|
self.save_session();
|
|
if self.docs.values().any(|d| d.buf.is_modified()) {
|
|
ctx.send_viewport_cmd(ViewportCommand::CancelClose);
|
|
self.dialog = Some(Dialog::ConfirmQuit);
|
|
}
|
|
}
|
|
self.layout(ui);
|
|
self.typing_completion(&ctx);
|
|
self.palette_ui(&ctx);
|
|
self.menu_ui(&ctx);
|
|
self.dialog_ui(&ctx);
|
|
self.settings_ui(&ctx);
|
|
self.completion_ui(&ctx);
|
|
self.toasts_ui(&ctx);
|
|
self.theme_wave_ui(&ctx);
|
|
self.smoke(&ctx);
|
|
if motion::busy() { ctx.request_repaint() }
|
|
else { ctx.request_repaint_after(Duration::from_millis(500)) }
|
|
}
|
|
|
|
/// With DAMSON_SMOKE=dir set: run a little, screenshot the real window, write a status, quit.
|
|
fn smoke(&mut self, ctx: &egui::Context) {
|
|
let Some(dir) = std::env::var_os("DAMSON_SMOKE").map(PathBuf::from) else { return };
|
|
self.smoke_frames += 1;
|
|
ctx.request_repaint();
|
|
match self.smoke_frames {
|
|
20 => self.run(ctx, Cmd::Side(0)),
|
|
45 => self.run(ctx, Cmd::ToggleTerminal),
|
|
120 => {
|
|
let status = format!("frames=120 docs={} terminals={} defs={} renderer=glow\n", self.docs.len(), self.terms.len(), self.reg.languages.len());
|
|
let ctx2 = ctx.clone();
|
|
ctx.send_viewport_cmd(ViewportCommand::Screenshot(egui::ScreenshotCallback::new(move |img| {
|
|
let (w, h) = (img.size[0] as u32, img.size[1] as u32);
|
|
let bytes: Vec<u8> = img.pixels.iter().flat_map(|c| c.to_array()).collect();
|
|
if let Some(pm) = resvg::tiny_skia::Pixmap::from_vec(bytes, resvg::tiny_skia::IntSize::from_wh(w, h).unwrap()) {
|
|
let _ = pm.save_png(dir.join("window.png"));
|
|
}
|
|
let _ = std::fs::write(dir.join("status.txt"), status);
|
|
ctx2.send_viewport_cmd(ViewportCommand::Close);
|
|
})));
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn layout(&mut self, ui: &mut Ui) {
|
|
let ctx = ui.ctx().clone();
|
|
let t = self.t.clone();
|
|
let full = ui.max_rect();
|
|
let p = ui.painter().clone();
|
|
p.rect_filled(full, cr(0.0), t.surface);
|
|
|
|
let z = spring("zen", self.zen as u8 as f32, motion::DEFAULT);
|
|
let zk = z.clamp(0.0, 1.0);
|
|
|
|
let rail_w = 78.0 * (1.0 - zk);
|
|
if rail_w > 1.0 {
|
|
let r = Rect::from_min_size(pos2(full.left() - 78.0 * z + 2.0, full.top() + 6.0), vec2(74.0, full.height() - 12.0));
|
|
self.rail(ui, r);
|
|
}
|
|
let side_k = spring("side/k", (self.side_open && !self.zen) as u8 as f32, Preset { stiffness: 620.0, damping: 0.72 });
|
|
let side_w = 296.0 * side_k.max(0.0);
|
|
let pad = 8.0;
|
|
let status_h = 48.0 * (1.0 - zk);
|
|
let body = Rect::from_min_max(pos2(full.left() + rail_w + pad * z.clamp(0.0, 1.0) + 2.0, full.top() + 8.0), pos2(full.right() - 10.0, full.bottom() - status_h - 8.0 * zk));
|
|
if side_k > 0.01 {
|
|
let r = Rect::from_min_size(body.min, vec2(side_w - 8.0, body.height()));
|
|
let mut sub = ui.new_child(egui::UiBuilder::new().max_rect(r));
|
|
sub.set_clip_rect(r.intersect(ui.clip_rect()));
|
|
self.side_panel(&mut sub, Rect::from_min_size(r.min, vec2(288.0, r.height())));
|
|
}
|
|
let stage = Rect::from_min_max(pos2(body.left() + side_w, body.top()), body.max);
|
|
|
|
let term_k = spring("term/k", self.term_open as u8 as f32, Preset { stiffness: 480.0, damping: 0.7 });
|
|
let reserved = (self.term_height + 8.0) * term_k.clamp(0.0, 1.0);
|
|
self.term_target = Rect::from_min_max(pos2(stage.left(), stage.bottom() - self.term_height), stage.max);
|
|
let editors = Rect::from_min_max(stage.min, pos2(stage.right(), stage.bottom() - reserved));
|
|
|
|
let n = self.panes.len();
|
|
let gap = 8.0;
|
|
let mut rects = vec![editors];
|
|
if n > 1 {
|
|
if self.split_vertical {
|
|
let y = editors.top() + editors.height() * self.split;
|
|
rects = vec![Rect::from_min_max(editors.min, pos2(editors.right(), y - gap / 2.0)), Rect::from_min_max(pos2(editors.left(), y + gap / 2.0), editors.max)];
|
|
} else {
|
|
let x = editors.left() + editors.width() * self.split;
|
|
rects = vec![Rect::from_min_max(editors.min, pos2(x - gap / 2.0, editors.bottom())), Rect::from_min_max(pos2(x + gap / 2.0, editors.top()), editors.max)];
|
|
}
|
|
let bar = if self.split_vertical { Rect::from_center_size(pos2(editors.center().x, rects[0].bottom() + gap / 2.0), vec2(editors.width(), gap + 4.0)) } else { Rect::from_center_size(pos2(rects[0].right() + gap / 2.0, editors.center().y), vec2(gap + 4.0, editors.height())) };
|
|
let resp = ui.interact(bar, ui.scope_id().with("split-bar"), Sense::drag());
|
|
if resp.hovered() || resp.dragged() { ctx.set_cursor_icon(if self.split_vertical { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal }) }
|
|
if resp.dragged() {
|
|
let d = resp.drag_delta();
|
|
self.split = (self.split + if self.split_vertical { d.y / editors.height() } else { d.x / editors.width() }).clamp(0.2, 0.8);
|
|
}
|
|
}
|
|
let mut find_card = None;
|
|
for (i, r) in rects.iter().enumerate() {
|
|
let has_controls = (r.right() - full.right()).abs() < 30.0 && (r.top() - editors.top()).abs() < 1.0;
|
|
let tab_h = 46.0 * (1.0 - zk);
|
|
let strip = Rect::from_min_max(r.min, pos2(r.right() - if has_controls { self.toolbar_width() } else { 0.0 }, r.top() + 44.0));
|
|
if tab_h > 8.0 {
|
|
let mut sub = ui.new_child(egui::UiBuilder::new().max_rect(strip.translate(vec2(0.0, -46.0 * zk))));
|
|
self.tabstrip(&mut sub, i, strip.translate(vec2(0.0, -46.0 * zk)));
|
|
}
|
|
let card = Rect::from_min_max(pos2(r.left(), r.top() + tab_h), r.max);
|
|
let focused = i == self.focus_pane;
|
|
p.rect_filled(card, cr(24.0), t.low);
|
|
if n > 1 && focused {
|
|
p.rect_stroke(card, cr(24.0), Stroke::new(1.5, alpha(t.primary, 0.5)), egui::StrokeKind::Inside);
|
|
}
|
|
if self.panes[i].tabs.is_empty() {
|
|
self.welcome(ui, card);
|
|
continue;
|
|
}
|
|
let mini_w = if self.s.preview { 112.0 } else { 0.0 };
|
|
let code = Rect::from_min_max(card.min, pos2(card.right() - mini_w - if mini_w > 0.0 { 8.0 } else { 0.0 }, card.bottom()));
|
|
self.editor(ui, i, code.shrink2(vec2(0.0, 2.0)));
|
|
if self.s.preview {
|
|
let rail = Rect::from_min_max(pos2(card.right() - mini_w - 8.0, card.top() + 8.0), pos2(card.right() - 8.0, card.bottom() - 8.0));
|
|
self.preview(ui, i, rail);
|
|
}
|
|
if focused {
|
|
find_card = Some(card);
|
|
self.caret_pos = self.caret_screen_of(ui, i, code);
|
|
}
|
|
}
|
|
if let Some(c) = find_card { self.find_bar(ui, c) }
|
|
|
|
self.toolbar(ui, full);
|
|
|
|
if term_k.abs() > 0.004 {
|
|
self.terminal_card(ui, self.term_target, term_k);
|
|
}
|
|
if status_h > 2.0 {
|
|
let r = Rect::from_min_max(pos2(body.left(), full.bottom() - 48.0 + 48.0 * zk), pos2(full.right() - 12.0, full.bottom() - 2.0 + 48.0 * zk));
|
|
self.status(ui, r);
|
|
}
|
|
}
|
|
|
|
fn caret_screen_of(&self, ui: &Ui, pane: usize, code: Rect) -> Pos2 {
|
|
let m = self.metrics(ui);
|
|
let p = &self.panes[pane];
|
|
let Some(tb) = p.tabs.get(p.active) else { return code.min };
|
|
let digits = self.docs[&tb.doc].buf.lines().to_string().len().max(3);
|
|
let gutter = if self.s.line_numbers { digits as f32 * m.cw * 0.92 + 42.0 } else { 34.0 };
|
|
pos2(code.left() + gutter + 6.0 + tb.caret[0].x - tb.scroll_x, code.top() + 8.0 + tb.caret[1].x - tb.scroll.x)
|
|
}
|
|
|
|
/// The icons at the top right: the ones chosen in Settings, then the menu logo at the end.
|
|
fn toolbar(&mut self, ui: &mut Ui, full: Rect) {
|
|
let t = self.t.clone();
|
|
let ctx = ui.ctx().clone();
|
|
let z = spring("zen", self.zen as u8 as f32, motion::DEFAULT).clamp(0.0, 1.0);
|
|
let y = full.top() + 30.0 - 60.0 * z;
|
|
let right = full.right() - 34.0;
|
|
let logo = pos2(right, y);
|
|
self.logo(ui, logo);
|
|
let all = crate::ui::commands::all();
|
|
let picks: Vec<&crate::ui::commands::Entry> = self.s.toolbar.iter().filter_map(|l| all.iter().find(|e| e.label == l)).collect();
|
|
let n = picks.len();
|
|
for (i, e) in picks.iter().enumerate() {
|
|
let x = right - 44.0 - (n - 1 - i) as f32 * 36.0;
|
|
let key = format!("bar/{}", e.label);
|
|
let tip = if e.keys.is_empty() { e.label.to_string() } else { format!("{} ({})", e.label, e.keys) };
|
|
let k = motion::spring_from(format!("{key}/in"), 0.4, 1.0, motion::DEFAULT);
|
|
if icon_btn(ui, &t, Rect::from_center_size(pos2(x, y), vec2(32.0, 32.0) * k), &key, e.ic, &tip, false).clicked() {
|
|
self.run(&ctx, e.cmd.clone());
|
|
}
|
|
}
|
|
}
|
|
|
|
fn toolbar_width(&self) -> f32 {
|
|
60.0 + self.s.toolbar.len() as f32 * 36.0
|
|
}
|
|
|
|
fn toasts_ui(&mut self, ctx: &egui::Context) {
|
|
let t = self.t.clone();
|
|
let now = ctx.input(|i| i.time);
|
|
for x in &mut self.toasts { if x.born < 0.0 { x.born = now } }
|
|
self.toasts.retain(|x| now - x.born < 3.6);
|
|
let screen = ctx.content_rect();
|
|
let mut y = screen.bottom() - 64.0;
|
|
for x in self.toasts.iter().rev() {
|
|
let age = (now - x.born) as f32;
|
|
let out = age > 3.2;
|
|
let k = motion::spring_from(format!("toast/{}", x.seq), 0.0, if out { 0.0 } else { 1.0 }, motion::DEFAULT);
|
|
let w = 66.0 + ctx.fonts_mut(|f| f.layout_no_wrap(x.text.clone(), fonts::ui(13.0), t.on_surface).size().x);
|
|
let size = vec2(lerp(44.0, w, k.clamp(0.0, 1.1)), 44.0);
|
|
let r = Rect::from_min_size(pos2(screen.center().x - size.x / 2.0, y + (1.0 - k) * 60.0 - 44.0), size);
|
|
let inv = (t.on_surface, t.surface);
|
|
egui::Area::new(Id::unique(("toast", x.seq))).order(egui::Order::Tooltip).fixed_pos(r.min).interactable(false).show(ctx, |ui| {
|
|
let p = ui.painter().with_clip_rect(ctx.content_rect());
|
|
shadow(&p, r, r.height() / 2.0, k.clamp(0.0, 1.0) * 0.8, t.dark);
|
|
p.rect_filled(r, cr(r.height() / 2.0), inv.0);
|
|
icons::paint(ctx, &p, r.left_center() + vec2(23.0, 0.0), 19.0, x.ic, alpha(inv.1, k.clamp(0.0, 1.0)));
|
|
if k > 0.5 {
|
|
p.with_clip_rect(r).text(r.left_center() + vec2(42.0, 0.0), Align2::LEFT_CENTER, &x.text, fonts::ui(13.0), alpha(inv.1, (k * 2.0 - 1.0).clamp(0.0, 1.0)));
|
|
}
|
|
});
|
|
y -= 52.0 * k.clamp(0.0, 1.0);
|
|
motion::keep_alive();
|
|
}
|
|
}
|
|
|
|
fn theme_wave_ui(&mut self, ctx: &egui::Context) {
|
|
let Some((c, born)) = self.theme_wave else { return };
|
|
let age = (ctx.input(|i| i.time) - born) as f32;
|
|
if age > 0.7 {
|
|
self.theme_wave = None;
|
|
return;
|
|
}
|
|
let k = age / 0.7;
|
|
let e = 1.0 - (1.0 - k).powi(3);
|
|
let radius = ctx.content_rect().size().length() * e;
|
|
let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, Id::unique("wave")));
|
|
p.circle_filled(c, radius, alpha(self.t.primary, 0.24 * (1.0 - k)));
|
|
motion::keep_alive();
|
|
}
|
|
}
|
|
|
|
impl eframe::App for App {
|
|
fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) {
|
|
App::ui(self, ui);
|
|
}
|
|
|
|
fn clear_color(&self, _: &egui::Visuals) -> [f32; 4] {
|
|
self.t.surface.to_normalized_gamma_f32()
|
|
}
|
|
|
|
fn on_exit(&mut self, _: Option<&eframe::glow::Context>) {
|
|
self.save_session();
|
|
self.s.save();
|
|
discord::shut_down(&self.presence);
|
|
}
|
|
}
|
|
|
|
/// `path:line` from the command line.
|
|
fn split_line(arg: &str) -> (PathBuf, Option<usize>) {
|
|
if let Some((p, l)) = arg.rsplit_once(':') {
|
|
if let Ok(n) = l.parse::<usize>() {
|
|
return (PathBuf::from(p), Some(n.saturating_sub(1)));
|
|
}
|
|
}
|
|
(PathBuf::from(arg), None)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::split_line;
|
|
|
|
#[test]
|
|
fn line_suffix_is_optional() {
|
|
assert_eq!(split_line("a/b.rs:12").1, Some(11));
|
|
assert_eq!(split_line("a/b.rs").1, None);
|
|
}
|
|
}
|