use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::time::{Duration, Instant};
use crossterm::event::{
Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use serde_json::Value;
use crate::document::Document;
use crate::editor::Editor;
use crate::finder::{self, Finder};
use crate::git::{self, GitInfo};
use crate::lsp::{find_root, Client, Reply, ServerSpec};
use crate::screen::{fit, Row, Screen, Span, Style};
use crate::search::{self, Hit};
use crate::terminal::Terminal;
use crate::tree::Tree;
#[cfg(test)]
mod tests;
const LSP_DEBOUNCE: Duration = Duration::from_millis(30);
const TREE_WIDTH: usize = 30;
const WHEEL_LINES: isize = 3;
const DOUBLE_CLICK: Duration = Duration::from_millis(400);
const CLOSE_ICON: char = '×';
const FINDER_ROWS: usize = 8;
#[derive(Clone, Copy, Debug, PartialEq)]
enum Picker {
Files,
Search,
Results,
Git,
Branches,
Commit,
NewBranch,
}
impl Picker {
fn prompt(self) -> &'static str {
match self {
Self::Files => " Open file: ",
Self::Search => " Search project: ",
Self::Results => " Matches: ",
Self::Git => " Git: ",
Self::Branches => " Switch to branch: ",
Self::Commit => " Commit message: ",
Self::NewBranch => " New branch: ",
}
}
fn is_question(self) -> bool {
matches!(self, Self::Search | Self::Commit | Self::NewBranch)
}
}
const GIT_MENU: [&str; 9] = [
"Stage this file",
"Unstage this file",
"Stage all changes",
"Unstage everything",
"Commit...",
"Switch branch...",
"New branch...",
"Pull",
"Push",
];
pub enum AppEvent {
Input(Event),
Lsp(usize, Option<Value>),
Git(Option<GitInfo>),
Committed(String, Option<Vec<String>>),
GitDone(String),
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Focus {
Editor,
Tree,
}
struct Server {
id: usize,
key: String,
client: Rc<RefCell<Client>>,
}
struct Layout {
tabs: usize,
tree: usize,
pane_width: usize,
pane_height: usize,
}
pub struct Workspace {
editors: Vec<Editor>,
active: usize,
tree: Tree,
show_tree: bool,
focus: Focus,
git: Option<GitInfo>,
finder: Option<Finder>,
picker: Picker,
hits: Vec<Hit>,
clipboard: String,
last_click: Option<(Instant, usize, usize)>,
clipboard_out: Option<String>,
servers: Vec<Server>,
next_server: usize,
events: Option<Sender<AppEvent>>,
lsp_setting: Option<String>,
message: String,
quit_pending: bool,
close_pending: bool,
should_quit: bool,
size: (usize, usize),
screen: Screen,
}
impl Workspace {
pub fn new(
root: PathBuf,
events: Option<Sender<AppEvent>>,
lsp_setting: Option<String>,
) -> Self {
Self {
editors: Vec::new(),
active: 0,
tree: Tree::new(root),
show_tree: false,
focus: Focus::Editor,
git: None,
finder: None,
picker: Picker::Files,
hits: Vec::new(),
clipboard: String::new(),
last_click: None,
clipboard_out: None,
servers: Vec::new(),
next_server: 0,
events,
lsp_setting,
message: String::new(),
quit_pending: false,
close_pending: false,
should_quit: false,
size: (0, 0),
screen: Screen::default(),
}
}
pub fn open_empty(&mut self) {
self.editors.push(Editor::new(Document::default()));
self.active = self.editors.len() - 1;
self.focus = Focus::Editor;
}
pub fn show_folder(&mut self) {
self.show_tree = true;
self.focus = Focus::Tree;
}
pub fn has_files(&self) -> bool {
!self.editors.is_empty()
}
fn say(&mut self, text: String) {
match self.editors.get_mut(self.active) {
Some(editor) => editor.message = text,
None => self.message = text,
}
}
pub fn open(&mut self, path: &Path) -> bool {
let path = std::fs::canonicalize(path)
.or_else(|_| std::path::absolute(path))
.unwrap_or_else(|_| path.to_path_buf());
let text = path.to_string_lossy().into_owned();
let name = path.file_name().map_or_else(
|| text.clone(),
|name| name.to_string_lossy().into_owned(),
);
if let Some(index) = self
.editors
.iter()
.position(|editor| editor.abs_path.as_deref() == Some(text.as_str()))
{
self.active = index;
} else if path.is_dir() {
self.say(format!("{name} is a folder"));
return false;
} else {
let document = match Document::open(&text) {
Ok(document) => document,
Err(error) => {
self.say(format!("Could not open {name}: {error}"));
return false;
}
};
let mut editor = Editor::new(document);
self.attach_lsp(&mut editor);
let placeholder = self.editors.len() == 1
&& self.editors[0].document.path.is_none()
&& !self.editors[0].document.dirty;
if placeholder {
self.editors.clear();
}
self.editors.push(editor);
self.active = self.editors.len() - 1;
self.refresh_git();
}
self.focus = Focus::Editor;
self.tree.reveal(&path);
true
}
fn activate(&mut self, index: usize) {
if index < self.editors.len() {
self.active = index;
self.focus = Focus::Editor;
if let Some(path) = self.editors[index].abs_path.clone() {
self.tree.reveal(Path::new(&path));
}
}
}
fn next_tab(&mut self, step: isize) {
let count = self.editors.len() as isize;
if count > 0 {
self.activate((self.active as isize + step).rem_euclid(count) as usize);
}
}
fn close_active(&mut self, was_pending: bool) {
let Some(editor) = self.editors.get_mut(self.active) else {
return;
};
if editor.document.dirty && !was_pending {
self.close_pending = true;
editor.message = "Unsaved changes! Close again to discard".into();
return;
}
let editor = self.editors.remove(self.active);
if let (Some(lsp), Some(path)) = (&editor.lsp, &editor.abs_path) {
lsp.borrow_mut().close(path);
}
drop(editor);
self.servers.retain(|server| !server.client.borrow().is_unused());
self.active = self.active.min(self.editors.len().saturating_sub(1));
if self.editors.is_empty() {
self.show_folder();
} else {
self.activate(self.active);
}
}
fn close_tab(&mut self, index: usize) {
let pending = std::mem::take(&mut self.close_pending) && index == self.active;
if index < self.editors.len() {
self.activate(index);
self.close_active(pending);
}
}
fn quit(&mut self, was_pending: bool) {
let unsaved = self.editors.iter().filter(|editor| editor.document.dirty).count();
if unsaved == 0 || was_pending {
self.should_quit = true;
return;
}
self.quit_pending = true;
if !self.editors[self.active].document.dirty {
let first = self.editors.iter().position(|editor| editor.document.dirty);
self.activate(first.unwrap_or(self.active));
}
self.say(match unsaved {
1 => "Unsaved changes! Ctrl+Q again to quit".into(),
_ => format!("Unsaved changes in {unsaved} files! Ctrl+Q again to quit"),
});
}
fn attach_lsp(&mut self, editor: &mut Editor) {
let (Some(events), Some(path)) = (&self.events, editor.abs_path.clone()) else {
return;
};
let setting = self.lsp_setting.as_deref();
let Some(spec) = ServerSpec::for_file(editor.language, &path, setting) else {
return;
};
let folder = Path::new(&path).parent().unwrap_or(Path::new("/"));
let root = find_root(folder, spec.root_markers);
let key = format!("{} {:?} {}", spec.command, spec.args, root.display());
let client = match self.servers.iter().find(|server| server.key == key) {
Some(server) => server.client.clone(),
None => {
let id = self.next_server;
self.next_server += 1;
let events = events.clone();
let forward = move |message| {
let _ = events.send(AppEvent::Lsp(id, message));
};
match Client::start(&spec, &root, forward) {
Ok(client) => {
editor.message = format!("Starting {}...", client.name);
let client = Rc::new(RefCell::new(client));
self.servers.push(Server {
id,
key,
client: client.clone(),
});
client
}
Err(_) => {
editor.message =
format!("No language server: {} not found", spec.command);
return;
}
}
}
};
let lines = &editor.document.lines;
client
.borrow_mut()
.open(&path, spec.language_id, &|| lines.join("\n"));
editor.attach_lsp(client);
}
fn handle_lsp(&mut self, id: usize, message: Option<Value>) {
let Some(position) = self.servers.iter().position(|server| server.id == id) else {
return;
};
let client = self.servers[position].client.clone();
let uses_it = |editor: &Editor| editor.lsp.as_ref().is_some_and(|lsp| Rc::ptr_eq(lsp, &client));
let Some(message) = message else {
let name = client.borrow().name.clone();
self.servers.remove(position);
for (index, editor) in self.editors.iter_mut().enumerate() {
if uses_it(editor) {
editor.detach_lsp();
if index == self.active {
editor.message = format!("Language server {name} stopped");
}
}
}
return;
};
let editors = &self.editors;
let text_of = |path: &str| {
editors
.iter()
.find(|editor| editor.abs_path.as_deref() == Some(path))
.map(|editor| editor.document.lines.join("\n"))
.unwrap_or_default()
};
let (path, reply) = client.borrow_mut().handle(&message, &text_of);
let in_front = self.editors.get(self.active).and_then(|editor| editor.abs_path.clone());
match reply {
Reply::Nothing => {}
Reply::Ready => {
if let Some(editor) = self.editors.get_mut(self.active).filter(|editor| uses_it(editor))
{
editor.apply_reply(Reply::Ready);
}
}
Reply::Hover(_) | Reply::Definition(_) if path != in_front => {}
Reply::Definition(Some(mut location)) => {
if Some(&location.path) != in_front.as_ref()
&& Path::new(&location.path).is_file()
&& self.open(Path::new(&location.path))
&& let Some(opened) = self.editors[self.active].abs_path.clone()
{
location.path = opened;
}
self.editors[self.active].apply_reply(Reply::Definition(Some(location)));
}
reply => {
if let Some(editor) = self
.editors
.iter_mut()
.find(|editor| editor.abs_path.is_some() && editor.abs_path == path)
{
editor.apply_reply(reply);
}
}
}
}
fn refresh_git(&self) {
if let Some(events) = &self.events {
let events = events.clone();
let root = self.tree.root().to_path_buf();
let open: Vec<String> = self
.editors
.iter()
.filter_map(|editor| editor.abs_path.clone())
.collect();
std::thread::spawn(move || {
let _ = events.send(AppEvent::Git(git::load(&root)));
for path in open {
let lines = git::committed_lines(Path::new(&path));
let _ = events.send(AppEvent::Committed(path, lines));
}
});
}
}
fn pick(&mut self, picker: Picker, items: Vec<String>) {
self.picker = picker;
self.finder = Some(match picker {
Picker::Files => Finder::with_files(items),
_ => Finder::list(items),
});
}
fn search_project(&mut self, query: &str) {
let files = finder::project_files(self.tree.root());
self.hits = search::in_files(self.tree.root(), &files, query);
if self.hits.is_empty() {
self.say(format!("No match for {query} in the project"));
return;
}
let lines = self
.hits
.iter()
.map(|hit| format!("{}:{}: {}", hit.file, hit.y + 1, hit.text))
.collect();
self.pick(Picker::Results, lines);
}
fn open_hit(&mut self, index: usize) {
let Some(hit) = self.hits.get(index) else {
return;
};
let (path, x, y) = (self.tree.root().join(&hit.file), hit.x, hit.y);
if self.open(&path) {
self.editors[self.active].jump_to(x, y);
}
}
fn open_git_menu(&mut self) {
if self.git.is_some() {
self.pick(Picker::Git, GIT_MENU.iter().map(|item| item.to_string()).collect());
} else {
self.say("This folder is not in git".into());
}
}
fn git_target(&self) -> Option<PathBuf> {
match (self.focus, self.tree.selected()) {
(Focus::Tree, Some(entry)) => Some(entry.path.clone()),
_ => self.editors.get(self.active)?.abs_path.as_ref().map(PathBuf::from),
}
}
fn git_command(&mut self, index: usize) {
let unsaved = self.editors.iter().any(|editor| editor.document.dirty);
match GIT_MENU[index] {
"Stage this file" | "Unstage this file" => {
let Some(path) = self.git_target() else {
return self.say("No file to stage: open or select one first".into());
};
let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
let path = path.to_string_lossy().into_owned();
if GIT_MENU[index] == "Stage this file" {
self.run_git(format!("Staged {name}"), move |root| {
git::action(root, &["add", "--", &path])
});
} else {
self.run_git(format!("Unstaged {name}"), move |root| {
git::action(root, &["restore", "--staged", "--", &path])
});
}
}
"Stage all changes" => {
self.run_git("Staged all changes".into(), |root| git::action(root, &["add", "--all"]));
}
"Unstage everything" => {
self.run_git("Unstaged everything".into(), |root| git::action(root, &["reset", "--quiet"]));
}
"Commit..." => self.pick(Picker::Commit, Vec::new()),
"New branch..." => self.pick(Picker::NewBranch, Vec::new()),
"Switch branch..." | "Pull" if unsaved => {
self.say("Save your changes first: this changes the files on disk".into());
}
"Switch branch..." => {
let branches = git::branches(self.tree.root());
self.pick(Picker::Branches, branches);
}
"Pull" => {
self.run_git("Pulled".into(), |root| git::action(root, &["pull", "--no-edit"]));
}
_ => self.run_git("Pushed".into(), git::push),
}
}
fn run_git(
&mut self,
done: String,
job: impl FnOnce(&Path) -> Result<(), String> + Send + 'static,
) {
let root = self.tree.root().to_path_buf();
let report = move || match job(&root) {
Ok(()) => done,
Err(error) => format!("git: {error}"),
};
match &self.events {
Some(events) => {
let events = events.clone();
std::thread::spawn(move || {
let _ = events.send(AppEvent::GitDone(report()));
});
self.say("Running git...".into());
}
None => {
let message = report();
self.git_done(message);
}
}
}
fn git_done(&mut self, message: String) {
self.tree.refresh();
self.reload_changed();
self.refresh_git();
self.say(message);
}
fn reload_changed(&mut self) {
for editor in &mut self.editors {
let Some(path) = editor.abs_path.clone().filter(|path| Path::new(path).is_file()) else {
continue;
};
if editor.document.dirty {
continue;
}
if let Ok(on_disk) = Document::open(&path)
&& on_disk.lines.join("\n") != editor.document.lines.join("\n")
{
editor.reload(&on_disk.lines);
}
}
}
pub fn run(&mut self, events: &Receiver<AppEvent>) -> std::io::Result<()> {
self.refresh_git();
while !self.should_quit {
self.size = Terminal::size()?;
let (frame, cursor) = self.render(self.size.0, self.size.1);
self.screen.draw(frame, self.size, cursor)?;
if let Some(text) = self.clipboard_out.take() {
Terminal::copy(&text)?;
}
let waiting_to_sync = self
.servers
.iter()
.any(|server| server.client.borrow().has_pending_changes());
let event = if waiting_to_sync {
match events.recv_timeout(LSP_DEBOUNCE) {
Ok(event) => Some(event),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => break,
}
} else {
match events.recv() {
Ok(event) => Some(event),
Err(_) => break,
}
};
match event {
Some(event) => {
self.handle_event(event);
while let Ok(event) = events.try_recv() {
self.handle_event(event);
}
}
None => self.editors.iter_mut().for_each(Editor::sync_lsp),
}
}
Ok(())
}
fn handle_event(&mut self, event: AppEvent) {
match event {
AppEvent::Input(Event::Key(key)) => self.handle_key(key),
AppEvent::Input(Event::Mouse(mouse)) => self.handle_mouse(mouse),
AppEvent::Input(Event::Paste(text)) => self.paste(&text),
AppEvent::Input(Event::FocusGained) => {
self.tree.refresh();
self.reload_changed();
self.refresh_git();
}
AppEvent::Input(_) => {}
AppEvent::Lsp(id, message) => self.handle_lsp(id, message),
AppEvent::Git(git) => self.git = git,
AppEvent::GitDone(message) => self.git_done(message),
AppEvent::Committed(path, lines) => {
if let Some(editor) = self
.editors
.iter_mut()
.find(|editor| editor.abs_path.as_deref() == Some(path.as_str()))
{
editor.set_git_base(lines);
}
}
}
}
fn handle_key(&mut self, key: KeyEvent) {
if key.kind == KeyEventKind::Release {
return;
}
if self.finder.is_some() {
self.finder_key(key);
return;
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
let quit_was_pending = std::mem::take(&mut self.quit_pending);
let close_was_pending = std::mem::take(&mut self.close_pending);
self.message.clear();
if let Some(editor) = self.editors.get_mut(self.active) {
editor.message.clear();
}
match key.code {
KeyCode::Char('q') if ctrl => self.quit(quit_was_pending),
KeyCode::Char('p') if ctrl || alt => {
self.picker = Picker::Files;
self.finder = Some(Finder::new(self.tree.root()));
}
KeyCode::Char('s') if alt => self.pick(Picker::Search, Vec::new()),
KeyCode::Char('g') if ctrl => self.open_git_menu(),
KeyCode::Char('v') if alt => self.open_git_menu(),
KeyCode::Char('v') if ctrl => {
let text = self.clipboard.clone();
self.paste(&text);
}
KeyCode::Char('b') if ctrl || alt => self.toggle_tree(),
KeyCode::Char('e') if alt => self.switch_focus(),
KeyCode::Char('w') if ctrl || alt => self.close_active(close_was_pending),
KeyCode::Char('.') if alt => self.next_tab(1),
KeyCode::Char(',') if alt => self.next_tab(-1),
KeyCode::PageDown if ctrl => self.next_tab(1),
KeyCode::PageUp if ctrl => self.next_tab(-1),
KeyCode::Char(digit @ '1'..='9') if alt => self.activate(digit as usize - '1' as usize),
_ if self.focus == Focus::Tree => self.tree_key(key),
_ => self.editor_key(key),
}
}
fn editor_key(&mut self, key: KeyEvent) {
let Some(editor) = self.editors.get_mut(self.active) else {
return;
};
editor.handle_key(key);
if let Some(text) = editor.copied.take() {
self.clipboard = text.clone();
self.clipboard_out = Some(text);
}
let saved = std::mem::take(&mut editor.just_saved);
let renamed = std::mem::take(&mut editor.renamed);
if renamed {
let mut editor = self.editors.remove(self.active);
self.attach_lsp(&mut editor);
self.editors.insert(self.active, editor);
}
if saved {
self.tree.refresh();
self.refresh_git();
}
if renamed && let Some(path) = self.editors[self.active].abs_path.clone() {
self.tree.reveal(Path::new(&path));
}
}
fn tree_key(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Up => self.tree.move_by(-1),
KeyCode::Down => self.tree.move_by(1),
KeyCode::PageUp => self.tree.move_by(-10),
KeyCode::PageDown => self.tree.move_by(10),
KeyCode::Home => self.tree.move_by(isize::MIN / 2),
KeyCode::End => self.tree.move_by(isize::MAX / 2),
KeyCode::Left => self.tree.left(),
KeyCode::Right => self.tree.right(),
KeyCode::Enter => {
if let Some(path) = self.tree.activate() {
self.open(&path);
}
}
KeyCode::Esc if self.has_files() => self.focus = Focus::Editor,
_ => {}
}
}
fn finder_key(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let Some(finder) = &mut self.finder else {
return;
};
match key.code {
KeyCode::Esc => self.finder = None,
KeyCode::Char('p' | 'q' | 'c') if ctrl => self.finder = None,
KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::ALT) => self.finder = None,
KeyCode::Enter => self.accept_picked(),
KeyCode::Up => finder.move_by(-1),
KeyCode::Down => finder.move_by(1),
KeyCode::Backspace => finder.backspace(),
KeyCode::Char(c) if !ctrl => finder.type_char(c),
_ => {}
}
}
fn accept_picked(&mut self) {
let Some(finder) = &self.finder else {
return;
};
let typed = finder.query.trim().to_string();
let index = finder.chosen_index();
let chosen = finder.chosen().map(String::from);
self.finder = None;
match (self.picker, index, chosen) {
(picker, ..) if picker.is_question() && typed.is_empty() => {}
(Picker::Search, ..) => self.search_project(&typed),
(Picker::Commit, ..) => {
let message = typed.clone();
self.run_git(format!("Committed: {typed}"), move |root| {
git::action(root, &["commit", "--message", &message])
});
}
(Picker::NewBranch, ..) => {
let name = typed.clone();
self.run_git(format!("On new branch {typed}"), move |root| {
git::action(root, &["switch", "--create", &name])
});
}
(Picker::Files, _, Some(file)) => {
let path = self.tree.root().join(file);
self.open(&path);
}
(Picker::Results, Some(index), _) => self.open_hit(index),
(Picker::Git, Some(index), _) => self.git_command(index),
(Picker::Branches, _, Some(branch)) => {
let name = branch.clone();
self.run_git(format!("Switched to {branch}"), move |root| {
git::action(root, &["switch", &name])
});
}
_ => {}
}
}
fn paste(&mut self, text: &str) {
if let Some(finder) = &mut self.finder {
text.chars()
.filter(|c| !c.is_control())
.for_each(|c| finder.type_char(c));
} else if self.focus == Focus::Editor
&& let Some(editor) = self.editors.get_mut(self.active)
{
editor.paste(text);
}
}
fn toggle_tree(&mut self) {
if self.show_tree && self.has_files() {
self.show_tree = false;
self.focus = Focus::Editor;
} else {
self.show_folder();
self.tree.refresh();
self.refresh_git();
}
}
fn switch_focus(&mut self) {
if self.focus == Focus::Tree && self.has_files() {
self.focus = Focus::Editor;
} else {
self.show_folder();
}
}
fn picker_mouse(&mut self, mouse: MouseEvent, layout: &Layout) {
let Some(finder) = &mut self.finder else {
return;
};
let (x, y) = (mouse.column as usize, mouse.row as usize);
let count = FINDER_ROWS.min(layout.pane_height.saturating_sub(2));
match mouse.kind {
MouseEventKind::ScrollDown => finder.move_by(1),
MouseEventKind::ScrollUp => finder.move_by(-1),
MouseEventKind::Down(MouseButton::Left) => {
let row = y.checked_sub(layout.tabs + 1).filter(|_| x >= layout.tree);
if row.is_some_and(|row| finder.select_row(row, count)) {
self.accept_picked();
} else if y != layout.tabs {
self.finder = None;
}
}
_ => {}
}
}
fn handle_mouse(&mut self, mouse: MouseEvent) {
let layout = self.layout(self.size.0, self.size.1);
if self.finder.is_some() {
return self.picker_mouse(mouse, &layout);
}
let (x, y) = (mouse.column as usize, mouse.row as usize);
let over_tree = x < layout.tree && y >= layout.tabs;
let over_tabs = y < layout.tabs;
match mouse.kind {
MouseEventKind::Down(MouseButton::Middle) if over_tabs => {
if let Some((tab, _)) = self.tab_at(x) {
self.close_tab(tab);
}
}
MouseEventKind::ScrollDown if over_tabs => self.next_tab(1),
MouseEventKind::ScrollUp if over_tabs => self.next_tab(-1),
MouseEventKind::Down(MouseButton::Left) => {
if over_tabs {
match self.tab_at(x) {
Some((tab, true)) => self.close_tab(tab),
Some((tab, false)) => self.activate(tab),
None => {}
}
} else if over_tree {
self.focus = Focus::Tree;
if let Some(row) = (y - layout.tabs).checked_sub(1)
&& let Some(path) = self.tree.click(row)
{
self.open(&path);
}
} else if let Some(editor) = self.editors.get_mut(self.active) {
self.focus = Focus::Editor;
editor.click(x - layout.tree, y - layout.tabs);
let now = Instant::now();
let double = self.last_click.is_some_and(|(at, last_x, last_y)| {
(last_x, last_y) == (x, y) && now.duration_since(at) < DOUBLE_CLICK
});
if double {
editor.select_word();
}
self.last_click = (!double).then_some((now, x, y));
}
}
MouseEventKind::Drag(MouseButton::Left)
if self.focus == Focus::Editor && y >= layout.tabs && x >= layout.tree =>
{
if let Some(editor) = self.editors.get_mut(self.active) {
editor.drag(x - layout.tree, y - layout.tabs);
}
}
MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => {
let lines = match mouse.kind {
MouseEventKind::ScrollDown => WHEEL_LINES,
_ => -WHEEL_LINES,
};
if over_tree {
self.tree.move_by(lines);
} else if let Some(editor) = self.editors.get_mut(self.active) {
editor.wheel(lines);
}
}
_ => {}
}
}
fn layout(&self, width: usize, height: usize) -> Layout {
let tabs = (self.editors.len() > 1) as usize;
let tree = if self.show_tree {
TREE_WIDTH.min(width / 2) + 1
} else {
0
};
Layout {
tabs,
tree,
pane_width: width.saturating_sub(tree),
pane_height: height.saturating_sub(tabs),
}
}
fn tab_labels(&self) -> Vec<String> {
self.editors
.iter()
.map(|editor| {
let dot = if editor.document.dirty { " ●" } else { "" };
format!(" {}{dot} {CLOSE_ICON} ", editor.name())
})
.collect()
}
fn tab_at(&self, x: usize) -> Option<(usize, bool)> {
let mut end = 0;
let tab = self.tab_labels().iter().position(|label| {
end += label.chars().count();
x < end
})?;
Some((tab, x + 2 >= end))
}
fn tab_row(&self, width: usize) -> Row {
let mut row = Row::new();
let mut used = 0;
for (index, label) in self.tab_labels().iter().enumerate() {
let label = fit(label, label.chars().count().min(width - used));
used += label.chars().count();
let style = if index == self.active { Style::Reverse } else { Style::Dim };
row.push(Span::new(style, label));
}
row
}
fn empty_pane(&self, width: usize, height: usize) -> Vec<Row> {
let mut rows = Vec::with_capacity(height);
for y in 0..height.saturating_sub(1) {
let text = match y.checked_sub(height / 3) {
Some(0) => concat!("curd editor -- v", env!("CARGO_PKG_VERSION")),
Some(2) => "Enter open the selected file",
Some(3) => "Ctrl+P find a file by name",
Some(4) => "Ctrl+Q quit",
_ => "",
};
let padding = width.saturating_sub(30) / 2;
let line: String = format!("{}{text}", " ".repeat(padding))
.chars()
.take(width)
.collect();
rows.push(vec![Span::new(Style::Dim, line)]);
}
if height > 0 {
let status = if self.message.is_empty() { "No file open" } else { &self.message };
rows.push(vec![Span::new(Style::Reverse, fit(status, width))]);
}
rows
}
fn render(&mut self, width: usize, height: usize) -> (Vec<Row>, Option<(usize, usize)>) {
let layout = self.layout(width, height);
let (pane_width, pane_height) = (layout.pane_width, layout.pane_height);
let mut pane = match self.editors.get_mut(self.active) {
Some(editor) => {
editor.scroll(
pane_width.saturating_sub(editor.gutter_width()),
pane_height.saturating_sub(1),
);
editor.render(pane_width, pane_height)
}
None => self.empty_pane(pane_width, pane_height),
};
let mut cursor = match (self.focus, self.editors.get(self.active)) {
(Focus::Editor, Some(editor)) => Some(editor.cursor_on_screen()),
_ => None,
};
if let Some(finder) = &self.finder {
let mut lines = vec![Span::new(
Style::Reverse,
fit(&format!("{}{}", self.picker.prompt(), finder.query), pane_width),
)];
let matches = finder.visible(FINDER_ROWS.min(pane_height.saturating_sub(2)));
if matches.is_empty() && !self.picker.is_question() {
let nothing = match self.picker {
Picker::Files => " no matching files",
_ => " nothing matches",
};
lines.push(Span::new(Style::Dim, fit(nothing, pane_width)));
}
for (path, selected) in matches {
lines.push(if selected {
Span::new(Style::Bold, fit(&format!(" > {path}"), pane_width))
} else {
Span::new(Style::Dim, fit(&format!(" {path}"), pane_width))
});
}
for (row, line) in pane.iter_mut().zip(lines) {
*row = vec![line];
}
let typed = self.picker.prompt().len() + finder.query.chars().count();
cursor = Some((typed.min(pane_width.saturating_sub(1)), 0));
}
let mut sidebar = (layout.tree > 0).then(|| {
let focused = self.focus == Focus::Tree && self.finder.is_none();
self.tree
.render(layout.tree - 1, pane_height, focused, self.git.as_ref())
});
let mut rows = Vec::with_capacity(height);
if layout.tabs > 0 && height > 0 {
rows.push(self.tab_row(width));
}
for (y, pane_row) in pane.into_iter().enumerate() {
let mut row = Row::new();
if let Some(sidebar) = &mut sidebar {
row.append(&mut sidebar[y]);
row.push(Span::new(Style::Dim, "│"));
}
row.extend(pane_row);
rows.push(row);
}
let cursor = cursor.map(|(x, y)| (x + layout.tree, y + layout.tabs));
(rows, cursor)
}
}