Skip to content

Commit

Permalink
refactor: split commands into separate files (#272)
Browse files Browse the repository at this point in the history
  • Loading branch information
sxyazi authored Oct 15, 2023
1 parent b840dcc commit e12ebd3
Show file tree
Hide file tree
Showing 54 changed files with 1,145 additions and 1,051 deletions.
22 changes: 9 additions & 13 deletions app/src/executor.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::{emit, files::FilesSorter, input::InputMode, manager::FinderCase, Ctx};
use core::{emit, files::FilesSorter, input::InputMode, tab::FinderCase, Ctx};

use config::{keymap::{Control, Exec, Key, KeymapLayer}, manager::SortBy, KEYMAP};
use shared::{optional_bool, Url};
Expand Down Expand Up @@ -97,17 +97,13 @@ impl Executor {
"yank" => cx.manager.yank(exec.named.contains_key("cut")),
"paste" => {
let dest = cx.manager.cwd();
let (cut, src) = cx.manager.yanked();
let (cut, ref src) = cx.manager.yanked;

let force = exec.named.contains_key("force");
if *cut {
cx.tasks.file_cut(src, dest, force)
} else {
cx.tasks.file_copy(src, dest, force)
}
if cut { cx.tasks.file_cut(src, dest, force) } else { cx.tasks.file_copy(src, dest, force) }
}
"link" => {
let (cut, src) = cx.manager.yanked();
let (cut, ref src) = cx.manager.yanked;
!cut
&& cx.tasks.file_link(
src,
Expand All @@ -117,7 +113,7 @@ impl Executor {
)
}
"remove" => {
let targets = cx.manager.selected().into_iter().map(|f| f.url_owned()).collect();
let targets = cx.manager.selected().into_iter().map(|f| f.url()).collect();
let force = exec.named.contains_key("force");
let permanently = exec.named.contains_key("permanently");
cx.tasks.file_remove(targets, force, permanently)
Expand Down Expand Up @@ -182,20 +178,20 @@ impl Executor {
} else {
exec.args.get(0).map(Url::from).unwrap_or_else(|| Url::from("/"))
};
cx.manager.tabs_mut().create(&path)
cx.manager.tabs.create(&path)
}
"tab_close" => {
let idx = exec.args.get(0).and_then(|i| i.parse().ok()).unwrap_or(0);
cx.manager.tabs_mut().close(idx)
cx.manager.tabs.close(idx)
}
"tab_switch" => {
let step = exec.args.get(0).and_then(|s| s.parse().ok()).unwrap_or(0);
let rel = exec.named.contains_key("relative");
cx.manager.tabs_mut().switch(step, rel)
cx.manager.tabs.switch(step, rel)
}
"tab_swap" => {
let step = exec.args.get(0).and_then(|s| s.parse().ok()).unwrap_or(0);
cx.manager.tabs_mut().swap(step)
cx.manager.tabs.swap(step)
}

// Tasks
Expand Down
2 changes: 1 addition & 1 deletion app/src/help/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl<'a> Widget for Layout<'a> {
Clear.render(area, buf);

let help = &self.cx.help;
Paragraph::new(help.keyword().unwrap_or_else(|| format!("{}.help", help.layer())))
Paragraph::new(help.keyword().unwrap_or_else(|| format!("{}.help", help.layer)))
.style(THEME.help.footer.into())
.render(chunks[1], buf);

Expand Down
6 changes: 3 additions & 3 deletions app/src/manager/preview.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::{manager::PreviewData, Ctx};
use core::{preview::PreviewData, Ctx};

use ansi_to_tui::IntoText;
use ratatui::{buffer::Buffer, layout::Rect, widgets::{Paragraph, Widget}};
Expand All @@ -16,11 +16,11 @@ impl<'a> Preview<'a> {
impl<'a> Widget for Preview<'a> {
fn render(self, area: Rect, buf: &mut Buffer) {
let manager = &self.cx.manager;
let Some(hovered) = manager.hovered().map(|h| h.url()) else {
let Some(hovered) = manager.hovered().map(|h| &h.url) else {
return;
};

let preview = manager.active().preview();
let preview = &manager.active().preview;
if !preview.same_path(hovered) {
return;
}
Expand Down
2 changes: 1 addition & 1 deletion app/src/root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ impl<'a> Widget for Root<'a> {
input::Input::new(self.cx).render(area, buf);
}

if self.cx.help.visible() {
if self.cx.help.visible {
help::Layout::new(self.cx).render(area, buf);
}

Expand Down
4 changes: 2 additions & 2 deletions core/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl Ctx {
}
Position::Hovered(rect @ Rect { mut x, y, width, height }) => {
let Some(r) =
self.manager.hovered().and_then(|h| self.manager.current().rect_current(h.url()))
self.manager.hovered().and_then(|h| self.manager.current().rect_current(&h.url))
else {
return self.area(&Position::Top(*rect));
};
Expand Down Expand Up @@ -72,7 +72,7 @@ impl Ctx {
pub fn layer(&self) -> KeymapLayer {
if self.which.visible {
KeymapLayer::Which
} else if self.help.visible() {
} else if self.help.visible {
KeymapLayer::Help
} else if self.input.visible {
KeymapLayer::Input
Expand Down
2 changes: 1 addition & 1 deletion core/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use shared::{InputError, RoCell, Url};
use tokio::sync::{mpsc::{self, UnboundedSender}, oneshot};

use super::{files::FilesOp, input::InputOpt, select::SelectOpt};
use crate::{manager::PreviewLock, tasks::TasksProgress};
use crate::{preview::PreviewLock, tasks::TasksProgress};

static TX: RoCell<UnboundedSender<Event>> = RoCell::new();

Expand Down
34 changes: 7 additions & 27 deletions core/src/files/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ use tokio::fs;

#[derive(Clone, Debug)]
pub struct File {
pub(super) url: Url,
pub(super) meta: Metadata,
pub(super) length: u64,
pub(super) link_to: Option<Url>,
pub(super) is_link: bool,
pub(super) is_hidden: bool,
pub url: Url,
pub meta: Metadata,
pub length: u64,
pub(super) link_to: Option<Url>,
pub is_link: bool,
pub is_hidden: bool,
}

impl File {
Expand Down Expand Up @@ -46,13 +46,7 @@ impl File {
impl File {
// --- Url
#[inline]
pub fn url(&self) -> &Url { &self.url }

#[inline]
pub fn url_mut(&mut self) -> &mut Url { &mut self.url }

#[inline]
pub fn url_owned(&self) -> Url { self.url.clone() }
pub fn url(&self) -> Url { self.url.clone() }

#[inline]
pub fn name(&self) -> Option<&OsStr> { self.url.file_name() }
Expand All @@ -69,27 +63,13 @@ impl File {
pub fn parent(&self) -> Option<Url> { self.url.parent_url() }

// --- Meta
#[inline]
pub fn meta(&self) -> &Metadata { &self.meta }

#[inline]
pub fn is_file(&self) -> bool { self.meta.is_file() }

#[inline]
pub fn is_dir(&self) -> bool { self.meta.is_dir() }

// --- Length
#[inline]
pub fn length(&self) -> u64 { self.length }

// --- Link to / Is link
#[inline]
pub fn link_to(&self) -> Option<&Url> { self.link_to.as_ref() }

#[inline]
pub fn is_link(&self) -> bool { self.is_link }

// -- Is hidden
#[inline]
pub fn is_hidden(&self) -> bool { self.is_hidden }
}
21 changes: 7 additions & 14 deletions core/src/files/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ use tokio::{fs, select, sync::mpsc::{self, UnboundedReceiver}};
use super::{File, FilesSorter, FILES_TICKET};

pub struct Files {
items: Vec<File>,
hidden: Vec<File>,
ticket: u64,
version: u64,
items: Vec<File>,
hidden: Vec<File>,
ticket: u64,
pub(crate) version: u64,

sizes: BTreeMap<Url, u64>,
selected: BTreeSet<Url>,
Expand Down Expand Up @@ -89,7 +89,7 @@ impl Files {
self.items.iter().any(|f| !self.selected.contains(&f.url))
};

self.selected = self.iter().map(|f| f.url_owned()).collect();
self.selected = self.iter().map(|f| f.url()).collect();
b
}
Some(false) => {
Expand All @@ -106,7 +106,7 @@ impl Files {
if self.selected.contains(&item.url) {
self.selected.remove(&item.url);
} else {
self.selected.insert(item.url_owned());
self.selected.insert(item.url());
}
}
!self.items.is_empty()
Expand All @@ -116,7 +116,7 @@ impl Files {

pub fn select_index(&mut self, indices: &BTreeSet<usize>, state: Option<bool>) -> bool {
let mut applied = false;
let paths: Vec<_> = self.pick(indices).iter().map(|f| f.url_owned()).collect();
let paths: Vec<_> = self.pick(indices).iter().map(|f| f.url()).collect();

for path in paths {
applied |= self.select(&path, state);
Expand Down Expand Up @@ -268,13 +268,6 @@ impl Files {
#[inline]
pub fn position(&self, url: &Url) -> Option<usize> { self.iter().position(|f| &f.url == url) }

#[inline]
pub fn duplicate(&self, idx: usize) -> Option<File> { self.items.get(idx).cloned() }

// --- Version
#[inline]
pub fn version(&self) -> u64 { self.version }

// --- Sizes
#[inline]
pub fn size(&self, url: &Url) -> Option<u64> { self.sizes.get(url).copied() }
Expand Down
4 changes: 2 additions & 2 deletions core/src/files/sorter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ impl FilesSorter {
}),
SortBy::Natural => self.sort_naturally(items),
SortBy::Size => items.sort_unstable_by(|a, b| {
let aa = if a.is_dir() { sizes.get(a.url()).copied() } else { None };
let bb = if b.is_dir() { sizes.get(b.url()).copied() } else { None };
let aa = if a.is_dir() { sizes.get(&a.url).copied() } else { None };
let bb = if b.is_dir() { sizes.get(&b.url).copied() } else { None };
self.cmp(aa.unwrap_or(a.length), bb.unwrap_or(b.length), self.promote(a, b))
}),
}
Expand Down
14 changes: 3 additions & 11 deletions core/src/help/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ use crate::{emit, input::Input};

#[derive(Default)]
pub struct Help {
visible: bool,
layer: KeymapLayer,
bindings: Vec<Control>,
pub visible: bool,
pub layer: KeymapLayer,
bindings: Vec<Control>,

// Filter
keyword: Option<String>,
Expand Down Expand Up @@ -127,14 +127,6 @@ impl Help {
}

impl Help {
// --- Visible
#[inline]
pub fn visible(&self) -> bool { self.visible }

// --- Layer
#[inline]
pub fn layer(&self) -> KeymapLayer { self.layer }

// --- Keyword
#[inline]
pub fn keyword(&self) -> Option<String> {
Expand Down
2 changes: 2 additions & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ mod highlighter;
pub mod input;
pub mod manager;
mod position;
pub mod preview;
pub mod select;
mod step;
pub mod tab;
pub mod tasks;
pub mod which;

Expand Down
10 changes: 10 additions & 0 deletions core/src/manager/commands/close.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use crate::{manager::Manager, tasks::Tasks};

impl Manager {
pub fn close(&mut self, tasks: &Tasks) -> bool {
if self.tabs.len() > 1 {
return self.tabs.close(self.tabs.idx);
}
self.quit(tasks, false)
}
}
43 changes: 43 additions & 0 deletions core/src/manager/commands/create.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use std::path::PathBuf;

use shared::Url;
use tokio::fs::{self};

use crate::{emit, files::{File, FilesOp}, input::InputOpt, manager::Manager};

impl Manager {
pub fn create(&self, force: bool) -> bool {
let cwd = self.cwd().to_owned();
tokio::spawn(async move {
let mut result = emit!(Input(InputOpt::top("Create:")));
let Some(Ok(name)) = result.recv().await else {
return Ok(());
};

let path = cwd.join(&name);
if !force && fs::symlink_metadata(&path).await.is_ok() {
match emit!(Input(InputOpt::top("Overwrite an existing file? (y/N)"))).recv().await {
Some(Ok(c)) if c == "y" || c == "Y" => (),
_ => return Ok(()),
}
}

if name.ends_with('/') {
fs::create_dir_all(&path).await?;
} else {
fs::create_dir_all(&path.parent().unwrap()).await.ok();
fs::File::create(&path).await?;
}

let child =
Url::from(path.components().take(cwd.components().count() + 1).collect::<PathBuf>());
if let Ok(f) = File::from(child.clone()).await {
emit!(Files(FilesOp::Creating(cwd, f.into_map())));
emit!(Hover(child));
emit!(Refresh);
}
Ok::<(), anyhow::Error>(())
});
false
}
}
19 changes: 19 additions & 0 deletions core/src/manager/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
mod close;
mod create;
mod open;
mod peek;
mod quit;
mod refresh;
mod rename;
mod suspend;
mod yank;

pub use close::*;
pub use create::*;
pub use open::*;
pub use peek::*;
pub use quit::*;
pub use refresh::*;
pub use rename::*;
pub use suspend::*;
pub use yank::*;
Loading

0 comments on commit e12ebd3

Please sign in to comment.