use gpui::{Animation, AnimationExt, Keystroke};
use super::*;
pub(super) const TRASH_WARNING: &str = "Emptying the trash cannot be undone. Items kuizer moved there earlier can no longer be restored.";
pub(super) const SYSTEM_NOTE: &str = "Each cache is cleaned by its package tool with the command below. A system dialog asks for your password when the tool needs administrator rights. Nothing goes to the trash.";
pub(super) const EXPLORER_NOTE: &str =
"It is moved to the trash, never deleted for good, so History can put it back.";
const COUNT_DIGITS: usize = 7;
#[derive(Debug, Clone)]
pub(super) struct Explored {
pub(super) candidate: Candidate,
pub(super) root: PathBuf,
}
impl PartialEq for Explored {
fn eq(&self, other: &Self) -> bool {
self.candidate.path == other.candidate.path
&& self.candidate.identity == other.candidate.identity
&& self.root == other.root
}
}
impl Eq for Explored {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Ask {
pub(super) keys: Vec<(Source, u64)>,
pub(super) explored: Option<Explored>,
pub(super) commands: Vec<String>,
pub(super) bytes: u64,
pub(super) generation: u64,
pub(super) typed: String,
pub(super) cancel: bool,
}
impl Ask {
pub(super) fn has(&self, source: Source) -> bool {
self.keys.iter().any(|(kind, _)| *kind == source)
}
fn count(&self) -> usize {
self.keys.len() + usize::from(self.explored.is_some())
}
pub(super) fn counted(&self) -> bool {
self.has(Source::Big) || self.explored.is_some()
}
pub(super) fn ready(&self) -> bool {
!self.counted() || self.typed == self.count().to_string()
}
}
pub(super) struct Leaving {
ask: Ask,
at: Instant,
}
pub(super) fn asks(source: Source) -> bool {
matches!(source, Source::Trash | Source::Big | Source::System)
}
impl Kuizer {
pub(super) fn ask_remove(&mut self, keys: &[(Source, u64)], cx: &mut Context<Self>) {
let mut seen = HashSet::new();
let mut resolved = Vec::new();
let mut bytes = 0u64;
for &key in keys {
if seen.insert(key)
&& let Some((_, candidate)) = self.item(key)
{
resolved.push(key);
bytes += candidate.usage.allocated;
}
}
if resolved.is_empty() {
return;
}
let commands = self.system_commands(&resolved);
self.open_ask(
Ask {
keys: resolved,
explored: None,
commands,
bytes,
generation: self.session.report_generation,
typed: String::new(),
cancel: true,
},
cx,
);
}
pub(super) fn ask_explored(&mut self, explored: Explored, cx: &mut Context<Self>) {
let bytes = explored.candidate.usage.allocated;
self.open_ask(
Ask {
keys: Vec::new(),
explored: Some(explored),
commands: Vec::new(),
bytes,
generation: self.session.report_generation,
typed: String::new(),
cancel: true,
},
cx,
);
}
fn open_ask(&mut self, ask: Ask, cx: &mut Context<Self>) {
self.overlays.menu = None;
self.list.filtering = false;
self.overlays.dialog = Some(Dialog::Remove(ask));
cx.notify();
}
pub(super) fn system_commands(&self, keys: &[(Source, u64)]) -> Vec<String> {
let Some(report) = self.report() else {
return Vec::new();
};
let tools = kuizer::system::Tools::for_user();
let session = kuizer::system::Session::graphical_only();
keys.iter()
.filter(|(source, _)| *source == Source::System)
.filter_map(|&key| {
let (position, _) = self.session.index.locate(report, key)?;
let (item, _) = report.system.get(position)?;
Some(
kuizer::system::preview_command(item, &self.config.system, &tools, &session)
.unwrap_or_else(|error| format!("{}: {error}", item.label)),
)
})
.collect()
}
pub(super) fn drop_remove(&mut self) {
if matches!(self.overlays.dialog, Some(Dialog::Remove(_))) {
self.overlays.dialog = None;
}
}
pub(super) fn close_remove(&mut self, cx: &mut Context<Self>) {
if !matches!(self.overlays.dialog, Some(Dialog::Remove(_))) {
return;
}
if let Some(Dialog::Remove(ask)) = self.overlays.dialog.take() {
self.leave_remove(ask, cx);
}
cx.notify();
}
pub(super) fn accept_remove(&mut self, cx: &mut Context<Self>) {
let Some(Dialog::Remove(ask)) = &self.overlays.dialog else {
return;
};
if ask.generation != self.session.report_generation {
self.close_remove(cx);
return;
}
if !ask.ready() {
return;
}
let Some(Dialog::Remove(ask)) = self.overlays.dialog.take() else {
return;
};
let keys = ask.keys.clone();
let explored = ask.explored.clone();
self.leave_remove(ask, cx);
match explored {
Some(explored) => self.clean_explored(explored, cx),
None => self.clean_keys(&keys, cx),
}
cx.notify();
}
fn leave_remove(&mut self, ask: Ask, cx: &mut Context<Self>) {
if motion::reduced() {
return;
}
let at = Instant::now();
self.session.remove_leaving = Some(Leaving { ask, at });
cx.spawn(async move |this, cx| {
cx.background_executor().timer(motion::STEP).await;
let _ = this.update(cx, |app, cx| {
if app
.session
.remove_leaving
.as_ref()
.is_some_and(|leaving| leaving.at == at)
{
app.session.remove_leaving = None;
cx.notify();
}
});
})
.detach();
}
pub(super) fn remove_confirm_key(
&mut self,
keystroke: &Keystroke,
repeat: bool,
cx: &mut Context<Self>,
) {
let action = self
.keymap
.lookup(Scope::Dialog, commands::stroke(keystroke));
let Some(Dialog::Remove(ask)) = &mut self.overlays.dialog else {
return;
};
match action {
Some(Key::Back) => self.close_remove(cx),
Some(Key::Confirm) if !ask.counted() && ask.cancel => self.close_remove(cx),
Some(Key::Confirm) => {
if !repeat {
self.accept_remove(cx);
}
}
Some(Key::DialogToggle) if !ask.counted() => {
ask.cancel = !ask.cancel;
cx.notify();
}
_ if ask.counted() => {
let mut typed = ask.typed.clone();
if field::edit(&self.keymap, &mut typed, keystroke, field::WORDS, || None)
&& typed.len() <= COUNT_DIGITS
&& typed.chars().all(|ch| ch.is_ascii_digit())
{
ask.typed = typed;
cx.notify();
}
}
_ => {}
}
}
pub(super) fn render_remove_confirm(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let (ask, open) = match (&self.overlays.dialog, &self.session.remove_leaving) {
(Some(Dialog::Remove(ask)), _) => (ask, true),
(_, Some(leaving)) => (&leaving.ask, false),
_ => return None,
};
let bar = self.remove_bar(ask, open, cx);
if motion::reduced() {
return Some(bar.into_any_element());
}
Some(
bar.with_animation(
if open {
"remove-confirm-in"
} else {
"remove-confirm-out"
},
Animation::new(motion::STEP).with_easing(motion::ease_out),
move |bar, progress| {
let shown = if open { progress } else { 1.0 - progress };
bar.opacity(shown)
.relative()
.top(unit(space::M * (1.0 - shown)))
},
)
.into_any_element(),
)
}
fn remove_bar(&self, ask: &Ask, open: bool, cx: &mut Context<Self>) -> Stateful<Div> {
let ring = || ring::outline(None, Rc::new(Cell::new(false)));
let count = ask.count();
let (trash, big) = (ask.has(Source::Trash), ask.has(Source::Big));
let system = ask.has(Source::System);
let only = ask.keys.iter().all(|(source, _)| *source == Source::Trash)
|| ask.keys.iter().all(|(source, _)| *source == Source::Big)
|| ask.keys.iter().all(|(source, _)| *source == Source::System);
let size = theme::bytes(ask.bytes);
let explored = ask.explored.as_ref().map(|explored| {
explored.candidate.path.file_name().map_or_else(
|| display_path(&explored.candidate.path),
|name| name.to_string_lossy().into_owned(),
)
});
let title = match (&explored, trash, big, system) {
(Some(name), ..) => format!("Move {name} to the trash, {size}?"),
(None, true, false, false) if only => format!("Empty the trash, {size}?"),
(None, false, true, false) if only => {
format!("Move {} to the trash, {size}?", plural(count, "large file"))
}
(None, false, false, true) if only => {
format!("Clean {}, {size}?", plural(count, "system cache"))
}
_ => format!("Remove {}, {size}?", plural(count, "item")),
};
let action = match (explored.is_some(), trash, big, system) {
(true, ..) => "Move to trash",
(false, true, false, false) if only => "Empty the trash",
(false, false, true, false) if only => "Move to trash",
(false, false, false, true) if only => "Clean",
_ => "Remove",
};
let all_trashed = ask.explored.is_some()
|| ask
.keys
.iter()
.all(|(source, _)| source.trashed(self.config.delete.mode));
let counted = ask.counted();
let ready = ask.ready();
let focus_cancel = open && !counted && ask.cancel;
let focus_action = open && !counted && !ask.cancel;
clean::floating(div().id("remove-confirm"))
.debug_selector(|| "remove-confirm".to_owned())
.flex()
.flex_col()
.gap(unit(space::M))
.w(unit(size::SUMMARY))
.max_w_full()
.p(unit(space::L))
.child(div().font_weight(FontWeight::SEMIBOLD).child(title))
.when(trash, |this| {
this.child(
div()
.debug_selector(|| "trash-warning".to_owned())
.text_size(unit(font::SMALL))
.text_color(theme::danger())
.child(TRASH_WARNING),
)
})
.when(system, |this| {
this.child(
div()
.debug_selector(|| "system-note".to_owned())
.text_size(unit(font::SMALL))
.text_color(theme::muted())
.child(SYSTEM_NOTE),
)
.child(
theme::mono(div())
.debug_selector(|| "system-commands".to_owned())
.flex()
.flex_col()
.gap(unit(space::XXS))
.p(unit(space::S))
.rounded(theme::radius_control())
.bg(theme::panel())
.border_1()
.border_color(theme::border())
.text_size(unit(font::SMALL))
.children(
ask.commands
.iter()
.map(|command| div().truncate().child(command.clone())),
),
)
})
.when(ask.explored.is_some(), |this| {
this.child(
div()
.debug_selector(|| "explorer-note".to_owned())
.text_size(unit(font::SMALL))
.text_color(theme::muted())
.child(EXPLORER_NOTE),
)
})
.when(big, |this| {
this.child(
div()
.debug_selector(|| "large-files-note".to_owned())
.text_size(unit(font::SMALL))
.text_color(theme::muted())
.child(
"Large files are personal files. They are moved to the trash, never deleted for good, so History can put them back.",
),
)
})
.when(counted, |this| {
this.child(
div()
.flex()
.items_center()
.gap(unit(space::M))
.text_size(unit(font::SMALL))
.text_color(theme::muted())
.child(format!("Type {count} to confirm"))
.child(
field::view("remove-count", &ask.typed, count.to_string(), open)
.debug_selector(|| "remove-count".to_owned())
.w(unit(col::S))
.text_color(theme::text()),
)
.when(!ask.typed.is_empty() && !ready, |this| {
this.child(
div()
.debug_selector(|| "remove-count-wrong".to_owned())
.text_color(theme::danger())
.child(format!("The count is {count}")),
)
}),
)
})
.child(
div()
.flex()
.justify_end()
.gap(unit(space::M))
.child(
ui::button("remove-cancel", "Cancel", ButtonKind::Secondary, open)
.debug_selector(|| "cancel-remove".to_owned())
.tip(
Tooltip::new("Keep everything")
.keys(&[&self.key_hint(Scope::Dialog, Key::Back)])
.build(),
)
.when(focus_cancel, |this| this.child(ring()))
.when(open, |this| {
this.on_click(cx.listener(|app, _: &ClickEvent, _, cx| {
app.close_remove(cx);
}))
}),
)
.child(
ui::button(
"remove-accept",
action,
if all_trashed {
ButtonKind::Primary
} else {
ButtonKind::Danger
},
open && ready,
)
.debug_selector(|| "confirm-remove".to_owned())
.tip(
Tooltip::new(if counted && !ready {
"Type the item count first"
} else {
"Start the removal"
})
.keys(&[&self.key_hint(Scope::Dialog, Key::Confirm)])
.build(),
)
.when(focus_action, |this| this.child(ring()))
.when(open && ready, |this| {
this.on_click(cx.listener(|app, _: &ClickEvent, _, cx| {
app.accept_remove(cx);
}))
}),
),
)
}
}