Skip to content

Visual Studio Code, rebuilt in Rust

Rust
41.7 KB
Raw Blame
//! workbench/services/dialogs: simpleFileDialog.ts, the quick pick file dialog that `files.simpleDialog.enable` shows
//! in place of the native panel. Paths are POSIX strings, as the `file` URIs upstream holds; a folder keeps its
//! trailing slash. The file system is read synchronously, so no update is ever pending (`updatingPromise`).

use std::path::PathBuf;

use futures::channel::oneshot;
use gpui::{Context, Window};

use super::Workbench;
use crate::file_dialog::FileDialog;
use crate::main_thread_quick_open::Owner;
use crate::quick_input::{Button, Entry, Event, Item, ItemActivation, Kind, QuickInput};

const SHOW_DOT_FILES_KEY: &str = "remoteFileDialog.showDotFiles";
const DOT_FILES_BUTTON: i64 = 0;

#[derive(Clone, Copy, PartialEq, Debug)]
enum UpdateResult {
    Updated,
    UpdatedWithTrailing,
    NotUpdated,
    InvalidPath,
}

/// A `FileQuickPickItem`; its handle is its index.
#[derive(Clone)]
struct FileItem {
    label: String,
    path: String,
    is_folder: bool,
    pickable: bool,
}

enum Validation {
    Valid,
    Invalid,
    /// `yesNoPrompt`; `create` makes the folder before the dialog resolves (the folder-only open dialog).
    Prompt { message: String, create: bool },
}

enum Accepted {
    Resolve(Vec<String>),
    Stay,
    Prompt { message: String, path: String, create: bool },
}

pub struct SimpleFileDialog {
    allow_files: bool,
    allow_folders: bool,
    filters: Vec<(String, Vec<String>)>,
    requires_trailing: bool,
    true_home: String,
    current_folder: String,
    trailing: Option<String>,
    user_entered_path_segment: String,
    auto_complete_path_segment: String,
    active_item: Option<i64>,
    bad_path: Option<String>,
    show_dot_files: bool,
    screen_reader: bool,
    busy: bool,
    items: Vec<FileItem>,
    hidden: bool,
    is_resolving: u32,
    is_accept_handled: bool,
    reply: Option<oneshot::Sender<Vec<PathBuf>>>,
}

/// The `yesNoPrompt` over the dialog `dialog`, for `path`.
pub struct SimpleFileDialogPrompt {
    dialog: i64,
    path: String,
    create: bool,
    is_resolving: bool,
}

impl Workbench {
    /// fileDialogService.ts `shouldUseSimplified`: only `file` paths reach the dialogs, so the setting decides.
    pub(super) fn uses_simple_file_dialog(&self) -> bool {
        self.setting("files.simpleDialog.enable") == true
    }

    /// `showOpenDialog` (`save` false) and `showSaveDialog` of the simple dialog: the picked paths, none when hidden.
    /// The dialog shows once the current update ends, in the main window.
    pub(super) fn simple_file_dialog(&mut self, dialog: FileDialog, save: bool, cx: &mut Context<Self>) -> oneshot::Receiver<Vec<PathBuf>> {
        let (sender, receiver) = oneshot::channel();
        let Some(window) = self.auxiliary_windows.main_window else { return receiver };
        cx.spawn(async move |workbench, cx| {
            let _ = window.update(cx, |_, window, cx| workbench.update(cx, |workbench, cx| workbench.show_simple_file_dialog(dialog, save, sender, window, cx)));
        })
        .detach();
        receiver
    }

    /// `getOptions` and `pickResource`.
    fn show_simple_file_dialog(&mut self, dialog: FileDialog, save: bool, reply: oneshot::Sender<Vec<PathBuf>>, window: &mut Window, cx: &mut Context<Self>) {
        let user_home = self.preferred_home().to_string_lossy().into_owned();
        let true_home = std::env::var("HOME").unwrap_or_else(|_| user_home.clone());
        let default = dialog.default_path.as_ref().map_or(user_home, |path| path.to_string_lossy().into_owned());
        let mut home_dir = default.clone();
        let ext = extname(&home_dir);
        let mut trailing = None;
        if !std::fs::metadata(&default).is_ok_and(|stat| stat.is_dir()) {
            home_dir = dirname(&default);
            trailing = Some(basename(&default));
        }
        let show_dot_files = self.workspace_storage.lock().unwrap().get(SHOW_DOT_FILES_KEY).is_none_or(|value| value == "true");
        let select_initial = match self.setting("files.simpleDialog.selectInitialPath").as_str() {
            Some("on") => true,
            Some("off") => false,
            _ => self.is_screen_reader_optimized(),
        };
        let state = SimpleFileDialog {
            allow_files: save || dialog.files,
            allow_folders: save || dialog.folders,
            filters: dialog.filters,
            requires_trailing: save,
            true_home,
            current_folder: dirname(&home_dir),
            trailing,
            user_entered_path_segment: String::new(),
            auto_complete_path_segment: String::new(),
            active_item: None,
            bad_path: None,
            show_dot_files,
            screen_reader: self.is_screen_reader_optimized(),
            busy: true,
            items: Vec::new(),
            hidden: false,
            is_resolving: 0,
            is_accept_handled: false,
            reply: Some(reply),
        };
        let mut pick = QuickInput::new(0, Kind::QuickPick);
        pick.can_select_many = !save && dialog.multiple;
        pick.match_on_label = false;
        pick.sort_by_label = false;
        pick.ignore_focus_out = true;
        pick.placeholder = Some(match pick.can_select_many {
            true => "Folder path (use Space to select items)".into(),
            false => "Folder path".into(),
        });
        pick.ok = true;
        pick.ok_label = dialog.button_label;
        pick.buttons = vec![state.dot_files_button()];
        pick.title = dialog.title;
        pick.set_value(path_from(&state.current_folder, true));
        let end = pick.input_box.len();
        pick.set_value_selection(Some((end, end)));
        pick.events.clear();
        let id = self.quick_inputs.add(pick, Owner::SimpleFileDialog(Box::new(state)));
        self.show_quick_input(id, window, cx);
        if let Some((pick, Owner::SimpleFileDialog(state))) = self.quick_inputs.get_with_owner_mut(id) {
            let trailing = state.trailing.clone();
            state.update_items(pick, &home_dir, true, trailing.as_deref());
            let len = pick.input_box.len();
            let selection = match (&state.trailing, !save && select_initial) {
                (_, true) => (0, len),
                (Some(trailing), false) => (len.saturating_sub(char_len(trailing)), len.saturating_sub(char_len(&ext))),
                (None, false) => (len, len),
            };
            pick.set_value_selection(Some(selection));
            state.busy = false;
        }
        self.flush_quick_input_events(window, cx);
    }

    pub(crate) fn simple_file_dialog_event(&mut self, id: i64, event: Event, window: &mut Window, cx: &mut Context<Self>) {
        let Some((pick, Owner::SimpleFileDialog(state))) = self.quick_inputs.get_with_owner_mut(id) else { return };
        match event {
            Event::ChangeValue(value) => state.handle_value_change(pick, &value),
            Event::ChangeActive(active) => state.change_active(pick, &active),
            Event::TriggerButton(DOT_FILES_BUTTON, _) => {
                let show = state.toggle_dot_files(pick);
                self.workspace_storage.lock().unwrap().set(SHOW_DOT_FILES_KEY, show.to_string());
            }
            Event::Accept(_) => self.handle_simple_file_dialog_accept(id, window, cx),
            Event::Hide => {
                state.hidden = true;
                if state.is_resolving == 0 {
                    self.resolve_simple_file_dialog(id, Vec::new(), window, cx);
                }
            }
            _ => {}
        }
        cx.notify();
    }

    /// `handleAccept`: no accept runs while one is handled.
    fn handle_simple_file_dialog_accept(&mut self, id: i64, window: &mut Window, cx: &mut Context<Self>) {
        let Some((pick, Owner::SimpleFileDialog(state))) = self.quick_inputs.get_with_owner_mut(id) else { return };
        if state.is_accept_handled {
            return;
        }
        state.is_accept_handled = true;
        state.is_resolving += 1;
        match state.on_did_accept(pick) {
            Accepted::Resolve(paths) => self.resolve_simple_file_dialog(id, paths, window, cx),
            Accepted::Stay if state.hidden => self.resolve_simple_file_dialog(id, Vec::new(), window, cx),
            Accepted::Stay => {
                state.is_resolving -= 1;
                state.is_accept_handled = false;
            }
            Accepted::Prompt { message, path, create } => self.show_simple_file_dialog_prompt(id, message, path, create, window, cx),
        }
    }

    /// `doResolve`: the dialog answers with the normalized paths and goes away.
    fn resolve_simple_file_dialog(&mut self, id: i64, paths: Vec<String>, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(Owner::SimpleFileDialog(state)) = self.quick_inputs.owner_mut(id)
            && let Some(reply) = state.reply.take()
        {
            let _ = reply.send(paths.iter().map(|path| PathBuf::from(remove_trailing_separator(&add_trailing_separator(path)))).collect());
        }
        self.hide_quick_input_by_id(id, window, cx);
        self.quick_inputs.remove(id);
    }

    /// `yesNoPrompt`: OK goes on, Cancel, Escape or typing goes back to the dialog.
    fn show_simple_file_dialog_prompt(&mut self, dialog: i64, message: String, path: String, create: bool, window: &mut Window, cx: &mut Context<Self>) {
        let mut prompt = QuickInput::new(0, Kind::QuickPick);
        prompt.title = Some(message);
        prompt.ignore_focus_out = true;
        prompt.ok = true;
        prompt.custom_label = Some("Cancel".into());
        prompt.custom_secondary = true;
        prompt.set_value(path_from(&path, false));
        prompt.events.clear();
        let id = self.quick_inputs.add(prompt, Owner::SimpleFileDialogPrompt(SimpleFileDialogPrompt { dialog, path, create, is_resolving: false }));
        self.show_quick_input(id, window, cx);
        self.flush_quick_input_events(window, cx);
    }

    pub(crate) fn simple_file_dialog_prompt_event(&mut self, id: i64, event: Event, window: &mut Window, cx: &mut Context<Self>) {
        let Some(Owner::SimpleFileDialogPrompt(prompt)) = self.quick_inputs.owner_mut(id) else { return };
        match event {
            Event::Accept(_) => {
                prompt.is_resolving = true;
                let (dialog, path, create) = (prompt.dialog, prompt.path.clone(), prompt.create);
                self.hide_quick_input_by_id(id, window, cx);
                self.quick_inputs.remove(id);
                if !create {
                    return self.resolve_simple_file_dialog(dialog, vec![path], window, cx);
                }
                match std::fs::create_dir_all(&path) {
                    Ok(()) => self.resolve_simple_file_dialog(dialog, vec![path], window, cx),
                    Err(error) => {
                        if let Some(pick) = self.quick_inputs.get_mut(dialog) {
                            pick.validation_message = Some(format!("Could not create folder: {error}"));
                        }
                        self.show_simple_file_dialog_again(dialog, window, cx);
                    }
                }
            }
            Event::Hide => {
                let (dialog, resolving) = (prompt.dialog, prompt.is_resolving);
                self.quick_inputs.remove(id);
                if !resolving {
                    self.show_simple_file_dialog_again(dialog, window, cx);
                }
            }
            Event::ChangeValue(_) | Event::Custom => self.hide_quick_input_by_id(id, window, cx),
            _ => {}
        }
        cx.notify();
    }

    /// The prompt answered no: the file pick shows again with its items, and the accept is over.
    fn show_simple_file_dialog_again(&mut self, dialog: i64, window: &mut Window, cx: &mut Context<Self>) {
        let Some(Owner::SimpleFileDialog(state)) = self.quick_inputs.owner_mut(dialog) else { return };
        state.hidden = false;
        state.is_resolving -= 1;
        state.is_accept_handled = false;
        self.show_quick_input(dialog, window, cx);
        // Showing another input emptied the shared list: the items are set again.
        if let Some(pick) = self.quick_inputs.get_mut(dialog) {
            let items = pick.items().to_vec();
            pick.set_items(items);
        }
        self.flush_quick_input_events(window, cx);
    }
}

impl SimpleFileDialog {
    fn dot_files_button(&self) -> Button {
        let (codicon, tooltip) = match self.show_dot_files {
            true => ("eye", "Hide dot files"),
            false => ("eye-closed", "Show dot files"),
        };
        Button { handle: DOT_FILES_BUTTON, codicon: Some(codicon.into()), tooltip: Some(tooltip.into()), always_visible: true, ..Button::default() }
    }

    /// The `remoteFileDialog.showDotFiles` storage listener: the folder lists again with the value kept.
    fn toggle_dot_files(&mut self, pick: &mut QuickInput) -> bool {
        self.show_dot_files = !self.show_dot_files;
        pick.buttons = vec![self.dot_files_button()];
        let starting_value = pick.input_box.value.clone();
        let folder_value = path_from(&self.current_folder, true);
        set_value_quietly(pick, folder_value.clone());
        let current_folder = self.current_folder.clone();
        self.try_update_items(pick, &folder_value, &current_folder, true);
        set_value_quietly(pick, starting_value);
        self.show_dot_files
    }

    fn handle_value_change(&mut self, pick: &mut QuickInput, value: &str) {
        if !self.is_value_change_from_user(pick) {
            return;
        }
        if !equals_ignore_case(value, &self.construct_full_user_path(pick)) && (!self.is_bad_subpath(value) || self.can_tilda_escape_hatch(value)) {
            pick.validation_message = None;
            let file_pick_box_uri = self.file_pick_box_value(pick);
            let mut updated = UpdateResult::NotUpdated;
            if !ends_with_slash(value) && equals_ignore_case(&self.current_folder, &dirname(&file_pick_box_uri)) {
                self.set_active_items(pick, value);
                return;
            } else if !equals_ignore_case(&self.current_folder, &file_pick_box_uri) {
                updated = self.try_update_items(pick, value, &file_pick_box_uri, false);
            }
            if matches!(updated, UpdateResult::NotUpdated | UpdateResult::UpdatedWithTrailing) {
                self.set_active_items(pick, value);
            }
        } else {
            pick.set_active_items(&[]);
            self.user_entered_path_segment.clear();
        }
    }

    /// `onDidChangeActive`: an item the user moved to fills the input box.
    fn change_active(&mut self, pick: &mut QuickInput, active: &[i64]) {
        self.is_accept_handled = false;
        let [item] = active else { return };
        if self.active_item == pick.active_handles().first().copied() {
            return;
        }
        pick.validation_message = None;
        let user_path = self.construct_full_user_path(pick);
        if !equals_ignore_case(&prefix(&pick.input_box.value, char_len(&user_path)), &user_path) {
            pick.set_value_selection(Some((0, pick.input_box.len())));
            self.insert_text(pick, &user_path, &user_path);
        }
        let user_entered = self.user_entered_path_segment.clone();
        self.set_auto_complete(pick, &user_entered, *item, true);
    }

    fn is_bad_subpath(&self, value: &str) -> bool {
        self.bad_path.as_ref().is_some_and(|bad| char_len(value) > char_len(bad) && equals_ignore_case(&prefix(value, char_len(bad)), bad))
    }

    fn is_value_change_from_user(&self, pick: &QuickInput) -> bool {
        let typed = format!("{}{}", self.user_entered_path_segment, self.auto_complete_path_segment);
        !equals_ignore_case(&pick.input_box.value, &path_append(&self.current_folder, &typed))
    }

    fn construct_full_user_path(&self, pick: &QuickInput) -> String {
        let value = &pick.input_box.value;
        let current_folder_path = path_from(&self.current_folder, false);
        if !equals_ignore_case(&prefix(value, char_len(&self.user_entered_path_segment)), &self.user_entered_path_segment) {
            return path_append(&self.current_folder, &self.user_entered_path_segment);
        }
        match equals_ignore_case(&prefix(value, char_len(&current_folder_path)), &current_folder_path) {
            true => current_folder_path,
            false => self.user_entered_path_segment.clone(),
        }
    }

    /// `filePickBoxValue`: the typed path, resolved against the current folder when it shares its root.
    fn file_pick_box_value(&self, pick: &QuickInput) -> String {
        let value = &pick.input_box.value;
        let direct = remote_uri_from(value.trim_end());
        let current_path = path_from(&self.current_folder, false);
        if equals_ignore_case(value, &current_path) {
            return self.current_folder.clone();
        }
        let relative = relative_path(&remote_uri_from(&current_path), &direct);
        let is_same_root = char_len(value) > 1 && char_len(&current_path) > 1 && equals_ignore_case(&prefix(value, 2), &prefix(&current_path, 2));
        if relative.is_empty() || !is_same_root {
            return direct;
        }
        let mut path = join_path(&self.current_folder, &relative);
        let direct_basename = basename(&direct);
        if direct_basename == "." || direct_basename == ".." {
            path = remote_uri_from(&path_append(&path, &direct_basename));
        }
        match has_trailing_separator(&direct) {
            true => add_trailing_separator(&path),
            false => path,
        }
    }

    fn on_did_accept(&mut self, pick: &mut QuickInput) -> Accepted {
        self.busy = true;
        let selected = pick.selected_handles();
        let active = pick.active_handles();
        if pick.can_select_many && !selected.is_empty() && selected.iter().all(|handle| self.items[*handle as usize].pickable) {
            let paths: Vec<String> = selected.iter().map(|handle| self.items[*handle as usize].path.clone()).collect();
            for path in &paths {
                // The listed items exist, so no prompt can come up here.
                if !matches!(self.validate(pick, Some(path)), Validation::Valid) {
                    self.busy = false;
                    return Accepted::Stay;
                }
            }
            self.busy = false;
            return Accepted::Resolve(paths);
        }
        if active.len() == 1 {
            let item = self.items[selected.first().copied().unwrap_or(active[0]) as usize].clone();
            if item.is_folder {
                match self.trailing.clone() {
                    Some(trailing) => _ = self.update_items(pick, &item.path, true, Some(&trailing)),
                    None => {
                        let new_path = path_from(&item.path, false);
                        let value = pick.input_box.value.clone();
                        if starts_with_ignore_case(&new_path, &value) && equals_ignore_case(&item.label, &basename(&item.path)) {
                            pick.set_value_selection(Some((char_len(&path_from(&self.current_folder, false)), char_len(&value))));
                            let insert = basename_with_trailing_slash(&item.path);
                            self.insert_text(pick, &new_path, &insert);
                        } else if item.label == ".." && starts_with_ignore_case(&value, &new_path) {
                            pick.set_value_selection(Some((char_len(&new_path), char_len(&value))));
                            self.insert_text(pick, &new_path, "");
                        } else {
                            self.update_items(pick, &item.path, true, None);
                        }
                    }
                }
                self.busy = false;
                return Accepted::Stay;
            }
        } else {
            let value = pick.input_box.value.clone();
            let uri = self.file_pick_box_value(pick);
            if self.try_update_items(pick, &value, &uri, false) != UpdateResult::NotUpdated {
                self.busy = false;
                return Accepted::Stay;
            }
        }
        let resolve_value = match active.len() {
            0 => Some(self.file_pick_box_value(pick)),
            1 => Some(self.items[selected.first().copied().unwrap_or(active[0]) as usize].path.clone()),
            _ => None,
        };
        let resolve_value = resolve_value.map(|value| self.add_postfix(&value));
        let validation = self.validate(pick, resolve_value.as_deref());
        self.busy = false;
        match (validation, resolve_value) {
            (Validation::Valid, Some(value)) => Accepted::Resolve(vec![value]),
            (Validation::Prompt { message, create }, Some(path)) => Accepted::Prompt { message, path, create },
            _ => Accepted::Stay,
        }
    }

    fn can_tilda_escape_hatch(&self, value: &str) -> bool {
        value.ends_with('~') && self.is_bad_subpath(value)
    }

    fn tilda_replace(&self, value: &str) -> String {
        if let Some(rest) = value.strip_prefix('~') {
            return join_path(&self.true_home, rest);
        }
        if self.can_tilda_escape_hatch(value) {
            return self.true_home.clone();
        }
        remote_uri_from(value)
    }

    fn try_update_items(&mut self, pick: &mut QuickInput, value: &str, value_uri: &str, reset: bool) -> UpdateResult {
        let updated = |file: bool| if file { UpdateResult::UpdatedWithTrailing } else { UpdateResult::Updated };
        if value.starts_with('~') || self.can_tilda_escape_hatch(value) {
            let new_dir = self.tilda_replace(value);
            return updated(self.update_items(pick, &new_dir, true, None));
        }
        if value == "\\" {
            let root = root(&self.current_folder);
            return updated(self.update_items(pick, &root, true, None));
        }
        let new_folder_is_old_folder = equals_ignore_case(&self.current_folder, value_uri);
        let new_folder_is_sub_folder = equals_ignore_case(&self.current_folder, &dirname(value_uri));
        let new_folder_is_parent = is_equal_or_parent_ignore_case(&self.current_folder, &dirname(value_uri));
        let new_folder_is_unrelated = !new_folder_is_parent && !new_folder_is_sub_folder;
        if (!new_folder_is_old_folder && (ends_with_slash(value) || new_folder_is_parent || new_folder_is_unrelated)) || reset {
            let is_directory = std::fs::metadata(value_uri).is_ok_and(|stat| stat.is_dir());
            if is_directory && basename(value_uri) != "." && ends_with_slash(value) {
                let folder = if ends_with_slash(value_uri) { value_uri.to_owned() } else { add_trailing_separator(value_uri) };
                return updated(self.update_items(pick, &folder, false, None));
            } else if ends_with_slash(value) {
                // A stat for every typed character is slow; more typing after a bad path is compared against it.
                pick.validation_message = Some("The path does not exist. Use ~ to go to your home directory.".into());
                self.bad_path = Some(value.to_owned());
                return UpdateResult::InvalidPath;
            }
            let input_uri_dirname = dirname(value_uri);
            let current_folder_without_sep = remove_trailing_separator(&add_trailing_separator(&self.current_folder));
            let input_uri_dirname_without_sep = remove_trailing_separator(&add_trailing_separator(&input_uri_dirname));
            let is_drive = value.len() == 2 && value.as_bytes()[0].is_ascii_alphabetic() && value.as_bytes()[1] == b':';
            if !equals_ignore_case(&current_folder_without_sep, &input_uri_dirname_without_sep)
                && (!is_drive || !equals_ignore_case(&prefix(&path_from(&self.current_folder, false), char_len(value)), value))
                && std::fs::metadata(&input_uri_dirname).is_ok_and(|stat| stat.is_dir())
            {
                self.bad_path = None;
                let folder = if ends_with_slash(&input_uri_dirname) { input_uri_dirname } else { add_trailing_separator(&input_uri_dirname) };
                return updated(self.update_items(pick, &folder, false, Some(&basename(value_uri))));
            }
        }
        self.bad_path = None;
        UpdateResult::NotUpdated
    }

    fn try_update_trailing(&mut self, value: &str) {
        if self.trailing.is_some() && !extname(value).is_empty() {
            self.trailing = Some(basename(value));
        }
    }

    fn set_active_items(&mut self, pick: &mut QuickInput, value: &str) {
        let value = path_from(&self.tilda_replace(value), false);
        let as_uri = remote_uri_from(&value);
        let input_basename = basename(&as_uri);
        let user_path = self.construct_full_user_path(pick);
        // The folder whose children show has to match the path in the input.
        let paths_equal = equals_ignore_case(&user_path, &prefix(&value, char_len(&user_path))) || equals_ignore_case(&value, &prefix(&user_path, char_len(&value)));
        if paths_equal {
            for handle in 0..self.items.len() as i64 {
                if self.set_auto_complete(pick, &input_basename, handle, false) {
                    return;
                }
            }
            let user_basename = match char_len(&input_basename) >= 2 {
                true => user_path.chars().skip((char_len(&user_path) + 2).saturating_sub(char_len(&input_basename))).collect(),
                false => String::new(),
            };
            self.user_entered_path_segment = if user_basename == input_basename { input_basename } else { String::new() };
        } else {
            self.user_entered_path_segment = input_basename;
        }
        self.auto_complete_path_segment.clear();
        pick.set_active_items(&[]);
        self.try_update_trailing(&as_uri);
    }

    fn set_auto_complete(&mut self, pick: &mut QuickInput, starting_basename: &str, handle: i64, force: bool) -> bool {
        if self.busy {
            // An autocomplete in the middle of an update can come out jumbled.
            self.user_entered_path_segment = starting_basename.to_owned();
            self.auto_complete_path_segment.clear();
            return false;
        }
        let item = self.items[handle as usize].clone();
        let item_basename = &item.label;
        if item_basename == ".." {
            // Never match the up directory item.
            self.user_entered_path_segment.clear();
            self.auto_complete_path_segment.clear();
            self.active_item = Some(handle);
            if force {
                self.exec_insert(pick, "");
            }
            return false;
        }
        if !force && char_len(item_basename) >= char_len(starting_basename) && equals_ignore_case(&prefix(item_basename, char_len(starting_basename)), starting_basename) {
            self.user_entered_path_segment = starting_basename.to_owned();
            self.active_item = Some(handle);
            self.auto_complete_path_segment.clear();
            match item.is_folder || self.trailing.is_none() {
                true => pick.set_active_items(&[handle]),
                false => pick.set_active_items(&[]),
            }
            return true;
        }
        let typed = format!("{}{}", self.user_entered_path_segment, self.auto_complete_path_segment);
        if force && !equals_ignore_case(&basename_with_trailing_slash(&item.path), &typed) {
            self.user_entered_path_segment.clear();
            if !self.screen_reader {
                self.auto_complete_path_segment = trim_trailing_slash(item_basename);
            }
            self.active_item = Some(handle);
            if !self.screen_reader {
                pick.set_value_selection(Some((char_len(&path_from(&self.current_folder, true)), pick.input_box.len())));
                let auto_complete = self.auto_complete_path_segment.clone();
                self.insert_text(pick, &path_append(&self.current_folder, &auto_complete), &auto_complete);
                let len = pick.input_box.len();
                pick.set_value_selection(Some((len.saturating_sub(char_len(&auto_complete)), len)));
            }
            return true;
        }
        self.user_entered_path_segment = starting_basename.to_owned();
        self.auto_complete_path_segment.clear();
        false
    }

    /// `execCommand('insertText')`: the text replaces the selection, and the change event runs right away.
    fn exec_insert(&mut self, pick: &mut QuickInput, text: &str) {
        let before = pick.events.len();
        pick.edit_input(|input| input.insert(None, text));
        if pick.events.len() > before
            && let Some(Event::ChangeValue(value)) = pick.events.pop()
        {
            self.handle_value_change(pick, &value);
        }
    }

    fn insert_text(&mut self, pick: &mut QuickInput, whole_value: &str, insert_text: &str) {
        self.exec_insert(pick, insert_text);
        if pick.input_box.value != whole_value {
            set_value_quietly(pick, whole_value.to_owned());
            self.handle_value_change(pick, whole_value);
        }
    }

    /// `addPostfix`: a saved name without one of the filters' extensions gets the first filter's.
    fn add_postfix(&self, uri: &str) -> String {
        // An extension can pass a filter with no extensions; upstream would append ".undefined".
        let Some(first_extension) = self.filters.first().and_then(|(_, extensions)| extensions.first()) else { return uri.to_owned() };
        if !self.requires_trailing || has_trailing_separator(uri) {
            return uri.to_owned();
        }
        let ext = extname(uri);
        let current_ext = ext.strip_prefix('.').unwrap_or(&ext);
        let has_ext = self.filters.iter().any(|(_, extensions)| extensions.iter().any(|extension| extension == "*" || extension == current_ext));
        match has_ext {
            true => uri.to_owned(),
            false => join_path(&dirname(uri), &format!("{}.{}", basename(uri), first_extension)),
        }
    }

    fn validate(&self, pick: &mut QuickInput, uri: Option<&str>) -> Validation {
        let Some(uri) = uri else {
            pick.validation_message = Some("Please enter a valid path.".into());
            return Validation::Invalid;
        };
        let stat_dirname = std::fs::metadata(dirname(uri)).ok();
        let stat = std::fs::metadata(uri).ok();
        let invalid = |pick: &mut QuickInput, message: &str| {
            pick.validation_message = Some(message.into());
            Validation::Invalid
        };
        if self.requires_trailing {
            return match (stat, stat_dirname) {
                (Some(stat), _) if stat.is_dir() => invalid(pick, "The folder already exists. Please use a new file name."),
                (Some(_), _) => Validation::Prompt { message: format!("{} already exists. Are you sure you want to overwrite it?", basename(uri)), create: false },
                _ if !crate::file_actions::is_valid_basename(&basename(uri)) => invalid(pick, "Please enter a valid file name."),
                (None, None) => Validation::Prompt { message: format!("The folder {} does not exist. Would you like to create it?", basename(&dirname(uri))), create: false },
                (None, Some(parent)) if !parent.is_dir() => invalid(pick, "Please enter a path that exists."),
                (None, Some(_)) => Validation::Valid,
            };
        }
        match stat {
            None if self.allow_folders && !self.allow_files && can_create_folder(uri) => {
                Validation::Prompt { message: format!("The folder {} does not exist. Would you like to create it?", basename(uri)), create: true }
            }
            None => invalid(pick, "Please enter a path that exists."),
            Some(stat) if stat.is_dir() && !self.allow_folders => invalid(pick, "Please select a file."),
            Some(stat) if !stat.is_dir() && !self.allow_files => invalid(pick, "Please select a folder."),
            Some(_) => Validation::Valid,
        }
    }

    /// Lists `new_folder` (a file lists its folder with its name typed); true when it was a file.
    fn update_items(&mut self, pick: &mut QuickInput, new_folder: &str, force: bool, trailing: Option<&str>) -> bool {
        self.busy = true;
        self.auto_complete_path_segment.clear();
        let was_dot_dot = trailing == Some("..");
        let mut trailing = trailing.filter(|_| !was_dot_dot).map(str::to_owned);
        let is_save = trailing.is_some();
        let mut new_folder = new_folder.to_owned();
        let mut result = false;
        if std::fs::metadata(&new_folder).is_ok_and(|stat| !stat.is_dir()) {
            trailing = Some(basename(&new_folder));
            new_folder = dirname(&new_folder);
            result = true;
        }
        let new_value = match &trailing {
            Some(trailing) => path_append(&new_folder, trailing),
            None => path_from(&new_folder, true),
        };
        let current_folder = if ends_with_slash(&new_folder) { new_folder } else { add_trailing_separator(&new_folder) };
        self.items = self.create_items(&current_folder);
        self.current_folder = current_folder;
        self.user_entered_path_segment = trailing.clone().unwrap_or_default();
        pick.item_activation = ItemActivation::None;
        pick.set_items(self.items.iter().enumerate().map(|(handle, item)| Entry::Item(quick_pick_item(handle as i64, item))).collect());
        // The user may have typed on meanwhile: only a value off the folder is replaced.
        if !equals_ignore_case(&pick.input_box.value, &new_value) && (force || was_dot_dot) {
            pick.set_value_selection(Some((0, pick.input_box.len())));
            self.insert_text(pick, &new_value, &new_value);
        }
        let len = pick.input_box.len();
        match &trailing {
            // The caret stays before the name to save.
            Some(trailing) if force && is_save => pick.set_value_selection(Some((len.saturating_sub(char_len(trailing)), len.saturating_sub(char_len(trailing))))),
            Some(_) => {}
            None => pick.set_value_selection(Some((len, len))),
        }
        self.busy = false;
        result
    }

    /// `createItems`: `..` first, then the folders, then the files the filters let through.
    fn create_items(&self, current_folder: &str) -> Vec<FileItem> {
        let mut items = Vec::new();
        for entry in std::fs::read_dir(current_folder).into_iter().flatten().flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            if !self.show_dot_files && name.starts_with('.') {
                continue;
            }
            let full_path = join_path(current_folder, &name);
            if std::fs::metadata(&full_path).is_ok_and(|stat| stat.is_dir()) {
                items.push(FileItem { label: name, path: add_trailing_separator(&full_path), is_folder: true, pickable: self.allow_folders });
            } else if self.allow_files && self.filter_file(&full_path) {
                items.push(FileItem { label: name, path: full_path, is_folder: false, pickable: true });
            }
        }
        items.sort_by(|one, two| two.is_folder.cmp(&one.is_folder).then_with(|| locale_compare(&trim_trailing_slash(&one.label), &trim_trailing_slash(&two.label))));
        let parent = dirname(current_folder);
        if parent != current_folder && std::fs::exists(&parent).unwrap_or(false) {
            items.insert(0, FileItem { label: "..".into(), path: add_trailing_separator(&parent), is_folder: true, pickable: false });
        }
        items
    }

    fn filter_file(&self, file: &str) -> bool {
        self.filters.is_empty() || self.filters.iter().any(|(_, extensions)| extensions.iter().any(|extension| extension == "*" || file.ends_with(&format!(".{extension}"))))
    }
}

fn quick_pick_item(handle: i64, item: &FileItem) -> Item {
    // `..` has no icon classes.
    let file_icon = (item.label != "..").then(|| PathBuf::from(&item.path));
    Item { handle, label: item.label.clone(), pickable: item.pickable, file_icon, folder_icon: item.is_folder, ..Item::default() }
}

/// `value = ...` from the dialog itself: no change event goes back to it.
fn set_value_quietly(pick: &mut QuickInput, value: String) {
    let before = pick.events.len();
    pick.set_value(value);
    pick.events.truncate(before);
}

/// `canCreateFolder`: the nearest existing ancestor is a folder, every missing name valid.
fn can_create_folder(uri: &str) -> bool {
    let mut candidate = uri.to_owned();
    loop {
        let name = basename(&candidate);
        if name.is_empty() || !crate::file_actions::is_valid_basename(&name) {
            return false;
        }
        let parent = dirname(&candidate);
        if parent == candidate {
            return false;
        }
        match std::fs::metadata(&parent) {
            Ok(stat) => return stat.is_dir(),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => candidate = parent,
            Err(_) => return false,
        }
    }
}

fn char_len(text: &str) -> usize {
    text.chars().count()
}

/// `substr(0, length)` in chars.
fn prefix(text: &str, length: usize) -> String {
    text.chars().take(length).collect()
}

fn equals_ignore_case(one: &str, two: &str) -> bool {
    one.to_lowercase() == two.to_lowercase()
}

fn starts_with_ignore_case(text: &str, candidate: &str) -> bool {
    char_len(text) >= char_len(candidate) && equals_ignore_case(&prefix(text, char_len(candidate)), candidate)
}

/// String `localeCompare`: case folded first, then the case.
fn locale_compare(one: &str, two: &str) -> std::cmp::Ordering {
    one.to_lowercase().cmp(&two.to_lowercase()).then_with(|| two.cmp(one))
}

fn ends_with_slash(path: &str) -> bool {
    path.ends_with('/') || path.ends_with('\\')
}

fn trim_trailing_slash(path: &str) -> String {
    match char_len(path) > 1 && ends_with_slash(path) {
        true => path[..path.len() - 1].to_owned(),
        false => path.to_owned(),
    }
}

/// `pathFromUri`.
fn path_from(path: &str, end_with_separator: bool) -> String {
    let mut result = path.replace('\n', "").replace('\\', "/");
    if end_with_separator && !ends_with_slash(&result) {
        result.push('/');
    }
    result
}

fn path_append(uri: &str, additional: &str) -> String {
    match additional {
        ".." | "." => path_from(uri, true) + additional,
        _ => path_from(&join_path(uri, additional), false),
    }
}

fn basename_with_trailing_slash(full_path: &str) -> String {
    let child = path_from(full_path, true);
    let parent = path_from(&dirname(full_path), true);
    child.chars().skip(char_len(&parent)).collect()
}

/// `remoteUriFrom` for `file`: `URI.file` of the path with forward slashes.
fn remote_uri_from(path: &str) -> String {
    let path = if path.starts_with("\\\\") { path.to_owned() } else { path.replace('\\', "/") };
    if path.starts_with('/') { path } else { format!("/{path}") }
}

/// `resources.dirname`: POSIX `dirname`, the trailing slash ignored.
fn dirname(path: &str) -> String {
    let trimmed = path.trim_end_matches('/');
    if trimmed.is_empty() {
        return if path.starts_with('/') { "/".into() } else { ".".into() };
    }
    match trimmed.rfind('/') {
        Some(0) => "/".into(),
        Some(index) => trimmed[..index].trim_end_matches('/').to_owned(),
        None => ".".into(),
    }
}

/// `resources.basename`: POSIX `basename`, the trailing slash ignored.
fn basename(path: &str) -> String {
    let trimmed = path.trim_end_matches('/');
    trimmed.rsplit('/').next().unwrap_or_default().to_owned()
}

/// POSIX `extname`: from the last dot of the name that does not start it.
fn extname(path: &str) -> String {
    let name = basename(path);
    match name.rfind('.') {
        Some(index) if index > 0 && name != ".." => name[index..].to_owned(),
        _ => String::new(),
    }
}

fn has_trailing_separator(path: &str) -> bool {
    path.len() > 1 && path.ends_with('/')
}

fn add_trailing_separator(path: &str) -> String {
    match path == "/" || has_trailing_separator(path) {
        true => path.to_owned(),
        false => format!("{path}/"),
    }
}

fn remove_trailing_separator(path: &str) -> String {
    match has_trailing_separator(path) {
        true => path[..path.len() - 1].to_owned(),
        false => path.to_owned(),
    }
}

/// `resources.joinPath`: POSIX `join`, normalized, the trailing slash kept.
fn join_path(base: &str, fragment: &str) -> String {
    match fragment.is_empty() {
        true => normalize(base),
        false => normalize(&format!("{base}/{fragment}")),
    }
}

/// POSIX `normalize` of an absolute path: `.` and `..` resolved, a trailing slash kept.
fn normalize(path: &str) -> String {
    let mut segments: Vec<&str> = Vec::new();
    for segment in path.split('/') {
        match segment {
            "" | "." => {}
            ".." => _ = segments.pop(),
            _ => segments.push(segment),
        }
    }
    let mut result = format!("/{}", segments.join("/"));
    if path.ends_with('/') && !segments.is_empty() {
        result.push('/');
    }
    result
}

/// POSIX `relative` between absolute paths.
fn relative_path(from: &str, to: &str) -> String {
    let (from, to) = (normalize(from), normalize(to));
    let from: Vec<&str> = from.split('/').filter(|segment| !segment.is_empty()).collect();
    let to: Vec<&str> = to.split('/').filter(|segment| !segment.is_empty()).collect();
    let common = from.iter().zip(&to).take_while(|(one, two)| one == two).count();
    let mut parts = vec![".."; from.len() - common];
    parts.extend(&to[common..]);
    parts.join("/")
}

fn is_equal_or_parent_ignore_case(base: &str, parent_candidate: &str) -> bool {
    if base == parent_candidate {
        return true;
    }
    if char_len(parent_candidate) > char_len(base) || !starts_with_ignore_case(base, parent_candidate) {
        return false;
    }
    if char_len(parent_candidate) == char_len(base) {
        return true;
    }
    let mut separator_offset = char_len(parent_candidate);
    if parent_candidate.ends_with('/') {
        separator_offset -= 1;
    }
    base.chars().nth(separator_offset) == Some('/')
}

fn root(path: &str) -> String {
    let mut last = path.to_owned();
    let mut dir = dirname(path);
    while last != dir {
        last = dir;
        dir = dirname(&last);
    }
    dir
}

#[cfg(test)]
mod tests;