Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

12.2 KB
Raw Blame
//! Several items renamed in place at once (issue 435, setting "F2 renames several items in place", off by default: then F2 on several
//! items opens the bulk rename window as before).
//!
//! F2 on a selection of several items opens the usual rename box on one of them (the item under the cursor, the LEADING one); the
//! other selected rows show the names they are getting, live. Every edit in the box (a character typed or deleted, a paste, a
//! selection replaced) is made in the other names too, from their start or from their end (`rf_core::rename::apply_edit` says how it
//! chooses), so Home, Delete takes the first character off all of them and typing at the end adds to all of them. A right click in
//! the box inserts, at the cursor, a number (each item its place in the view, from the top), today's date, or the item's own date of
//! creation or change. Enter (or a click elsewhere) applies the names with the bulk rename's swap-safe plan, each one undoable; Escape
//! leaves them as they were.
//!
//! The pure part (the edit, the tokens) is `rf_core::rename`; this file holds the state of one such rename and its wiring.

use gpui_kit::component::input::{InputEvent, InputState};
use gpui_kit::*;
use rf_core::rename::{self, RenameError};

use crate::folder_view::FolderView;
use crate::t;

/// One item of the rename.
pub struct Item {
    pub ei: u32,
    /// Its name when the rename began (rows find their item by it).
    pub old: String,
    /// What its box holds: the name, or the name without its extension when the list hides extensions.
    pub text: String,
    /// The extension the list hides for it (with its dot), put back when the name is applied.
    pub hidden_ext: Option<String>,
}

/// The rename under way.
pub struct Multi {
    /// The item whose box the user types in.
    pub lead: u32,
    /// Every item, the leading one too, in the view's order (the numbers count in it).
    pub items: Vec<Item>,
    /// The leading box's text after the last edit that was passed on.
    before: String,
    /// A token was inserted: the names are filled in item by item (`rename::fill_tokens`).
    tokens: bool,
}

impl Multi {
    /// [`Multi::shown`] for the item that had the name `old`.
    pub fn shown_named(&self, old: &str, modified_ms: i64, created_ms: i64) -> Option<String> {
        let ei = self.items.iter().find(|i| i.old == old)?.ei;
        self.shown(ei, modified_ms, created_ms)
    }

    /// The name `ei` would get now, as its row shows it (tokens filled in), when it is one of the items.
    pub fn shown(&self, ei: u32, modified_ms: i64, created_ms: i64) -> Option<String> {
        let k = self.items.iter().position(|i| i.ei == ei)?;
        let text = &self.items[k].text;
        Some(if self.tokens { rename::fill_tokens(text, k as i64 + 1, modified_ms, created_ms) } else { text.clone() })
    }
}

/// What the box's right-click menu can insert.
#[derive(Clone, Copy)]
enum Token {
    Number,
    Today,
    Created,
    Modified,
}

impl FolderView {
    /// F2 on several items with the setting on: the names are edited in place. False when that cannot be (items of different folders,
    /// inside an archive, a read-only place): the caller opens the bulk rename window instead.
    pub(crate) fn begin_multi_rename(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
        if self.shell_read_only(cx) {
            return false;
        }
        let order: Vec<u32> = self.visible.iter().copied().filter(|ei| self.selected.contains(ei)).collect();
        if order.len() < 2 {
            return false;
        }
        let Some(dir) = self.parent_of(order[0]).map(|d| d.to_path_buf()) else { return false };
        if order.iter().any(|&ei| self.parent_of(ei) != Some(dir.as_path())) || crate::archive_view::split_inside(&dir.join(&*self.entry(order[0]).name)).is_some() {
            return false;
        }
        let lead = self.cursor_entry().filter(|ei| order.contains(ei)).unwrap_or(order[0]);
        let items: Vec<Item> = order
            .iter()
            .map(|&ei| {
                let hidden_ext = self.hidden_extension(ei, cx);
                let name = self.entry(ei).name.to_string();
                let text = match &hidden_ext {
                    Some(ext) => name[..name.len() - ext.len()].to_string(),
                    None => name,
                };
                Item { ei, old: self.entry(ei).name.to_string(), text, hidden_ext }
            })
            .collect();
        let lead_text = items.iter().find(|i| i.ei == lead).map(|i| i.text.clone()).unwrap_or_default();
        // the cursor at the end of the name (before a shown extension): a selection replaced would replace different parts of names of
        // different lengths
        let e = self.entry(lead);
        let at = if e.is_dir() || self.hidden_extension(lead, cx).is_some() { lead_text.len() } else { e.stem_len().min(lead_text.len()) };
        let input = cx.new(|cx| InputState::new(window, cx).default_value(lead_text.clone()));
        let sub = cx.subscribe_in(&input, window, |this, _, ev: &InputEvent, window, cx| match ev {
            InputEvent::Change => this.multi_sync(cx),
            InputEvent::PressEnter { .. } => this.commit_multi_rename(window, cx),
            // (the box's own menu takes the focus while it is open: that is no leaving)
            InputEvent::Blur if !crate::fluent_menu::is_open(cx) => this.commit_multi_rename(window, cx),
            _ => {}
        });
        input.update(cx, |s, cx| {
            s.set_context_menu_enabled(false);
            s.focus(window, cx);
            s.set_selected_range(at..at, cx);
        });
        self.set_renaming(Some((lead, input)), Some(sub));
        self.multi = Some(Multi { lead, items, before: lead_text, tokens: false });
        cx.notify();
        true
    }

    /// The leading box changed: the same edit is made in the other names.
    fn multi_sync(&mut self, cx: &mut Context<Self>) {
        let Some(now) = self.renaming.as_ref().map(|(_, i)| i.read(cx).value().to_string()) else { return };
        let Some(m) = self.multi.as_mut() else { return };
        if now == m.before {
            return;
        }
        let edit = rename::edit_between(&m.before, &now);
        for it in &mut m.items {
            it.text = if it.ei == m.lead { now.clone() } else { rename::apply_edit(&it.text, &edit) };
        }
        m.before = now;
        cx.notify();
    }

    /// A right click in the leading box: what can be inserted at the cursor.
    pub(crate) fn multi_rename_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        use crate::fluent_menu::{Item as MenuItem, Menu, MenuIcon};
        use gpui_kit::assets::IconName as L;
        let me = cx.entity().downgrade();
        let row = |label: &'static str, icon: L, token: Token| {
            let me = me.clone();
            MenuItem::action(crate::i18n::t(label), MenuIcon::Lucide(icon), move |window, cx| {
                let _ = me.update(cx, |v, cx| v.multi_insert(token, window, cx));
            })
        };
        let items = vec![
            row("Sıra numarası ekle", L::Hash, Token::Number),
            row("Bugünün tarihini ekle", L::Calendar, Token::Today),
            row("Oluşturma tarihini ekle", L::CalendarPlus, Token::Created),
            row("Değiştirme tarihini ekle", L::CalendarClock, Token::Modified),
        ];
        crate::fluent_menu::show(Menu { quick: Vec::new(), items }, window.mouse_position(), window, cx);
    }

    fn multi_insert(&mut self, token: Token, window: &mut Window, cx: &mut Context<Self>) {
        let Some(count) = self.multi.as_ref().map(|m| m.items.len()) else { return };
        let Some(input) = self.renaming.as_ref().map(|(_, i)| i.clone()) else { return };
        let text = match token {
            // as wide as the last number (01..12, 001..120), at least two digits
            Token::Number => format!("{{n:0{}}}", count.to_string().len().max(2)),
            Token::Today => "{today}".to_string(),
            Token::Created => "{created}".to_string(),
            Token::Modified => "{date}".to_string(),
        };
        input.update(cx, |s, cx| {
            s.focus(window, cx);
            s.insert(text, window, cx);
        });
        if let Some(m) = self.multi.as_mut() {
            m.tokens = true;
        }
        // (the insert is a quiet one: no Change comes for it)
        self.multi_sync(cx);
    }

    /// Enter, or a press outside the box: the names are applied.
    pub(crate) fn commit_multi_rename(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.multi_sync(cx);
        let Some(m) = self.multi.take() else { return };
        self.set_renaming(None, None);
        window.focus(&self.focus, cx);
        let Some(dir) = self.parent_of(m.lead).map(|d| d.to_path_buf()) else { return };
        let fix = cx.global::<crate::settings::Settings>().fix_name_characters;
        let mut pairs: Vec<(String, String)> = Vec::new();
        let mut problems: Vec<String> = Vec::new();
        for it in &m.items {
            let e = self.entry(it.ei);
            let old = e.name.to_string();
            let shown = m.shown(it.ei, e.modified_ms, e.created_ms).unwrap_or_default();
            let mut text = shown.trim().to_string();
            if fix {
                text = rename::tidy_name(&text);
            }
            let new = match &it.hidden_ext {
                Some(ext) if !text.is_empty() => format!("{text}{ext}"),
                _ => text,
            };
            if let Err(err) = rename::validate(&new) {
                problems.push(format!("{old} → {new}: {}", crate::i18n::td(&err.to_string())));
            }
            pairs.push((old, new));
        }
        // the new names among themselves, and against the folder's other items
        let lower = |s: &str| s.to_lowercase();
        let olds: std::collections::HashSet<String> = pairs.iter().map(|(o, _)| lower(o)).collect();
        let mut seen = std::collections::HashSet::new();
        for (old, new) in &pairs {
            if new.is_empty() {
                continue;
            }
            if !seen.insert(lower(new)) {
                problems.push(format!("{old} → {new}: {}", crate::i18n::td(&RenameError::Duplicate.to_string())));
            } else if !olds.contains(&lower(new)) && dir.join(new).exists() {
                problems.push(format!("{old} → {new}: {}", crate::i18n::td(&RenameError::Exists.to_string())));
            }
        }
        pairs.retain(|(o, n)| o != n);
        if !problems.is_empty() {
            problems.dedup();
            let more = problems.len().saturating_sub(8);
            let mut msg = problems.into_iter().take(8).collect::<Vec<_>>().join("\n");
            if more > 0 {
                msg.push_str(&format!("\n… +{more}"));
            }
            msg.push_str("\n\n");
            msg.push_str(t!("Hiçbir öğe yeniden adlandırılmadı."));
            crate::prompt::notice(t!("Yeniden adlandır").to_string(), msg, window, cx);
            cx.notify();
            return;
        }
        if pairs.is_empty() {
            cx.notify();
            return;
        }
        let names: Vec<String> = pairs.iter().map(|(_, n)| n.clone()).collect();
        self.select_when_listed(names, cx);
        let work = cx.background_spawn(async move { crate::bulk_rename::run_plan(&dir, &pairs) });
        cx.spawn_in(window, async move |_, cx| {
            let errors = work.await;
            if !errors.is_empty() {
                let _ = cx.update(|window, cx| {
                    crate::prompt::notice(t!("Yeniden adlandır").to_string(), errors.join("\n"), window, cx);
                });
            }
        })
        .detach();
        cx.notify();
    }

    /// The name a row shows: while several items are renamed in place, the name an item is getting; else as [`row_name`] says.
    pub(crate) fn row_label(&self, e: &rf_core::Entry, show_ext: bool, renamed: Option<&(std::sync::Arc<str>, std::sync::Arc<str>)>) -> String {
        self.multi
            .as_ref()
            .and_then(|m| m.shown_named(&e.name, e.modified_ms, e.created_ms))
            .unwrap_or_else(|| crate::folder_view::row_name(e, show_ext, renamed))
    }

    /// Escape: the names stay as they were.
    pub(crate) fn cancel_multi_rename(&mut self) {
        self.multi = None;
    }
}