дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-21 17:10:45 +02:00
Порівняти коміти
30
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
cdc228daf0 | ||
|
|
0527ff4218 | ||
|
|
e5b2f4dfc7 | ||
|
|
a3617aa3e9 | ||
|
|
bd7d4c475b | ||
|
|
15e32d5af6 | ||
|
|
3de76f1a63 | ||
|
|
262b91d89a | ||
|
|
4d6a21c695 | ||
|
|
7de8fb850e | ||
|
|
acb850758a | ||
|
|
6bf69cfb2a | ||
|
|
6829022b71 | ||
|
|
54611ff80a | ||
|
|
cacfc4142f | ||
|
|
237f7ee5a5 | ||
|
|
2321929709 | ||
|
|
6d788cb6f8 | ||
|
|
662c32eb05 | ||
|
|
82ff84e69e | ||
|
|
7ec0d3dbec | ||
|
|
466556603d | ||
|
|
3b2deb6ad8 | ||
|
|
f2429a8c14 | ||
|
|
f3e80ba020 | ||
|
|
f767bd2e7c | ||
|
|
51174842cc | ||
|
|
e4ece2bd8d | ||
|
|
a5093c0cd1 | ||
|
|
9a0256c7d4 |
No files matched your search
@@ -16,18 +16,55 @@ pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
/// For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
|
||||
///
|
||||
/// - Windows: release builds use the GUI subsystem, so without `CREATE_NO_WINDOW` every
|
||||
/// console child flashes a `cmd` window.
|
||||
/// console child flashes a `cmd` window. Batch files also need a PATH small enough for cmd.
|
||||
/// - Linux AppImage, reloaded and project variables: see [`host_env`].
|
||||
///
|
||||
/// Variables the call site has already set are kept; call it before `env_clear` and after
|
||||
/// `current_dir`, which picks the project environment.
|
||||
/// Explicit variables take precedence over the host environment. Call after setting
|
||||
/// `current_dir` and any explicit `PATH`, and before `env_clear`.
|
||||
pub fn prepare(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
host_env(cmd)
|
||||
host_env(cmd);
|
||||
#[cfg(windows)]
|
||||
compact_batch_path(cmd);
|
||||
cmd
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn compact_batch_path(cmd: &mut Command) {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::{Component, Prefix};
|
||||
|
||||
// Rust runs these files through cmd.exe, which drops inherited variables over this limit.
|
||||
const CMD_ENV_LIMIT: usize = 8191;
|
||||
let extension = Path::new(cmd.get_program()).extension();
|
||||
if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) {
|
||||
return;
|
||||
}
|
||||
let path = match cmd.get_envs().find(|(key, _)| key.eq_ignore_ascii_case("PATH")) {
|
||||
Some((_, path)) => path.map(OsStr::to_owned),
|
||||
None => std::env::var_os("PATH"),
|
||||
};
|
||||
let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return };
|
||||
|
||||
// The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are
|
||||
// missing now, keeping search precedence and leaving UNC and relative paths alone.
|
||||
let dirs = std::env::split_paths(&path).filter(|dir| {
|
||||
let local = dir.is_absolute()
|
||||
&& matches!(dir.components().next(), Some(Component::Prefix(p))
|
||||
if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)));
|
||||
!local
|
||||
|| !std::fs::symlink_metadata(dir)
|
||||
.is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory))
|
||||
});
|
||||
if let Ok(compact) = std::env::join_paths(dirs)
|
||||
&& compact.encode_wide().count() <= CMD_ENV_LIMIT
|
||||
{
|
||||
cmd.env("PATH", compact);
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and
|
||||
@@ -885,6 +922,44 @@ mod tests {
|
||||
assert!(!process_alive(pid));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn batch_launch_keeps_runtime_paths_when_cmd_would_drop_path() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let script = root.path().join("server.CMD");
|
||||
std::fs::write(&script, "@echo off\r\nif not defined PATH exit /b 42\r\n").unwrap();
|
||||
let selected = root.path().join("Selected Runtime");
|
||||
let fallback = root.path().join("Fallback Runtime");
|
||||
std::fs::create_dir(&selected).unwrap();
|
||||
std::fs::create_dir(&fallback).unwrap();
|
||||
let relative = Path::new("relative");
|
||||
let unc = Path::new(r"\\openidea-test\share\bin");
|
||||
let missing = root.path().join("uninstalled-".repeat(12));
|
||||
let path = std::env::join_paths(
|
||||
std::iter::once(selected.as_path()).chain(std::iter::repeat_n(missing.as_path(), 60)).chain([
|
||||
unc,
|
||||
relative,
|
||||
fallback.as_path(),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let compact = std::env::join_paths([selected.as_path(), unc, relative, fallback.as_path()]).unwrap();
|
||||
|
||||
let path_in = |cmd: &Command| {
|
||||
cmd.get_envs()
|
||||
.find_map(|(key, value)| key.eq_ignore_ascii_case("PATH").then(|| value.map(OsStr::to_owned)))
|
||||
.flatten()
|
||||
};
|
||||
let mut cmd = Command::new(&script);
|
||||
cmd.current_dir(root.path()).env("PATH", &path);
|
||||
prepare(&mut cmd);
|
||||
assert_eq!(path_in(&cmd), Some(compact));
|
||||
assert!(cmd.status().unwrap().success());
|
||||
|
||||
let mut native = Command::new(root.path().join("server.exe"));
|
||||
assert_eq!(path_in(prepare(native.env("PATH", &path))), Some(path));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn process_alive_rejects_ids_that_are_not_a_single_process() {
|
||||
|
||||
@@ -770,6 +770,8 @@ pub struct AppearanceSettings {
|
||||
pub show_tool_window_names: bool,
|
||||
pub show_tool_window_badges: bool,
|
||||
pub widescreen_tool_windows: bool,
|
||||
/// Each tool window keeps its own size; off, the windows of a side share one.
|
||||
pub remember_tool_window_sizes: bool,
|
||||
/// View › Appearance › Toolbar; hidden leaves IDEA's compact window header.
|
||||
pub show_main_toolbar: bool,
|
||||
pub show_status_bar: bool,
|
||||
@@ -898,6 +900,7 @@ impl Default for AppearanceSettings {
|
||||
show_tool_window_names: false,
|
||||
show_tool_window_badges: true,
|
||||
widescreen_tool_windows: false,
|
||||
remember_tool_window_sizes: false,
|
||||
show_main_toolbar: true,
|
||||
show_status_bar: true,
|
||||
navigation_bar: NavigationBarPosition::StatusBar,
|
||||
|
||||
@@ -20,6 +20,34 @@ pub struct VcsSettings {
|
||||
pub shelf: ShelfSettings,
|
||||
/// Issue Navigation: commit-message patterns turned into links.
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
/// root (`.` for the root itself) or absolute outside it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct VcsMappings {
|
||||
/// Detected repositories the IDE leaves alone: no Git or Commit integration, files stay.
|
||||
pub excluded: Vec<String>,
|
||||
/// Repository roots detection does not reach (outside the project, or deeper).
|
||||
pub added: Vec<String>,
|
||||
}
|
||||
|
||||
impl VcsMappings {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.excluded.is_empty() && self.added.is_empty()
|
||||
}
|
||||
|
||||
/// `path` resolved against `project_root`.
|
||||
pub fn resolve(project_root: &std::path::Path, path: &str) -> std::path::PathBuf {
|
||||
match path {
|
||||
"" | "." => project_root.to_path_buf(),
|
||||
p if std::path::Path::new(p).is_absolute() => p.into(),
|
||||
p => project_root.join(p),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for VcsSettings {
|
||||
@@ -34,6 +62,7 @@ impl Default for VcsSettings {
|
||||
confirmation: VcsConfirmationSettings::default(),
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,6 +106,9 @@ pub struct GitSettings {
|
||||
/// The non-modal Commit tool window works on the index: Staged / Unstaged groups,
|
||||
/// stage and unstage instead of inclusion checkboxes, and no change lists.
|
||||
pub staging_area: bool,
|
||||
/// Scan the working tree with `git status` (for file systems whose metadata only
|
||||
/// the system git reads correctly) instead of in process.
|
||||
pub cli_status: bool,
|
||||
}
|
||||
|
||||
impl Default for GitSettings {
|
||||
@@ -101,6 +133,7 @@ impl Default for GitSettings {
|
||||
push_dialog_only_protected: false,
|
||||
combine_stash_and_shelf: false,
|
||||
staging_area: false,
|
||||
cli_status: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_vfs::FileEntry;
|
||||
use ide_workspace::DeletionUndo;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -163,14 +164,27 @@ pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool)
|
||||
/// Moving to the trash can take a while (large trees): kept off the main thread.
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> {
|
||||
// Local History keeps the contents so deleted files can be restored.
|
||||
let project = host.project(window).ok();
|
||||
let history = project.as_ref().map(|p| p.history.clone());
|
||||
delete_with_history(host, window, path, false).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Moves an item to the Trash and returns the snapshot for Project View Undo.
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_delete_with_undo(host: &Host, window: &str, path: PathBuf) -> IdeResult<DeletionUndo> {
|
||||
delete_with_history(host, window, path, true).await
|
||||
}
|
||||
|
||||
async fn delete_with_history(host: &Host, window: &str, path: PathBuf, undoable: bool) -> IdeResult<DeletionUndo> {
|
||||
let project = if undoable { Some(host.project(window)?) } else { host.project(window).ok() };
|
||||
host.blocking(move || {
|
||||
let paths = ide_workspace::file_ops::deletion_paths(&path)?;
|
||||
if let Some(h) = history {
|
||||
for p in &paths {
|
||||
h.record_deletion(p, DELETE_SNAPSHOT_LIMIT);
|
||||
let mut undo = DeletionUndo::default();
|
||||
if let Some(p) = &project {
|
||||
if undoable {
|
||||
undo = p.history.capture_deletion_undo(&paths, DELETE_SNAPSHOT_LIMIT);
|
||||
} else {
|
||||
for pth in &paths {
|
||||
p.history.record_deletion(pth, DELETE_SNAPSHOT_LIMIT);
|
||||
}
|
||||
}
|
||||
}
|
||||
ide_workspace::file_ops::delete(&path)?;
|
||||
@@ -178,11 +192,17 @@ pub async fn fs_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()
|
||||
if let Some(p) = project {
|
||||
let _ = p.with_backend_of(&path, |r| r.files_deleted(&paths));
|
||||
}
|
||||
Ok(())
|
||||
Ok(undo)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || Ok(project.history.restore_deletion_undo(undo))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_copy(host: &Host, window: &str, from: PathBuf, to: PathBuf) -> IdeResult<()> {
|
||||
let project = host.project(window).ok();
|
||||
@@ -280,9 +300,11 @@ ide_command::domain!(
|
||||
fs_create_file,
|
||||
fs_create_file_bytes,
|
||||
fs_delete,
|
||||
fs_delete_with_undo,
|
||||
fs_entry_kind,
|
||||
fs_read_dir,
|
||||
fs_read_text,
|
||||
fs_rename,
|
||||
fs_set_writable,
|
||||
fs_undo_delete,
|
||||
);
|
||||
@@ -68,6 +68,31 @@ pub async fn find_files_named(host: &Host, window: &str, name: String) -> IdeRes
|
||||
blocking(move || Ok(project.index.files_named(&name).into_iter().map(Into::into).collect())).await
|
||||
}
|
||||
|
||||
/// The files of a custom scope (`file:src//*.ts`), for the Project view's scope panes.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScopeFiles {
|
||||
pub paths: Vec<IpcPath>,
|
||||
/// More files than `limit` matched; `paths` holds the first ones.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn scope_files(host: &Host, window: &str, pattern: String, limit: u32) -> IdeResult<ScopeFiles> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let mask = ide_search::FileMask::new(&[], &project.search_excludes())?;
|
||||
let scope = ide_search::SearchScope::Pattern { pattern };
|
||||
let mut files =
|
||||
ide_search::scope_files(&project.root, &scope, &mask, None, &ide_core::CancellationToken::new())?;
|
||||
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
|
||||
let truncated = files.len() > limit as usize;
|
||||
files.truncate(limit as usize);
|
||||
Ok(ScopeFiles { paths: files.into_iter().map(|f| f.path.into()).collect(), truncated })
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Folders holding indexed files, for `@` references.
|
||||
#[command(trust = always)]
|
||||
pub async fn find_dirs(host: &Host, window: &str, query: String, limit: u32) -> IdeResult<Vec<FileMatch>> {
|
||||
@@ -375,6 +400,7 @@ ide_command::domain!(
|
||||
path_completions,
|
||||
recent_files,
|
||||
remove_recent,
|
||||
scope_files,
|
||||
web_goto,
|
||||
web_unresolved_references,
|
||||
);
|
||||
@@ -302,6 +302,15 @@ pub fn set_settings(
|
||||
}
|
||||
});
|
||||
}
|
||||
// Directory Mappings change which repositories the project has.
|
||||
if key == "vcs" || key == "vcs.mappings" || key.starts_with("vcs.mappings.") {
|
||||
let affected = affected();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
for project in affected {
|
||||
project.refresh_repositories();
|
||||
}
|
||||
});
|
||||
}
|
||||
if key == "ssh" || key.starts_with("ssh.") {
|
||||
host.ssh.set_configs(host.global_settings.effective().ssh.configs);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>>
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
}
|
||||
repos.status()
|
||||
})
|
||||
@@ -40,6 +41,7 @@ pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::P
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
}
|
||||
repos.status_paths(&paths)
|
||||
})
|
||||
|
||||
@@ -338,6 +338,13 @@ fn keep_private(root: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Directory Mappings: the repository roots detection finds, before any are excluded or added.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_detected_roots(host: &Host, window: &str) -> IdeResult<Vec<PathBuf>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.detected_repository_roots()).await
|
||||
}
|
||||
|
||||
/// The project's repositories, the primary one first.
|
||||
#[command(trust = always)]
|
||||
pub fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
@@ -1061,6 +1068,22 @@ pub async fn vcs_config_get(
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.config_get(&key))).await
|
||||
}
|
||||
|
||||
/// Git User Name Is Not Defined: sets `user.name` / `user.email` for commits in the
|
||||
/// repository, or globally.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_set_user_identity(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
name: String,
|
||||
email: String,
|
||||
global: bool,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.set_user_identity(&name, &email, global))).await
|
||||
}
|
||||
|
||||
/// Local history operation that may take a while (hooks, large checkouts); git's
|
||||
/// output streams through `on_output`. Cancellable.
|
||||
#[command(trust = trusted)]
|
||||
@@ -1569,6 +1592,7 @@ ide_command::domain!(
|
||||
vcs_compare_paths,
|
||||
vcs_compare_scope,
|
||||
vcs_config_get,
|
||||
vcs_set_user_identity,
|
||||
vcs_conflict_versions,
|
||||
vcs_create_branch,
|
||||
vcs_create_patch,
|
||||
@@ -1616,6 +1640,7 @@ ide_command::domain!(
|
||||
vcs_revision_files,
|
||||
vcs_reword,
|
||||
vcs_roots,
|
||||
vcs_detected_roots,
|
||||
vcs_shelf_delete,
|
||||
vcs_shelf_diff,
|
||||
vcs_shelf_import,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! watchers and the per-project services, opened by [`crate::Host::open_project`].
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::workflow_settings::VcsMappings;
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink};
|
||||
use ide_index::ProjectIndex;
|
||||
use ide_language::{FileTypes, LanguageRegistry, SyntaxCache};
|
||||
@@ -955,10 +956,27 @@ fn scan_repositories(
|
||||
}
|
||||
}
|
||||
|
||||
/// The repository containing `root` and those nested below it or below a content root.
|
||||
/// The repository containing `root` and those nested below it or below a content root,
|
||||
/// with the project's Directory Mappings applied.
|
||||
/// The project-open scan and the watcher's rescan share these skip rules.
|
||||
fn discover_repositories(root: &Path, settings: &SettingsStore, build_cache: &Path, trusted: bool) -> IdeResult<Repos> {
|
||||
let ignored = settings.effective().ignored_names();
|
||||
let settings = settings.effective();
|
||||
let found = detect_repositories(root, &settings, build_cache, trusted)?;
|
||||
let mappings = &settings.vcs.mappings;
|
||||
if mappings.is_empty() {
|
||||
return Ok(found);
|
||||
}
|
||||
let resolve = |list: &[String]| -> Vec<PathBuf> { list.iter().map(|p| VcsMappings::resolve(root, p)).collect() };
|
||||
Ok(found.mapped(&resolve(&mappings.excluded), &resolve(&mappings.added), root))
|
||||
}
|
||||
|
||||
fn detect_repositories(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
build_cache: &Path,
|
||||
trusted: bool,
|
||||
) -> IdeResult<Repos> {
|
||||
let ignored = settings.ignored_names();
|
||||
let skip = |p: &Path| {
|
||||
p.file_name().is_some_and(|n| {
|
||||
let name = n.to_string_lossy();
|
||||
@@ -968,11 +986,17 @@ fn discover_repositories(root: &Path, settings: &SettingsStore, build_cache: &Pa
|
||||
})
|
||||
};
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(&settings.effective(), root, build_cache, trusted));
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &skip)
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// The repository roots detection finds, before Directory Mappings exclude or add any.
|
||||
pub fn detected_repository_roots(&self) -> IdeResult<Vec<PathBuf>> {
|
||||
let settings = self.settings.effective();
|
||||
Ok(detect_repositories(&self.root, &settings, &self.build_cache_dir(), self.is_trusted())?.roots())
|
||||
}
|
||||
|
||||
pub fn refresh_repositories(&self) {
|
||||
scan_repositories(
|
||||
&self.root,
|
||||
@@ -1076,6 +1100,7 @@ impl Project {
|
||||
apply_git_executable(&settings);
|
||||
}
|
||||
repo.set_ignored_names(settings.ignored_names());
|
||||
repo.set_cli_status(settings.vcs.git.cli_status);
|
||||
f(repo)
|
||||
}
|
||||
|
||||
|
||||
@@ -241,6 +241,15 @@ impl PathFilter {
|
||||
(!rel.is_empty()).then_some(rel)
|
||||
}
|
||||
|
||||
/// Recent Files' stored form: the store key for a project file, the absolute
|
||||
/// path for one outside it (a scratch file). Loading joins it to the root,
|
||||
/// which leaves an absolute path as it is.
|
||||
pub(crate) fn recent_key(&self, path: &Path) -> Option<String> {
|
||||
self.store_key(path).or_else(|| {
|
||||
(path.is_absolute() && !path.starts_with(&self.root)).then(|| path.to_str().map(str::to_owned))?
|
||||
})
|
||||
}
|
||||
|
||||
fn excluded_rel(&self, rel: &str) -> bool {
|
||||
self.excludes.is_match(rel)
|
||||
}
|
||||
|
||||
@@ -400,15 +400,10 @@ impl ProjectIndex {
|
||||
|
||||
/// Boost for "recent files" ranking.
|
||||
/// Records a recently opened file; a virtual document's URI (library
|
||||
/// class) is kept verbatim, like IDEA lists library classes in Recent Files.
|
||||
/// class) is kept verbatim, and a file outside the project (a scratch file)
|
||||
/// by its absolute path.
|
||||
pub fn mark_recent(&self, path: &Path) {
|
||||
let path = match path.to_str() {
|
||||
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
|
||||
_ => match self.normalize(path) {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let Some(path) = self.recent_key(path) else { return };
|
||||
{
|
||||
let mut r = self.shared.recent.lock();
|
||||
r.retain(|p| p != &path);
|
||||
@@ -420,13 +415,7 @@ impl ProjectIndex {
|
||||
|
||||
/// Drops a file from Recent Files (Delete in the ⌘E popup).
|
||||
pub fn remove_recent(&self, path: &Path) {
|
||||
let path = match path.to_str() {
|
||||
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
|
||||
_ => match self.normalize(path) {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let Some(path) = self.recent_key(path) else { return };
|
||||
{
|
||||
let mut r = self.shared.recent.lock();
|
||||
let before = r.len();
|
||||
@@ -473,6 +462,20 @@ impl ProjectIndex {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// How Recent Files stores `path`: a virtual URI verbatim, a project file normalized,
|
||||
/// and an existing file outside the root canonicalized. Excluded files under the root
|
||||
/// are left out.
|
||||
fn recent_key(&self, path: &Path) -> Option<PathBuf> {
|
||||
if path.to_str().is_some_and(ide_core::text::is_virtual_uri) {
|
||||
return Some(path.to_owned());
|
||||
}
|
||||
if let Some(p) = self.normalize(path) {
|
||||
return Some(p);
|
||||
}
|
||||
let p = dunce::canonicalize(path).ok().filter(|p| p.is_file())?;
|
||||
(!p.starts_with(&self.root)).then_some(p)
|
||||
}
|
||||
|
||||
/// Absolute path inside the root (or a content root), or `None` for paths outside the project.
|
||||
fn normalize(&self, path: &Path) -> Option<PathBuf> {
|
||||
let filter = self.shared.filter();
|
||||
|
||||
@@ -251,6 +251,26 @@ fn recent_files_skip_deleted_files_but_keep_virtual_documents() {
|
||||
assert_eq!(idx.recent_files(), vec![virt]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_files_keep_files_outside_the_project() {
|
||||
let fx = sample();
|
||||
let scratches = tempfile::tempdir().unwrap();
|
||||
let scratch = dunce::canonicalize(scratches.path()).unwrap().join("generated-requests.http");
|
||||
std::fs::write(&scratch, "GET http://localhost\n").unwrap();
|
||||
let app = fx.root.join("web/app.py");
|
||||
{
|
||||
let idx = fx.open();
|
||||
idx.mark_recent(&app);
|
||||
idx.mark_recent(&scratch);
|
||||
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
}
|
||||
let idx = fx.open();
|
||||
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()], "persisted by absolute path");
|
||||
idx.remove_recent(&scratch);
|
||||
assert_eq!(idx.recent_files(), vec![app]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_skips_unchanged_files_on_reopen() {
|
||||
let fx = sample();
|
||||
|
||||
@@ -591,7 +591,7 @@ impl Shared {
|
||||
let update_elapsed = update_started.elapsed();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Some(store) = &self.store {
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
|
||||
let d = self.data.read();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
|
||||
@@ -976,7 +976,7 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
if save_recent && let Some(store) = &self.store {
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
|
||||
if let Err(e) = store.save_recent(&rels) {
|
||||
tracing::warn!("index cache: saving recent files failed: {e}");
|
||||
}
|
||||
|
||||
@@ -407,18 +407,14 @@ impl Peer {
|
||||
let resolved = resolve_spawn_program(command, env);
|
||||
let mut cmd = tokio::process::Command::new(&resolved);
|
||||
// The working directory first: it picks the project's environment.
|
||||
cmd.current_dir(cwd);
|
||||
cmd.current_dir(cwd)
|
||||
.envs(ide_core::process::shell_env_in(cwd))
|
||||
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
// Wrappers (`npx`, `codex.cmd`, launcher scripts) start the real server as a child:
|
||||
// stopping the connection stops the whole tree.
|
||||
ide_core::process::own_group(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.envs(ide_core::process::shell_env_in(cwd))
|
||||
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
|
||||
let mut child = cmd.spawn()?;
|
||||
let stdin = child.stdin.take().ok_or_else(|| std::io::Error::other("child stdin unavailable"))?;
|
||||
let stdout = child.stdout.take().ok_or_else(|| std::io::Error::other("child stdout unavailable"))?;
|
||||
|
||||
@@ -23,6 +23,7 @@ pub(crate) mod configuration;
|
||||
mod extract_interface;
|
||||
mod formatter;
|
||||
mod generated;
|
||||
pub(crate) use generated::is_processor_output;
|
||||
mod hierarchy;
|
||||
pub(crate) mod jvm_inspect;
|
||||
mod move_refactoring;
|
||||
|
||||
@@ -25,6 +25,18 @@ pub(crate) struct GeneratedScan {
|
||||
pub roots: Vec<GeneratedRoot>,
|
||||
}
|
||||
|
||||
/// Whether `path` is in (or is) an annotation-processor output folder:
|
||||
/// `generated-sources/annotations` or `generated-test-sources/test-annotations`. jdtls
|
||||
/// runs the processors itself and writes there; javac (a Maven build) writes the same
|
||||
/// files, and jdtls must not take those as edits (#4128).
|
||||
pub(crate) fn is_processor_output(path: &Path) -> bool {
|
||||
let parts: Vec<_> = path.components().map(|c| c.as_os_str()).collect();
|
||||
parts.windows(2).any(|w| {
|
||||
(w[0] == "generated-sources" && w[1] == "annotations")
|
||||
|| (w[0] == "generated-test-sources" && w[1] == "test-annotations")
|
||||
})
|
||||
}
|
||||
|
||||
/// Generated Java source folders under `root` (a reactor or one module).
|
||||
pub(crate) fn scan(root: &Path) -> GeneratedScan {
|
||||
let mut modules = Vec::new();
|
||||
@@ -260,6 +272,20 @@ fn plugins_removed(build: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recognizes_annotation_processor_output() {
|
||||
for (path, expected) in [
|
||||
("/p/m/target/generated-sources/annotations/com/x/FooMappingImpl.java", true),
|
||||
("/p/m/target/generated-sources/annotations", true),
|
||||
("/p/m/build-out/generated-test-sources/test-annotations/com/x/T.java", true),
|
||||
("/p/m/target/generated-sources/protobuf/java/com/x/Hello.java", false),
|
||||
("/p/m/src/main/java/annotations/Foo.java", false),
|
||||
("/p/m/target/classes/com/x/FooMappingImpl.class", false),
|
||||
] {
|
||||
assert_eq!(is_processor_output(Path::new(path)), expected, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
|
||||
@@ -160,12 +160,13 @@ const DEAD_SHIM_MESSAGES: &[&str] =
|
||||
/// server that dies like that on every start is missing (an install hint), not crashing.
|
||||
/// Anything but a clear "not installed" answer from the shim counts as working.
|
||||
fn reject_dead_shim(binary: PathBuf, search: &OsStr, root: &Path) -> Option<PathBuf> {
|
||||
if !binary.parent().is_some_and(|d| d.file_name().is_some_and(|n| n == "shims")) {
|
||||
if binary.parent().and_then(Path::file_name) != Some(OsStr::new("shims")) {
|
||||
return Some(binary);
|
||||
}
|
||||
let Ok(mut child) = ide_core::process::prepare(std::process::Command::new(&binary).current_dir(root))
|
||||
let mut cmd = std::process::Command::new(&binary);
|
||||
cmd.current_dir(root).env("PATH", search);
|
||||
let Ok(mut child) = ide_core::process::prepare(&mut cmd)
|
||||
.arg("--version")
|
||||
.env("PATH", search)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
|
||||
@@ -3057,7 +3057,12 @@ impl LspManager {
|
||||
for s in servers {
|
||||
let Some(run) = s.running() else { continue };
|
||||
let open = open.get(&(s.id, run.generation)).filter(|_| run.caps.read().sync != SyncKind::None);
|
||||
// jdtls owns its annotation-processor output; javac's copy of those files is not an edit.
|
||||
let jdtls = s.name == "jdtls";
|
||||
let send = |p: &PathBuf, change: Change| {
|
||||
if jdtls && jdtls::is_processor_output(p) {
|
||||
return false;
|
||||
}
|
||||
change == Change::Deleted
|
||||
|| !open
|
||||
.is_some_and(|paths| paths.contains(p) || canonical.get(p).is_some_and(|c| paths.contains(c)))
|
||||
|
||||
@@ -94,10 +94,9 @@ pub(crate) fn connect_or_start(
|
||||
let args = substitute_args(&config.args, port, root);
|
||||
|
||||
let mut cmd = tokio::process::Command::new(binary);
|
||||
cmd.current_dir(root);
|
||||
cmd.current_dir(root).envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(&args)
|
||||
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
|
||||
@@ -991,6 +991,33 @@ async fn files_changed_on_disk_reach_the_servers_of_their_language() {
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// jdtls runs the annotation processors itself and writes their output; a Maven build's
|
||||
/// copy of those files must not reach it as an edit, or jdtls recompiles javac's copy and
|
||||
/// overwrites its classes with broken ones (#4128).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn jdtls_does_not_hear_of_annotation_processor_output() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let (doc, _) = h.open("Open.java", "class Open {}");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
let source = h.root.join("m/src/main/java/com/x/FooMapping.java");
|
||||
let generated = h.root.join("m/target/generated-sources/annotations/com/x/FooMappingImpl.java");
|
||||
let test_generated = h.root.join("m/target/generated-test-sources/test-annotations/com/x/T.java");
|
||||
h.mgr.watched_files_changed(
|
||||
&[test_generated],
|
||||
&[generated.clone(), source.clone()],
|
||||
std::slice::from_ref(&generated),
|
||||
&[h.root.join("m/target/generated-sources/annotations")],
|
||||
);
|
||||
eventually(|| !s.notified("workspace/didChangeWatchedFiles").is_empty()).await;
|
||||
h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.unwrap();
|
||||
assert_eq!(
|
||||
s.notified("workspace/didChangeWatchedFiles"),
|
||||
vec![json!({ "changes": [{ "uri": uri_of(&source), "type": 2 }] })]
|
||||
);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// An external change to a document open on the server's current instance reaches it only
|
||||
/// through the reload's `didChange`: a watched-file change for it too would make a server
|
||||
/// that re-reads the file on one (csharp-ls) apply the reload and then the diff computed
|
||||
|
||||
@@ -14,7 +14,7 @@ pub use deploy::{
|
||||
Deployment, DeploymentCoverage, SyncAction, SyncEntry, SyncStatus, SyncStep, TransferReport, coverage,
|
||||
};
|
||||
pub use mapping::{Excludes, Mappings, ResolvedMapping};
|
||||
pub use service::{DeployedPath, DeploymentRoot, RemoteService};
|
||||
pub use service::{DeployedPath, DeploymentRoot, RemoteService, default_targets};
|
||||
pub use target::{RemoteRuns, RemoteStart};
|
||||
|
||||
pub mod plugin_target;
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Deployment over SFTP, FTP or local folders, and SSH run targets.
|
||||
//! Shared by IPC commands and project save/delete hooks.
|
||||
|
||||
use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, TransferReport, status};
|
||||
use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, TransferError, TransferReport, status};
|
||||
use crate::mapping::{Excludes, Mappings, ResolvedMapping, posix};
|
||||
use crate::target::{RemoteRuns, RemoteStart, SyncFn, rewrite_external_classpath};
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentServer, DeploymentType, RunTarget};
|
||||
@@ -65,6 +65,39 @@ pub fn server(settings: &Settings, id: Option<&str>) -> IdeResult<DeploymentServ
|
||||
.ok_or_else(|| IdeError::not_found(format!("no deployment server {id}")))
|
||||
}
|
||||
|
||||
/// The servers automatic upload goes to: the default server, or each server of the default group.
|
||||
pub fn default_targets(settings: &Settings) -> Vec<String> {
|
||||
let d = &settings.deployment;
|
||||
match d.groups.iter().find(|g| g.id == d.default_server) {
|
||||
Some(group) => group.servers.iter().filter(|id| d.servers.iter().any(|s| &s.id == *id)).cloned().collect(),
|
||||
None if d.default_server.is_empty() => Vec::new(),
|
||||
None => vec![d.default_server.clone()],
|
||||
}
|
||||
}
|
||||
|
||||
/// One report for transfers to several servers, failures named after their server.
|
||||
fn merge_reports(reports: Vec<(String, IdeResult<TransferReport>)>) -> IdeResult<TransferReport> {
|
||||
if let [(_, _)] = reports.as_slice() {
|
||||
return reports.into_iter().next().map(|(_, r)| r).unwrap_or_else(|| Ok(TransferReport::default()));
|
||||
}
|
||||
let mut out = TransferReport::default();
|
||||
for (server, report) in reports {
|
||||
match report {
|
||||
Ok(r) => {
|
||||
out.files += r.files;
|
||||
out.skipped += r.skipped;
|
||||
out.errors.extend(
|
||||
r.errors.into_iter().map(|e| TransferError { message: format!("{server}: {}", e.message), ..e }),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
out.errors.push(TransferError { path: String::new(), message: format!("{server}: {}", e.message) })
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn run_target(settings: &Settings, id: &str) -> IdeResult<RunTarget> {
|
||||
settings
|
||||
.run_targets
|
||||
@@ -391,15 +424,17 @@ impl RemoteService {
|
||||
.await;
|
||||
return Some(r);
|
||||
}
|
||||
if settings.deployment.auto_upload == AutoUpload::Never
|
||||
|| settings.deployment.default_server.is_empty()
|
||||
|| !path.starts_with(root)
|
||||
{
|
||||
let targets = default_targets(settings);
|
||||
if settings.deployment.auto_upload == AutoUpload::Never || targets.is_empty() || !path.starts_with(root) {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
self.upload(settings, root, None, &[path.to_path_buf()], CancellationToken::new(), &mut |_, _, _| {}).await,
|
||||
)
|
||||
let mut reports = Vec::new();
|
||||
for id in targets {
|
||||
let paths = [path.to_path_buf()];
|
||||
let r = self.upload(settings, root, Some(&id), &paths, CancellationToken::new(), &mut |_, _, _| {}).await;
|
||||
reports.push((id, r));
|
||||
}
|
||||
Some(merge_reports(reports))
|
||||
}
|
||||
|
||||
/// After files were deleted locally: their remote copies too (automatic upload + Delete remote files).
|
||||
@@ -410,10 +445,16 @@ impl RemoteService {
|
||||
paths: &[PathBuf],
|
||||
) -> Option<IdeResult<TransferReport>> {
|
||||
let d = &settings.deployment;
|
||||
if d.auto_upload == AutoUpload::Never || !d.delete_remote || d.default_server.is_empty() {
|
||||
let targets = default_targets(settings);
|
||||
if d.auto_upload == AutoUpload::Never || !d.delete_remote || targets.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(self.delete_remote(settings, root, None, paths).await)
|
||||
let mut reports = Vec::new();
|
||||
for id in targets {
|
||||
let r = self.delete_remote(settings, root, Some(&id), paths).await;
|
||||
reports.push((id, r));
|
||||
}
|
||||
Some(merge_reports(reports))
|
||||
}
|
||||
|
||||
// --- run targets ---------------------------------------------------------------
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Local deployment uses the service entry points used by SFTP and save hooks.
|
||||
use ide_core::CancellationToken;
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentMapping, DeploymentServer, DeploymentType};
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentGroup, DeploymentMapping, DeploymentServer, DeploymentType};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_remote::{RemoteService, SyncAction, SyncStatus, SyncStep};
|
||||
use ide_ssh::{FsConnection, SshFiles, SshManager};
|
||||
@@ -410,3 +410,40 @@ async fn download_into_copies_only_the_selected_items() {
|
||||
.unwrap();
|
||||
assert_eq!((report.files, report.errors.len()), (0, 1), "{report:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn automatic_upload_to_a_default_group_reaches_each_of_its_servers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let (staging, live) = (tmp.path().join("staging"), tmp.path().join("live"));
|
||||
for dir in [root.join("src"), staging.clone(), live.clone()] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("src/a.txt"), "v1").unwrap();
|
||||
let mut settings = settings(&staging);
|
||||
settings.deployment.servers.push(DeploymentServer {
|
||||
id: "live".into(),
|
||||
kind: DeploymentType::Local,
|
||||
root_path: live.to_string_lossy().into_owned(),
|
||||
mappings: vec![DeploymentMapping { deployment: "app".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
});
|
||||
settings.deployment.groups.push(DeploymentGroup {
|
||||
id: "all".into(),
|
||||
name: "All".into(),
|
||||
servers: vec!["local".into(), "live".into(), "gone".into()],
|
||||
});
|
||||
settings.deployment.default_server = "all".into();
|
||||
assert_eq!(ide_remote::default_targets(&settings), ["local", "live"]);
|
||||
|
||||
let service = service(tmp.path());
|
||||
let saved = service.on_saved(&settings, &root, &root.join("src/a.txt")).await.unwrap().unwrap();
|
||||
assert_eq!((saved.files, saved.errors.len()), (2, 0), "{saved:?}");
|
||||
for target in [&staging, &live] {
|
||||
assert_eq!(std::fs::read_to_string(target.join("app/src/a.txt")).unwrap(), "v1");
|
||||
}
|
||||
std::fs::remove_file(root.join("src/a.txt")).unwrap();
|
||||
let deleted = service.on_deleted(&settings, &root, &[root.join("src/a.txt")]).await.unwrap().unwrap();
|
||||
assert!(deleted.errors.is_empty(), "{deleted:?}");
|
||||
assert!(!staging.join("app/src/a.txt").exists() && !live.join("app/src/a.txt").exists());
|
||||
}
|
||||
@@ -24,6 +24,8 @@ pub struct JvmPresentation {
|
||||
pub kind: Option<JvmTypeKind>,
|
||||
pub spring_boot: bool,
|
||||
pub runnable: bool,
|
||||
/// `@Deprecated`, or a Java `@deprecated` Javadoc tag.
|
||||
pub deprecated: bool,
|
||||
}
|
||||
|
||||
fn text<'a>(node: Node, source: &'a str) -> &'a str {
|
||||
@@ -139,6 +141,19 @@ pub fn jvm_type_header(source: &str) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The Javadoc right before `node` has a `@deprecated` block tag.
|
||||
fn javadoc_deprecated(node: Node, source: &str) -> bool {
|
||||
let Some(doc) = node.prev_named_sibling().filter(|n| n.kind() == "block_comment") else {
|
||||
return false;
|
||||
};
|
||||
let doc = text(doc, source);
|
||||
doc.starts_with("/**")
|
||||
&& doc.lines().any(|line| {
|
||||
let line = line.trim_start().trim_start_matches("/**").trim_start_matches('*').trim_start();
|
||||
line.strip_prefix("@deprecated").is_some_and(|rest| !rest.starts_with(|c: char| c.is_alphanumeric()))
|
||||
})
|
||||
}
|
||||
|
||||
fn is_type(node: Node) -> bool {
|
||||
matches!(
|
||||
node.kind(),
|
||||
@@ -221,7 +236,9 @@ impl StructureService {
|
||||
})
|
||||
})
|
||||
});
|
||||
Ok(JvmPresentation { kind: Some(kind), spring_boot, runnable })
|
||||
let deprecated = modifiers.is_some_and(|m| annotation(m, snap.text, "Deprecated"))
|
||||
|| cx.grammar == "java" && javadoc_deprecated(node, snap.text);
|
||||
Ok(JvmPresentation { kind: Some(kind), spring_boot, runnable, deprecated })
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -103,3 +103,29 @@ fn a_cut_off_file_is_classified_by_its_type_header() {
|
||||
let closed = format!("{}}}", jvm_type_header(cut).unwrap());
|
||||
assert_eq!(presentation("java", &closed).kind, Some(AbstractClass));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deprecated_primary_types() {
|
||||
for (language, source) in [
|
||||
("java", "@Deprecated public class Foo {}"),
|
||||
("java", "@java.lang.Deprecated(since = \"2\") interface Foo {}"),
|
||||
("java", "/**\n * Old.\n * @deprecated use Bar\n */\npublic class Foo {}"),
|
||||
("java", "/** @deprecated */ class Foo {}"),
|
||||
("kotlin", "@Deprecated(\"use Bar\") class Foo"),
|
||||
("kotlin", "@kotlin.Deprecated(\"x\", level = DeprecationLevel.ERROR) object Foo {}"),
|
||||
] {
|
||||
assert!(presentation(language, source).deprecated, "{language}: {source}");
|
||||
}
|
||||
for (language, source) in [
|
||||
("java", "public class Foo {}"),
|
||||
("java", "/* @deprecated */ class Foo {}"),
|
||||
("java", "// @Deprecated\nclass Foo {}"),
|
||||
("java", "/** See {@link Old}; @deprecatedSince is not a tag. */ class Foo {}"),
|
||||
("java", "class Foo { @Deprecated void old() {} }"),
|
||||
("java", "@Deprecated class Other {} class Foo {}"),
|
||||
("kotlin", "class Foo { @Deprecated(\"x\") fun old() {} }"),
|
||||
("kotlin", "/** @deprecated */ class Foo"),
|
||||
] {
|
||||
assert!(!presentation(language, source).deprecated, "{language}: {source}");
|
||||
}
|
||||
}
|
||||
@@ -768,6 +768,8 @@ pub struct Repo {
|
||||
git_dir: PathBuf,
|
||||
inner: std::sync::Mutex<repo::Cache>,
|
||||
ignored: std::sync::RwLock<IgnoredNames>,
|
||||
/// Working-tree status from `git status` instead of gitoxide.
|
||||
cli_status: std::sync::atomic::AtomicBool,
|
||||
log_index: std::sync::Mutex<log_index::LogIndex>,
|
||||
log_signatures: std::sync::Mutex<std::collections::HashMap<String, LogDetails>>,
|
||||
}
|
||||
@@ -794,6 +796,11 @@ impl Repo {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
*self.ignored.write().unwrap_or_else(|p| p.into_inner()) = names;
|
||||
}
|
||||
/// Read the working-tree status with `git status` rather than in process: for file systems
|
||||
/// (encryption or protection layers) whose metadata only the system git reads correctly.
|
||||
pub fn set_cli_status(&self, on: bool) {
|
||||
self.cli_status.store(on, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
/// Staged (HEAD↔index) and unstaged (index↔worktree, incl. untracked) changes,
|
||||
/// sorted by path. Conflicted files report `unstaged: Conflicted` and no staged kind.
|
||||
pub fn status(&self) -> IdeResult<Vec<FileStatus>> {
|
||||
@@ -1164,6 +1171,20 @@ impl Repo {
|
||||
Ok((out.code == Some(0)).then(|| out.stdout_str().trim().to_string()))
|
||||
}
|
||||
|
||||
/// Sets `user.name` and `user.email` for commits: in this repository's config, or in the
|
||||
/// user's global one (`global`).
|
||||
pub fn set_user_identity(&self, name: &str, email: &str, global: bool) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let scope = if global { "--global" } else { "--local" };
|
||||
for (key, value) in [("user.name", name.trim()), ("user.email", email.trim())] {
|
||||
if value.is_empty() {
|
||||
return Err(IdeError::invalid(format!("{key} must not be empty")));
|
||||
}
|
||||
cli::run(&self.root, &["config", scope, key, value], None)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- writes (git CLI) ----
|
||||
pub fn stage(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
|
||||
@@ -76,6 +76,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
git_dir,
|
||||
inner: std::sync::Mutex::new(cache),
|
||||
ignored: Default::default(),
|
||||
cli_status: Default::default(),
|
||||
log_index: Default::default(),
|
||||
log_signatures: Default::default(),
|
||||
}))
|
||||
|
||||
@@ -76,6 +76,29 @@ impl Repos {
|
||||
Ok(Self::new(Repo::discover(project_root)?.into_iter().collect(), project_root))
|
||||
}
|
||||
|
||||
/// Directory Mappings applied: the repositories at `excluded` roots are dropped (their
|
||||
/// files stay in the project) and those at `added` roots join, the primary one being the
|
||||
/// repository of `project_root` if it remains.
|
||||
pub fn mapped(&self, excluded: &[PathBuf], added: &[PathBuf], project_root: &Path) -> Self {
|
||||
let same = |a: &Path, b: &Path| a == b || dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
|
||||
let mut repos: Vec<Arc<Repo>> =
|
||||
self.repos.iter().filter(|r| !excluded.iter().any(|e| same(e, r.root()))).cloned().collect();
|
||||
for root in added {
|
||||
if excluded.iter().any(|e| same(e, root)) || repos.iter().any(|r| same(r.root(), root)) {
|
||||
continue;
|
||||
}
|
||||
match Repo::discover(root) {
|
||||
Ok(Some(r)) if same(r.root(), root) => repos.push(Arc::new(r)),
|
||||
Ok(_) => tracing::debug!("mapped directory {} is not a git root", root.display()),
|
||||
Err(e) => tracing::debug!("mapped directory {}: {}", root.display(), e.message),
|
||||
}
|
||||
}
|
||||
repos.sort_by(|a, b| a.root().cmp(b.root()));
|
||||
let roots: Vec<&Path> = repos.iter().map(|r| r.root()).collect();
|
||||
let primary = innermost(&roots, project_root, false).or((!repos.is_empty()).then_some(0));
|
||||
Self { repos, primary }
|
||||
}
|
||||
|
||||
/// Worktree roots, sorted.
|
||||
pub fn roots(&self) -> Vec<PathBuf> {
|
||||
self.repos.iter().map(|r| r.root().to_path_buf()).collect()
|
||||
@@ -222,6 +245,34 @@ mod tests {
|
||||
assert!(ok, "git init in {}", dir.display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_mappings_exclude_and_add_repositories() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
let outside = root.parent().unwrap().join("sdk");
|
||||
git_init(&root);
|
||||
git_init(&root.join("app"));
|
||||
git_init(&root.join("reference-sdk"));
|
||||
git_init(&root.join("a/b/c/d/deep"));
|
||||
git_init(&outside);
|
||||
|
||||
let detected = Repos::discover(&root, &|_| false).unwrap();
|
||||
let mapped =
|
||||
detected.mapped(&[root.join("reference-sdk")], &[outside.clone(), root.join("a/b/c/d/deep")], &root);
|
||||
let roots: Vec<&Path> = mapped.all().iter().map(|r| r.root()).collect();
|
||||
assert_eq!(roots, [root.as_path(), &root.join("a/b/c/d/deep"), &root.join("app"), &outside]);
|
||||
assert_eq!(mapped.primary().unwrap().root(), root);
|
||||
// The excluded repository's files belong to the enclosing one again.
|
||||
assert_eq!(mapped.for_path(&root.join("reference-sdk/lib.rs")).unwrap().root(), root);
|
||||
|
||||
// The project root excluded: only the other repositories remain; a folder that is no
|
||||
// repository root is not added.
|
||||
let without_root = detected.mapped(std::slice::from_ref(&root), &[root.join("a")], &root);
|
||||
let roots: Vec<&Path> = without_root.all().iter().map(|r| r.root()).collect();
|
||||
assert_eq!(roots, [&root.join("app"), &root.join("reference-sdk")]);
|
||||
assert!(without_root.for_path(&root.join("README.md")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_nested_repositories_and_routes_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -20,10 +20,14 @@ pub(crate) fn status(r: &Repo) -> IdeResult<Vec<FileStatus>> {
|
||||
let ignored = r.ignored.read().unwrap_or_else(|p| p.into_inner()).clone();
|
||||
// gitoxide stops at the first IO error (a directory it may not read), where git warns
|
||||
// and lists the rest: git answers then.
|
||||
let (map, conflicts) = gix_status(r, &ignored).or_else(|e| {
|
||||
tracing::debug!("status via gitoxide failed, asking git: {}", e.message);
|
||||
cli_status(r, &ignored)
|
||||
})?;
|
||||
let (map, conflicts) = if r.cli_status.load(std::sync::atomic::Ordering::Acquire) {
|
||||
cli_status(r, &ignored)?
|
||||
} else {
|
||||
gix_status(r, &ignored).or_else(|e| {
|
||||
tracing::debug!("status via gitoxide failed, asking git: {}", e.message);
|
||||
cli_status(r, &ignored)
|
||||
})?
|
||||
};
|
||||
Ok(collect(r, &ignored, map, conflicts))
|
||||
}
|
||||
|
||||
|
||||
@@ -2252,3 +2252,39 @@ fn status_paths_reads_only_the_named_paths() {
|
||||
// An empty list is the full status, so a caller that lost the paths stays correct.
|
||||
assert_eq!(repo.status_paths(&[]).unwrap().len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_the_commit_identity_in_the_repository() {
|
||||
let fx = Fixture::new();
|
||||
fx.git(&["config", "--unset", "user.name"]);
|
||||
fx.git(&["config", "--unset", "user.email"]);
|
||||
let repo = fx.repo();
|
||||
repo.set_user_identity(" Ada Lovelace ", "[email protected]", false).unwrap();
|
||||
assert_eq!(fx.git(&["config", "--local", "user.name"]), "Ada Lovelace");
|
||||
assert_eq!(fx.git(&["config", "--local", "user.email"]), "[email protected]");
|
||||
assert_eq!(repo.config_get("user.email").unwrap().as_deref(), Some("[email protected]"));
|
||||
let blank = repo.set_user_identity("Ada", " ", false).unwrap_err();
|
||||
assert_eq!(blank.kind, ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_from_the_git_command_line_matches_the_in_process_one() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "a\n");
|
||||
fx.write("staged.txt", "a\n");
|
||||
fx.write("gone.txt", "a\n");
|
||||
fx.commit_all("base");
|
||||
fx.write("a.txt", "b\n");
|
||||
fx.write("staged.txt", "b\n");
|
||||
fx.git(&["add", "staged.txt"]);
|
||||
std::fs::remove_file(fx.path("gone.txt")).unwrap();
|
||||
fx.write("dir/new.txt", "n\n");
|
||||
let repo = fx.repo();
|
||||
repo.set_ignored_names(ide_core::settings::Settings::default().ignored_names());
|
||||
let show = |s: Vec<FileStatus>| s.into_iter().map(|f| (f.rel_path, f.staged, f.unstaged)).collect::<Vec<_>>();
|
||||
let in_process = show(repo.status().unwrap());
|
||||
repo.set_cli_status(true);
|
||||
let from_git = show(repo.status().unwrap());
|
||||
assert_eq!(from_git, in_process);
|
||||
assert_eq!(from_git.len(), 4, "{from_git:#?}");
|
||||
}
|
||||
@@ -17,6 +17,31 @@ fn exists(path: &Path) -> bool {
|
||||
fs::symlink_metadata(path).is_ok()
|
||||
}
|
||||
|
||||
fn validate_destination(path: &Path) -> IdeResult<()> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::path::Component;
|
||||
|
||||
if matches!(path.components().next(), Some(Component::Prefix(prefix)) if prefix.kind().is_verbatim()) {
|
||||
return Ok(());
|
||||
}
|
||||
// Win32 can silently strip trailing periods and spaces when resolving a path.
|
||||
for component in path.components() {
|
||||
if let Component::Normal(name) = component
|
||||
&& matches!(name.as_encoded_bytes().last(), Some(b'.' | b' '))
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Windows file and folder names cannot end with a period or space ({:?})",
|
||||
name,
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = path;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_parent(path: &Path) -> IdeResult<()> {
|
||||
if let Some(parent) = path.parent()
|
||||
&& !parent.as_os_str().is_empty()
|
||||
@@ -27,16 +52,12 @@ fn ensure_parent(path: &Path) -> IdeResult<()> {
|
||||
}
|
||||
|
||||
pub(crate) fn create_file(path: &Path) -> IdeResult<()> {
|
||||
if exists(path) {
|
||||
return Err(already_exists(path));
|
||||
}
|
||||
ensure_parent(path)?;
|
||||
fs::OpenOptions::new().write(true).create_new(true).open(path)?;
|
||||
Ok(())
|
||||
create_file_bytes(path, &[])
|
||||
}
|
||||
|
||||
pub(crate) fn create_file_bytes(path: &Path, data: &[u8]) -> IdeResult<()> {
|
||||
use std::io::Write;
|
||||
validate_destination(path)?;
|
||||
if exists(path) {
|
||||
return Err(already_exists(path));
|
||||
}
|
||||
@@ -64,6 +85,7 @@ pub(crate) fn set_writable(path: &Path, writable: bool) -> IdeResult<()> {
|
||||
}
|
||||
|
||||
pub(crate) fn create_dir(path: &Path) -> IdeResult<()> {
|
||||
validate_destination(path)?;
|
||||
if exists(path) {
|
||||
return Err(already_exists(path));
|
||||
}
|
||||
@@ -95,6 +117,7 @@ pub(crate) fn validate_rename(from: &Path, to: &Path) -> IdeResult<()> {
|
||||
if from == to {
|
||||
return Ok(());
|
||||
}
|
||||
validate_destination(to)?;
|
||||
// A case-only rename on a case-insensitive file system sees `to` as existing.
|
||||
if exists(to) && !same_file(from, to) {
|
||||
return Err(already_exists(to));
|
||||
@@ -151,6 +174,7 @@ pub(crate) fn delete(path: &Path, use_trash: bool) -> IdeResult<()> {
|
||||
|
||||
pub(crate) fn copy(from: &Path, to: &Path) -> IdeResult<()> {
|
||||
let meta = fs::symlink_metadata(from).map_err(|_| not_found(from))?;
|
||||
validate_destination(to)?;
|
||||
if exists(to) {
|
||||
return Err(already_exists(to));
|
||||
}
|
||||
|
||||
@@ -428,6 +428,54 @@ fn create_file_bytes_creates_parents() {
|
||||
assert_eq!(std::fs::read(path).unwrap(), [0, 255]);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_file_operations_reject_ambiguous_destinations_before_mutating() {
|
||||
let (_tmp, root) = root();
|
||||
let source = root.join("source.txt");
|
||||
write(&source, "original");
|
||||
|
||||
for name in ["example.txt.", "example.txt ", "first/nested./child", "first/nested /child"] {
|
||||
let destination = root.join(name);
|
||||
for result in [
|
||||
create_file(&destination),
|
||||
create_file_bytes(&destination, b"new"),
|
||||
create_dir(&destination),
|
||||
validate_rename(&source, &destination),
|
||||
rename(&source, &destination),
|
||||
copy(&source, &destination),
|
||||
] {
|
||||
assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidInput, "{name:?}");
|
||||
}
|
||||
let names: Vec<_> = fs::read_dir(&root).unwrap().map(|entry| entry.unwrap().file_name()).collect();
|
||||
assert_eq!(names, ["source.txt"], "{name:?}");
|
||||
assert_eq!(fs::read(&source).unwrap(), b"original");
|
||||
}
|
||||
|
||||
create_file(&root.join(".config.d/file.txt")).unwrap();
|
||||
assert!(root.join(".config.d/file.txt").is_file());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn create_file_preserves_literal_verbatim_path() {
|
||||
let (_tmp, root) = root();
|
||||
let path = fs::canonicalize(&root).unwrap().join("example.txt.");
|
||||
create_file(&path).unwrap();
|
||||
assert!(path.is_file());
|
||||
assert!(!root.join("example.txt").exists());
|
||||
fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn create_file_preserves_trailing_dots_and_spaces() {
|
||||
let (_tmp, root) = root();
|
||||
let path = root.join("folder./example.txt ");
|
||||
create_file(&path).unwrap();
|
||||
assert!(path.is_file());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn create_file_bytes_does_not_follow_existing_symlink() {
|
||||
|
||||
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -30,6 +30,35 @@ pub struct HistoryEntry {
|
||||
pub size: u64,
|
||||
#[serde(default)]
|
||||
pub kind: HistoryKind,
|
||||
/// Exact on-disk bytes for Undo when document text omits a BOM or line endings.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(skip)]
|
||||
undo_blob: Option<UndoBlob>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
struct UndoBlob {
|
||||
id: String,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
impl HistoryEntry {
|
||||
fn snapshot(path: &Path, text: &str, label: &str, timestamp_ms: f64) -> Self {
|
||||
Self {
|
||||
id: blake3::hash(text.as_bytes()).to_hex().to_string(),
|
||||
path: path.into(),
|
||||
timestamp_ms,
|
||||
label: label.to_owned(),
|
||||
size: text.len() as u64,
|
||||
kind: HistoryKind::Snapshot,
|
||||
undo_blob: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn blobs(&self) -> impl Iterator<Item = (&str, u64)> {
|
||||
std::iter::once((self.id.as_str(), self.size))
|
||||
.chain(self.undo_blob.iter().map(|blob| (blob.id.as_str(), blob.size)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes under a folder (Show History on a directory).
|
||||
@@ -42,6 +71,23 @@ pub struct DirectoryHistory {
|
||||
pub deleted: Vec<ide_core::IpcPath>,
|
||||
}
|
||||
|
||||
/// Paths and contents captured for one delete operation. Directory history is
|
||||
/// intentionally broader and can contain paths deleted in an earlier operation.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeletionUndo {
|
||||
directories: Vec<ide_core::IpcPath>,
|
||||
files: Vec<DeletedFile>,
|
||||
skipped: Vec<ide_core::IpcPath>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeletedFile {
|
||||
path: ide_core::IpcPath,
|
||||
id: String,
|
||||
}
|
||||
|
||||
/// How much history is kept (Settings › Advanced › Local History).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Retention {
|
||||
@@ -108,22 +154,56 @@ fn valid_id(id: &str) -> bool {
|
||||
|
||||
fn valid_entry(e: &HistoryEntry) -> bool {
|
||||
match e.kind {
|
||||
HistoryKind::Snapshot => valid_id(&e.id),
|
||||
HistoryKind::Snapshot => valid_id(&e.id) && e.undo_blob.as_ref().is_none_or(|blob| valid_id(&blob.id)),
|
||||
HistoryKind::Label => e.id.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text of a file for an automatic snapshot: small, non-binary files only.
|
||||
fn read_snapshot_text(path: &Path) -> Option<String> {
|
||||
read_snapshot_disk_text(path).map(|text| document_text(&text).into_owned())
|
||||
}
|
||||
|
||||
fn read_snapshot_disk_text(path: &Path) -> Option<String> {
|
||||
let meta = fs::metadata(path).ok()?;
|
||||
if !meta.is_file() || meta.len() > AUTO_SNAPSHOT_LIMIT {
|
||||
return None;
|
||||
}
|
||||
let bytes = fs::read(path).ok()?;
|
||||
if bytes.iter().take(8192).any(|b| *b == 0) {
|
||||
let mut bytes = Vec::new();
|
||||
fs::File::open(path).ok()?.take(AUTO_SNAPSHOT_LIMIT + 1).read_to_end(&mut bytes).ok()?;
|
||||
if bytes.len() as u64 > AUTO_SNAPSHOT_LIMIT || bytes.iter().take(8192).any(|b| *b == 0) {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(bytes).ok().map(|text| document_text(&text).into_owned())
|
||||
String::from_utf8(bytes).ok()
|
||||
}
|
||||
|
||||
/// Directory junctions and similar reparse points must not be traversed.
|
||||
fn is_link(metadata: &fs::Metadata) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
metadata.file_attributes() & 0x400 != 0
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
metadata.file_type().is_symlink()
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_deleted_bytes(path: &Path, bytes: &[u8]) -> IdeResult<()> {
|
||||
let parent = path.parent().ok_or_else(|| IdeError::invalid("missing parent for deleted file"))?;
|
||||
// Publish only a complete file, and never replace a new file at that path.
|
||||
let mut builder = tempfile::Builder::new();
|
||||
builder.prefix(".undo.openidea-tmp-");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
builder.permissions(fs::Permissions::from_mode(0o666));
|
||||
}
|
||||
let mut pending = builder.tempfile_in(parent)?;
|
||||
pending.write_all(bytes)?;
|
||||
pending.persist_noclobber(path).map_err(|error| error.error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `text` as a document holds it: without the UTF-8 BOM and with `\n` line endings. Saves
|
||||
@@ -191,55 +271,60 @@ impl LocalHistory {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self, path: &Path, content: &str, label: &str, force: bool) -> IdeResult<()> {
|
||||
let id = blake3::hash(content.as_bytes()).to_hex().to_string();
|
||||
let mut state = self.state.lock();
|
||||
if !force && state.last.get(path) == Some(&id) {
|
||||
return Ok(());
|
||||
/// Called with the history lock held, so prune cannot remove a blob before its entry exists.
|
||||
fn store_blob(&self, id: &str, bytes: &[u8]) -> IdeResult<()> {
|
||||
let blob = self.blob_path(id);
|
||||
if !blob.exists() {
|
||||
fs::create_dir_all(blob.parent().expect("blob has a parent"))?;
|
||||
ide_vfs::write_atomic(&blob, bytes)?;
|
||||
}
|
||||
self.store_locked(&mut state, path, id, content, label, now_ms())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self, path: &Path, content: &str, label: &str, force: bool, original: Option<&str>) -> IdeResult<String> {
|
||||
let mut state = self.state.lock();
|
||||
let entry = HistoryEntry::snapshot(path, content, label, now_ms());
|
||||
if !force && state.last.get(path) == Some(&entry.id) {
|
||||
return Ok(entry.id);
|
||||
}
|
||||
self.store_locked(&mut state, entry, content, original)
|
||||
}
|
||||
|
||||
fn store_locked(
|
||||
&self,
|
||||
state: &mut HistoryState,
|
||||
path: &Path,
|
||||
id: String,
|
||||
mut entry: HistoryEntry,
|
||||
content: &str,
|
||||
label: &str,
|
||||
timestamp_ms: f64,
|
||||
) -> IdeResult<()> {
|
||||
let blob = self.blob_path(&id);
|
||||
if !blob.exists() {
|
||||
fs::create_dir_all(blob.parent().expect("blob has a parent"))?;
|
||||
ide_vfs::write_atomic(&blob, content.as_bytes())?;
|
||||
}
|
||||
let entry = HistoryEntry {
|
||||
id,
|
||||
path: path.into(),
|
||||
timestamp_ms,
|
||||
label: label.to_owned(),
|
||||
size: content.len() as u64,
|
||||
kind: HistoryKind::Snapshot,
|
||||
original: Option<&str>,
|
||||
) -> IdeResult<String> {
|
||||
self.store_blob(&entry.id, content.as_bytes())?;
|
||||
entry.undo_blob = if let Some(original) = original.filter(|text| *text != content) {
|
||||
let id = blake3::hash(original.as_bytes()).to_hex().to_string();
|
||||
self.store_blob(&id, original.as_bytes())?;
|
||||
Some(UndoBlob { id, size: original.len() as u64 })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.append(state, entry)
|
||||
let undo_id = entry.undo_blob.as_ref().map_or_else(|| entry.id.clone(), |blob| blob.id.clone());
|
||||
self.append(state, entry)?;
|
||||
Ok(undo_id)
|
||||
}
|
||||
|
||||
/// Records a snapshot unless it equals the latest one recorded for `path`.
|
||||
pub fn record(&self, path: &Path, content: &str, label: &str) -> IdeResult<()> {
|
||||
self.store(path, content, label, false)
|
||||
self.store(path, content, label, false, None).map(|_| ())
|
||||
}
|
||||
|
||||
/// Records a snapshot even when the content did not change, so the event
|
||||
/// ("Deleted", "Before refactoring: Move") shows in the history.
|
||||
pub fn record_event(&self, path: &Path, content: &str, label: &str) -> IdeResult<()> {
|
||||
self.store(path, content, label, true)
|
||||
self.store(path, content, label, true, None).map(|_| ())
|
||||
}
|
||||
|
||||
/// Snapshots the file on disk (small text files only); `force` as in [`record_event`](Self::record_event).
|
||||
pub fn record_file(&self, path: &Path, label: &str, force: bool) -> IdeResult<bool> {
|
||||
match read_snapshot_text(path) {
|
||||
Some(text) => self.store(path, &text, label, force).map(|()| true),
|
||||
Some(text) => self.store(path, &text, label, force, None).map(|_| true),
|
||||
None => Ok(false),
|
||||
}
|
||||
}
|
||||
@@ -265,8 +350,8 @@ impl LocalHistory {
|
||||
(Some(modified), Some(oldest)) => modified.max(oldest - 1.0).min(now),
|
||||
_ => now,
|
||||
};
|
||||
let id = blake3::hash(text.as_bytes()).to_hex().to_string();
|
||||
self.store_locked(&mut state, path, id, &text, ORIGINAL, timestamp).map(|()| true)
|
||||
let entry = HistoryEntry::snapshot(path, &text, ORIGINAL, timestamp);
|
||||
self.store_locked(&mut state, entry, &text, None).map(|_| true)
|
||||
}
|
||||
|
||||
/// Snapshots `path`, or every file below it when it is a folder (at most `limit`
|
||||
@@ -290,6 +375,92 @@ impl LocalHistory {
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Captures only paths that belong to this delete, including empty folders.
|
||||
/// The backup observes the same content limit as automatic history, but
|
||||
/// keeps exact bytes so a recreated file does not pick up new file defaults.
|
||||
pub fn capture_deletion_undo(&self, paths: &[PathBuf], limit: usize) -> DeletionUndo {
|
||||
let mut undo = DeletionUndo::default();
|
||||
let mut remaining = limit;
|
||||
for path in paths {
|
||||
self.capture_deleted_entry(path, &mut remaining, &mut undo);
|
||||
}
|
||||
undo
|
||||
}
|
||||
|
||||
fn capture_deleted_entry(&self, path: &Path, remaining: &mut usize, undo: &mut DeletionUndo) {
|
||||
if *remaining == 0 {
|
||||
undo.skipped.push(path.into());
|
||||
return;
|
||||
}
|
||||
*remaining -= 1;
|
||||
|
||||
let Ok(metadata) = fs::symlink_metadata(path) else {
|
||||
undo.skipped.push(path.into());
|
||||
return;
|
||||
};
|
||||
if is_link(&metadata) {
|
||||
undo.skipped.push(path.into());
|
||||
} else if metadata.is_dir() {
|
||||
if path.file_name().is_some_and(|name| name == ".git") {
|
||||
undo.skipped.push(path.into());
|
||||
return;
|
||||
}
|
||||
undo.directories.push(path.into());
|
||||
let Ok(entries) = fs::read_dir(path) else {
|
||||
undo.skipped.push(path.into());
|
||||
return;
|
||||
};
|
||||
for entry in entries {
|
||||
if *remaining == 0 {
|
||||
// Identify the unscanned subtree without enumerating the rest of it.
|
||||
undo.skipped.push(path.into());
|
||||
break;
|
||||
}
|
||||
if let Ok(entry) = entry {
|
||||
self.capture_deleted_entry(&entry.path(), remaining, undo);
|
||||
} else if !undo.skipped.iter().any(|entry| entry.as_ref() == path) {
|
||||
undo.skipped.push(path.into());
|
||||
}
|
||||
}
|
||||
} else if let Some(id) = read_snapshot_disk_text(path)
|
||||
.and_then(|raw| self.store(path, &document_text(&raw), DELETED, true, Some(&raw)).ok())
|
||||
{
|
||||
undo.files.push(DeletedFile { path: path.into(), id });
|
||||
} else {
|
||||
undo.skipped.push(path.into());
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns entries the caller should direct the user to recover from the
|
||||
/// system Trash. A newly occupied path and its subtree are left alone.
|
||||
pub fn restore_deletion_undo(&self, undo: DeletionUndo) -> Vec<ide_core::IpcPath> {
|
||||
let mut skipped = undo.skipped;
|
||||
let mut blocked: Vec<ide_core::IpcPath> = Vec::new();
|
||||
for path in undo.directories {
|
||||
if blocked.iter().any(|parent| path.starts_with(parent)) {
|
||||
continue;
|
||||
}
|
||||
if let Err(error) = fs::create_dir(&*path) {
|
||||
tracing::debug!("cannot restore deleted directory {}: {error}", path.display());
|
||||
skipped.push(path.clone());
|
||||
blocked.push(path);
|
||||
}
|
||||
}
|
||||
for file in undo.files {
|
||||
if blocked.iter().any(|parent| file.path.starts_with(parent)) {
|
||||
continue;
|
||||
}
|
||||
let restored = self.read_blob(&file.id).and_then(|bytes| restore_deleted_bytes(&file.path, &bytes));
|
||||
if let Err(error) = restored {
|
||||
tracing::debug!("cannot restore deleted file {}: {error}", file.path.display());
|
||||
skipped.push(file.path);
|
||||
}
|
||||
}
|
||||
skipped.sort();
|
||||
skipped.dedup();
|
||||
skipped
|
||||
}
|
||||
|
||||
/// The watcher saw `paths` disappear: files with history that are gone get a
|
||||
/// "Deleted" entry pointing at their last content (unless one was recorded already).
|
||||
pub fn note_removed(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
@@ -315,6 +486,7 @@ impl LocalHistory {
|
||||
label: DELETED.into(),
|
||||
size,
|
||||
kind: HistoryKind::Snapshot,
|
||||
undo_blob: None,
|
||||
};
|
||||
self.append(&mut state, entry)?;
|
||||
}
|
||||
@@ -334,6 +506,7 @@ impl LocalHistory {
|
||||
label: label.to_owned(),
|
||||
size: 0,
|
||||
kind: HistoryKind::Label,
|
||||
undo_blob: None,
|
||||
};
|
||||
let mut state = self.state.lock();
|
||||
self.append(&mut state, entry)
|
||||
@@ -379,15 +552,12 @@ impl LocalHistory {
|
||||
Ok(DirectoryHistory { entries, deleted })
|
||||
}
|
||||
|
||||
pub fn content(&self, id: &str) -> IdeResult<String> {
|
||||
fn read_blob(&self, id: &str) -> IdeResult<Vec<u8>> {
|
||||
if !valid_id(id) {
|
||||
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
|
||||
}
|
||||
match fs::read(self.blob_path(id)) {
|
||||
Ok(bytes) => {
|
||||
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
|
||||
Ok(document_text(&text).into_owned())
|
||||
}
|
||||
Ok(bytes) => Ok(bytes),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
Err(IdeError::not_found(format!("history snapshot {id} not found")))
|
||||
}
|
||||
@@ -395,11 +565,24 @@ impl LocalHistory {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn content(&self, id: &str) -> IdeResult<String> {
|
||||
let bytes = self.read_blob(id)?;
|
||||
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
|
||||
Ok(document_text(&text).into_owned())
|
||||
}
|
||||
|
||||
/// Bytes stored in blobs.
|
||||
pub fn stored_bytes(&self) -> u64 {
|
||||
let state = self.state.lock();
|
||||
let mut seen = HashSet::new();
|
||||
state.entries.iter().filter(|e| e.kind == HistoryKind::Snapshot && seen.insert(&e.id)).map(|e| e.size).sum()
|
||||
state
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| e.kind == HistoryKind::Snapshot)
|
||||
.flat_map(HistoryEntry::blobs)
|
||||
.filter(|(id, _)| seen.insert(*id))
|
||||
.map(|(_, size)| size)
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Drops entries older than `max_age_days` calendar days and unreferenced blobs.
|
||||
@@ -430,7 +613,7 @@ impl LocalHistory {
|
||||
}
|
||||
ide_vfs::write_atomic(&self.index_path(), text.as_bytes())?;
|
||||
|
||||
let referenced: HashSet<&str> = kept.iter().map(|e| e.id.as_str()).collect();
|
||||
let referenced: HashSet<&str> = kept.iter().flat_map(HistoryEntry::blobs).map(|(id, _)| id).collect();
|
||||
for shard in fs::read_dir(self.dir.join("blobs"))?.flatten() {
|
||||
let Ok(files) = fs::read_dir(shard.path()) else { continue };
|
||||
let mut remaining = 0usize;
|
||||
@@ -467,8 +650,8 @@ fn retain(entries: Vec<HistoryEntry>, retention: Retention) -> Vec<HistoryEntry>
|
||||
};
|
||||
// Size bound: unique blob bytes, oldest snapshots dropped first.
|
||||
let mut refs: HashMap<String, (usize, u64)> = HashMap::new();
|
||||
for e in kept.iter().filter(|e| e.kind == HistoryKind::Snapshot) {
|
||||
refs.entry(e.id.clone()).or_insert((0, e.size)).0 += 1;
|
||||
for (id, size) in kept.iter().filter(|e| e.kind == HistoryKind::Snapshot).flat_map(HistoryEntry::blobs) {
|
||||
refs.entry(id.to_owned()).or_insert((0, size)).0 += 1;
|
||||
}
|
||||
let mut total: u64 = refs.values().map(|(_, size)| size).sum();
|
||||
if total <= retention.max_bytes {
|
||||
@@ -482,10 +665,12 @@ fn retain(entries: Vec<HistoryEntry>, retention: Retention) -> Vec<HistoryEntry>
|
||||
break;
|
||||
}
|
||||
drop[i] = true;
|
||||
let r = refs.get_mut(&kept[i].id).expect("counted");
|
||||
r.0 -= 1;
|
||||
if r.0 == 0 {
|
||||
total -= r.1;
|
||||
for (id, _) in kept[i].blobs() {
|
||||
let r = refs.get_mut(id).expect("counted");
|
||||
r.0 -= 1;
|
||||
if r.0 == 0 {
|
||||
total -= r.1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut i = 0;
|
||||
@@ -578,6 +763,7 @@ mod tests {
|
||||
label: "Saved".into(),
|
||||
size,
|
||||
kind,
|
||||
undo_blob: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -660,6 +846,78 @@ mod tests {
|
||||
assert_eq!(h.stored_bytes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_undo_captures_current_bytes_and_empty_folders() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let folder = root.join("subject");
|
||||
let empty = folder.join("empty-child/leaf");
|
||||
fs::create_dir_all(&empty).unwrap();
|
||||
let history = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let obsolete = folder.join("obsolete.txt");
|
||||
fs::write(&obsolete, "deleted before the folder").unwrap();
|
||||
history.capture_deletion_undo(std::slice::from_ref(&obsolete), 100);
|
||||
fs::remove_file(&obsolete).unwrap();
|
||||
let current = folder.join("current.txt");
|
||||
let original = b"\xEF\xBB\xBFheader\r\nbody\n";
|
||||
fs::write(¤t, original).unwrap();
|
||||
history.record(¤t, "header\nbody\n", "Saved").unwrap();
|
||||
let large = folder.join("sample.bin");
|
||||
fs::write(&large, vec![0; 2_300_000]).unwrap();
|
||||
|
||||
let undo = history.capture_deletion_undo(std::slice::from_ref(&folder), 100);
|
||||
let revisions = history.list(¤t).unwrap();
|
||||
assert!(revisions.iter().any(|entry| entry.label == DELETED));
|
||||
assert_eq!(revisions[0].id, revisions[1].id, "visible revisions share the normalized content");
|
||||
let blob = undo.files[0].id.clone();
|
||||
assert_ne!(blob, revisions[0].id);
|
||||
assert_eq!(
|
||||
history.stored_bytes(),
|
||||
("deleted before the folder".len() + "header\nbody\n".len() + original.len()) as u64
|
||||
);
|
||||
history.apply_retention(Retention::default()).unwrap();
|
||||
fs::remove_dir_all(&folder).unwrap();
|
||||
assert_eq!(history.restore_deletion_undo(undo), vec![large]);
|
||||
assert_eq!(fs::read(¤t).unwrap(), original);
|
||||
assert!(empty.is_dir());
|
||||
assert!(!obsolete.exists());
|
||||
history.clear().unwrap();
|
||||
assert!(!history.blob_path(&blob).exists(), "pruning removes the exact bytes too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_undo_preserves_new_files_and_reports_unavailable_entries() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let folder = root.join("folder");
|
||||
fs::create_dir_all(&folder).unwrap();
|
||||
let history = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let file = folder.join("old.txt");
|
||||
fs::write(&file, "before deletion").unwrap();
|
||||
|
||||
let undo = history.capture_deletion_undo(std::slice::from_ref(&folder), 100);
|
||||
fs::remove_dir_all(&folder).unwrap();
|
||||
fs::create_dir_all(&folder).unwrap();
|
||||
fs::write(&file, "recreated").unwrap();
|
||||
assert_eq!(history.restore_deletion_undo(undo), vec![folder.clone()]);
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), "recreated");
|
||||
|
||||
let file_only = history.capture_deletion_undo(std::slice::from_ref(&file), 100);
|
||||
fs::write(&file, "new contents").unwrap();
|
||||
assert_eq!(history.restore_deletion_undo(file_only), vec![file.clone()]);
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), "new contents");
|
||||
|
||||
let limited = history.capture_deletion_undo(std::slice::from_ref(&folder), 1);
|
||||
assert_eq!(limited.skipped, vec![folder]);
|
||||
assert!(limited.files.is_empty());
|
||||
|
||||
let expired = history.capture_deletion_undo(std::slice::from_ref(&file), 100);
|
||||
fs::remove_file(&file).unwrap();
|
||||
history.clear().unwrap();
|
||||
assert_eq!(history.restore_deletion_undo(expired), vec![file.clone()]);
|
||||
assert!(!file.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retention_keeps_working_days_and_bounds_size() {
|
||||
let id = |c: char| c.to_string().repeat(64);
|
||||
|
||||
@@ -25,7 +25,7 @@ pub use documents::{DetectLanguage, DocumentEncoding, DocumentInfo, DocumentLang
|
||||
pub use editorconfig::{EditorConfig, EditorConfigProps};
|
||||
pub use file_defaults::FileDefaults;
|
||||
pub use file_moves::{FileMove, FileMoves, UndoOutcome};
|
||||
pub use history::{DirectoryHistory, HistoryEntry, HistoryKind, LocalHistory, Retention};
|
||||
pub use history::{DeletionUndo, DirectoryHistory, HistoryEntry, HistoryKind, LocalHistory, Retention};
|
||||
pub use recent::{RecentProject, RecentProjectGroup, RecentProjects};
|
||||
pub use roots::{ProjectRoots, RootKind, SourceFolder};
|
||||
pub use settings::{SettingsScope, SettingsStore};
|
||||
|
||||
@@ -47,13 +47,19 @@ The Windows packages aren't code-signed yet, so Microsoft Defender SmartScreen m
|
||||
|
||||
## The window stays blank or stops responding on Linux
|
||||
|
||||
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal with the DMA-BUF renderer turned off, for example:
|
||||
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal through XWayland first:
|
||||
|
||||
```sh
|
||||
GDK_BACKEND=x11 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
The page is still drawn on the GPU this way; at a fractional display scale the window may look less sharp. If that does not help, turn the DMA-BUF renderer off instead:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
The page is then drawn without the GPU, so dragging large panels can be slower. To keep the setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line to `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`.
|
||||
The page is then drawn without the GPU, so dragging large panels can be slower. To keep either setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line, for example to `Exec=env GDK_BACKEND=x11 openidea`.
|
||||
|
||||
## OpenIDEA exits at startup with a data directory error
|
||||
|
||||
|
||||
@@ -47,13 +47,19 @@ Windows 安装包目前还没有代码签名,Microsoft Defender SmartScreen
|
||||
|
||||
## Linux 上窗口空白或无响应
|
||||
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中关闭 DMA-BUF 渲染器启动,例如:
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中通过 XWayland 启动:
|
||||
|
||||
```sh
|
||||
GDK_BACKEND=x11 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
这样页面仍由 GPU 绘制;在非整数缩放比例下,窗口可能不够清晰。如果仍有问题,改为关闭 DMA-BUF 渲染器启动:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上这个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并把其中的 `Exec=` 一行改成 `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`。
|
||||
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上其中一个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并修改其中的 `Exec=` 一行,例如改成 `Exec=env GDK_BACKEND=x11 openidea`。
|
||||
|
||||
## 启动时提示数据目录错误并退出
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ async function stubRepository(page: Page) {
|
||||
h.vcs_status = () => (committed ? [] : changes);
|
||||
h.vcs_stage = () => null;
|
||||
h.vcs_unstage = () => null;
|
||||
h.vcs_config_get = () => "configured";
|
||||
h.vcs_commit = () => {
|
||||
committed = true;
|
||||
return "2222222";
|
||||
|
||||
@@ -34,6 +34,7 @@ async function stubTwentyChanges(page: Page) {
|
||||
h.vcs_status = () => all.filter((f) => !committed.has(f.path));
|
||||
h.vcs_stage = () => null;
|
||||
h.vcs_unstage = () => null;
|
||||
h.vcs_config_get = () => "configured";
|
||||
h.vcs_commit = (args) => {
|
||||
for (const path of (args.options as { stage: string[] }).stage) committed.add(path);
|
||||
return "2222222";
|
||||
|
||||
@@ -1,5 +1,58 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("records double-modifier gestures in the shortcut filter and assignment dialog", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
|
||||
const filterToggle = settings.getByRole("button", { name: "Find Actions by Shortcut", exact: true });
|
||||
await filterToggle.click();
|
||||
const filter = settings.getByRole("textbox", { name: "Find actions by shortcut", exact: true });
|
||||
await expect(filter).toBeFocused();
|
||||
await page.keyboard.press("Shift");
|
||||
await page.keyboard.press("Control");
|
||||
await page.keyboard.press("Shift");
|
||||
await expect(filter).toHaveText("Press a shortcut to find actions");
|
||||
await page.keyboard.press("Shift");
|
||||
await expect(filter).toHaveText("⇧⇧");
|
||||
const actions = settings.getByRole("tree", { name: "Actions" });
|
||||
await expect(actions.getByRole("treeitem", { name: /Search Everywhere/ })).toBeVisible();
|
||||
await expect(actions.getByRole("treeitem", { name: /Find Action/ })).toHaveCount(0);
|
||||
|
||||
await filterToggle.click();
|
||||
await settings.getByRole("textbox", { name: "Search actions" }).fill("Find Action");
|
||||
await actions.getByRole("treeitem", { name: /Find Action/ }).click();
|
||||
await settings.getByRole("button", { name: "Add Keyboard Shortcut", exact: true }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "Keyboard Shortcut: Find Action…", exact: true });
|
||||
const first = dialog.getByRole("textbox", { name: "First stroke" });
|
||||
const secondToggle = dialog.getByRole("checkbox", { name: "Second stroke:" });
|
||||
const ok = dialog.getByRole("button", { name: "OK", exact: true });
|
||||
await secondToggle.click();
|
||||
await first.click();
|
||||
await page.keyboard.press("Control");
|
||||
await page.keyboard.press("Control");
|
||||
await expect(first).toHaveText("⌃⌃");
|
||||
await expect(secondToggle).toBeDisabled();
|
||||
await expect(dialog.getByText("Run Anything…", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("dialog", { name: "Run Anything", exact: true })).toHaveCount(0);
|
||||
await expect(ok).toBeEnabled();
|
||||
|
||||
await page.keyboard.press("Alt");
|
||||
await page.keyboard.down("Alt");
|
||||
await page.keyboard.press("ArrowUp");
|
||||
await page.keyboard.up("Alt");
|
||||
await expect(first).toHaveText("⌥⌥↑");
|
||||
await expect(ok).toBeEnabled();
|
||||
|
||||
await page.keyboard.press("Meta+k");
|
||||
const second = dialog.getByRole("textbox", { name: "Second stroke" });
|
||||
await second.click();
|
||||
await page.keyboard.press("Meta+i");
|
||||
await expect(first).toHaveText("⌘K");
|
||||
await expect(second).toHaveText("⌘I");
|
||||
await expect(ok).toBeEnabled();
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
});
|
||||
|
||||
for (const activation of ["double-click", "Enter"] as const) {
|
||||
test(`Keymap ${activation} offers mouse and keyboard shortcuts`, async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
|
||||
@@ -248,6 +248,7 @@ fs_create_dir always project_host bin
|
||||
fs_create_file always project_host bindings sync
|
||||
fs_create_file_bytes always project_host bindings async
|
||||
fs_delete always project_host bindings async
|
||||
fs_delete_with_undo always project_host bindings async
|
||||
fs_entry_kind always project_host bindings async
|
||||
fs_open_with_system always desktop bindings async
|
||||
fs_probe always project_host bindings async
|
||||
@@ -258,6 +259,7 @@ fs_read_text always project_host bin
|
||||
fs_rename always project_host bindings async
|
||||
fs_resolve_reference always project_host bindings async
|
||||
fs_set_writable always project_host bindings sync
|
||||
fs_undo_delete always project_host bindings async
|
||||
gh_account_repos trusted desktop bindings async
|
||||
gh_api trusted desktop bindings async
|
||||
gh_availability trusted desktop bindings async
|
||||
@@ -537,6 +539,7 @@ scaffold_catalog always project_host bin
|
||||
scaffold_create always project_host bindings async
|
||||
scaffold_options always project_host bindings async
|
||||
scaffold_requirements always project_host bindings async
|
||||
scope_files always project_host bindings async
|
||||
sdk_container_python trusted project_host bindings sync
|
||||
sdk_container_python_refresh trusted project_host bindings async
|
||||
sdk_detect outside_restricted project_host bindings async
|
||||
@@ -628,6 +631,7 @@ vcs_create_tag trusted project_host bin
|
||||
vcs_delete_branch trusted project_host bindings async
|
||||
vcs_delete_tag trusted project_host bindings async
|
||||
vcs_detected_git always project_host bindings sync
|
||||
vcs_detected_roots always project_host bindings async
|
||||
vcs_diff_hunks always project_host bindings async
|
||||
vcs_diff_numstat always project_host bindings async
|
||||
vcs_diff_revisions always project_host bindings async
|
||||
@@ -668,6 +672,7 @@ vcs_revision_children always project_host bin
|
||||
vcs_revision_files always project_host bindings async
|
||||
vcs_reword trusted project_host bindings async
|
||||
vcs_roots always project_host bindings sync
|
||||
vcs_set_user_identity trusted project_host bindings async
|
||||
vcs_shelf_delete trusted project_host bindings async
|
||||
vcs_shelf_diff trusted project_host bindings async
|
||||
vcs_shelf_import trusted project_host bindings async
|
||||
|
||||
+86
-5
@@ -604,6 +604,8 @@ export const commands = {
|
||||
fsCreateFileBytes: (path: string, data: number[]) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
|
||||
/** Moving to the trash can take a while (large trees): kept off the main thread. */
|
||||
fsDelete: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_delete", { path })),
|
||||
/** Moves an item to the Trash and returns the snapshot for Project View Undo. */
|
||||
fsDeleteWithUndo: (path: string) => typedError<DeletionUndo, IdeError>(__TAURI_INVOKE("fs_delete_with_undo", { path })),
|
||||
fsEntryKind: (path: string) => typedError<EntryKind, IdeError>(__TAURI_INVOKE("fs_entry_kind", { path })),
|
||||
/**
|
||||
* Opens a project file with its default application (Office, PDF readers). The checks run here,
|
||||
@@ -631,6 +633,7 @@ export const commands = {
|
||||
* state). Returns whether the file is read-only now.
|
||||
*/
|
||||
fsSetWritable: (path: string, writable: boolean) => typedError<boolean, IdeError>(__TAURI_INVOKE("fs_set_writable", { path, writable })),
|
||||
fsUndoDelete: (undo: DeletionUndo) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("fs_undo_delete", { undo })),
|
||||
/** The repositories of the account gh is signed in to ("Get from Version Control" › GitHub); needs no project. */
|
||||
ghAccountRepos: () => typedError<GhAccountRepos, IdeError>(__TAURI_INVOKE("gh_account_repos")),
|
||||
/** A GitHub GraphQL / REST call through `gh api`; returns the response body. */
|
||||
@@ -662,9 +665,9 @@ export const commands = {
|
||||
/** Shows a GTK file chooser attached to `window`. `None` when the user cancels. */
|
||||
gtkPickPaths: (options: GtkPickOptions) => typedError<IpcPath[] | null, IdeError>(__TAURI_INVOKE("gtk_pick_paths", { options })),
|
||||
historyContent: (id: string) => typedError<string, IdeError>(__TAURI_INVOKE("history_content", { id })),
|
||||
historyList: (path: string) => typedError<HistoryEntry[], IdeError>(__TAURI_INVOKE("history_list", { path })),
|
||||
historyList: (path: string) => typedError<HistoryEntry_Serialize[], IdeError>(__TAURI_INVOKE("history_list", { path })),
|
||||
/** Show History on a folder: snapshots of the files under it (deleted ones included) and labels. */
|
||||
historyListDir: (path: string) => typedError<DirectoryHistory, IdeError>(__TAURI_INVOKE("history_list_dir", { path })),
|
||||
historyListDir: (path: string) => typedError<DirectoryHistory_Serialize, IdeError>(__TAURI_INVOKE("history_list_dir", { path })),
|
||||
/** Local History › Put Label…: a named point in the history of every file. */
|
||||
historyPutLabel: (label: string) => typedError<null, IdeError>(__TAURI_INVOKE("history_put_label", { label })),
|
||||
/**
|
||||
@@ -1395,6 +1398,7 @@ export const commands = {
|
||||
scaffoldOptions: (generator: string, values: { [key in string]: string }, request: RequestId) => typedError<Field[], IdeError>(__TAURI_INVOKE("scaffold_options", { generator, values, request })),
|
||||
/** The programs a generator needs for `values`, and whether they are installed. */
|
||||
scaffoldRequirements: (generator: string, values: { [key in string]: string }) => typedError<Requirement[], IdeError>(__TAURI_INVOKE("scaffold_requirements", { generator, values })),
|
||||
scopeFiles: (pattern: string, limit: number) => typedError<ScopeFiles, IdeError>(__TAURI_INVOKE("scope_files", { pattern, limit })),
|
||||
/** The project interpreter when it is a Docker or Compose run target's, with its snapshot. */
|
||||
sdkContainerPython: () => typedError<{
|
||||
/** The run target's id. */
|
||||
@@ -1707,6 +1711,8 @@ export const commands = {
|
||||
vcsDeleteTag: (repo: string | null, name: string) => typedError<DeletedTag, IdeError>(__TAURI_INVOKE("vcs_delete_tag", { repo, name })),
|
||||
/** The auto-detected git executable (shown as the field's placeholder). */
|
||||
vcsDetectedGit: () => __TAURI_INVOKE<string | null>("vcs_detected_git"),
|
||||
/** Directory Mappings: the repository roots detection finds, before any are excluded or added. */
|
||||
vcsDetectedRoots: () => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_detected_roots")),
|
||||
/** Line hunks between two arbitrary texts (diff viewer, commit dialog). */
|
||||
vcsDiffHunks: (oldText: string, newText: string) => __TAURI_INVOKE<LineHunk[]>("vcs_diff_hunks", { oldText, newText }),
|
||||
/**
|
||||
@@ -1781,6 +1787,11 @@ export const commands = {
|
||||
vcsReword: (repo: string | null, commit: string, message: string) => typedError<HeadChange, IdeError>(__TAURI_INVOKE("vcs_reword", { repo, commit, message })),
|
||||
/** The project's repositories, the primary one first. */
|
||||
vcsRoots: () => typedError<VcsRoot[], IdeError>(__TAURI_INVOKE("vcs_roots")),
|
||||
/**
|
||||
* Git User Name Is Not Defined: sets `user.name` / `user.email` for commits in the
|
||||
* repository, or globally.
|
||||
*/
|
||||
vcsSetUserIdentity: (repo: string | null, name: string, email: string, global: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_set_user_identity", { repo, name, email, global })),
|
||||
vcsShelfDelete: (id: string, path: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_shelf_delete", { id, path })),
|
||||
vcsShelfDiff: (id: string) => typedError<ShelfDiffFile[], IdeError>(__TAURI_INVOKE("vcs_shelf_diff", { id })),
|
||||
vcsShelfImport: (repo: string | null, name: string, patch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_shelf_import", { repo, name, patch })),
|
||||
@@ -2844,6 +2855,8 @@ export type AppearanceSettings_Deserialize = {
|
||||
showToolWindowNames?: boolean,
|
||||
showToolWindowBadges?: boolean,
|
||||
widescreenToolWindows?: boolean,
|
||||
/** Each tool window keeps its own size; off, the windows of a side share one. */
|
||||
rememberToolWindowSizes?: boolean,
|
||||
/** View › Appearance › Toolbar; hidden leaves IDEA's compact window header. */
|
||||
showMainToolbar?: boolean,
|
||||
showStatusBar?: boolean,
|
||||
@@ -2915,6 +2928,8 @@ export type AppearanceSettings_Serialize = {
|
||||
showToolWindowNames: boolean,
|
||||
showToolWindowBadges: boolean,
|
||||
widescreenToolWindows: boolean,
|
||||
/** Each tool window keeps its own size; off, the windows of a side share one. */
|
||||
rememberToolWindowSizes: boolean,
|
||||
/** View › Appearance › Toolbar; hidden leaves IDEA's compact window header. */
|
||||
showMainToolbar: boolean,
|
||||
showStatusBar: boolean,
|
||||
@@ -4737,6 +4752,11 @@ export type DeletedBranch = {
|
||||
unmerged: boolean,
|
||||
};
|
||||
|
||||
export type DeletedFile = {
|
||||
path: IpcPath,
|
||||
id: string,
|
||||
};
|
||||
|
||||
/** A deleted tag, enough to restore it (Restore in the tag-deleted notification). */
|
||||
export type DeletedTag = {
|
||||
name: string,
|
||||
@@ -4744,6 +4764,16 @@ export type DeletedTag = {
|
||||
target: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* Paths and contents captured for one delete operation. Directory history is
|
||||
* intentionally broader and can contain paths deleted in an earlier operation.
|
||||
*/
|
||||
export type DeletionUndo = {
|
||||
directories: IpcPath[],
|
||||
files: DeletedFile[],
|
||||
skipped: IpcPath[],
|
||||
};
|
||||
|
||||
export type Dependency = {
|
||||
id: string,
|
||||
name: string,
|
||||
@@ -4980,9 +5010,20 @@ export type DirectoryCompareProgress = {
|
||||
export type DirectoryCompareStatus = "leftOnly" | "rightOnly" | "different" | "equal";
|
||||
|
||||
/** Changes under a folder (Show History on a directory). */
|
||||
export type DirectoryHistory = {
|
||||
export type DirectoryHistory = DirectoryHistory_Serialize | DirectoryHistory_Deserialize;
|
||||
|
||||
/** Changes under a folder (Show History on a directory). */
|
||||
export type DirectoryHistory_Deserialize = {
|
||||
/** Snapshots of files under the folder and labels, newest first. */
|
||||
entries: HistoryEntry[],
|
||||
entries: HistoryEntry_Deserialize[],
|
||||
/** Files with history that no longer exist on disk. */
|
||||
deleted: IpcPath[],
|
||||
};
|
||||
|
||||
/** Changes under a folder (Show History on a directory). */
|
||||
export type DirectoryHistory_Serialize = {
|
||||
/** Snapshots of files under the folder and labels, newest first. */
|
||||
entries: HistoryEntry_Serialize[],
|
||||
/** Files with history that no longer exist on disk. */
|
||||
deleted: IpcPath[],
|
||||
};
|
||||
@@ -6245,6 +6286,11 @@ export type GitSettings = {
|
||||
* stage and unstage instead of inclusion checkboxes, and no change lists.
|
||||
*/
|
||||
stagingArea?: boolean,
|
||||
/**
|
||||
* Scan the working tree with `git status` (for file systems whose metadata only
|
||||
* the system git reads correctly) instead of in process.
|
||||
*/
|
||||
cliStatus?: boolean,
|
||||
};
|
||||
|
||||
export type GoBuildTags = {
|
||||
@@ -6594,7 +6640,9 @@ export type Highlight = {
|
||||
|
||||
export type HighlightKind = "text" | "read" | "write";
|
||||
|
||||
export type HistoryEntry = {
|
||||
export type HistoryEntry = HistoryEntry_Serialize | HistoryEntry_Deserialize;
|
||||
|
||||
export type HistoryEntry_Deserialize = {
|
||||
/** Content hash (blake3 hex); identifies the stored blob. Empty for labels. */
|
||||
id: string,
|
||||
path: IpcPath,
|
||||
@@ -6605,6 +6653,17 @@ export type HistoryEntry = {
|
||||
kind?: HistoryKind,
|
||||
};
|
||||
|
||||
export type HistoryEntry_Serialize = {
|
||||
/** Content hash (blake3 hex); identifies the stored blob. Empty for labels. */
|
||||
id: string,
|
||||
path: IpcPath,
|
||||
timestampMs: number | null,
|
||||
/** e.g. "Saved", "External change", "Deleted", "Before refactoring: Move". */
|
||||
label: string,
|
||||
size: number,
|
||||
kind: HistoryKind,
|
||||
};
|
||||
|
||||
export type HistoryKind =
|
||||
/** A stored revision of `path`. */
|
||||
"snapshot" |
|
||||
@@ -7418,6 +7477,8 @@ export type JvmPresentation = {
|
||||
kind: JvmTypeKind | null,
|
||||
springBoot: boolean,
|
||||
runnable: boolean,
|
||||
/** `@Deprecated`, or a Java `@deprecated` Javadoc tag. */
|
||||
deprecated: boolean,
|
||||
};
|
||||
|
||||
export type JvmReferrer = {
|
||||
@@ -10418,6 +10479,13 @@ export type Scope = {
|
||||
expensive: boolean,
|
||||
};
|
||||
|
||||
/** The files of a custom scope (`file:src//*.ts`), for the Project view's scope panes. */
|
||||
export type ScopeFiles = {
|
||||
paths: IpcPath[],
|
||||
/** More files than `limit` matched; `paths` holds the first ones. */
|
||||
truncated: boolean,
|
||||
};
|
||||
|
||||
/** One installed interpreter / toolchain. */
|
||||
export type Sdk = {
|
||||
/**
|
||||
@@ -11728,6 +11796,17 @@ export type VcsConfirmationSettings = {
|
||||
onPatchCreated?: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
* root (`.` for the root itself) or absolute outside it.
|
||||
*/
|
||||
export type VcsMappings = {
|
||||
/** Detected repositories the IDE leaves alone: no Git or Commit integration, files stay. */
|
||||
excluded?: string[],
|
||||
/** Repository roots detection does not reach (outside the project, or deeper). */
|
||||
added?: string[],
|
||||
};
|
||||
|
||||
/** A repository of the project (IDEA's VCS root). */
|
||||
export type VcsRoot = {
|
||||
/** Worktree root. */
|
||||
@@ -11753,6 +11832,8 @@ export type VcsSettings = {
|
||||
shelf?: ShelfSettings,
|
||||
/** Issue Navigation: commit-message patterns turned into links. */
|
||||
issueNavigation?: IssueLink[],
|
||||
/** Directory Mappings: repository roots added to or excluded from the detected ones. */
|
||||
mappings?: VcsMappings,
|
||||
};
|
||||
|
||||
/** The tool that creates a new Python environment in "Add Python Interpreter". */
|
||||
|
||||
@@ -101,6 +101,9 @@
|
||||
color: var(--fg-muted);
|
||||
margin-left: -2px;
|
||||
}
|
||||
.deprecated {
|
||||
text-decoration-line: line-through;
|
||||
}
|
||||
.dupe {
|
||||
color: var(--fg-faint);
|
||||
margin-left: 4px;
|
||||
@@ -308,7 +311,7 @@
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0 -3px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.sideTabsResizer:focus-visible::after {
|
||||
background: color-mix(in srgb, var(--focus-ring) 55%, transparent);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ContributedToolbar } from "@/workbench/ContributedToolbar";
|
||||
import { useFilePresentationIcons } from "@/ui/filePresentation";
|
||||
import { useFilePresentations } from "@/ui/filePresentation";
|
||||
/**
|
||||
* The editor area: split layout of panes, each with IDEA-style tabs (preview
|
||||
* tab in italics, pinned tabs, modified dot, file icons coloured by file
|
||||
@@ -190,8 +190,8 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const { showExtension, markModified, showCloseButton, showFileIcon, showDirectoryForNonUnique, showFullPathOnHover } =
|
||||
tabPrefs;
|
||||
|
||||
const fileIcons = useFilePresentationIcons(
|
||||
showFileIcon ? tabs.flatMap((t) => (t.input.kind === "file" && t.input.path ? [t.input.path] : [])) : [],
|
||||
const files = useFilePresentations(
|
||||
tabs.flatMap((t) => (t.input.kind === "file" && t.input.path ? [t.input.path] : [])),
|
||||
);
|
||||
const items: TabItem[] = useMemo(() => {
|
||||
// A kind's title may change without the tab state (a renamed agent task).
|
||||
@@ -210,18 +210,20 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
: null;
|
||||
const kindMark = tabTrailing(t.input, kinds);
|
||||
const pin = t.pinned ? <Icon name="pin" size={11} className={styles.pin} label="Pinned" /> : null;
|
||||
const file = t.input.kind === "file" && t.input.path ? files.get(t.input.path) : undefined;
|
||||
const title = markModified && dirty[i] ? `*${name}` : name;
|
||||
return {
|
||||
id: t.id,
|
||||
label: (
|
||||
<>
|
||||
{markModified && dirty[i] ? `*${name}` : name}
|
||||
{file?.deprecated ? <span className={styles.deprecated}>{title}</span> : title}
|
||||
{dupe && <span className={styles.dupe}>{dupe}</span>}
|
||||
</>
|
||||
),
|
||||
text: dupe ? `${name} — ${dupe}` : name,
|
||||
icon: showFileIcon
|
||||
? t.input.kind === "file" && t.input.path
|
||||
? fileIcons.get(t.input.path)
|
||||
? file?.icon
|
||||
: tabIcon(t.input, kinds)
|
||||
: undefined,
|
||||
italic: t.preview,
|
||||
@@ -245,7 +247,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
};
|
||||
});
|
||||
}, [
|
||||
fileIcons,
|
||||
files,
|
||||
tabs,
|
||||
kinds,
|
||||
titleRevision,
|
||||
|
||||
@@ -62,7 +62,7 @@ export function SideTabsResizer({ side }: { side: "left" | "right" }) {
|
||||
handle.setPointerCapture(e.pointerId);
|
||||
const origin = e.clientX;
|
||||
const previous = pane.style.getPropertyValue(LIMIT_VAR);
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
let next: number | null = null;
|
||||
// Only this pane follows the pointer; every group takes the new width on release.
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
|
||||
@@ -241,6 +241,7 @@ describe("completion helpers", () => {
|
||||
it("finds identifier ends", () => {
|
||||
expect(identifierEnd("foo.barBaz(1)", 4)).toBe(10);
|
||||
expect(identifierEnd("x ", 1)).toBe(1);
|
||||
expect(identifierEnd("a𐐀\u0301;", 1)).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -704,15 +705,27 @@ describe("lookup commit characters", () => {
|
||||
});
|
||||
|
||||
describe("explicit completion", () => {
|
||||
function editor(labels: string[]) {
|
||||
function editor(labels: string[], doc = "pri|", serverItems = false) {
|
||||
const source: CompletionSource = (ctx) => {
|
||||
const word = ctx.matchBefore(/\w*/);
|
||||
return { from: word?.from ?? ctx.pos, options: labels.map((label) => ({ label })) };
|
||||
const from = word?.from ?? ctx.pos;
|
||||
const options = labels.map((label) =>
|
||||
serverItems
|
||||
? makeCompletion(item({ label, insertText: label, kind: "field" }), {
|
||||
doc: 1,
|
||||
path: "/p/a.ts",
|
||||
language: "typescript",
|
||||
pos: ctx.pos,
|
||||
text: ctx.state.doc,
|
||||
})
|
||||
: { label },
|
||||
);
|
||||
return { from, options };
|
||||
};
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "pri",
|
||||
selection: { anchor: 3 },
|
||||
doc: doc.replace("|", ""),
|
||||
selection: { anchor: doc.indexOf("|") },
|
||||
extensions: [completionExtension(), EditorState.languageData.of(() => [{ openideaCompletion: source }])],
|
||||
}),
|
||||
parent: document.body,
|
||||
@@ -720,13 +733,35 @@ describe("explicit completion", () => {
|
||||
return view;
|
||||
}
|
||||
|
||||
it("inserts a sole candidate right away (IDEA)", async () => {
|
||||
const view = editor(["println"]);
|
||||
it.each([
|
||||
["pri|", "println"],
|
||||
["pri|;", "println;"],
|
||||
])("inserts a sole candidate right away at the end of a prefix (%s)", async (doc, expected) => {
|
||||
const view = editor(["println"], doc);
|
||||
explicitCompletion(view);
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toBe("println"), { timeout: 2000 });
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toBe(expected), { timeout: 2000 });
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it.each(["first|Name", "fir|Name", "first|𐐀Name"])(
|
||||
"leaves the lookup open inside an identifier (%s)",
|
||||
async (reference) => {
|
||||
const doc = `const person = { firstName: "Ada", lastName: "Lovelace" };\nconst value = person.${reference};`;
|
||||
const view = editor(["firstName"], doc, true);
|
||||
try {
|
||||
explicitCompletion(view);
|
||||
await vi.waitFor(() => expect(currentCompletions(view.state)).toHaveLength(1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
expect(view.state.doc.toString()).toBe(doc.replace("|", ""));
|
||||
expect(currentCompletions(view.state)).toHaveLength(1);
|
||||
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Tab" }), "editor")).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe(doc.replace(reference, "firstName"));
|
||||
} finally {
|
||||
view.destroy();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps a sole candidate in the list when auto-insert is off", async () => {
|
||||
useProject.setState({ settings: { editor: { completion: { autoInsertSingle: false } } } as unknown as Settings });
|
||||
const view = editor(["println"]);
|
||||
|
||||
@@ -899,12 +899,18 @@ const lookupTracker = ViewPlugin.fromClass(
|
||||
if (options.length === 1 && editorPrefs().completion.autoInsertSingle) {
|
||||
const doc = u.state.doc;
|
||||
setTimeout(() => {
|
||||
const now = currentCompletions(view.state);
|
||||
const state = view.state;
|
||||
const now = currentCompletions(state);
|
||||
const { head } = state.selection.main;
|
||||
const line = state.doc.lineAt(head);
|
||||
const column = head - line.from;
|
||||
// Keep the lookup open so Tab can replace the remaining identifier.
|
||||
if (
|
||||
view.state.doc === doc &&
|
||||
completionStatus(view.state) === "active" &&
|
||||
state.doc === doc &&
|
||||
completionStatus(state) === "active" &&
|
||||
now.length === 1 &&
|
||||
now[0] === options[0]
|
||||
now[0] === options[0] &&
|
||||
identifierEnd(line.text, column) === column
|
||||
)
|
||||
acceptCompletion(view);
|
||||
}, AUTO_INSERT_DELAY);
|
||||
@@ -914,7 +920,7 @@ const lookupTracker = ViewPlugin.fromClass(
|
||||
},
|
||||
);
|
||||
|
||||
/** ⌃Space: explicit completion (a focused lookup; a sole candidate is inserted at once). */
|
||||
/** ⌃Space: explicit completion with a focused lookup. */
|
||||
export function explicitCompletion(view: EditorView): boolean {
|
||||
explicitPending.add(view);
|
||||
const started = startCompletion(view);
|
||||
|
||||
@@ -180,12 +180,15 @@ export function typeColumnText(
|
||||
return !detail || /^auto[- ]?import$/i.test(detail) ? source : `${detail} (${source})`;
|
||||
}
|
||||
|
||||
const WORD_CHAR = /[\p{L}\p{N}_$]/u;
|
||||
const WORD_CHAR = /[\p{L}\p{N}\p{M}_$]/u;
|
||||
|
||||
/** End of the identifier starting at `pos` in `line` (for ⇥ Replace without a server range). */
|
||||
export function identifierEnd(text: string, pos: number): number {
|
||||
let i = pos;
|
||||
while (i < text.length && WORD_CHAR.test(text[i]!)) i++;
|
||||
for (const char of text.slice(pos)) {
|
||||
if (!WORD_CHAR.test(char)) break;
|
||||
i += char.length;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ export function ChangesResizer() {
|
||||
const start = pane.getBoundingClientRect().width;
|
||||
const origin = e.clientX;
|
||||
const previous = session.style.getPropertyValue(WIDTH_VAR);
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
let next: number | null = null;
|
||||
// Only this session follows the pointer; every task takes the new width on release.
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
|
||||
@@ -1253,7 +1253,7 @@
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0 -3px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.changesResizer:focus-visible::after {
|
||||
background: color-mix(in srgb, var(--focus-ring) 55%, transparent);
|
||||
|
||||
@@ -108,6 +108,13 @@
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3) var(--space-3) 0;
|
||||
}
|
||||
|
||||
.recent {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(10, minmax(0, 1fr));
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createRoot, type Root } from "react-dom/client";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { RgbaColorPicker } from "react-colorful";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { IconButton, Popup } from "@/ui";
|
||||
import { Button, IconButton, Popup, T } from "@/ui";
|
||||
import { fromHex, toHex8, type Rgba } from "./colors";
|
||||
import styles from "./ColorPicker.module.css";
|
||||
|
||||
@@ -13,6 +13,7 @@ interface PickerRequest {
|
||||
value: Rgba;
|
||||
onChange?: (value: Rgba) => void;
|
||||
onCommit?: (value: Rgba) => void;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
let root: Root | null = null;
|
||||
@@ -63,28 +64,36 @@ function render() {
|
||||
}
|
||||
|
||||
export function openColorPicker(request: PickerRequest) {
|
||||
closeColorPicker();
|
||||
closeColorPicker(true);
|
||||
active = { ...request, initial: [...request.value] };
|
||||
sequence++;
|
||||
render();
|
||||
}
|
||||
|
||||
export function closeColorPicker() {
|
||||
function closeColorPicker(commit = false) {
|
||||
const previous = active;
|
||||
active = null;
|
||||
if (root) render();
|
||||
if (previous?.value.some((channel, index) => channel !== previous.initial[index])) rememberColor(previous.value);
|
||||
previous?.onCommit?.(previous.value);
|
||||
if (!previous) return;
|
||||
if (commit && previous.value.some((channel, index) => channel !== previous.initial[index])) {
|
||||
rememberColor(previous.value);
|
||||
previous.onCommit?.(previous.value);
|
||||
} else previous.onCancel?.();
|
||||
}
|
||||
|
||||
export function closeColorPickerFor(view: EditorView) {
|
||||
if (active?.view !== view) return;
|
||||
const cancel = active.onCancel;
|
||||
active = null;
|
||||
if (root) render();
|
||||
// Destruction and reconfiguration can happen during an editor update.
|
||||
if (cancel) queueMicrotask(cancel);
|
||||
}
|
||||
|
||||
export function disposeColorPicker() {
|
||||
const cancel = active?.onCancel;
|
||||
active = null;
|
||||
cancel?.();
|
||||
root?.unmount();
|
||||
host?.remove();
|
||||
root = null;
|
||||
@@ -140,14 +149,17 @@ function Picker({ id, request }: { id: number; request: PickerRequest }) {
|
||||
const t = useTx();
|
||||
const eyeDropper = (window as EyeDropperWindow).EyeDropper;
|
||||
useEffect(() => {
|
||||
const close = () => closeColorPickerFor(request.view);
|
||||
const close = () => {
|
||||
if (sequence === id) closeColorPicker();
|
||||
};
|
||||
request.view.scrollDOM.addEventListener("scroll", close);
|
||||
return () => request.view.scrollDOM.removeEventListener("scroll", close);
|
||||
}, [request.view]);
|
||||
}, [id, request.view]);
|
||||
|
||||
const update = (next: Rgba) => {
|
||||
if (sequence !== id || !active) return;
|
||||
setValue(next);
|
||||
if (sequence === id && active) active = { ...active, value: next };
|
||||
active = { ...active, value: next };
|
||||
request.onChange?.(next);
|
||||
};
|
||||
const channel = (index: 0 | 1 | 2, text: string) => {
|
||||
@@ -185,98 +197,113 @@ function Picker({ id, request }: { id: number; request: PickerRequest }) {
|
||||
anchor={request.anchor}
|
||||
placement="bottom-start"
|
||||
offset={4}
|
||||
onClose={closeColorPicker}
|
||||
onClose={(reason) => closeColorPicker(reason !== "escape")}
|
||||
aria-label={t("Color picker")}
|
||||
className={styles.popup}
|
||||
trapFocus
|
||||
closeOnDeactivate={false}
|
||||
>
|
||||
<div className={styles.pickerArea}>
|
||||
<RgbaColorPicker
|
||||
className={styles.control}
|
||||
color={{ r: value[0], g: value[1], b: value[2], a: value[3] }}
|
||||
onChange={({ r, g, b, a }) => update([r, g, b, a])}
|
||||
/>
|
||||
<div className={styles.sampleRow}>
|
||||
<IconButton
|
||||
icon="eyedropper"
|
||||
title="Pick screen color"
|
||||
size="small"
|
||||
disabled={!eyeDropper || sampling}
|
||||
onClick={() => void sampleScreen()}
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!event.currentTarget.querySelector('[aria-invalid="true"]')) closeColorPicker(true);
|
||||
}}
|
||||
>
|
||||
<div className={styles.pickerArea}>
|
||||
<RgbaColorPicker
|
||||
className={styles.control}
|
||||
color={{ r: value[0], g: value[1], b: value[2], a: value[3] }}
|
||||
onChange={({ r, g, b, a }) => update([r, g, b, a])}
|
||||
/>
|
||||
<div className={styles.preview} role="img" aria-label={t("Current color")}>
|
||||
<span style={{ backgroundColor: `rgba(${value.join(", ")})` }} />
|
||||
<div className={styles.sampleRow}>
|
||||
<IconButton
|
||||
icon="eyedropper"
|
||||
title="Pick screen color"
|
||||
size="small"
|
||||
disabled={!eyeDropper || sampling}
|
||||
onClick={() => void sampleScreen()}
|
||||
/>
|
||||
<div className={styles.preview} role="img" aria-label={t("Current color")}>
|
||||
<span style={{ backgroundColor: `rgba(${value.join(", ")})` }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.fields}>
|
||||
<Field
|
||||
label="R"
|
||||
name="Red"
|
||||
value={String(value[0])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(0, v)}
|
||||
/>
|
||||
<Field
|
||||
label="G"
|
||||
name="Green"
|
||||
value={String(value[1])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(1, v)}
|
||||
/>
|
||||
<Field
|
||||
label="B"
|
||||
name="Blue"
|
||||
value={String(value[2])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(2, v)}
|
||||
/>
|
||||
<Field
|
||||
label="A%"
|
||||
name="Alpha percent"
|
||||
value={String(Math.round(value[3] * 100))}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(100)}
|
||||
onValid={alpha}
|
||||
/>
|
||||
<Field
|
||||
label={t("HEX")}
|
||||
name="Hexadecimal"
|
||||
value={toHex8(value).slice(1).toUpperCase()}
|
||||
maxLength={9}
|
||||
inputMode="text"
|
||||
isValid={(v) => fromHex(v) !== null}
|
||||
onValid={hex}
|
||||
/>
|
||||
</div>
|
||||
{recent.length > 0 && (
|
||||
<div className={styles.recent} role="group" aria-label={t("Recent colors")}>
|
||||
{recent.map((hex) => (
|
||||
<button
|
||||
key={hex}
|
||||
type="button"
|
||||
title={hex.toUpperCase()}
|
||||
aria-label={`${t("Recent color")} ${hex.toUpperCase()}`}
|
||||
aria-pressed={hex.toLowerCase() === toHex8(value)}
|
||||
className={styles.recentColor}
|
||||
onClick={() => {
|
||||
const next = fromHex(hex);
|
||||
if (next) update(next);
|
||||
}}
|
||||
>
|
||||
<span style={{ backgroundColor: hex }} />
|
||||
</button>
|
||||
))}
|
||||
<div className={styles.fields}>
|
||||
<Field
|
||||
label="R"
|
||||
name="Red"
|
||||
value={String(value[0])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(0, v)}
|
||||
/>
|
||||
<Field
|
||||
label="G"
|
||||
name="Green"
|
||||
value={String(value[1])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(1, v)}
|
||||
/>
|
||||
<Field
|
||||
label="B"
|
||||
name="Blue"
|
||||
value={String(value[2])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(2, v)}
|
||||
/>
|
||||
<Field
|
||||
label="A%"
|
||||
name="Alpha percent"
|
||||
value={String(Math.round(value[3] * 100))}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(100)}
|
||||
onValid={alpha}
|
||||
/>
|
||||
<Field
|
||||
label={t("HEX")}
|
||||
name="Hexadecimal"
|
||||
value={toHex8(value).slice(1).toUpperCase()}
|
||||
maxLength={9}
|
||||
inputMode="text"
|
||||
isValid={(v) => fromHex(v) !== null}
|
||||
onValid={hex}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{recent.length > 0 && (
|
||||
<div className={styles.recent} role="group" aria-label={t("Recent colors")}>
|
||||
{recent.map((hex) => (
|
||||
<button
|
||||
key={hex}
|
||||
type="button"
|
||||
title={hex.toUpperCase()}
|
||||
aria-label={`${t("Recent color")} ${hex.toUpperCase()}`}
|
||||
aria-pressed={hex.toLowerCase() === toHex8(value)}
|
||||
className={styles.recentColor}
|
||||
onClick={() => {
|
||||
const next = fromHex(hex);
|
||||
if (next) update(next);
|
||||
}}
|
||||
>
|
||||
<span style={{ backgroundColor: hex }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.actions}>
|
||||
<Button size="small" onClick={() => closeColorPicker()}>
|
||||
<T>Cancel</T>
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" size="small">
|
||||
<T>Apply</T>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { act } from "react";
|
||||
import { fireEvent } from "@testing-library/react";
|
||||
import { act, fireEvent, screen } from "@testing-library/react";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, undo, undoDepth } from "@codemirror/commands";
|
||||
import { vue } from "@codemirror/lang-vue";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { colorPreviewGutter } from "./gutter";
|
||||
@@ -17,6 +17,75 @@ afterEach(() => {
|
||||
localStorage.removeItem("openidea.colorPicker.recent.v1");
|
||||
});
|
||||
|
||||
async function openCssPicker() {
|
||||
view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "color: #112233;",
|
||||
extensions: [
|
||||
history(),
|
||||
colorPreviewGutter({ doc: 1, path: "/p/a.css", language: "css", uiMode: null, readOnly: false }),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
const swatch = view.dom.querySelector(".cm-openidea-gutter-colors .cm-gutterElement span")!;
|
||||
await act(async () => fireEvent.mouseDown(swatch, { button: 0 }));
|
||||
return view;
|
||||
}
|
||||
|
||||
const changeHex = async (value: string) =>
|
||||
act(async () => fireEvent.change(screen.getByRole("textbox", { name: "Hexadecimal" }), { target: { value } }));
|
||||
|
||||
it("discards the preview on Escape and leaves other edits in the document and undo history", async () => {
|
||||
const view = await openCssPicker();
|
||||
await changeHex("445566");
|
||||
expect(view.contentDOM.textContent).toContain("#445566");
|
||||
expect(view.state.doc.toString()).toBe("color: #112233;");
|
||||
view.dispatch({ changes: { from: 0, insert: "/* note */ " }, userEvent: "input.type" });
|
||||
expect(view.contentDOM.textContent).toContain("#445566");
|
||||
await act(async () => fireEvent.keyDown(document, { key: "Escape" }));
|
||||
expect(view.state.doc.toString()).toBe("/* note */ color: #112233;");
|
||||
expect(undoDepth(view.state)).toBe(1);
|
||||
expect(undo(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("color: #112233;");
|
||||
expect(localStorage.getItem("openidea.colorPicker.recent.v1")).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ dismissal: "Apply", dismiss: () => fireEvent.click(screen.getByRole("button", { name: "Apply" })), commit: true },
|
||||
{ dismissal: "outside click", dismiss: () => fireEvent.pointerDown(document.body), commit: true },
|
||||
{
|
||||
dismissal: "Cancel",
|
||||
dismiss: () => fireEvent.click(screen.getByRole("button", { name: "Cancel" })),
|
||||
commit: false,
|
||||
},
|
||||
{ dismissal: "scroll", dismiss: (view: EditorView) => fireEvent.scroll(view.scrollDOM), commit: false },
|
||||
])("$dismissal closes the picker and preserves independent edits", async ({ dismiss, commit }) => {
|
||||
const view = await openCssPicker();
|
||||
view.dispatch({ changes: { from: 0, insert: "/* note */ " }, userEvent: "input.type" });
|
||||
await changeHex("aabbcc");
|
||||
await changeHex("445566");
|
||||
expect(view.contentDOM.textContent).toContain("#445566");
|
||||
await act(async () => dismiss(view));
|
||||
expect(screen.queryByRole("dialog", { name: "Color picker" })).not.toBeInTheDocument();
|
||||
expect(view.state.doc.toString()).toBe(`/* note */ color: ${commit ? "#445566" : "#112233"};`);
|
||||
expect(undoDepth(view.state)).toBe(commit ? 2 : 1);
|
||||
if (commit) {
|
||||
expect(undo(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("/* note */ color: #112233;");
|
||||
}
|
||||
});
|
||||
|
||||
it("discards a preview whose color was changed by another edit", async () => {
|
||||
const view = await openCssPicker();
|
||||
await changeHex("445566");
|
||||
view.dispatch({ changes: { from: 7, to: 14, insert: "#aabbcc" }, userEvent: "input.type" });
|
||||
expect(view.contentDOM.textContent).toContain("#aabbcc");
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
|
||||
expect(view.state.doc.toString()).toBe("color: #aabbcc;");
|
||||
expect(undoDepth(view.state)).toBe(1);
|
||||
});
|
||||
|
||||
it("samples a screen color and offers it again as a recent color", async () => {
|
||||
vi.stubGlobal(
|
||||
"EyeDropper",
|
||||
@@ -39,9 +108,10 @@ it("samples a screen color and offers it again as a recent color", async () => {
|
||||
};
|
||||
await open();
|
||||
await act(async () => fireEvent.click(document.querySelector('button[aria-label="Pick screen color"]')!));
|
||||
expect(view.state.doc.toString()).toBe("color: #4c78ce;");
|
||||
expect(view.contentDOM.textContent).toContain("#4c78ce");
|
||||
|
||||
await act(async () => fireEvent.keyDown(document, { key: "Escape" }));
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
|
||||
expect(view.state.doc.toString()).toBe("color: #4c78ce;");
|
||||
expect(JSON.parse(localStorage.getItem("openidea.colorPicker.recent.v1")!)).toEqual(["#4c78ceff"]);
|
||||
|
||||
await open();
|
||||
@@ -96,14 +166,15 @@ it("updates a CSS literal from alpha and hex fields and ignores invalid input",
|
||||
|
||||
const field = (name: string) => document.querySelector<HTMLInputElement>(`input[aria-label="${name}"]`)!;
|
||||
await act(async () => fireEvent.change(field("Alpha percent"), { target: { value: "50" } }));
|
||||
expect(view.state.doc.toString()).toBe("color: #abcdef80;");
|
||||
expect(view.contentDOM.textContent).toContain("#abcdef80");
|
||||
expect(field("Hexadecimal").value).toBe("ABCDEF80");
|
||||
|
||||
await act(async () => fireEvent.change(field("Hexadecimal"), { target: { value: "00FF0080" } }));
|
||||
expect(view.state.doc.toString()).toBe("color: #00ff0080;");
|
||||
expect(view.contentDOM.textContent).toContain("#00ff0080");
|
||||
expect(field("Green").value).toBe("255");
|
||||
|
||||
await act(async () => fireEvent.change(field("Red"), { target: { value: "256" } }));
|
||||
expect(view.state.doc.toString()).toBe("color: #00ff0080;");
|
||||
expect(view.contentDOM.textContent).toContain("#00ff0080");
|
||||
expect(view.state.doc.toString()).toBe("color: #abcdef;");
|
||||
expect(field("Red").getAttribute("aria-invalid")).toBe("true");
|
||||
});
|
||||
@@ -2,8 +2,9 @@
|
||||
* Color preview gutter: a swatch on each line with a color literal (the first one), as IDEA's
|
||||
* color gutter icons. Picking a color replaces the literal in its own format.
|
||||
*/
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { GutterMarker, gutter, type EditorView } from "@codemirror/view";
|
||||
import { StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { Decoration, EditorView, GutterMarker, WidgetType, gutter } from "@codemirror/view";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { findColors, formatColor, isMarkupLanguage, parseComputed, type ColorMatch, type Rgba } from "./colors";
|
||||
@@ -77,47 +78,114 @@ function lineColor(view: EditorView, pos: number, language: string): ColorMatch
|
||||
);
|
||||
}
|
||||
|
||||
/** Opens the color picker for `color` at `from`; each valid pick replaces the literal. */
|
||||
interface ColorEdit {
|
||||
id: symbol;
|
||||
from: number;
|
||||
to: number;
|
||||
original: string;
|
||||
preview: string;
|
||||
}
|
||||
|
||||
class ColorPreviewWidget extends WidgetType {
|
||||
constructor(readonly text: string) {
|
||||
super();
|
||||
}
|
||||
override eq(other: ColorPreviewWidget): boolean {
|
||||
return this.text === other.text;
|
||||
}
|
||||
override toDOM(view: EditorView): HTMLElement {
|
||||
const span = view.dom.ownerDocument.createElement("span");
|
||||
span.textContent = this.text;
|
||||
return span;
|
||||
}
|
||||
}
|
||||
|
||||
const setColorEdit = StateEffect.define<ColorEdit | null>();
|
||||
const colorEdit = StateField.define<ColorEdit | null>({
|
||||
create: () => null,
|
||||
update(edit, tr) {
|
||||
for (const effect of tr.effects) if (effect.is(setColorEdit)) return effect.value;
|
||||
if (!edit || !tr.docChanged) return edit;
|
||||
const from = tr.changes.mapPos(edit.from, 1);
|
||||
const to = tr.changes.mapPos(edit.to, -1);
|
||||
return from < to && tr.newDoc.sliceString(from, to) === edit.original ? { ...edit, from, to } : null;
|
||||
},
|
||||
provide: (field) =>
|
||||
EditorView.decorations.from(field, (edit) =>
|
||||
edit && edit.preview !== edit.original
|
||||
? Decoration.set(Decoration.replace({ widget: new ColorPreviewWidget(edit.preview) }).range(edit.from, edit.to))
|
||||
: Decoration.none,
|
||||
),
|
||||
});
|
||||
|
||||
/** Shows a local preview. The document and undo history change only when the choice is committed. */
|
||||
function pickColor(view: EditorView, from: number, color: ColorMatch, at: { x: number; y: number }) {
|
||||
const rgba = rgbaOf(color.text);
|
||||
if (!rgba) return;
|
||||
let current = color.text;
|
||||
const id = Symbol();
|
||||
const target = () => {
|
||||
const edit = view.state.field(colorEdit, false);
|
||||
return view.dom.isConnected && edit?.id === id ? edit : null;
|
||||
};
|
||||
openColorPicker({
|
||||
view,
|
||||
anchor: at,
|
||||
value: rgba,
|
||||
onChange: (next) => {
|
||||
if (!view.dom.isConnected || view.state.readOnly || view.state.sliceDoc(from, from + current.length) !== current)
|
||||
return;
|
||||
const text = formatColor(next, color);
|
||||
if (text === current) return;
|
||||
view.dispatch({ changes: { from, to: from + current.length, insert: text }, userEvent: "input.color" });
|
||||
current = text;
|
||||
const edit = target();
|
||||
if (!edit || view.state.readOnly) return;
|
||||
const preview = next.every((channel, index) => channel === rgba[index])
|
||||
? edit.original
|
||||
: formatColor(next, color);
|
||||
if (preview !== edit.preview) view.dispatch({ effects: setColorEdit.of({ ...edit, preview }) });
|
||||
},
|
||||
onCommit: (next) => {
|
||||
const edit = target();
|
||||
if (!edit) return;
|
||||
const effects = setColorEdit.of(null);
|
||||
const insert = formatColor(next, color);
|
||||
if (view.state.readOnly || insert === edit.original) view.dispatch({ effects });
|
||||
else
|
||||
view.dispatch({
|
||||
changes: { from: edit.from, to: edit.to, insert },
|
||||
effects,
|
||||
userEvent: "input.color",
|
||||
annotations: isolateHistory.of("full"),
|
||||
});
|
||||
},
|
||||
onCancel: () => {
|
||||
if (target()) view.dispatch({ effects: setColorEdit.of(null) });
|
||||
},
|
||||
});
|
||||
view.dispatch({
|
||||
effects: setColorEdit.of({ id, from, to: from + color.text.length, original: color.text, preview: color.text }),
|
||||
});
|
||||
}
|
||||
|
||||
export function colorPreviewGutter(ctx: EditorDocContext): Extension {
|
||||
return gutter({
|
||||
class: `${styles.gutter} cm-openidea-gutter-colors`,
|
||||
lineMarker: (view, block) => {
|
||||
const color = lineColor(view, block.from, ctx.language);
|
||||
return color ? new Swatch(color, !view.state.readOnly) : null;
|
||||
},
|
||||
lineMarkerChange: (update) => update.docChanged || update.startState.readOnly !== update.state.readOnly,
|
||||
domEventHandlers: {
|
||||
mousedown: (view, block, event) => {
|
||||
const e = event as MouseEvent;
|
||||
const swatch = e.target instanceof Element ? e.target.closest(`.${styles.swatch}`) : null;
|
||||
if (e.button !== 0 || !swatch || view.state.readOnly) return false;
|
||||
const line = view.state.doc.lineAt(block.from);
|
||||
return [
|
||||
colorEdit,
|
||||
gutter({
|
||||
class: `${styles.gutter} cm-openidea-gutter-colors`,
|
||||
lineMarker: (view, block) => {
|
||||
const color = lineColor(view, block.from, ctx.language);
|
||||
if (!color) return false;
|
||||
e.preventDefault();
|
||||
const rect = swatch.getBoundingClientRect();
|
||||
pickColor(view, line.from + color.from, color, { x: rect.left, y: rect.bottom });
|
||||
return true;
|
||||
return color ? new Swatch(color, !view.state.readOnly) : null;
|
||||
},
|
||||
},
|
||||
});
|
||||
lineMarkerChange: (update) => update.docChanged || update.startState.readOnly !== update.state.readOnly,
|
||||
domEventHandlers: {
|
||||
mousedown: (view, block, event) => {
|
||||
const e = event as MouseEvent;
|
||||
const swatch = e.target instanceof Element ? e.target.closest(`.${styles.swatch}`) : null;
|
||||
if (e.button !== 0 || !swatch || view.state.readOnly) return false;
|
||||
const line = view.state.doc.lineAt(block.from);
|
||||
const color = lineColor(view, block.from, ctx.language);
|
||||
if (!color) return false;
|
||||
e.preventDefault();
|
||||
const rect = swatch.getBoundingClientRect();
|
||||
pickColor(view, line.from + color.from, color, { x: rect.left, y: rect.bottom });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { act } from "react";
|
||||
import { fireEvent } from "@testing-library/react";
|
||||
import { act, fireEvent, screen } from "@testing-library/react";
|
||||
const ipc = vi.hoisted(() => ({
|
||||
pluginLanguageVisuals: vi.fn(),
|
||||
pluginColorPresentations: vi.fn(async () => ({ status: "ok", data: ["red"] })),
|
||||
@@ -20,38 +19,52 @@ afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
it("uses plugin presentations to replace precisely the reported range", async () => {
|
||||
vi.useFakeTimers();
|
||||
ipc.pluginLanguageVisuals.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: {
|
||||
version: 1,
|
||||
injections: [],
|
||||
gutterActions: [],
|
||||
colors: [
|
||||
["p", { range: { start: { line: 0, col: 1 }, end: { line: 0, col: 2 } }, red: 1, green: 0, blue: 0, alpha: 1 }],
|
||||
],
|
||||
},
|
||||
});
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "xyz",
|
||||
extensions: pluginColorPreview({ doc: 1, path: "/p/a", language: "text", uiMode: null, readOnly: false }),
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
const swatch = view.dom.querySelector<HTMLButtonElement>("button")!;
|
||||
await act(async () => swatch.click());
|
||||
const picker = document.querySelector<HTMLInputElement>('input[aria-label="Hexadecimal"]')!;
|
||||
await act(async () => fireEvent.change(picker, { target: { value: "00FF0080" } }));
|
||||
await act(async () => fireEvent.keyDown(document, { key: "Escape" }));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(view.state.doc.toString()).toBe("xredz");
|
||||
expect(ipc.pluginColorPresentations).toHaveBeenCalledWith(
|
||||
1,
|
||||
"p",
|
||||
expect.objectContaining({ red: 0, green: 1, blue: 0, alpha: 128 / 255 }),
|
||||
);
|
||||
});
|
||||
it.each(["Apply", "Escape"])(
|
||||
"uses plugin presentations to replace the reported range only on commit (%s)",
|
||||
async (dismissal) => {
|
||||
vi.useFakeTimers();
|
||||
ipc.pluginLanguageVisuals.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: {
|
||||
version: 1,
|
||||
injections: [],
|
||||
gutterActions: [],
|
||||
colors: [
|
||||
[
|
||||
"p",
|
||||
{ range: { start: { line: 0, col: 1 }, end: { line: 0, col: 2 } }, red: 1, green: 0, blue: 0, alpha: 1 },
|
||||
],
|
||||
],
|
||||
},
|
||||
});
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "xyz",
|
||||
extensions: pluginColorPreview({ doc: 1, path: "/p/a", language: "text", uiMode: null, readOnly: false }),
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
const swatch = view.dom.querySelector<HTMLButtonElement>("button")!;
|
||||
await act(async () => swatch.click());
|
||||
const picker = document.querySelector<HTMLInputElement>('input[aria-label="Hexadecimal"]')!;
|
||||
await act(async () => fireEvent.change(picker, { target: { value: "00FF0080" } }));
|
||||
await act(async () => {
|
||||
if (dismissal === "Apply") fireEvent.click(screen.getByRole("button", { name: "Apply" }));
|
||||
else fireEvent.keyDown(document, { key: "Escape" });
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
if (dismissal === "Escape") {
|
||||
expect(view.state.doc.toString()).toBe("xyz");
|
||||
expect(ipc.pluginColorPresentations).not.toHaveBeenCalled();
|
||||
return;
|
||||
}
|
||||
expect(view.state.doc.toString()).toBe("xredz");
|
||||
expect(ipc.pluginColorPresentations).toHaveBeenCalledWith(
|
||||
1,
|
||||
"p",
|
||||
expect.objectContaining({ red: 0, green: 1, blue: 0, alpha: 128 / 255 }),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Plugin colors use the shared picker and provider-supplied replacement strings. */
|
||||
import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { GutterMarker, ViewPlugin, gutter, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { shownAgain, type EditorDocContext } from "@/editor/api";
|
||||
import { rangeToOffsets } from "@/editor/lsp/positions";
|
||||
import { pluginVisuals } from "@/editor/lsp/pluginVisuals";
|
||||
@@ -75,10 +76,14 @@ function pick(view: EditorView, ctx: EditorDocContext, plugin: string, color: Co
|
||||
void call(commands.pluginColorPresentations(ctx.doc, plugin, chosen))
|
||||
.then((list) => {
|
||||
const apply = (insert: string) => {
|
||||
if (view.state.doc === text && !view.state.readOnly)
|
||||
view.dispatch({ changes: { from, to, insert }, userEvent: "input.color" });
|
||||
if (view.dom.isConnected && view.state.doc === text && !view.state.readOnly)
|
||||
view.dispatch({
|
||||
changes: { from, to, insert },
|
||||
userEvent: "input.color",
|
||||
annotations: isolateHistory.of("full"),
|
||||
});
|
||||
};
|
||||
if (view.state.doc !== text) return;
|
||||
if (!view.dom.isConnected || view.state.doc !== text) return;
|
||||
if (list.length === 1) apply(list[0]!);
|
||||
else if (list.length)
|
||||
showContextMenu(
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
right: -3px;
|
||||
width: 6px;
|
||||
height: 100%;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.rowNumber {
|
||||
display: flex;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DataSource } from "@/platform/ipc";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
save: vi.fn(),
|
||||
password: vi.fn(),
|
||||
sshSecret: vi.fn(),
|
||||
sources: vi.fn(),
|
||||
connected: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
commands: {
|
||||
...actual.commands,
|
||||
dbSaveSources: backend.save,
|
||||
dbSetPassword: backend.password,
|
||||
dbSetSshSecret: backend.sshSecret,
|
||||
dbSources: backend.sources,
|
||||
dbConnected: backend.connected,
|
||||
},
|
||||
};
|
||||
});
|
||||
import { DatabaseDialogs } from "./Dialogs";
|
||||
import { useDatabase } from "./store";
|
||||
|
||||
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
|
||||
const mysql: DataSource = { id: "my", name: "MySQL", driver: "mysql", user: "manage" };
|
||||
const tunnelled: DataSource = {
|
||||
...mysql,
|
||||
ssh: { enabled: true, host: "bastion", port: 22, user: "u", auth: "password", saveSecret: false },
|
||||
} as DataSource;
|
||||
|
||||
function ask(kind: "password" | "sshSecret", source: DataSource) {
|
||||
const resolve = vi.fn();
|
||||
useDatabase.setState({
|
||||
sources: [source],
|
||||
dialog: kind === "password" ? { kind, source, resolve } : { kind, source, prompt: "password required", resolve },
|
||||
});
|
||||
render(<DatabaseDialogs />);
|
||||
return resolve;
|
||||
}
|
||||
|
||||
function answer(secret: string) {
|
||||
fireEvent.change(document.querySelector("input[type=password]")!, { target: { value: secret } });
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Save password" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const m of Object.values(backend)) m.mockReset();
|
||||
backend.save.mockResolvedValue(ok(null));
|
||||
backend.password.mockResolvedValue(ok(null));
|
||||
backend.sshSecret.mockResolvedValue(ok(null));
|
||||
backend.sources.mockImplementation(async () => ok(backend.save.mock.calls.at(-1)?.[0] ?? [mysql]));
|
||||
backend.connected.mockResolvedValue(ok([]));
|
||||
});
|
||||
|
||||
describe("connect-time secret prompts", () => {
|
||||
it("turns on the data source's Save password when it is ticked in the prompt", async () => {
|
||||
const resolve = ask("password", mysql);
|
||||
answer("secret");
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(true));
|
||||
expect(backend.save).toHaveBeenCalledWith([{ ...mysql, savePassword: true }]);
|
||||
expect(backend.password).toHaveBeenCalledWith("my", "secret", true);
|
||||
});
|
||||
|
||||
it("only stores the password when the setting already matches", async () => {
|
||||
const resolve = ask("password", { ...mysql, savePassword: true });
|
||||
fireEvent.change(document.querySelector("input[type=password]")!, { target: { value: "secret" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(true));
|
||||
expect(backend.save).not.toHaveBeenCalled();
|
||||
expect(backend.password).toHaveBeenCalledWith("my", "secret", true);
|
||||
});
|
||||
|
||||
it("turns on the SSH tunnel's Save password of the data source's own SSH settings", async () => {
|
||||
const resolve = ask("sshSecret", tunnelled);
|
||||
answer("ssh-secret");
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(true));
|
||||
expect(backend.save).toHaveBeenCalledWith([{ ...tunnelled, ssh: { ...tunnelled.ssh, saveSecret: true } }]);
|
||||
expect(backend.sshSecret).toHaveBeenCalledWith("my", "ssh-secret", true);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { call, commands, type DataSource } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, Input, lazyComponent, T } from "@/ui";
|
||||
import { sshLabel } from "./model";
|
||||
import { SourceDialog, snowflakeSecretLabel } from "./SourceDialog";
|
||||
import { closeDialog, useDatabase } from "./store";
|
||||
import { closeDialog, saveSource, sourceById, useDatabase } from "./store";
|
||||
import styles from "./Database.module.css";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -27,7 +27,9 @@ function PasswordDialog({ source, resolve }: { source: DataSource; resolve: (ok:
|
||||
resolve(ok);
|
||||
};
|
||||
const submit = async () => {
|
||||
await call(commands.dbSetPassword(source.id ?? "", password, save));
|
||||
// The checkbox is the data source's Save password setting: saved passwords are read only when it is on.
|
||||
if (save !== !!source.savePassword) await saveSource({ ...source, savePassword: save }, password);
|
||||
else await call(commands.dbSetPassword(source.id ?? "", password, save));
|
||||
done(true);
|
||||
};
|
||||
return (
|
||||
@@ -81,7 +83,12 @@ function SshSecretDialog({
|
||||
resolve(ok);
|
||||
};
|
||||
const submit = async () => {
|
||||
await call(commands.dbSetSshSecret(source.id ?? "", secret, save));
|
||||
// As for the password: the data source's own SSH settings read a saved secret only when Save is on.
|
||||
// An SSH configuration keeps its own setting.
|
||||
const stored = sourceById(source.id);
|
||||
if (stored?.ssh && !stored.ssh.config?.trim() && save !== !!stored.ssh.saveSecret)
|
||||
await saveSource({ ...stored, ssh: { ...stored.ssh, saveSecret: save } }, undefined, secret);
|
||||
else await call(commands.dbSetSshSecret(source.id ?? "", secret, save));
|
||||
done(true);
|
||||
};
|
||||
return (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { executeAction, getAction, isActionEnabled, registerActions } from "@/platform/actions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useState } from "react";
|
||||
@@ -699,6 +700,33 @@ describe("Set NULL / Set DEFAULT (issue #2331, phase 1)", () => {
|
||||
{ name: "c", type: "text", default: "now()" },
|
||||
];
|
||||
|
||||
it("keeps the invoking grid available to a popup using its captured focus context", async () => {
|
||||
const onEdit = vi.fn();
|
||||
render(
|
||||
<>
|
||||
<Grid columns={[columns[0]!]} rowCount={1} value={() => "old"} editable onEdit={onEdit} />
|
||||
<div role="dialog">
|
||||
<input aria-label="Action query" />
|
||||
</div>
|
||||
<button>Outside the grid</button>
|
||||
</>,
|
||||
);
|
||||
fireEvent.mouseDown(screen.getByRole("gridcell"), { button: 0 });
|
||||
const source = { ...getContext() };
|
||||
const action = getAction("db.setCellNull")!;
|
||||
expect(isActionEnabled(action, source)).toBe(true);
|
||||
|
||||
act(() => screen.getByLabelText("Action query").focus());
|
||||
expect(isActionEnabled(action)).toBe(false);
|
||||
expect(isActionEnabled(action, source)).toBe(true);
|
||||
act(() => screen.getByRole("grid").focus());
|
||||
await act(() => executeAction(action.id));
|
||||
expect(onEdit).toHaveBeenCalledWith(0, 0, null);
|
||||
|
||||
act(() => screen.getByRole("button", { name: "Outside the grid" }).focus());
|
||||
expect(isActionEnabled(action, source)).toBe(false);
|
||||
});
|
||||
|
||||
it("sets NULL on the selection from the context menu and ⌘⌫, skipping NOT NULL columns", async () => {
|
||||
const onEdit = vi.fn();
|
||||
render(
|
||||
|
||||
@@ -574,7 +574,7 @@ export function Grid(props: GridProps) {
|
||||
const startResize = (e: MouseEvent, col: number) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
const startX = e.clientX;
|
||||
const start = widths[col] ?? 100;
|
||||
const move = (ev: globalThis.MouseEvent) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { registerActions, type ActionContext } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { getContext, setContext } from "@/platform/context";
|
||||
|
||||
export type CellCopy = "tsv" | "csv" | "onerow" | "header" | "rowsTsv" | "rowsCsv";
|
||||
|
||||
@@ -26,7 +26,7 @@ let active: CellActions | null = null;
|
||||
|
||||
/** The focused grid (not while a text field in it has focus). */
|
||||
export function activeCellGrid(): CellActions | null {
|
||||
return active;
|
||||
return getContext().dbCellGridFocus ? active : null;
|
||||
}
|
||||
|
||||
const COPIES: Array<[CellCopy, string, string]> = [
|
||||
@@ -53,12 +53,18 @@ export function installCellActions(): () => void {
|
||||
const onFocus = (event: FocusEvent) => {
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
const root = target?.closest("[data-db-cell-grid]");
|
||||
// A popup can query the grid that opened it with its captured context.
|
||||
if (!root && target?.closest("[data-popup], [role=dialog]")) {
|
||||
setContext("dbCellGridFocus", false);
|
||||
return;
|
||||
}
|
||||
active =
|
||||
root && !target?.closest("input, textarea, select, [contenteditable='true']") ? (grids.get(root) ?? null) : null;
|
||||
setContext("dbCellGridFocus", !!active);
|
||||
};
|
||||
document.addEventListener("focusin", onFocus);
|
||||
const handle = ({ arg }: ActionContext) => (arg as CellActions | undefined) ?? active;
|
||||
const handle = ({ arg, ctx }: ActionContext) =>
|
||||
(arg as CellActions | undefined) ?? (ctx.dbCellGridFocus ? active : null);
|
||||
const dispose = registerActions([
|
||||
{
|
||||
id: "db.toggleBooleanCell",
|
||||
|
||||
@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({
|
||||
actions: [] as { id: string; run: (context: { arg: string[] }) => unknown }[],
|
||||
servers: [] as DeploymentServerValid[],
|
||||
groups: [] as { id: string; name: string; servers: string[] }[],
|
||||
defaultServer: "one",
|
||||
coverage: [] as { server: string; paths: string[]; skipped: { path: string; message: string }[] }[],
|
||||
choose: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
@@ -38,7 +39,9 @@ vi.mock("@/platform/project", () => ({
|
||||
useProject: { getState: () => ({ project: { root: "/project" } }) },
|
||||
}));
|
||||
vi.mock("@/platform/workflowSettings", () => ({
|
||||
workflowSettings: () => ({ deployment: { servers: mocks.servers, groups: mocks.groups, defaultServer: "one" } }),
|
||||
workflowSettings: () => ({
|
||||
deployment: { servers: mocks.servers, groups: mocks.groups, defaultServer: mocks.defaultServer },
|
||||
}),
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", () => ({
|
||||
notifications: () => ({ notify: mocks.notify }),
|
||||
@@ -74,6 +77,7 @@ beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.servers = ["one", "two"].map((id) => ({ id, name: id, kind: "local" }) as DeploymentServerValid);
|
||||
mocks.groups = [];
|
||||
mocks.defaultServer = "one";
|
||||
mocks.coverage = [
|
||||
{
|
||||
server: "one",
|
||||
@@ -112,6 +116,15 @@ describe("server groups", () => {
|
||||
expect(mocks.upload).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Cannot upload to one" }));
|
||||
});
|
||||
it("uploads to each server of the default group without asking", async () => {
|
||||
mocks.groups = [{ id: "g", name: "Production", servers: ["two", "one"] }];
|
||||
mocks.defaultServer = "g";
|
||||
mocks.coverage[1]!.paths = ["/project/a"];
|
||||
mocks.actions.find((action) => action.id === "deployment.uploadToDefault")!.run({ arg: ["/project/a"] });
|
||||
await vi.waitFor(() => expect(mocks.upload).toHaveBeenCalledTimes(2));
|
||||
expect(mocks.upload.mock.calls.map((c) => c[1])).toEqual(["two", "one"]);
|
||||
expect(mocks.choose).not.toHaveBeenCalled();
|
||||
});
|
||||
it("uploads to every covered server of the group in order", async () => {
|
||||
mocks.groups = [{ id: "g", name: "Production", servers: ["two", "one"] }];
|
||||
mocks.coverage[1]!.paths = ["/project/b"];
|
||||
|
||||
@@ -25,7 +25,7 @@ import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { notifications, projectViewSelection, toolWindowService } from "@/workbench/contributions";
|
||||
import { chooseItem } from "@/workbench/inputDialogs";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { initialSyncChoices, resolveServer, serverLabel, summarizeReport, targetPaths } from "./model";
|
||||
import { defaultGroup, initialSyncChoices, resolveServer, serverLabel, summarizeReport, targetPaths } from "./model";
|
||||
import { withSsh } from "./ssh";
|
||||
import { REMOTE_HOST_WINDOW, patchSync, useDeployment } from "./store";
|
||||
import styles from "./Deployment.module.css";
|
||||
@@ -468,7 +468,15 @@ export function registerDeploymentActions(): () => void {
|
||||
icon: "export",
|
||||
when,
|
||||
keywords: ["deploy", "sftp", "upload", "remote"],
|
||||
run: withTargets(async (paths) => transfer("upload", await defaultServer("Upload to", paths), paths)),
|
||||
run: withTargets(async (paths) => {
|
||||
// The default server group: each of its servers in turn, as Upload to… on the group does.
|
||||
const group = defaultGroup(deployment());
|
||||
if (group) {
|
||||
for (const server of group.servers) await transfer("upload", server, paths);
|
||||
return;
|
||||
}
|
||||
await transfer("upload", await defaultServer("Upload to", paths), paths);
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: "deployment.uploadTo",
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
sshRemedy,
|
||||
summarizeReport,
|
||||
transferMenuEntries,
|
||||
defaultGroup,
|
||||
syncChoices,
|
||||
syncSteps,
|
||||
targetPaths,
|
||||
@@ -111,6 +112,18 @@ describe("servers and reports", () => {
|
||||
expect(actions([a], "")).toEqual(named);
|
||||
expect(actions([a, b], "a")).toEqual([...named, ...choosers]);
|
||||
expect(actions([a, b], "")).toEqual(choosers);
|
||||
// A default server group uploads to its servers; the rest choose one server.
|
||||
const groups = [{ id: "g", name: "All stages", servers: [b.id, a.id] }];
|
||||
expect(
|
||||
transferMenuEntries({ ...DEFAULT_DEPLOYMENT, servers: [a, b], groups, defaultServer: "g" }).map(
|
||||
(e) => e.label ?? e.action,
|
||||
),
|
||||
).toEqual(["Upload to All stages", ...choosers]);
|
||||
expect(defaultGroup({ ...DEFAULT_DEPLOYMENT, servers: [a, b], groups, defaultServer: "g" })?.servers).toEqual([
|
||||
b,
|
||||
a,
|
||||
]);
|
||||
expect(defaultGroup({ ...DEFAULT_DEPLOYMENT, servers: [a, b], groups, defaultServer: "a" })).toBeNull();
|
||||
});
|
||||
|
||||
it("summarizes transfer reports", () => {
|
||||
|
||||
@@ -88,8 +88,27 @@ export function resolveServer(settings: DeploymentSettingsValid, id: string | nu
|
||||
|
||||
export const serverLabel = (s: Pick<DeploymentServerValid, "id" | "name">) => s.name.trim() || s.id;
|
||||
|
||||
/** The default target when it is a server group: its name and servers, in upload order. */
|
||||
export function defaultGroup(
|
||||
settings: DeploymentSettingsValid,
|
||||
): { name: string; servers: DeploymentServerValid[] } | null {
|
||||
const group = settings.groups.find((g) => g.id === settings.defaultServer);
|
||||
if (!group) return null;
|
||||
const servers = group.servers.flatMap((id) => settings.servers.find((s) => s.id === id) ?? []);
|
||||
return { name: group.name.trim() || group.id, servers };
|
||||
}
|
||||
|
||||
/** Transfer entries of the Deployment menu: named after the default server, choosers when there are several. */
|
||||
export function transferMenuEntries(settings: DeploymentSettingsValid): { action: string; label?: string }[] {
|
||||
// A default group uploads to each of its servers; downloads and syncs pick one server.
|
||||
const group = defaultGroup(settings);
|
||||
if (group)
|
||||
return [
|
||||
{ action: "deployment.uploadToDefault", label: tx`Upload to ${group.name}` },
|
||||
{ action: "deployment.uploadTo" },
|
||||
{ action: "deployment.downloadFrom" },
|
||||
{ action: "deployment.syncWith" },
|
||||
];
|
||||
const target = resolveServer(settings, null);
|
||||
const name = target && serverLabel(target);
|
||||
const named = target
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
showServiceView,
|
||||
} from "@/workbench/contributions";
|
||||
import { registerFileNavigation } from "./fileNavigation";
|
||||
import { registerUrlNavigation } from "./urlNavigation";
|
||||
import { registerVariableNavigation } from "./variableNavigation";
|
||||
import { HTTP_LANGUAGE, httpEditorExtension, refreshRequests, requestAtCaret } from "./editor";
|
||||
import { HttpClientHeaderActions, HttpClientView } from "./HttpClientView";
|
||||
@@ -143,6 +144,7 @@ export function activate(): () => void {
|
||||
registerSpringEndpointProvider(),
|
||||
registerFeignNavigation(),
|
||||
registerVariableNavigation(),
|
||||
registerUrlNavigation(),
|
||||
registerFileNavigation(),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root) resetHttpClient();
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ConstantPool, type ConstantFiles } from "./constants";
|
||||
import { controllersOf } from "./endpoints";
|
||||
import { parseSource } from "./source";
|
||||
|
||||
function project(files: Record<string, string>): ConstantFiles & { reads: string[] } {
|
||||
const reads: string[] = [];
|
||||
return {
|
||||
reads,
|
||||
filesNamed: vi.fn(async (name: string) => Object.keys(files).filter((p) => p.endsWith(`/${name}`))),
|
||||
read: async (path) => {
|
||||
reads.push(path);
|
||||
return files[path] ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function paths(text: string, files: ConstantFiles) {
|
||||
const file = parseSource(text);
|
||||
const pool = new ConstantPool(files);
|
||||
await pool.load([file]);
|
||||
return controllersOf(file, pool.resolverFor(file)).flatMap((c) =>
|
||||
c.endpoints.map((e) => `${e.httpMethod} ${e.paths}`),
|
||||
);
|
||||
}
|
||||
|
||||
const defines = {
|
||||
"/p/common/src/main/java/com/acme/common/AppServiceDefine.java": `package com.acme.common;
|
||||
public interface AppServiceDefine {
|
||||
String API_WEBAPI_PREFIX = "/api";
|
||||
}`,
|
||||
"/p/cockpit/src/main/java/com/acme/cockpit/CockpitApiDefine.java": `package com.acme.cockpit;
|
||||
public interface CockpitApiDefine {
|
||||
String API_COCKPIT_PREFIX = "/cockpit";
|
||||
String PATH_MAP = "/map";
|
||||
}`,
|
||||
};
|
||||
|
||||
describe("mapping constants of other classes", () => {
|
||||
it("joins constants of interfaces in other files and modules", async () => {
|
||||
const files = project(defines);
|
||||
const text = `package com.acme.cockpit.web;
|
||||
import com.acme.common.AppServiceDefine;
|
||||
import com.acme.cockpit.CockpitApiDefine;
|
||||
@RestController
|
||||
@RequestMapping(AppServiceDefine.API_WEBAPI_PREFIX + CockpitApiDefine.API_COCKPIT_PREFIX)
|
||||
public class CockpitMapController {
|
||||
@GetMapping(CockpitApiDefine.PATH_MAP + "/layers")
|
||||
public MapLayerVO layers(@RequestParam(required = false) String type) { return null; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /api/cockpit/map/layers"]);
|
||||
});
|
||||
|
||||
it("follows static imports, superclasses and constants built from other classes", async () => {
|
||||
const files = project({
|
||||
...defines,
|
||||
"/p/web/src/main/java/com/acme/web/Routes.java": `package com.acme.web;
|
||||
import com.acme.common.AppServiceDefine;
|
||||
public final class Routes {
|
||||
public static final String ORDERS = AppServiceDefine.API_WEBAPI_PREFIX + "/orders";
|
||||
}`,
|
||||
"/p/web/src/main/java/com/acme/web/BaseController.java": `package com.acme.web;
|
||||
public abstract class BaseController {
|
||||
protected static final String ITEMS = "/items";
|
||||
}`,
|
||||
});
|
||||
const text = `package com.acme.web;
|
||||
import static com.acme.web.Routes.ORDERS;
|
||||
@RestController
|
||||
@RequestMapping(ORDERS)
|
||||
public class OrderController extends BaseController {
|
||||
@GetMapping(ITEMS + "/{id}")
|
||||
public Item item(@PathVariable String id) { return null; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /api/orders/items/{id}"]);
|
||||
});
|
||||
|
||||
it("prefers the imported package when several classes share the name", async () => {
|
||||
const files = project({
|
||||
"/p/a/src/main/java/com/a/Paths.java": `package com.a;\npublic interface Paths { String ROOT = "/a"; }`,
|
||||
"/p/b/src/main/java/com/b/Paths.java": `package com.b;\npublic interface Paths { String ROOT = "/b"; }`,
|
||||
});
|
||||
const text = `package com.app;
|
||||
import com.b.Paths;
|
||||
@RestController
|
||||
class C {
|
||||
@GetMapping(Paths.ROOT)
|
||||
String get() { return ""; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /b"]);
|
||||
});
|
||||
|
||||
it("looks each class up once, and leaves out a constant no project file declares", async () => {
|
||||
const files = project(defines);
|
||||
const text = `@RestController
|
||||
class C {
|
||||
@GetMapping(Missing.PATH)
|
||||
String a() { return ""; }
|
||||
@GetMapping(CockpitApiDefine.PATH_MAP)
|
||||
String b() { return ""; }
|
||||
@PostMapping(CockpitApiDefine.PATH_MAP + "/x")
|
||||
String c() { return ""; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /", "GET /map", "POST /map/x"]);
|
||||
expect(files.reads).toEqual(["/p/cockpit/src/main/java/com/acme/cockpit/CockpitApiDefine.java"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* Constants that mapping paths take from other classes: `Paths.API + "/orders"`,
|
||||
* statically imported ones and those of a superclass. Their classes are found by
|
||||
* file name in the index, read and kept until a Java / Kotlin file changes.
|
||||
*/
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Constants, type ExternalConstant } from "./endpoints";
|
||||
import { allClasses, parseSource, type Expr, type SourceFile } from "./source";
|
||||
|
||||
export interface ConstantFiles {
|
||||
/** The project's files called `name`. */
|
||||
filesNamed(name: string): Promise<string[]>;
|
||||
read(path: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
const EXTENSIONS = [".java", ".kt"];
|
||||
/** Classes looked up per pool, and how many hops from a controller to a constant's class. */
|
||||
const MAX_CLASSES = 256;
|
||||
const MAX_DEPTH = 3;
|
||||
/** Qualifiers Spring and the JDK own: never project classes. */
|
||||
const LIBRARY = new Set(["MediaType", "RequestMethod", "HttpMethod", "HttpHeaders", "HttpStatus", "String", "Integer"]);
|
||||
|
||||
const isClassName = (s: string | undefined): s is string => !!s && /^[A-Z]/.test(s);
|
||||
const simpleType = (t: string) => t.replace(/<.*$/, "").replace(/\(.*$/, "").trim().split(".").pop() ?? "";
|
||||
|
||||
/** `C` of `a.b.C.NAME` / `a.b.C.*` (a static import; the parser drops the `static`). */
|
||||
function staticImportClass(imp: string): string | null {
|
||||
const parts = imp.split(".");
|
||||
const owner = parts[parts.length - 2];
|
||||
return parts.length >= 3 && isClassName(owner) ? owner : null;
|
||||
}
|
||||
|
||||
/** Classes whose constants `file` can use without naming the class. */
|
||||
function inheritedClasses(file: SourceFile): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const imp of file.imports) {
|
||||
const c = staticImportClass(imp);
|
||||
if (c) out.add(c);
|
||||
}
|
||||
for (const c of allClasses(file)) if (c.superclass) out.add(simpleType(c.superclass));
|
||||
return [...out].filter(isClassName);
|
||||
}
|
||||
|
||||
function qualifiers(expr: Expr, out: Set<string>) {
|
||||
for (let i = 0; i + 2 < expr.length; i++) {
|
||||
const [a, dot, b] = [expr[i]!, expr[i + 1]!, expr[i + 2]!];
|
||||
if (a.kind === "id" && dot.kind === "p" && dot.text === "." && b.kind === "id" && isClassName(a.text))
|
||||
out.add(a.text);
|
||||
}
|
||||
}
|
||||
|
||||
/** Classes `file` takes constants from: qualifiers in annotations and constant initializers, and the inherited ones. */
|
||||
export function referencedClasses(file: SourceFile): string[] {
|
||||
const out = new Set(inheritedClasses(file));
|
||||
const classes = allClasses(file);
|
||||
for (const c of classes) {
|
||||
for (const a of [...c.annotations, ...c.methods.flatMap((m) => m.annotations)])
|
||||
for (const expr of a.args.values()) qualifiers(expr, out);
|
||||
for (const f of c.fields) if (f.init) qualifiers(f.init, out);
|
||||
}
|
||||
for (const f of file.fields) if (f.init) qualifiers(f.init, out);
|
||||
const own = new Set(classes.map((c) => c.name));
|
||||
return [...out].filter((c) => !own.has(c) && !LIBRARY.has(c));
|
||||
}
|
||||
|
||||
export class ConstantPool {
|
||||
/** Class name → constants of its file; `null` when no project file declares it. */
|
||||
private readonly classes = new Map<string, Constants | null>();
|
||||
private readonly pending = new Map<string, Promise<SourceFile | null>>();
|
||||
private readonly resolving = new Set<string>();
|
||||
|
||||
constructor(private readonly files: ConstantFiles) {}
|
||||
|
||||
/** Resolves the constants `file` takes from classes loaded so far. */
|
||||
resolverFor(file: SourceFile): ExternalConstant {
|
||||
const inherited = inheritedClasses(file);
|
||||
return (qualifier, name) => {
|
||||
for (const owner of qualifier ? [qualifier] : inherited) {
|
||||
const key = `${owner}.${name}`;
|
||||
const constants = this.classes.get(owner);
|
||||
if (!constants || this.resolving.has(key)) continue;
|
||||
this.resolving.add(key);
|
||||
try {
|
||||
const v = constants.named(name);
|
||||
if (v != null) return v;
|
||||
} finally {
|
||||
this.resolving.delete(key);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Loads the classes `files` take constants from, and theirs in turn; true when one of them is now known. */
|
||||
async load(files: readonly SourceFile[]): Promise<boolean> {
|
||||
let added = false;
|
||||
let round = [...files];
|
||||
for (let depth = 0; depth < MAX_DEPTH && round.length; depth++) {
|
||||
const next: SourceFile[] = [];
|
||||
for (const file of round)
|
||||
for (const name of referencedClasses(file)) {
|
||||
if (this.classes.has(name) && !this.pending.has(name)) continue;
|
||||
if (!this.pending.has(name) && this.classes.size >= MAX_CLASSES) continue;
|
||||
const isNew = !this.pending.has(name);
|
||||
const loaded = await this.lookup(name, file);
|
||||
if (!loaded) continue;
|
||||
added = true;
|
||||
if (isNew) next.push(loaded);
|
||||
}
|
||||
round = next;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
private lookup(name: string, from: SourceFile): Promise<SourceFile | null> {
|
||||
const running = this.pending.get(name);
|
||||
if (running) return running;
|
||||
this.classes.set(name, null);
|
||||
const promise = this.find(name, from)
|
||||
.then((file) => {
|
||||
if (file) {
|
||||
const constants = new Constants(file, this.resolverFor(file));
|
||||
// Nested classes too: `Outer.Inner.NAME` names `Inner`.
|
||||
for (const c of allClasses(file))
|
||||
if (c.name === name || !this.classes.get(c.name)) this.classes.set(c.name, constants);
|
||||
}
|
||||
return file;
|
||||
})
|
||||
.catch(() => null)
|
||||
.finally(() => this.pending.delete(name));
|
||||
this.pending.set(name, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
/** The file declaring class `name`, preferring the package `from` imports it from, then its own package. */
|
||||
private async find(name: string, from: SourceFile): Promise<SourceFile | null> {
|
||||
const imported = from.imports.find((i) => i.endsWith(`.${name}`) || i.includes(`.${name}.`));
|
||||
const pkg = imported ? imported.slice(0, imported.indexOf(`.${name}`)) : from.packageName;
|
||||
for (const ext of EXTENSIONS) {
|
||||
const paths = (await this.files.filesNamed(`${name}${ext}`)).map((p) => p.replace(/\\/g, "/"));
|
||||
if (!paths.length) continue;
|
||||
const suffix = `/${pkg.replace(/\./g, "/")}/${name}${ext}`;
|
||||
const path = paths.find((p) => p.endsWith(suffix)) ?? paths[0]!;
|
||||
const text = await this.files.read(path);
|
||||
if (text != null) return parseSource(text);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const projectFiles: ConstantFiles = {
|
||||
filesNamed: async (name) => (await call(commands.findFilesNamed(name))).map(String),
|
||||
read: async (path) => {
|
||||
try {
|
||||
return await call(commands.fsReadText(path));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let shared: ConstantPool | null = null;
|
||||
|
||||
/** The project's pool, shared by the route index and the editors. */
|
||||
export function constantPool(): ConstantPool {
|
||||
return (shared ??= new ConstantPool(projectFiles));
|
||||
}
|
||||
|
||||
/** Forgets the loaded classes (a Java / Kotlin file changed, or the project closed). */
|
||||
export function resetConstantPool() {
|
||||
shared = null;
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { useProject } from "@/platform/project";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { notifications, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { constantPool } from "./constants";
|
||||
import { springAt, springControllers, type Controller, type Endpoint } from "./endpoints";
|
||||
import { bodyLookup, findHost, renderRequest, skeleton, type SourceReader } from "./request";
|
||||
import { parseSource } from "./source";
|
||||
@@ -39,6 +40,11 @@ export const sourceReader: SourceReader = {
|
||||
filesNamed: (name) => call(commands.findFilesNamed(name)),
|
||||
};
|
||||
|
||||
/** Controllers of `text`, with the other classes' constants loaded so far. */
|
||||
function controllersIn(text: string): Controller[] {
|
||||
return springControllers(text, (file) => constantPool().resolverFor(file));
|
||||
}
|
||||
|
||||
/** One request per endpoint (`paths[i]` picks another path of the mapping). */
|
||||
export interface Target {
|
||||
endpoint: Endpoint;
|
||||
@@ -109,7 +115,7 @@ function controllerItems(sourcePath: string, text: string, c: Controller): MenuI
|
||||
|
||||
/** Editor context menu items for the caret at `offset`: the generate actions (a path choice for several paths). */
|
||||
export function springMenuItems(sourcePath: string, text: string, offset: number): MenuItem[] {
|
||||
const { controller, endpoint } = springAt(springControllers(text), offset);
|
||||
const { controller, endpoint } = springAt(controllersIn(text), offset);
|
||||
const items: MenuItem[] = [];
|
||||
if (endpoint)
|
||||
items.push(
|
||||
@@ -136,7 +142,7 @@ export async function generateAtCaret(scope: "endpoint" | "controller"): Promise
|
||||
const e = activeEditor();
|
||||
if (!e || !SPRING_LANGUAGES.has(e.ctx.language)) return;
|
||||
const text = e.view.state.doc.toString();
|
||||
const { controller, endpoint } = springAt(springControllers(text), e.view.state.selection.main.head);
|
||||
const { controller, endpoint } = springAt(controllersIn(text), e.view.state.selection.main.head);
|
||||
const endpoints = scope === "endpoint" ? (endpoint ? [endpoint] : []) : (controller?.endpoints ?? []);
|
||||
if (!endpoints.length) {
|
||||
notifications().notify({
|
||||
@@ -178,7 +184,7 @@ function computeMarks(state: EditorState): Mark[] {
|
||||
const doc = state.doc;
|
||||
const marks: Mark[] = [];
|
||||
const lineStart = (offset: number) => doc.lineAt(Math.min(offset, doc.length)).from;
|
||||
for (const c of springControllers(doc.toString())) {
|
||||
for (const c of controllersIn(doc.toString())) {
|
||||
if (c.endpoints.length)
|
||||
marks.push({
|
||||
pos: lineStart(c.offset),
|
||||
@@ -239,9 +245,18 @@ export function springEditorExtension(ctx: EditorDocContext): Extension {
|
||||
const same =
|
||||
cur.length === found.length && cur.every((m, i) => m.pos === found[i]!.pos && m.key === found[i]!.key);
|
||||
if (!same) this.view.dispatch({ effects: setMarks.of(found) });
|
||||
// Paths built from other classes' constants: load those classes, then mark again.
|
||||
if (found.length) {
|
||||
const pool = constantPool();
|
||||
void pool.load([parseSource(this.view.state.doc.toString())]).then((loaded) => {
|
||||
if (loaded && pool === constantPool() && !this.destroyed) this.schedule(0);
|
||||
});
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
destroyed = false;
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
clearTimeout(this.timer);
|
||||
}
|
||||
},
|
||||
@@ -250,7 +265,7 @@ export function springEditorExtension(ctx: EditorDocContext): Extension {
|
||||
// Only files that have mappings (the gutter found some) are parsed again here.
|
||||
if (!view.state.field(marksField, false)?.length) return [];
|
||||
const text = view.state.doc.toString();
|
||||
const { controller, endpoint } = springAt(springControllers(text), view.state.selection.main.head);
|
||||
const { controller, endpoint } = springAt(controllersIn(text), view.state.selection.main.head);
|
||||
const out: ContributedIntention[] = [];
|
||||
if (endpoint)
|
||||
out.push({
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* Spring Web request mappings of a Java / Kotlin source: `@RequestMapping` /
|
||||
* `@GetMapping`… methods of `@RestController` / `@Controller` classes, with
|
||||
* the class-level mapping applied. Constants are resolved within the file.
|
||||
* the class-level mapping applied. Constants are resolved within the file, and
|
||||
* through an {@link ExternalConstant} in other classes (`constants.ts`).
|
||||
*/
|
||||
import {
|
||||
allClasses,
|
||||
@@ -86,12 +87,27 @@ const MEDIA_TYPES: Record<string, string> = {
|
||||
TEXT_XML: "text/xml",
|
||||
};
|
||||
|
||||
/** The value of constant `name` of another class (`qualifier`, or an inherited / statically imported one when absent). */
|
||||
export type ExternalConstant = (qualifier: string | undefined, name: string) => string | null;
|
||||
|
||||
/** Evaluates string-valued annotation arguments within one file. */
|
||||
export class Constants {
|
||||
private readonly fields = new Map<string, Expr>();
|
||||
constructor(file: SourceFile) {
|
||||
for (const f of [...file.fields, ...allClasses(file).flatMap((c) => c.fields)])
|
||||
private readonly classes: Set<string>;
|
||||
constructor(
|
||||
file: SourceFile,
|
||||
private readonly external?: ExternalConstant,
|
||||
) {
|
||||
const classes = allClasses(file);
|
||||
for (const f of [...file.fields, ...classes.flatMap((c) => c.fields)])
|
||||
if (f.init && !this.fields.has(f.name)) this.fields.set(f.name, f.init);
|
||||
this.classes = new Set(classes.map((c) => c.name));
|
||||
}
|
||||
|
||||
/** The value of this file's constant `name`. */
|
||||
named(name: string): string | null {
|
||||
const init = this.fields.get(name);
|
||||
return init ? this.value(init, false, new Set([name])) : null;
|
||||
}
|
||||
|
||||
/** Every element of an array (`{a, b}`, `[a, b]`, `arrayOf(a, b)`) or the single value; unresolvable ones dropped. */
|
||||
@@ -133,7 +149,8 @@ export class Constants {
|
||||
(m, a: string | undefined, b: string | undefined) => {
|
||||
const name = (a ?? b)!;
|
||||
const init = seen.has(name) ? undefined : this.fields.get(name);
|
||||
return init ? (this.value(init, false, new Set([...seen, name])) ?? m) : m;
|
||||
if (init) return this.value(init, false, new Set([...seen, name])) ?? m;
|
||||
return seen.has(name) ? m : (this.external?.(undefined, name) ?? m);
|
||||
},
|
||||
);
|
||||
if (part.length === 1 && part[0]!.kind === "num") return part[0]!.text;
|
||||
@@ -144,11 +161,20 @@ export class Constants {
|
||||
const last = names[names.length - 1]!;
|
||||
const qualifier = names[names.length - 2];
|
||||
if (qualifier === "MediaType") return MEDIA_TYPES[last.replace(/_VALUE$/, "")] ?? null;
|
||||
// `Other.NAME` of a class declared elsewhere.
|
||||
if (qualifier && !this.classes.has(qualifier)) {
|
||||
const v = this.external?.(qualifier, last);
|
||||
if (v != null) return v;
|
||||
}
|
||||
const init = this.fields.get(last);
|
||||
if (init && !seen.has(last)) {
|
||||
seen.add(last);
|
||||
return this.value(init, enums, seen);
|
||||
}
|
||||
if (!qualifier && !enums) {
|
||||
const v = this.external?.(undefined, last);
|
||||
if (v != null) return v;
|
||||
}
|
||||
return enums ? last : null;
|
||||
}
|
||||
}
|
||||
@@ -267,8 +293,8 @@ function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Const
|
||||
};
|
||||
}
|
||||
|
||||
export function controllersOf(file: SourceFile): Controller[] {
|
||||
const constants = new Constants(file);
|
||||
export function controllersOf(file: SourceFile, external?: ExternalConstant): Controller[] {
|
||||
const constants = new Constants(file, external);
|
||||
const out: Controller[] = [];
|
||||
for (const cls of allClasses(file)) {
|
||||
if (!cls.annotations.some((a) => CONTROLLER.has(a.name))) continue;
|
||||
@@ -279,10 +305,11 @@ export function controllersOf(file: SourceFile): Controller[] {
|
||||
}
|
||||
|
||||
/** Controllers of a Java / Kotlin source, with their endpoints. */
|
||||
export function springControllers(text: string): Controller[] {
|
||||
export function springControllers(text: string, external?: (file: SourceFile) => ExternalConstant): Controller[] {
|
||||
// Cheap guard: most files are not controllers.
|
||||
if (!/@(?:[\w.]+\.)?(?:Rest)?Controller\b/.test(text)) return [];
|
||||
return controllersOf(parseSource(text));
|
||||
const file = parseSource(text);
|
||||
return controllersOf(file, external?.(file));
|
||||
}
|
||||
|
||||
/** The controller and endpoint whose declaration holds `offset`. */
|
||||
|
||||
@@ -3,6 +3,7 @@ import { call, commands, onIdeEvent, type ProjectInfo } from "@/platform/ipc";
|
||||
import { ipcPath, isSameOrInside } from "@/platform/paths";
|
||||
import { projectFolder, relativePath, useProject } from "@/platform/project";
|
||||
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { constantPool, resetConstantPool } from "./constants";
|
||||
import { controllersOf } from "./endpoints";
|
||||
import { controllerMethods, type ControllerMethod } from "./feign";
|
||||
import { parseSource } from "./source";
|
||||
@@ -38,6 +39,7 @@ export function isRouteSource(path: string): boolean {
|
||||
/** Forgets the index, so the next search rescans the project. */
|
||||
export function clearRouteIndex() {
|
||||
cached = null;
|
||||
resetConstantPool();
|
||||
}
|
||||
|
||||
/** The project's routes, scanned once per project and kept in memory. */
|
||||
@@ -67,6 +69,7 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
|
||||
const sources = await call(commands.springRouteSources());
|
||||
const routes: EndpointEntry[] = [];
|
||||
const controllers: ControllerTarget[] = [];
|
||||
const parsed = [];
|
||||
for (const source of sources) {
|
||||
const path = ipcPath(source.path);
|
||||
const folder = project ? projectFolder(project, path)?.root : root;
|
||||
@@ -74,9 +77,14 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
|
||||
const base = ipcPath(folder).replace(/\/$/, "");
|
||||
if (!isSameOrInside(path, base)) continue;
|
||||
if (!source.text.includes("Controller")) continue;
|
||||
const file = parseSource(source.text);
|
||||
parsed.push({ source, path, base, file: parseSource(source.text) });
|
||||
}
|
||||
// Mapping paths built from other classes' constants need those classes first.
|
||||
const pool = constantPool();
|
||||
await pool.load(parsed.map((p) => p.file));
|
||||
for (const { source, path, base, file } of parsed) {
|
||||
controllers.push(...controllerMethods(source.text, file).map((method) => ({ ...method, path })));
|
||||
for (const controller of controllersOf(file)) {
|
||||
for (const controller of controllersOf(file, pool.resolverFor(file))) {
|
||||
for (const endpoint of controller.endpoints) {
|
||||
const at = lineCol(source.text, endpoint.offset);
|
||||
// A mapping without a path answers nothing to look up by URL; the method
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Text } from "@codemirror/state";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { EndpointEntry } from "@/workbench/contributions";
|
||||
import { endpointsFor, requestPathAt } from "./urlNavigation";
|
||||
|
||||
const entry = (method: string, url: string, methodName = "handler"): EndpointEntry => ({
|
||||
method,
|
||||
url,
|
||||
controller: "C",
|
||||
methodName,
|
||||
path: "/p/C.java",
|
||||
rel: "C.java",
|
||||
line: 3,
|
||||
col: 4,
|
||||
});
|
||||
|
||||
describe("request URL navigation", () => {
|
||||
const doc = Text.of([
|
||||
"### 读取本区配置",
|
||||
"GET http://localhost:19210/api/cockpit/config?x=1",
|
||||
"Content-Type: application/json",
|
||||
"",
|
||||
"###",
|
||||
"POST {{host}}/api/orders/{{id}}/items",
|
||||
"http://localhost:8080/health",
|
||||
"GET /relative/path",
|
||||
]);
|
||||
const at = (line: number, col: number) => doc.line(line).from + col;
|
||||
|
||||
it("finds the method and the path of the URL under the caret", () => {
|
||||
const get = requestPathAt(doc, at(2, 30));
|
||||
expect(get).toMatchObject({ method: "GET", path: "/api/cockpit/config" });
|
||||
expect(doc.sliceString(get!.from, get!.to)).toBe("/api/cockpit/config");
|
||||
expect(requestPathAt(doc, at(6, 20))).toMatchObject({ method: "POST", path: "/api/orders/{{id}}/items" });
|
||||
expect(requestPathAt(doc, at(7, 5))).toMatchObject({ method: "GET", path: "/health" });
|
||||
expect(requestPathAt(doc, at(8, 8))).toMatchObject({ method: "GET", path: "/relative/path" });
|
||||
expect(requestPathAt(doc, at(1, 5))).toBeNull();
|
||||
expect(requestPathAt(doc, at(3, 5))).toBeNull();
|
||||
expect(requestPathAt(doc, at(2, 1))).toBeNull();
|
||||
});
|
||||
|
||||
it("matches the endpoint by method, path variables and a context path", () => {
|
||||
const endpoints = [
|
||||
entry("GET", "/api/cockpit/config", "getConfig"),
|
||||
entry("POST", "/api/cockpit/config", "saveConfig"),
|
||||
entry("POST", "/api/orders/{id}/items", "addItem"),
|
||||
entry("GET", "/files/**", "file"),
|
||||
entry("*", "/any", "any"),
|
||||
];
|
||||
const names = (method: string, path: string) => endpointsFor(endpoints, method, path).map((e) => e.methodName);
|
||||
expect(names("GET", "/api/cockpit/config")).toEqual(["getConfig"]);
|
||||
expect(names("POST", "/api/orders/{{id}}/items")).toEqual(["addItem"]);
|
||||
expect(names("POST", "/api/orders/42/items")).toEqual(["addItem"]);
|
||||
expect(names("GET", "/files/a/b.txt")).toEqual(["file"]);
|
||||
expect(names("DELETE", "/any")).toEqual(["any"]);
|
||||
expect(names("GET", "/app/api/cockpit/config")).toEqual(["getConfig"]);
|
||||
expect(names("PUT", "/api/cockpit/config")).toEqual([]);
|
||||
expect(names("GET", "/api/cockpit")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Navigate › Declaration (⌘-click, ⌘B) on a request URL in a `.http` file: the
|
||||
* handler of the endpoint the request reaches (a Spring mapping, a plugin's
|
||||
* endpoint), matched by method and path.
|
||||
*/
|
||||
import type { Text } from "@codemirror/state";
|
||||
import { docOf } from "@/editor/lsp/lsp";
|
||||
import { registerNavigationProvider, type NavigationMatch } from "@/editor/navigationProviders";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { searchEndpoints, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { HTTP_LANGUAGE } from "./editor";
|
||||
import { METHODS } from "./language";
|
||||
|
||||
/** The request line holding `offset`: its method and the path part of the URL, as document offsets. */
|
||||
export function requestPathAt(
|
||||
doc: Text,
|
||||
offset: number,
|
||||
): { method: string; path: string; from: number; to: number } | null {
|
||||
const line = doc.lineAt(offset);
|
||||
const m = new RegExp(`^(\\s*(?:(${METHODS.join("|")})\\s+)?)(\\S+)`).exec(line.text);
|
||||
if (!m) return null;
|
||||
const url = m[3]!;
|
||||
// The scheme and host, or a `{{host}}` variable standing for them.
|
||||
const origin = /^(?:https?:\/\/[^/\s?#]+|\{\{[^}]+\}\}(?=\/))/.exec(url)?.[0];
|
||||
if (origin === undefined && !(m[2] && url.startsWith("/"))) return null;
|
||||
const start = line.from + m[1]!.length;
|
||||
if (offset < start || offset > start + url.length) return null;
|
||||
const path = url.slice(origin?.length ?? 0).replace(/[?#].*$/, "");
|
||||
// No path (`http://host`): the whole URL is the link.
|
||||
const from = path ? start + (origin?.length ?? 0) : start;
|
||||
return { method: m[2] ?? "GET", path: path || "/", from, to: path ? from + path.length : start + url.length };
|
||||
}
|
||||
|
||||
const segments = (p: string) => p.split("/").filter(Boolean);
|
||||
|
||||
/** How `request` segments match mapping `pattern` segments: `{var}`, `*` and `**` in the mapping, `{{var}}` in the request. */
|
||||
function matches(request: string[], pattern: string[]): boolean {
|
||||
if (!pattern.length) return !request.length;
|
||||
const [p, ...rest] = pattern;
|
||||
if (p === "**") return request.some((_, i) => matches(request.slice(i), rest)) || matches([], rest);
|
||||
if (!request.length) return false;
|
||||
const [r, ...more] = request;
|
||||
const variable = /^\{[^}]*\}$/.test(p!) || p === "*" || /^\{\{[^}]+\}\}$/.test(r!);
|
||||
return (variable || decodeURIComponent(r!) === p) && matches(more, rest);
|
||||
}
|
||||
|
||||
/** Endpoints `method` `path` reaches: the exact path, else after a context path (`/app` + mapping). */
|
||||
export function endpointsFor(endpoints: readonly EndpointEntry[], method: string, path: string): EndpointEntry[] {
|
||||
const request = segments(path);
|
||||
const sameMethod = endpoints.filter((e) => e.method === method || e.method === "*");
|
||||
const exact = sameMethod.filter((e) => matches(request, segments(e.url)));
|
||||
if (exact.length) return exact;
|
||||
for (let skip = 1; skip < request.length; skip++) {
|
||||
const found = sameMethod.filter((e) => matches(request.slice(skip), segments(e.url)));
|
||||
if (found.length) return found;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export async function urlTargets(doc: Text, offset: number): Promise<NavigationMatch | null> {
|
||||
const at = requestPathAt(doc, offset);
|
||||
if (!at) return null;
|
||||
const endpoints = await searchEndpoints(useProject.getState().project?.root ?? null);
|
||||
const found = endpointsFor(endpoints, at.method, at.path);
|
||||
if (!found.length) return null;
|
||||
return {
|
||||
from: at.from,
|
||||
to: at.to,
|
||||
targets: found.map((e) => ({
|
||||
path: e.path,
|
||||
range: { start: { line: e.line, col: e.col }, end: { line: e.line, col: e.col + e.methodName.length } },
|
||||
name: e.handler ?? `${e.controller}.${e.methodName}`,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function registerUrlNavigation(): () => void {
|
||||
return registerNavigationProvider(async (view, offset) => {
|
||||
const doc = docOf(view);
|
||||
if (!doc || doc.virtual || doc.language !== HTTP_LANGUAGE) return null;
|
||||
return urlTargets(view.state.doc, offset);
|
||||
});
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { useProjectTree } from "./store";
|
||||
import styles from "./FileRefactor.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { hostOs } from "@/platform/remote";
|
||||
|
||||
export type FileRefactorRequest =
|
||||
| {
|
||||
@@ -189,7 +190,12 @@ function RenameDialog({ request }: { request: Extract<FileRefactorRequest, { kin
|
||||
const stem = request.dir ? current : splitExtension(current)[0];
|
||||
el.setSelectionRange(0, stem.length || current.length);
|
||||
}, [current, request.dir]);
|
||||
const check = validateName(name, { siblings: request.siblings, current, caseInsensitive });
|
||||
const check = validateName(name, {
|
||||
siblings: request.siblings,
|
||||
current,
|
||||
caseInsensitive,
|
||||
windows: hostOs() === "windows",
|
||||
});
|
||||
const error = name === current ? null : check.error;
|
||||
const submit = () => {
|
||||
if (busy || error) return;
|
||||
@@ -357,7 +363,7 @@ function CopyDialog({ request }: { request: Extract<FileRefactorRequest, { kind:
|
||||
const error = request.paths.some((p) => isSameOrInside(dest, p) && dest !== parentOf(p))
|
||||
? "Cannot copy a folder into itself"
|
||||
: single
|
||||
? validateName(name, { siblings, caseInsensitive }).error
|
||||
? validateName(name, { siblings, caseInsensitive, windows: hostOs() === "windows" }).error
|
||||
: null;
|
||||
const subject = single
|
||||
? `Copy ${request.dir ? "directory" : "file"} '${nameOf(single)}'`
|
||||
|
||||
@@ -1,20 +1,36 @@
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { IconButton, type MenuItem } from "@/ui";
|
||||
import { VIEW_MODES, setViewMode, setViewOption, useProjectTree, type ViewOptions } from "./store";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { userScopes } from "@/platform/scopes";
|
||||
import { VIEW_MODES, setScopeView, setViewMode, setViewOption, useProjectTree, type ViewOptions } from "./store";
|
||||
import type { SortKey } from "./model";
|
||||
|
||||
/** The title's "Project ▾" pane switcher (IDEA: Project / Project Files / Open Files / …). */
|
||||
export function useProjectTitleMenu(): { label: string; items: MenuItem[] } {
|
||||
const mode = useProjectTree((s) => s.mode);
|
||||
const scope = useProjectTree((s) => s.scope);
|
||||
const unity = useProjectTree((s) => s.unity);
|
||||
// User scopes (Settings › Scopes) follow the built-in panes, as in IDEA.
|
||||
const scopes = userScopes(useProject((s) => (s.settings as { scopes?: unknown } | null)?.scopes));
|
||||
const items: MenuItem[] = VIEW_MODES.filter(([id]) => id !== "unity" || unity).map(([id, label]) => ({
|
||||
id,
|
||||
label,
|
||||
checked: id === mode,
|
||||
run: () => setViewMode(id),
|
||||
}));
|
||||
if (scopes.length) {
|
||||
items.push({ kind: "separator" });
|
||||
for (const s of scopes)
|
||||
items.push({
|
||||
id: `scope:${s.name}`,
|
||||
label: s.name,
|
||||
checked: mode === "scope" && scope === s.name,
|
||||
run: () => setScopeView(s.name),
|
||||
});
|
||||
}
|
||||
return {
|
||||
label: VIEW_MODES.find(([id]) => id === mode)?.[1] ?? "Project",
|
||||
items: VIEW_MODES.filter(([id]) => id !== "unity" || unity).map(([id, label]) => ({
|
||||
id,
|
||||
label,
|
||||
checked: id === mode,
|
||||
run: () => setViewMode(id),
|
||||
})),
|
||||
label: mode === "scope" ? (scope ?? "Project") : (VIEW_MODES.find(([id]) => id === mode)?.[1] ?? "Project"),
|
||||
items,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,9 @@
|
||||
.excluded {
|
||||
color: var(--vcs-ignored);
|
||||
}
|
||||
.deprecated {
|
||||
text-decoration-line: line-through;
|
||||
}
|
||||
.error {
|
||||
text-decoration-line: underline;
|
||||
text-decoration-style: wavy;
|
||||
@@ -63,6 +66,10 @@
|
||||
text-decoration-skip-ink: none;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
/* The error's wavy underline takes the text decoration; the strike-out is drawn underneath. */
|
||||
.deprecated.error {
|
||||
background: linear-gradient(currentColor, currentColor) 0 55% / 100% 1px no-repeat;
|
||||
}
|
||||
.suffix {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
|
||||
@@ -347,6 +347,8 @@ const Row = memo(function Row({
|
||||
// Maven / Gradle module folders are bold too, as in IDEA.
|
||||
moduleFolder && styles.moduleLabel,
|
||||
faded && !deco.color && styles.excluded,
|
||||
// IDEA strikes out deprecated classes.
|
||||
file?.deprecated && styles.deprecated,
|
||||
deco.error && styles.error,
|
||||
)}
|
||||
style={deco.color ? { color: deco.color } : undefined}
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
*/
|
||||
import type { FileMove, UndoOutcome, WorkspaceEdit } from "@/bindings";
|
||||
import { openEditorPaths } from "@/editor/api";
|
||||
import { notifyFilesMoved } from "@/platform/fileOps";
|
||||
import { notifyFilesMoved, trackFileMove } from "@/platform/fileOps";
|
||||
import { call, commands, emitLocalIdeEvent, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import { projectFs } from "./fs";
|
||||
import { isSameOrInside, nameOf, parentOf } from "./paths";
|
||||
@@ -185,13 +186,19 @@ export function movedPath(path: string, moves: readonly FileMove[]): string {
|
||||
|
||||
/** IDEA retargets editors of moved files: unsaved changes are saved first, tabs reopen at the new paths. */
|
||||
async function withEditorsFollowing<T>(run: () => Promise<T>, done: (r: T) => FileMove[]): Promise<T> {
|
||||
const projectRoot = () => useProject.getState().project?.root ?? null;
|
||||
const root = projectRoot();
|
||||
const editor = maybeEditorService();
|
||||
const openBefore = editor ? openEditorPaths() : [];
|
||||
if (editor) await saveAllQuietly(editor);
|
||||
const active = editor?.activePath() ?? null;
|
||||
const result = await run();
|
||||
const applied = done(result);
|
||||
await notifyFilesMoved(applied);
|
||||
const { result, applied } = await trackFileMove(root, async () => {
|
||||
const result = await run();
|
||||
const applied = done(result);
|
||||
if (root === projectRoot()) await notifyFilesMoved(applied);
|
||||
return { result, applied };
|
||||
});
|
||||
if (root !== projectRoot()) return result;
|
||||
const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));
|
||||
if (applied.length)
|
||||
emitLocalIdeEvent({
|
||||
|
||||
@@ -18,8 +18,8 @@ export interface ProjectFs {
|
||||
createFileBytes(path: string, data: Uint8Array): Promise<void>;
|
||||
createDir(path: string): Promise<void>;
|
||||
rename(from: string, to: string): Promise<void>;
|
||||
/** Moves to the trash when possible. */
|
||||
delete(path: string): Promise<void>;
|
||||
/** Moves to the trash when possible and returns a restore function reporting skipped paths. */
|
||||
delete(path: string): Promise<() => Promise<string[]>>;
|
||||
copy(from: string, to: string): Promise<void>;
|
||||
importLocal(from: string, to: string, upload?: LocalImport): Promise<string[]>;
|
||||
}
|
||||
@@ -37,8 +37,9 @@ export const tauriFs: ProjectFs = {
|
||||
createDir: async (path) => void (await call(commands.fsCreateDir(path))),
|
||||
rename: async (from, to) => void (await call(commands.fsRename(from, to))),
|
||||
delete: async (path) => {
|
||||
await call(commands.fsDelete(path));
|
||||
const undo = await call(commands.fsDeleteWithUndo(path));
|
||||
notifyFileOperation({ kind: "deleted", paths: [path] });
|
||||
return () => call(commands.fsUndoDelete(undo));
|
||||
},
|
||||
copy: async (from, to) => {
|
||||
await call(commands.fsCopy(from, to));
|
||||
@@ -238,8 +239,16 @@ export class MemoryFs implements ProjectFs {
|
||||
|
||||
async delete(path: string) {
|
||||
if (!this.nodes.has(path)) throw err("notFound", `${path} not found`);
|
||||
for (const p of [...this.nodes.keys()]) if (p === path || isInside(p, path)) this.nodes.delete(p);
|
||||
const deleted = [...this.nodes].filter(([p]) => p === path || isInside(p, path));
|
||||
for (const [p] of deleted) this.nodes.delete(p);
|
||||
this.emit({ removed: [path] });
|
||||
return async () => {
|
||||
if (this.nodes.has(path)) return [path];
|
||||
this.mkdirp(parentOf(path));
|
||||
for (const [p, node] of deleted) this.nodes.set(p, node);
|
||||
this.emit({ created: deleted.map(([p]) => p) });
|
||||
return [];
|
||||
};
|
||||
}
|
||||
|
||||
async copy(from: string, to: string) {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/** Project view: the "project" tool window, its file operations and actions. */
|
||||
import { onEditorEvent, openEditorPaths } from "@/editor/api";
|
||||
import { commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { userScopes } from "@/platform/scopes";
|
||||
import { useBuildModel } from "@/platform/buildModel";
|
||||
import { effectiveContentRoots, validateProjectStructure, type RootFolder } from "@/platform/languageSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -12,6 +14,7 @@ import {
|
||||
registerOverlay,
|
||||
registerProjectViewRoot,
|
||||
registerToolWindow,
|
||||
notifications,
|
||||
registerUndoHandler,
|
||||
setProjectViewLead,
|
||||
useLocalChanges,
|
||||
@@ -38,10 +41,14 @@ import {
|
||||
reloadLoadedDirs,
|
||||
setChangedFiles,
|
||||
setOpenFiles,
|
||||
setScopeFiles,
|
||||
setViewMode,
|
||||
useProjectTree,
|
||||
} from "./store";
|
||||
|
||||
/** Files a scope pane lists at most. */
|
||||
const SCOPE_FILES_LIMIT = 20000;
|
||||
|
||||
export function activate(): () => void {
|
||||
loadHomeDir();
|
||||
let unityTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -194,6 +201,53 @@ export function activate(): () => void {
|
||||
if (s.lists !== prev.lists) syncChanged();
|
||||
});
|
||||
|
||||
// Scope panes: the files of the chosen user scope, again as files come and go.
|
||||
let scopeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let scopeGeneration = 0;
|
||||
const syncScope = () => {
|
||||
clearTimeout(scopeTimer);
|
||||
scopeTimer = setTimeout(() => void loadScopeFiles(++scopeGeneration), 150);
|
||||
};
|
||||
const loadScopeFiles = async (gen: number) => {
|
||||
const { mode, scope } = useProjectTree.getState();
|
||||
if (mode !== "scope" || !scope || !isTauri()) return;
|
||||
const pattern = userScopes().find((s) => s.name === scope)?.pattern;
|
||||
if (!pattern?.trim()) return setScopeFiles([]);
|
||||
try {
|
||||
const found = await call(commands.scopeFiles(pattern, SCOPE_FILES_LIMIT));
|
||||
if (gen !== scopeGeneration) return;
|
||||
setScopeFiles(found.paths);
|
||||
if (found.truncated)
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
group: "project",
|
||||
key: "project.scopeTruncated",
|
||||
title: tx`The scope ${scope} has more than ${SCOPE_FILES_LIMIT} files; the Project view shows the first ones`,
|
||||
});
|
||||
} catch (e) {
|
||||
if (gen !== scopeGeneration) return;
|
||||
setScopeFiles([]);
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
group: "project",
|
||||
key: "project.scopeError",
|
||||
title: tx`Cannot show the scope ${scope}`,
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
}
|
||||
};
|
||||
syncScope();
|
||||
const unsubScopeMode = useProjectTree.subscribe((s, prev) => {
|
||||
if (s.mode !== prev.mode || s.scope !== prev.scope) syncScope();
|
||||
});
|
||||
const unsubScopeSettings = useProject.subscribe((s, prev) => {
|
||||
const scopes = (x: typeof s) => (x.settings as { scopes?: unknown } | null)?.scopes;
|
||||
if (scopes(s) !== scopes(prev)) syncScope();
|
||||
});
|
||||
const unsubScopeFs = onIdeEvent("fsChanged", (e) => {
|
||||
if (e.created.length || e.removed.length) syncScope();
|
||||
});
|
||||
|
||||
// IDEA's navigation bar shows the tree's current node while the tree is the
|
||||
// user's context; the editor hands it back on focus or on a tab switch.
|
||||
const publishLead = () => setProjectViewLead(leadSelection());
|
||||
@@ -211,6 +265,10 @@ export function activate(): () => void {
|
||||
() => clearTimeout(openTimer),
|
||||
unsubEditor,
|
||||
unsubDecorations,
|
||||
() => clearTimeout(scopeTimer),
|
||||
unsubScopeMode,
|
||||
unsubScopeSettings,
|
||||
unsubScopeFs,
|
||||
() => {
|
||||
unsubLead();
|
||||
setProjectViewLead(null);
|
||||
|
||||
@@ -13,7 +13,7 @@ import { osClipboard } from "./clipboard";
|
||||
import { lastFileRefactoring, nextFileOperation, runFileRefactoring, undoFileRefactoring } from "./fileRefactor";
|
||||
import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs";
|
||||
import { beginLocalImport, projectFs } from "./fs";
|
||||
import { call, commands, IpcError, isCancelled } from "@/platform/ipc";
|
||||
import { IpcError, isCancelled } from "@/platform/ipc";
|
||||
import { MEMBER_PREFIX, type ProjectNode } from "./model";
|
||||
import {
|
||||
isInside,
|
||||
@@ -501,33 +501,31 @@ export async function deleteSelection(nodes: ProjectNode[] = selectedNodes()) {
|
||||
const fs = projectFs(root);
|
||||
const parents = new Set<string>();
|
||||
const errors: string[] = [];
|
||||
const deleted: string[] = [];
|
||||
const deleted: NonNullable<typeof lastDelete>["items"] = [];
|
||||
for (const p of paths) {
|
||||
try {
|
||||
await fs.delete(p);
|
||||
const restore = await fs.delete(p);
|
||||
parents.add(parentOf(p));
|
||||
deleted.push(p);
|
||||
deleted.push({ path: p, restore });
|
||||
} catch (e) {
|
||||
errors.push(`${nameOf(p)}: ${errorMessage(e)}`);
|
||||
}
|
||||
}
|
||||
if (deleted.length) {
|
||||
const dirs = new Set(nodes.filter((n) => n.dir).map((n) => n.path));
|
||||
lastDelete = { paths: deleted, dirs: deleted.filter((p) => dirs.has(p)), seq: nextFileOperation() };
|
||||
}
|
||||
if (deleted.length && get().root === root) lastDelete = { root, items: deleted, seq: nextFileOperation() };
|
||||
if (errors.length)
|
||||
notifications().notify({ level: "error", title: "Some items could not be deleted", body: errors.join("\n") });
|
||||
await Promise.all([...parents].map((d) => loadDir(d, true)));
|
||||
if (next) revealPath(next, refocus);
|
||||
}
|
||||
|
||||
/** The last Delete in the Project view; Undo brings its files back from Local History. */
|
||||
let lastDelete: { paths: string[]; dirs: string[]; seq: number } | null = null;
|
||||
/** The last Delete in the Project view and the exact snapshots from that operation. */
|
||||
let lastDelete: { root: string; items: Array<{ path: string; restore: () => Promise<string[]> }>; seq: number } | null =
|
||||
null;
|
||||
|
||||
/** Undo in the Project view: reverts the latest delete or move / rename; false when there is none. */
|
||||
export function undoLastFileOperation(): boolean {
|
||||
const move = lastFileRefactoring();
|
||||
if (lastDelete && (!move || lastDelete.seq > move.seq)) {
|
||||
if (lastDelete && lastDelete.root === get().root && (!move || lastDelete.seq > move.seq)) {
|
||||
void undoDelete();
|
||||
return true;
|
||||
}
|
||||
@@ -536,43 +534,37 @@ export function undoLastFileOperation(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Restores the deleted files (and folders) from their last Local History snapshots. */
|
||||
/** Restores only entries captured before this Delete. */
|
||||
export async function undoDelete(): Promise<boolean> {
|
||||
const op = lastDelete;
|
||||
const { root } = get();
|
||||
if (!op || !root) return false;
|
||||
if (!op || get().root !== op.root) return false;
|
||||
lastDelete = null;
|
||||
const fs = projectFs(root);
|
||||
const failed: string[] = [];
|
||||
const failed = new Set<string>();
|
||||
const parents = new Set<string>();
|
||||
for (const p of op.paths) {
|
||||
let restored: string | undefined;
|
||||
for (const { path, restore } of op.items) {
|
||||
if (get().root !== op.root) break;
|
||||
try {
|
||||
const history = await call(commands.historyListDir(p));
|
||||
const gone = new Set(history.deleted);
|
||||
const latest = new Map<string, string>();
|
||||
for (const e of history.entries)
|
||||
if (e.kind === "snapshot" && e.id && gone.has(e.path) && !latest.has(e.path)) latest.set(e.path, e.id);
|
||||
const dir = op.dirs.includes(p);
|
||||
if (!latest.size && !dir) throw new Error("no Local History snapshot");
|
||||
if (dir) await fs.createDir(p);
|
||||
for (const [path, id] of latest) await call(commands.historyRestore(path, id));
|
||||
parents.add(parentOf(p));
|
||||
const skipped = await restore();
|
||||
for (const skippedPath of skipped) failed.add(skippedPath);
|
||||
if (!restored && !skipped.includes(path)) restored = path;
|
||||
} catch {
|
||||
failed.push(nameOf(p));
|
||||
failed.add(path);
|
||||
}
|
||||
parents.add(parentOf(path));
|
||||
}
|
||||
if (get().root !== op.root) return false;
|
||||
await Promise.all([...parents].map((d) => loadDir(d, true)));
|
||||
const restored = op.paths.find((p) => !failed.includes(nameOf(p)));
|
||||
if (restored) revealPath(restored, true);
|
||||
const names = failed.join(", ");
|
||||
if (failed.length)
|
||||
const names = [...failed].join("\n");
|
||||
if (failed.size)
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
title: "Some items could not be restored",
|
||||
body: tx`Not in Local History: ${names}. They are in the Trash.`,
|
||||
body: tx`Check the system Trash for these items. ${names}`,
|
||||
key: "project.undoDelete",
|
||||
});
|
||||
return !failed.length;
|
||||
return !failed.size;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -79,6 +79,15 @@ describe("validateName", () => {
|
||||
expect(validateName("/abs", { siblings, allowNested: true }).error).toMatch(/start with/);
|
||||
});
|
||||
|
||||
it("rejects Windows names that the filesystem would trim", () => {
|
||||
const options = { siblings, allowNested: true };
|
||||
for (const name of ["example.txt.", "example.txt ", "folder./file", "folder /file"]) {
|
||||
expect(validateName(name, { ...options, windows: true }).error).toMatch(/end with a period or space/);
|
||||
expect(validateName(name, options).error).toBeNull();
|
||||
}
|
||||
expect(validateName(".settings/file.txt", { ...options, windows: true }).error).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts the current name and case-only renames", () => {
|
||||
expect(validateName("Order.kt", { siblings, current: "Order.kt" }).error).toBeNull();
|
||||
expect(validateName("order.kt", { siblings, current: "Order.kt", caseInsensitive: true }).error).toBeNull();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** POSIX path helpers for backend paths (the backend always reports `/`-separated absolute paths). */
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
export { isSameOrInside } from "@/platform/paths";
|
||||
|
||||
@@ -79,7 +80,7 @@ export interface ValidateOptions {
|
||||
current?: string;
|
||||
/** Compare names case-insensitively (macOS / Windows default file systems). */
|
||||
caseInsensitive?: boolean;
|
||||
/** Windows' reserved characters are rejected. */
|
||||
/** Apply Windows naming rules. */
|
||||
windows?: boolean;
|
||||
}
|
||||
|
||||
@@ -99,6 +100,8 @@ export function validateName(raw: string, opts: ValidateOptions): NameCheck {
|
||||
if (seg === "." || seg === "..") return { error: `'${seg}' is not a valid name` };
|
||||
if (opts.windows && (WINDOWS_INVALID.test(seg) || WINDOWS_RESERVED.test(seg)))
|
||||
return { error: `'${seg}' is not a valid file name` };
|
||||
if (opts.windows && (seg.endsWith(".") || seg.endsWith(" ")))
|
||||
return { error: tx("Windows file and folder names cannot end with a period or space") };
|
||||
if (seg.length > 255) return { error: "Name is too long" };
|
||||
}
|
||||
const fold = (s: string) => (opts.caseInsensitive ? s.toLowerCase() : s);
|
||||
|
||||
@@ -84,7 +84,7 @@ function storedOptions(): ViewOptions {
|
||||
}
|
||||
|
||||
/** IDEA's Project view panes ("Project ▾" in the tool window header). */
|
||||
export type ViewMode = "unity" | "project" | "projectFiles" | "openFiles" | "changedFiles" | "scratches";
|
||||
export type ViewMode = "unity" | "project" | "projectFiles" | "openFiles" | "changedFiles" | "scratches" | "scope";
|
||||
|
||||
export const VIEW_MODES: ReadonlyArray<[ViewMode, string]> = [
|
||||
["unity", "Unity"],
|
||||
@@ -96,7 +96,7 @@ export const VIEW_MODES: ReadonlyArray<[ViewMode, string]> = [
|
||||
];
|
||||
|
||||
/** Modes listing just some files (expanded as they appear). */
|
||||
export const isFilteredMode = (mode: ViewMode) => mode === "openFiles" || mode === "changedFiles";
|
||||
export const isFilteredMode = (mode: ViewMode) => mode === "openFiles" || mode === "changedFiles" || mode === "scope";
|
||||
|
||||
export type Editing =
|
||||
| { kind: "new"; parent: string; nodeKind: "file" | "dir"; pkg?: PackageKind }
|
||||
@@ -134,12 +134,17 @@ interface ProjectTreeState {
|
||||
openFiles: readonly string[];
|
||||
/** Files with VCS changes (All Changed Files mode). */
|
||||
changedFiles: readonly string[];
|
||||
/** The user scope a "scope" pane shows (Settings › Scopes), by name. */
|
||||
scope: string | null;
|
||||
/** The files of `scope`. */
|
||||
scopeFiles: readonly string[];
|
||||
/** Loaded document outlines per file path, for the "Show Members" rows (empty for unsupported files). */
|
||||
outlines: ReadonlyMap<string, readonly OutlineItem[]>;
|
||||
}
|
||||
|
||||
const OPTIONS_KEY = "openidea.projectTree.options";
|
||||
const MODE_KEY = "openidea.projectTree.mode";
|
||||
const SCOPE_KEY = "openidea.projectTree.scope";
|
||||
const expandedKey = (root: string) => `openidea.projectTree.expanded:${root}`;
|
||||
const MAX_PERSISTED = 3000;
|
||||
|
||||
@@ -178,11 +183,14 @@ export const useProjectTree = create<ProjectTreeState>(() => ({
|
||||
mode: readMode(),
|
||||
openFiles: [],
|
||||
changedFiles: [],
|
||||
scope: readJson<string>(SCOPE_KEY),
|
||||
scopeFiles: [],
|
||||
outlines: new Map(),
|
||||
}));
|
||||
|
||||
function readMode(): ViewMode {
|
||||
const m = readJson<string>(MODE_KEY);
|
||||
if (m === "scope" && readJson<string>(SCOPE_KEY)) return "scope";
|
||||
return VIEW_MODES.find(([id]) => id === m)?.[0] ?? "project";
|
||||
}
|
||||
|
||||
@@ -210,7 +218,13 @@ let memo: {
|
||||
const EMPTY_MODEL: TreeModel = { roots: [], children: new Map(), byKey: new Map(), keyOfPath: new Map() };
|
||||
|
||||
const filesOf = (s: ProjectTreeState) =>
|
||||
s.mode === "openFiles" ? s.openFiles : s.mode === "changedFiles" ? s.changedFiles : null;
|
||||
s.mode === "openFiles"
|
||||
? s.openFiles
|
||||
: s.mode === "changedFiles"
|
||||
? s.changedFiles
|
||||
: s.mode === "scope"
|
||||
? s.scopeFiles
|
||||
: null;
|
||||
|
||||
function treeOptions(s: ProjectTreeState): TreeOptions {
|
||||
return s.mode === "unity" && s.unity && s.root ? { ...s.options, compact: false, unityRoot: s.root } : s.options;
|
||||
@@ -424,6 +438,25 @@ export function setOpenFiles(paths: readonly string[]) {
|
||||
if (prev.length !== paths.length || prev.some((p, i) => p !== paths[i])) set({ openFiles: [...paths] });
|
||||
}
|
||||
|
||||
/** Shows the user scope `name` as a pane of the Project view (IDEA's scope views). */
|
||||
export function setScopeView(name: string) {
|
||||
const s = get();
|
||||
if (s.mode === "scope" && s.scope === name) return;
|
||||
writeJson(SCOPE_KEY, name);
|
||||
if (s.mode === "scope") {
|
||||
autoExpanded.clear();
|
||||
set({ scope: name, scopeFiles: [], expanded: new Set(), selected: new Set(), lead: null, editing: null });
|
||||
return;
|
||||
}
|
||||
set({ scope: name, scopeFiles: [] });
|
||||
setViewMode("scope");
|
||||
}
|
||||
|
||||
export function setScopeFiles(paths: readonly string[]) {
|
||||
const prev = get().scopeFiles;
|
||||
if (prev.length !== paths.length || prev.some((p, i) => p !== paths[i])) set({ scopeFiles: [...paths] });
|
||||
}
|
||||
|
||||
export function setChangedFiles(paths: readonly string[]) {
|
||||
const prev = get().changedFiles;
|
||||
if (prev.length !== paths.length || prev.some((p, i) => p !== paths[i])) set({ changedFiles: [...paths] });
|
||||
|
||||
@@ -1,59 +1,40 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const history = vi.hoisted(() => ({
|
||||
restored: [] as Array<[string, string]>,
|
||||
snapshots: [] as Array<{ id: string; path: string }>,
|
||||
}));
|
||||
|
||||
vi.mock("@/workbench/messages", () => ({
|
||||
confirm: async () => true,
|
||||
confirmChecked: async () => ({ checked: false }),
|
||||
ask: async () => ({ button: "cancel", checked: false }),
|
||||
}));
|
||||
|
||||
vi.mock("@/editor/refactor", () => ({
|
||||
fileUsages: async () => ({ status: "ok", usages: [] }),
|
||||
askUsagesDetected: async () => "cancel",
|
||||
viewUsages: () => {},
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
// Local History as the backend keeps it: deleted files' snapshots, newest first.
|
||||
historyListDir: (dir: string) => {
|
||||
const entries = history.snapshots
|
||||
.filter((s) => s.path === dir || s.path.startsWith(`${dir}/`))
|
||||
.map((s) => ({ ...s, timestampMs: 0, label: "Deleted", size: 1, kind: "snapshot" }));
|
||||
return ok({ entries, deleted: [...new Set(entries.map((e) => e.path))] });
|
||||
},
|
||||
historyRestore: (path: string, id: string) => {
|
||||
history.restored.push([path, id]);
|
||||
return fs.createFile(path).then(() => ok(null));
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { MemoryFs, setProjectFsForTests } = await import("./fs");
|
||||
const { currentModel, initProjectTree, loadDir } = await import("./store");
|
||||
const { deleteSelection, undoLastFileOperation } = await import("./operations");
|
||||
let fs: InstanceType<typeof MemoryFs>;
|
||||
|
||||
describe("Undo in the Project view", () => {
|
||||
beforeEach(() => {
|
||||
fs = new MemoryFs({ "/p/a.txt": "a", "/p/lib/x.ts": "x", "/p/lib/empty/": null }, "/p");
|
||||
let fs: InstanceType<typeof MemoryFs>;
|
||||
|
||||
beforeEach(async () => {
|
||||
fs = new MemoryFs(
|
||||
{
|
||||
"/p/lib/current.txt": "current",
|
||||
"/p/lib/obsolete.txt": "obsolete",
|
||||
"/p/lib/empty-child/leaf": null,
|
||||
"/p/a.txt": "a",
|
||||
},
|
||||
"/p",
|
||||
);
|
||||
setProjectFsForTests(fs, "/p");
|
||||
initProjectTree("/p", "proj");
|
||||
history.restored.length = 0;
|
||||
history.snapshots = [
|
||||
{ id: "new-a", path: "/p/a.txt" },
|
||||
{ id: "old-a", path: "/p/a.txt" },
|
||||
{ id: "x1", path: "/p/lib/x.ts" },
|
||||
];
|
||||
await loadDir("/p");
|
||||
await loadDir("/p/lib");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setProjectFsForTests(null);
|
||||
initProjectTree(null);
|
||||
@@ -61,19 +42,17 @@ describe("Undo in the Project view", () => {
|
||||
|
||||
const labels = (dir: string) => (currentModel().children.get(dir) ?? []).map((n) => n.label);
|
||||
|
||||
it("brings deleted files and folders back from their latest Local History snapshots", async () => {
|
||||
await loadDir("/p");
|
||||
expect(labels("/p")).toEqual(["lib", "a.txt"]);
|
||||
it("restores a batch exactly as it was before Delete", async () => {
|
||||
await deleteSelection([currentModel().byKey.get("/p/lib/obsolete.txt")!]);
|
||||
expect(fs.nodes.has("/p/lib/obsolete.txt")).toBe(false);
|
||||
await deleteSelection([currentModel().byKey.get("/p/a.txt")!, currentModel().byKey.get("/p/lib")!]);
|
||||
expect(labels("/p")).toEqual([]);
|
||||
|
||||
expect(undoLastFileOperation()).toBe(true);
|
||||
await vi.waitFor(() => expect(labels("/p")).toEqual(["lib", "a.txt"]));
|
||||
expect(history.restored).toEqual([
|
||||
["/p/a.txt", "new-a"],
|
||||
["/p/lib/x.ts", "x1"],
|
||||
]);
|
||||
// Undone once: nothing left to undo.
|
||||
expect(fs.nodes.has("/p/lib/current.txt")).toBe(true);
|
||||
expect(fs.nodes.has("/p/lib/empty-child/leaf")).toBe(true);
|
||||
expect(fs.nodes.has("/p/lib/obsolete.txt")).toBe(false);
|
||||
expect(undoLastFileOperation()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -216,6 +216,25 @@ describe("project view modes", () => {
|
||||
).toEqual(["README.md"]);
|
||||
});
|
||||
|
||||
it("shows a user scope's files as a pane", () => {
|
||||
store.setScopeView("Changed for FTP");
|
||||
expect(useProjectTree.getState()).toMatchObject({ mode: "scope", scope: "Changed for FTP" });
|
||||
store.setScopeFiles(["/p/src/App.kt", "/p/README.md"]);
|
||||
autoExpand(currentModel());
|
||||
expect(
|
||||
currentModel()
|
||||
.children.get("/p")!
|
||||
.map((n) => n.label),
|
||||
).toEqual(["src", "README.md"]);
|
||||
expect(modeShows("/p/src/App.kt")).toBe(true);
|
||||
expect(modeShows("/p/src/Other.kt")).toBe(false);
|
||||
// Another scope starts from its own files.
|
||||
store.setScopeView("Other");
|
||||
expect(useProjectTree.getState()).toMatchObject({ mode: "scope", scope: "Other", scopeFiles: [] });
|
||||
setViewMode("project");
|
||||
expect(useProjectTree.getState().mode).toBe("project");
|
||||
});
|
||||
|
||||
it("reveals library files through their group nodes", async () => {
|
||||
await loadDir("/py/lib/python3.12");
|
||||
expect(revealPath("/py/lib/python3.12/os.py")).toBe(true);
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { deleteCharForward, history, redo, undo } from "@codemirror/commands";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { bookmarkGutter } from "../bookmarks/gutter";
|
||||
import { bookmarkByMnemonic, loadBookmarks, updateBookmarkData, useBookmarks, type Bookmark } from "../bookmarks/store";
|
||||
|
||||
const path = "/project/file.txt";
|
||||
const bookmark = (line: number, text: string, extra: Partial<Bookmark> = {}): Bookmark => ({
|
||||
path,
|
||||
line,
|
||||
text,
|
||||
created: line + 1,
|
||||
list: "default",
|
||||
...extra,
|
||||
});
|
||||
|
||||
let view: EditorView | undefined;
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
loadBookmarks("/project");
|
||||
});
|
||||
afterEach(() => {
|
||||
view?.destroy();
|
||||
view = undefined;
|
||||
});
|
||||
|
||||
function editor(doc: string, items: Bookmark[]) {
|
||||
updateBookmarkData((d) => ({ ...d, items, lists: [...d.lists, { id: "custom", name: "Investigate" }] }));
|
||||
view = new EditorView({ doc, parent: document.body, extensions: [history(), bookmarkGutter(path, () => {})] });
|
||||
return view;
|
||||
}
|
||||
|
||||
describe("bookmark gutter edits", () => {
|
||||
it.each([
|
||||
["plain text", ["first", "remove", "survive"]],
|
||||
["TypeScript", ["const first = 1;", "const remove = 2;", "const survive = 3;"]],
|
||||
])("keeps the surviving bookmark's identity after deleting the adjacent line in %s", async (_kind, lines) => {
|
||||
const survivor = bookmark(2, lines[2]!, { mnemonic: "3", description: "Review this", list: "custom" });
|
||||
const otherFile = bookmark(0, "other file", { path: "/project/other", mnemonic: "4" });
|
||||
const v = editor(lines.join("\n"), [bookmark(1, lines[1]!), survivor, otherFile]);
|
||||
v.dispatch({ selection: { anchor: v.state.doc.line(2).from, head: v.state.doc.line(3).from } });
|
||||
expect(deleteCharForward(v)).toBe(true);
|
||||
await Promise.resolve();
|
||||
|
||||
const moved = { ...survivor, line: 1 };
|
||||
expect(v.state.doc.toString()).toBe([lines[0], lines[2]].join("\n"));
|
||||
expect(useBookmarks.getState().items).toEqual([moved, otherFile]);
|
||||
expect(bookmarkByMnemonic(useBookmarks.getState().items, "3")).toEqual(moved);
|
||||
expect(v.dom.querySelector(".cm-openidea-bookmarkMnemonic")?.textContent).toBe("3");
|
||||
expect(v.dom.querySelector(".cm-openidea-bookmark")).toBeNull();
|
||||
|
||||
expect(undo(v)).toBe(true);
|
||||
await Promise.resolve();
|
||||
expect(v.state.doc.toString()).toBe(lines.join("\n"));
|
||||
expect(bookmarkByMnemonic(useBookmarks.getState().items, "3")).toEqual(survivor);
|
||||
expect(redo(v)).toBe(true);
|
||||
await Promise.resolve();
|
||||
expect(bookmarkByMnemonic(useBookmarks.getState().items, "3")).toEqual(moved);
|
||||
});
|
||||
|
||||
it("preserves an adjacent empty line's bookmark when its predecessor is deleted", async () => {
|
||||
const blank = bookmark(2, "", { mnemonic: "3" });
|
||||
const v = editor("first\nremove\n\nlast", [bookmark(1, "remove"), blank]);
|
||||
v.dispatch({ changes: { from: v.state.doc.line(2).from, to: v.state.doc.line(3).from } });
|
||||
await Promise.resolve();
|
||||
expect(useBookmarks.getState().items).toEqual([{ ...blank, line: 1 }]);
|
||||
});
|
||||
|
||||
it("keeps a surviving anchor when a replacement consumes the preceding line", async () => {
|
||||
const survivor = bookmark(2, "survive", { mnemonic: "3" });
|
||||
const v = editor("first\nremove\nsurvive", [bookmark(1, "remove"), survivor]);
|
||||
v.dispatch({ changes: { from: v.state.doc.line(2).from, to: v.state.doc.line(3).from, insert: "new " } });
|
||||
await Promise.resolve();
|
||||
expect(useBookmarks.getState().items).toEqual([{ ...survivor, line: 1, text: "new survive" }]);
|
||||
});
|
||||
|
||||
it("tracks an inserted line and keeps a bookmark when its first character is deleted", async () => {
|
||||
const saved = bookmark(1, "sample", { mnemonic: "3", description: "Review this" });
|
||||
const v = editor("first\nsample", [saved]);
|
||||
const start = v.state.doc.line(2).from;
|
||||
v.dispatch({ changes: { from: start, to: start + 1 } });
|
||||
await Promise.resolve();
|
||||
expect(useBookmarks.getState().items).toEqual([saved]);
|
||||
v.dispatch({ changes: { from: start, insert: "new line\n" } });
|
||||
await Promise.resolve();
|
||||
expect(useBookmarks.getState().items).toEqual([{ ...saved, line: 2, text: "ample" }]);
|
||||
});
|
||||
|
||||
it("keeps the first bookmark when two surviving lines are joined", async () => {
|
||||
const first = bookmark(0, "first", { mnemonic: "1" });
|
||||
const v = editor("first\nsecond", [first, bookmark(1, "second", { mnemonic: "2" })]);
|
||||
v.dispatch({ changes: { from: 5, to: 6 } });
|
||||
await Promise.resolve();
|
||||
expect(useBookmarks.getState().items).toEqual([first]);
|
||||
});
|
||||
|
||||
it("publishes a deletion once when the edit is mirrored in another view", async () => {
|
||||
const survivor = bookmark(2, "survive", { mnemonic: "3", description: "Review this", list: "custom" });
|
||||
const v = editor("first\nremove\nsurvive", [bookmark(1, "remove"), survivor]);
|
||||
const other = new EditorView({
|
||||
doc: v.state.doc,
|
||||
parent: document.body,
|
||||
extensions: bookmarkGutter(path, () => {}),
|
||||
});
|
||||
try {
|
||||
const changes = { from: v.state.doc.line(2).from, to: v.state.doc.line(3).from };
|
||||
v.dispatch({ changes });
|
||||
other.dispatch({ changes });
|
||||
await Promise.resolve();
|
||||
expect(useBookmarks.getState().items).toEqual([{ ...survivor, line: 1 }]);
|
||||
expect(other.dom.querySelector(".cm-openidea-bookmarkMnemonic")?.textContent).toBe("3");
|
||||
expect(other.dom.querySelector(".cm-openidea-bookmark")).toBeNull();
|
||||
} finally {
|
||||
other.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { notifyFilesMoved, pendingFileMoves, trackFileMove } from "@/platform/fileOps";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { activate } from "../index";
|
||||
import { loadBookmarks, updateBookmarkData, useBookmarks, type BookmarkData } from "../bookmarks/store";
|
||||
|
||||
const root = "C:/project";
|
||||
const bookmark = {
|
||||
path: `${root}/docs/nested/notes.txt`,
|
||||
line: 2,
|
||||
text: "review this line",
|
||||
mnemonic: "7",
|
||||
description: "Review",
|
||||
list: "work",
|
||||
created: 3,
|
||||
};
|
||||
const folder = { path: `${root}/docs`, dir: true, list: "work", created: 1 };
|
||||
const file = { path: bookmark.path, dir: false, list: "work", created: 2 };
|
||||
const neighbor = { path: `${root}/docs-other`, dir: true, list: "work", created: 4 };
|
||||
const initial: BookmarkData = {
|
||||
items: [bookmark],
|
||||
paths: [folder, file, neighbor],
|
||||
lists: [{ id: "work", name: "Work" }],
|
||||
defaultList: "work",
|
||||
};
|
||||
|
||||
function removePaths(...removed: string[]) {
|
||||
emitLocalIdeEvent({ type: "fsChanged", removed, created: [], modified: [] });
|
||||
}
|
||||
|
||||
describe("bookmarks during file refactoring", () => {
|
||||
let dispose: (() => void) | void;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useProject.setState({ project: { root } as never });
|
||||
dispose = activate();
|
||||
updateBookmarkData(() => initial);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
dispose?.();
|
||||
useProject.setState({ project: null });
|
||||
loadBookmarks(null);
|
||||
});
|
||||
|
||||
it("retargets a file bookmark and its mnemonic line bookmark", async () => {
|
||||
const to = `${root}/docs/nested/renamed.txt`;
|
||||
await notifyFilesMoved([{ from: file.path, to }]);
|
||||
removePaths(file.path);
|
||||
expect(useBookmarks.getState().items).toEqual([{ ...bookmark, path: to }]);
|
||||
expect(useBookmarks.getState().paths).toContainEqual({ ...file, path: to });
|
||||
});
|
||||
|
||||
it("retargets a folder and its descendants and keeps the mapping through undo", async () => {
|
||||
const to = `${root}/archive`;
|
||||
const movedFile = `${to}/nested/notes.txt`;
|
||||
await notifyFilesMoved([{ from: folder.path, to }]);
|
||||
removePaths(folder.path, file.path);
|
||||
loadBookmarks(root);
|
||||
expect(useBookmarks.getState().items).toEqual([{ ...bookmark, path: movedFile }]);
|
||||
expect(useBookmarks.getState().paths).toEqual([{ ...folder, path: to }, { ...file, path: movedFile }, neighbor]);
|
||||
|
||||
await notifyFilesMoved([{ from: to, to: folder.path }]);
|
||||
removePaths(to);
|
||||
expect(useBookmarks.getState().items).toEqual(initial.items);
|
||||
expect(useBookmarks.getState().paths).toEqual(expect.arrayContaining(initial.paths));
|
||||
});
|
||||
|
||||
it("waits for an in-flight move before pruning watcher removals", async () => {
|
||||
const to = `${root}/docs/nested/renamed.txt`;
|
||||
await trackFileMove(root, async () => {
|
||||
removePaths(file.path, neighbor.path);
|
||||
expect(useBookmarks.getState().items).toEqual(initial.items);
|
||||
await notifyFilesMoved([{ from: file.path, to }]);
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
const { items, paths } = useBookmarks.getState();
|
||||
expect(items).toEqual([{ ...bookmark, path: to }]);
|
||||
expect(paths).toEqual([folder, { ...file, path: to }]);
|
||||
});
|
||||
});
|
||||
|
||||
it("handles unrelated deletions after a failed move and clears pending state", async () => {
|
||||
await expect(
|
||||
trackFileMove(root, async () => {
|
||||
removePaths(neighbor.path);
|
||||
expect(useBookmarks.getState().paths).toContainEqual(neighbor);
|
||||
throw new Error("Rename failed");
|
||||
}),
|
||||
).rejects.toThrow("Rename failed");
|
||||
expect(pendingFileMoves(root)).toBeNull();
|
||||
await vi.waitFor(() => expect(useBookmarks.getState().paths).toEqual([folder, file]));
|
||||
removePaths(folder.path);
|
||||
expect(useBookmarks.getState().items).toEqual([]);
|
||||
expect(useBookmarks.getState().paths).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not apply a deferred removal to another project", async () => {
|
||||
await trackFileMove(root, async () => {
|
||||
removePaths(folder.path);
|
||||
useProject.setState({ project: { root: "C:/other" } as never });
|
||||
updateBookmarkData(() => initial);
|
||||
});
|
||||
expect(useBookmarks.getState()).toMatchObject({ scope: "C:/other", items: [bookmark] });
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
marksOf,
|
||||
toggleMnemonic,
|
||||
renameBookmarks,
|
||||
setFileLines,
|
||||
toggleBookmark,
|
||||
updateBookmarks,
|
||||
useBookmarks,
|
||||
@@ -28,20 +27,6 @@ describe("bookmark helpers", () => {
|
||||
expect(linesOf(list, "/p/b.kt")).toEqual([3]);
|
||||
});
|
||||
|
||||
it("moves lines after edits and collapses duplicates", () => {
|
||||
const list = [
|
||||
{ path: "/p/a", line: 1, text: "a", created: 1 },
|
||||
{ path: "/p/a", line: 5, text: "b", created: 2 },
|
||||
{ path: "/p/z", line: 0, text: "z", created: 3 },
|
||||
];
|
||||
const moved = setFileLines(list, "/p/a", [
|
||||
{ line: 3, text: "a" },
|
||||
{ line: 3, text: "b" },
|
||||
]);
|
||||
expect(moved.map((b) => `${b.path}:${b.line}`)).toEqual(["/p/a:3", "/p/z:0"]);
|
||||
expect(moved[0]!.created).toBe(1);
|
||||
});
|
||||
|
||||
it("follows renames and drops deleted files", () => {
|
||||
const list = [
|
||||
{ path: "/p/dir/a", line: 1, text: "", created: 1 },
|
||||
@@ -97,19 +82,15 @@ describe("mnemonic bookmarks", () => {
|
||||
expect(linesOf(list, "/p/a")).toEqual([3]);
|
||||
});
|
||||
|
||||
it("keeps mnemonics and descriptions when lines move or storage reloads", () => {
|
||||
it("keeps mnemonics and descriptions when storage reloads", () => {
|
||||
const list: Bookmark[] = [{ path: "/p/a", line: 1, text: "a", created: 1, mnemonic: "7", description: "note" }];
|
||||
expect(setFileLines(list, "/p/a", [{ line: 4, text: "a" }])[0]).toMatchObject({
|
||||
line: 4,
|
||||
mnemonic: "7",
|
||||
description: "note",
|
||||
});
|
||||
localStorage.setItem(
|
||||
"openidea.bookmarks.v1:/m",
|
||||
JSON.stringify([...list, { path: "/p/b", line: 0, mnemonic: "ab" }]),
|
||||
);
|
||||
loadBookmarks("/m");
|
||||
expect(useBookmarks.getState().items.map((b) => b.mnemonic)).toEqual(["7", undefined]);
|
||||
expect(useBookmarks.getState().items[0]).toMatchObject({ line: 1, description: "note" });
|
||||
});
|
||||
|
||||
it("F3 on a selection uses it as the description; Rename edits it", () => {
|
||||
|
||||
@@ -39,6 +39,28 @@ function setup(overrides: Partial<SeDeps> = {}) {
|
||||
const fm = (rel: string) => ({ path: `/p/${rel}`, relPath: rel, score: 1, indices: [] });
|
||||
|
||||
describe("SeController", () => {
|
||||
it("filters recent actions when disabled actions are excluded", async () => {
|
||||
const { c, last } = setup({
|
||||
actions: () => [
|
||||
{ id: "blocked", title: "Blocked", run: () => {} },
|
||||
{ id: "available", title: "Available", run: () => {} },
|
||||
],
|
||||
isEnabled: (a) => a.id === "available",
|
||||
recentActions: () => ["blocked", "available"],
|
||||
});
|
||||
const recent = () => last().sections.get("recentActions")!.items;
|
||||
c.run({ query: "", tab: "actions", includeNonProject: false, includeDisabled: false, extra: {} });
|
||||
await flush();
|
||||
expect(recent()).toMatchObject([{ id: "available", enabled: true }]);
|
||||
|
||||
c.run({ query: "", tab: "actions", includeNonProject: true, includeDisabled: true, extra: {} });
|
||||
await flush();
|
||||
expect(recent()).toMatchObject([
|
||||
{ id: "blocked", enabled: false },
|
||||
{ id: "available", enabled: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("streams each section independently", async () => {
|
||||
const files = deferred<ReturnType<typeof fm>[]>();
|
||||
const { c, last } = setup({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { clearContext, getContext, setContext, type ContextKeys } from "@/platform/context";
|
||||
import type { SeDeps } from "../everywhere/controller";
|
||||
|
||||
const defaultFindFiles: SeDeps["findFiles"] = async (q) =>
|
||||
@@ -28,13 +29,16 @@ vi.mock("../common/open", async (orig) => ({
|
||||
openLocation: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock("../everywhere/deps", () => ({
|
||||
ipcDeps: () => fakeDeps(),
|
||||
loadLanguages: async () => [
|
||||
{ id: "kotlin", name: "Kotlin", extensions: ["kt"] },
|
||||
{ id: "markdown", name: "Markdown", extensions: ["md"] },
|
||||
],
|
||||
}));
|
||||
vi.mock("../everywhere/deps", async (orig) => {
|
||||
const { ipcDeps } = await orig<typeof import("../everywhere/deps")>();
|
||||
return {
|
||||
ipcDeps: (ctx: ContextKeys) => ({ ...fakeDeps(), isEnabled: ipcDeps(ctx).isEnabled }),
|
||||
loadLanguages: async () => [
|
||||
{ id: "kotlin", name: "Kotlin", extensions: ["kt"] },
|
||||
{ id: "markdown", name: "Markdown", extensions: ["md"] },
|
||||
],
|
||||
};
|
||||
});
|
||||
vi.mock("../find/windowStore", async (orig) => ({
|
||||
...(await orig<typeof import("../find/windowStore")>()),
|
||||
ipcFindDeps: () => ({
|
||||
@@ -219,6 +223,73 @@ describe("Search Everywhere dialog", () => {
|
||||
disposers.forEach((d) => d());
|
||||
});
|
||||
|
||||
it("hides unavailable commands until requested and uses the editor's captured context for available ones", async () => {
|
||||
const unavailable = vi.fn();
|
||||
const available = vi.fn();
|
||||
const disposers = [
|
||||
registerAction({
|
||||
id: "test.cellNull",
|
||||
title: "Set Test Cell NULL",
|
||||
when: "testEditorFocus",
|
||||
enabled: () => false,
|
||||
run: unavailable,
|
||||
}),
|
||||
registerAction({
|
||||
id: "test.cellDefault",
|
||||
title: "Set Test Cell Default",
|
||||
when: "testEditorFocus",
|
||||
enabled: ({ ctx }) => ctx.testEditorFocus === true && !ctx.popupOpen,
|
||||
run: available,
|
||||
}),
|
||||
];
|
||||
try {
|
||||
render(
|
||||
<>
|
||||
<button
|
||||
onFocus={() => setContext("testEditorFocus", true)}
|
||||
onBlur={() => setContext("testEditorFocus", false)}
|
||||
>
|
||||
Test editor
|
||||
</button>
|
||||
<SearchEverywhereOverlay />
|
||||
</>,
|
||||
);
|
||||
act(() => screen.getByRole("button", { name: "Test editor" }).focus());
|
||||
act(() => showSearchEverywhere("actions", { query: "Set Test Cell NULL" }));
|
||||
await tick();
|
||||
expect(getContext().testEditorFocus).toBe(false);
|
||||
const checkbox = screen.getByLabelText("Include disabled actions");
|
||||
const input = screen.getByLabelText("Search query");
|
||||
const nullAction = () => screen.queryByRole("option", { name: /Set Test Cell NULL/ });
|
||||
expect(checkbox).not.toBeChecked();
|
||||
expect(nullAction()).toBeNull();
|
||||
expect(screen.getByText("Nothing found", { exact: true })).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(checkbox);
|
||||
await tick();
|
||||
expect(checkbox).toBeChecked();
|
||||
expect(nullAction()?.querySelector('[aria-disabled="true"]')).toBeInTheDocument();
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(unavailable).not.toHaveBeenCalled();
|
||||
expect(useSearchEverywhere.getState().open).toBe(true);
|
||||
|
||||
fireEvent.click(checkbox);
|
||||
await tick();
|
||||
expect(nullAction()).toBeNull();
|
||||
fireEvent.change(input, { target: { value: "Set Test Cell Default" } });
|
||||
await tick();
|
||||
const action = screen.getByRole("option", { name: /Set Test Cell Default/ });
|
||||
expect(action.querySelector('[aria-disabled="true"]')).toBeNull();
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
await tick();
|
||||
expect(available).toHaveBeenCalledOnce();
|
||||
expect(useSearchEverywhere.getState().open).toBe(false);
|
||||
} finally {
|
||||
disposers.forEach((dispose) => dispose());
|
||||
clearContext("testEditorFocus");
|
||||
}
|
||||
});
|
||||
|
||||
it("filters Files by file type from the funnel, remembering the choice", async () => {
|
||||
render(<SearchEverywhereOverlay />);
|
||||
act(() => showSearchEverywhere("files", { query: "order" }));
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { OutlineItem } from "@/platform/ipc";
|
||||
|
||||
const openLocation = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../common/open", async (orig) => ({
|
||||
...(await orig<typeof import("../common/open")>()),
|
||||
openLocation,
|
||||
}));
|
||||
vi.mock("../structure/store", async (orig) => ({
|
||||
...(await orig<typeof import("../structure/store")>()),
|
||||
useLiveOutline: () => undefined,
|
||||
@@ -9,6 +14,7 @@ vi.mock("../structure/store", async (orig) => ({
|
||||
|
||||
const { FileStructureOverlay, useFileStructurePopup } = await import("../structure/StructureView");
|
||||
const { useOutline, useStructureOptions } = await import("../structure/store");
|
||||
const { useTracking } = await import("../common/tracking");
|
||||
|
||||
const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => ({
|
||||
name,
|
||||
@@ -19,16 +25,19 @@ const item = (name: string, kind: OutlineItem["kind"], line: number, children: O
|
||||
children,
|
||||
});
|
||||
|
||||
function open() {
|
||||
function open(
|
||||
items = [
|
||||
item("OrderController", "class", 0, [item("list", "method", 2), item("create", "method", 8)]),
|
||||
item("helper", "function", 22),
|
||||
],
|
||||
path = "/p/Order.kt",
|
||||
) {
|
||||
useOutline.setState({
|
||||
path: "/p/Order.kt",
|
||||
path,
|
||||
doc: 1,
|
||||
loading: false,
|
||||
error: null,
|
||||
items: [
|
||||
item("OrderController", "class", 0, [item("list", "method", 2), item("create", "method", 8)]),
|
||||
item("helper", "function", 22),
|
||||
],
|
||||
items,
|
||||
});
|
||||
useStructureOptions.setState({ narrowDown: true });
|
||||
render(<FileStructureOverlay />);
|
||||
@@ -37,8 +46,21 @@ function open() {
|
||||
}
|
||||
|
||||
const rows = () => screen.getAllByRole("treeitem").map((r) => r.textContent);
|
||||
const selected = () => screen.queryByRole("treeitem", { selected: true });
|
||||
const functionsPath = "/p/functions.ts";
|
||||
|
||||
afterEach(() => act(() => useFileStructurePopup.setState({ open: false })));
|
||||
function openFunctions(narrowDown: boolean) {
|
||||
useTracking.setState({ caret: { path: functionsPath, doc: 1, line: 6, col: 5, offset: 128 } });
|
||||
const input = open([item("process", "function", 0), item("separate", "function", 6)], functionsPath);
|
||||
if (!narrowDown) fireEvent.click(screen.getByLabelText("Narrow down on typing"));
|
||||
return input;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
act(() => useFileStructurePopup.setState({ open: false }));
|
||||
useTracking.setState({ caret: null });
|
||||
openLocation.mockClear();
|
||||
});
|
||||
|
||||
describe("File Structure popup", () => {
|
||||
it("shows the outline as an expanded tree; ←/→ collapse and expand", () => {
|
||||
@@ -60,6 +82,44 @@ describe("File Structure popup", () => {
|
||||
expect(rows()).toEqual(["OrderController", "list", "create", "helper"]);
|
||||
});
|
||||
|
||||
it("leaves the full tree unselected when the highlight query stops matching", () => {
|
||||
const input = openFunctions(false);
|
||||
fireEvent.change(input, { target: { value: "separate" } });
|
||||
expect(selected()).toHaveTextContent("separate");
|
||||
fireEvent.change(input, { target: { value: "separateZ" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(useFileStructurePopup.getState().open).toBe(true);
|
||||
expect(rows()).toEqual(["process", "separate"]);
|
||||
expect(selected()).toBeNull();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("No matches");
|
||||
expect(openLocation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["", "separate"])("navigates to the intended symbol for query %j", async (query) => {
|
||||
const input = openFunctions(false);
|
||||
fireEvent.change(input, { target: { value: query } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
await waitFor(() => expect(openLocation).toHaveBeenCalledWith(functionsPath, { line: 6, col: 4 }, { focus: true }));
|
||||
});
|
||||
|
||||
it("still navigates after an explicit selection in the full tree", async () => {
|
||||
const input = openFunctions(false);
|
||||
fireEvent.change(input, { target: { value: "separateZ" } });
|
||||
fireEvent.keyDown(input, { key: "ArrowDown" });
|
||||
expect(selected()).toHaveTextContent("process");
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
await waitFor(() => expect(openLocation).toHaveBeenCalledWith(functionsPath, { line: 0, col: 4 }, { focus: true }));
|
||||
});
|
||||
|
||||
it("keeps narrow mode empty for an unmatched query", () => {
|
||||
const input = openFunctions(true);
|
||||
fireEvent.change(input, { target: { value: "separateZ" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(screen.getByText("No symbols")).toBeInTheDocument();
|
||||
expect(useFileStructurePopup.getState().open).toBe(true);
|
||||
expect(openLocation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows a Vue component's script declarations nested under its script block", () => {
|
||||
useOutline.setState({
|
||||
path: "/p/App.vue",
|
||||
|
||||
@@ -132,6 +132,23 @@ describe("recent files switcher", () => {
|
||||
).toEqual(["README.md"]);
|
||||
});
|
||||
|
||||
it("shows a scratch file under its root's label", () => {
|
||||
const labelled = [{ path: "/data/scratches", label: "Scratches" }];
|
||||
const items = filterRecentFiles(
|
||||
["/data/scratches/api/generated-requests.http", "/p/src/Main.kt", "/elsewhere/a.txt"],
|
||||
"",
|
||||
{
|
||||
root: "/p",
|
||||
labelled,
|
||||
},
|
||||
);
|
||||
expect(items.map((f) => [f.rel, f.dir])).toEqual([
|
||||
["Scratches/api/generated-requests.http", "Scratches/api"],
|
||||
["src/Main.kt", "src"],
|
||||
["/elsewhere/a.txt", "/elsewhere"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("preselects the previous file when the current one is first", () => {
|
||||
const items = filterRecentFiles(paths, "", { root: "/p" });
|
||||
expect(initialFileIndex(items, "/p/src/Main.kt", "")).toBe(1);
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
* follow the code. ⌘-click (Ctrl-click) in the gutter toggles a bookmark, as
|
||||
* in IDEA.
|
||||
*/
|
||||
import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { RangeSet, StateEffect, StateField, type Extension, type Text, type Transaction } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
|
||||
import { emptyGutterSpacer } from "@/editor/api";
|
||||
import { hasPrimaryModifier } from "@/platform/keymap";
|
||||
import { marksOf, setFileLines, updateBookmarks, useBookmarks } from "./store";
|
||||
import { sortBookmarks, updateBookmarks, useBookmarks, type Bookmark } from "./store";
|
||||
|
||||
const SVG_NS = "http://www.w3.org/2000/svg";
|
||||
|
||||
@@ -53,31 +53,69 @@ class SpacerMarker extends GutterMarker {
|
||||
const plain = new BookmarkMarker(null);
|
||||
const spacer = new SpacerMarker();
|
||||
|
||||
type Mark = { line: number; mnemonic: string | null };
|
||||
const setMarks = StateEffect.define<readonly Bookmark[]>();
|
||||
|
||||
const setMarks = StateEffect.define<Mark[]>();
|
||||
|
||||
function build(doc: EditorView["state"]["doc"], marks: readonly Mark[]): RangeSet<BookmarkMarker> {
|
||||
function build(doc: Text, bookmarks: readonly Bookmark[]) {
|
||||
const seen = new Set<number>();
|
||||
const ranges = [...marks]
|
||||
const ranges = bookmarks
|
||||
.filter((m) => m.line >= 0 && m.line < doc.lines && !seen.has(m.line) && seen.add(m.line))
|
||||
.sort((a, b) => a.line - b.line)
|
||||
.map((m) => (m.mnemonic ? new BookmarkMarker(m.mnemonic) : plain).range(doc.line(m.line + 1).from));
|
||||
return RangeSet.of(ranges);
|
||||
return { bookmarks, markers: RangeSet.of(ranges) };
|
||||
}
|
||||
|
||||
function marksIn(view: EditorView, set: RangeSet<BookmarkMarker>): Mark[] {
|
||||
const out: Mark[] = [];
|
||||
const iter = set.iter();
|
||||
while (iter.value) {
|
||||
out.push({ line: view.state.doc.lineAt(iter.from).number - 1, mnemonic: iter.value.mnemonic });
|
||||
iter.next();
|
||||
function moveBookmarks(bookmarks: readonly Bookmark[], tr: Transaction): readonly Bookmark[] {
|
||||
if (bookmarks.length === 0) return bookmarks;
|
||||
const { doc } = tr.startState;
|
||||
const { changes, newDoc } = tr;
|
||||
const removals: { from: number; to: number }[] = [];
|
||||
changes.iterChanges((from, to, _fromB, _toB, insert) => {
|
||||
if (from < to && insert.lines === 1) removals.push({ from, to });
|
||||
});
|
||||
const seen = new Set<number>();
|
||||
const moved: Bookmark[] = [];
|
||||
for (const bookmark of bookmarks) {
|
||||
if (bookmark.line < 0 || bookmark.line >= doc.lines) {
|
||||
moved.push(bookmark);
|
||||
continue;
|
||||
}
|
||||
const line = doc.line(bookmark.line + 1);
|
||||
// A line disappears when deletion covers its text and a line break.
|
||||
// An empty line uses its following break, so deleting its predecessor leaves it intact.
|
||||
if (
|
||||
removals.some(
|
||||
({ from, to }) => from <= line.from && to >= line.to && (to > line.to || (line.length > 0 && from < line.from)),
|
||||
)
|
||||
)
|
||||
continue;
|
||||
const next = newDoc.lineAt(changes.mapPos(line.from, 1));
|
||||
if (seen.has(next.number)) continue;
|
||||
seen.add(next.number);
|
||||
const number = next.number - 1;
|
||||
moved.push(
|
||||
number === bookmark.line ? bookmark : { ...bookmark, line: number, text: next.text.trim().slice(0, 200) },
|
||||
);
|
||||
}
|
||||
return out;
|
||||
return moved;
|
||||
}
|
||||
|
||||
const sameMarks = (a: readonly Mark[], b: readonly Mark[]) =>
|
||||
a.length === b.length && a.every((v, i) => v.line === b[i]!.line && v.mnemonic === b[i]!.mnemonic);
|
||||
const sameBookmarks = (a: readonly Bookmark[], b: readonly Bookmark[]) =>
|
||||
a.length === b.length &&
|
||||
a.every((mark, i) => {
|
||||
const other = b[i]!;
|
||||
return (
|
||||
mark === other ||
|
||||
(mark.path === other.path &&
|
||||
mark.line === other.line &&
|
||||
mark.text === other.text &&
|
||||
mark.mnemonic === other.mnemonic &&
|
||||
mark.description === other.description &&
|
||||
mark.list === other.list &&
|
||||
mark.created === other.created)
|
||||
);
|
||||
});
|
||||
|
||||
const fileBookmarks = (list: readonly Bookmark[], path: string) => list.filter((b) => b.path === path);
|
||||
|
||||
/** The 0-based line of a click in the gutter, or null outside it. */
|
||||
function gutterLine(view: EditorView, e: MouseEvent): number | null {
|
||||
@@ -88,12 +126,12 @@ function gutterLine(view: EditorView, e: MouseEvent): number | null {
|
||||
}
|
||||
|
||||
export function bookmarkGutter(path: string, toggle: (line: number) => void): Extension {
|
||||
const field = StateField.define<RangeSet<BookmarkMarker>>({
|
||||
create: (state) => build(state.doc, marksOf(useBookmarks.getState().items, path)),
|
||||
const field = StateField.define<ReturnType<typeof build>>({
|
||||
create: (state) => build(state.doc, fileBookmarks(useBookmarks.getState().items, path)),
|
||||
update(value, tr) {
|
||||
let next = tr.docChanged ? value.map(tr.changes) : value;
|
||||
for (const e of tr.effects) if (e.is(setMarks)) next = build(tr.state.doc, e.value);
|
||||
return next;
|
||||
const effect = tr.effects.find((e) => e.is(setMarks));
|
||||
if (effect) return build(tr.newDoc, effect.value);
|
||||
return tr.docChanged ? build(tr.newDoc, moveBookmarks(value.bookmarks, tr)) : value;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -104,15 +142,17 @@ export function bookmarkGutter(path: string, toggle: (line: number) => void): Ex
|
||||
constructor(private readonly view: EditorView) {
|
||||
this.unsub = useBookmarks.subscribe((s, prev) => {
|
||||
if (s.items === prev.items) return;
|
||||
const want = marksOf(s.items, path);
|
||||
if (!sameMarks(want, marksIn(this.view, this.view.state.field(field)))) {
|
||||
const want = fileBookmarks(s.items, path);
|
||||
if (sameBookmarks(want, fileBookmarks(prev.items, path))) return;
|
||||
if (!sameBookmarks(want, this.view.state.field(field).bookmarks)) {
|
||||
this.view.dispatch({ effects: setMarks.of(want) });
|
||||
}
|
||||
});
|
||||
// Bookmarks may have changed while this editor was being created.
|
||||
const want = marksOf(useBookmarks.getState().items, path);
|
||||
if (!sameMarks(want, marksIn(view, view.state.field(field)))) {
|
||||
queueMicrotask(() => view.dispatch({ effects: setMarks.of(want) }));
|
||||
if (!sameBookmarks(fileBookmarks(useBookmarks.getState().items, path), view.state.field(field).bookmarks)) {
|
||||
queueMicrotask(() =>
|
||||
view.dispatch({ effects: setMarks.of(fileBookmarks(useBookmarks.getState().items, path)) }),
|
||||
);
|
||||
}
|
||||
// Capture phase: runs before the breakpoint gutter's click handler, which ⌘-click must not reach.
|
||||
view.dom.addEventListener("mousedown", this.onMouseDown, true);
|
||||
@@ -127,22 +167,16 @@ export function bookmarkGutter(path: string, toggle: (line: number) => void): Ex
|
||||
};
|
||||
update(u: ViewUpdate) {
|
||||
if (!u.docChanged || this.pending) return;
|
||||
if (sameBookmarks(u.startState.field(field).bookmarks, u.state.field(field).bookmarks)) return;
|
||||
this.pending = true;
|
||||
// Write back after the update cycle (dispatching inside update is not allowed).
|
||||
queueMicrotask(() => {
|
||||
this.pending = false;
|
||||
const view = this.view;
|
||||
if (!view.dom.isConnected) return;
|
||||
const marks = marksIn(view, view.state.field(field));
|
||||
const stored = marksOf(useBookmarks.getState().items, path);
|
||||
if (sameMarks(marks, stored)) return;
|
||||
updateBookmarks((list) =>
|
||||
setFileLines(
|
||||
list,
|
||||
path,
|
||||
marks.map((m) => ({ line: m.line, text: view.state.doc.line(m.line + 1).text })),
|
||||
),
|
||||
);
|
||||
const marks = view.state.field(field).bookmarks;
|
||||
if (sameBookmarks(marks, fileBookmarks(useBookmarks.getState().items, path))) return;
|
||||
updateBookmarks((list) => sortBookmarks([...list.filter((b) => b.path !== path), ...marks]));
|
||||
});
|
||||
}
|
||||
destroy() {
|
||||
@@ -157,10 +191,10 @@ export function bookmarkGutter(path: string, toggle: (line: number) => void): Ex
|
||||
sync,
|
||||
gutter({
|
||||
class: "cm-openidea-bookmarks",
|
||||
markers: (v) => v.state.field(field),
|
||||
markers: (v) => v.state.field(field).markers,
|
||||
// Reserve the bookmark's width only while this file has bookmarks.
|
||||
initialSpacer: () => emptyGutterSpacer,
|
||||
updateSpacer: (_spacer, u) => (u.state.field(field).size ? spacer : emptyGutterSpacer),
|
||||
updateSpacer: (_spacer, u) => (u.state.field(field).markers.size ? spacer : emptyGutterSpacer),
|
||||
}),
|
||||
theme,
|
||||
];
|
||||
|
||||
@@ -148,31 +148,6 @@ export function removeBookmarks(list: readonly Bookmark[], pred: (b: Bookmark) =
|
||||
return list.filter((b) => !pred(b));
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the lines of `path`'s bookmarks after an edit moved them
|
||||
* (`lines` in the same order as the file's current bookmarks; duplicates collapse).
|
||||
*/
|
||||
export function setFileLines(
|
||||
list: readonly Bookmark[],
|
||||
path: string,
|
||||
lines: ReadonlyArray<{ line: number; text: string }>,
|
||||
): Bookmark[] {
|
||||
const old = list.filter((b) => b.path === path);
|
||||
const seen = new Set<number>();
|
||||
const moved: Bookmark[] = [];
|
||||
lines.forEach((l, i) => {
|
||||
if (seen.has(l.line)) return;
|
||||
seen.add(l.line);
|
||||
const prev = old[i];
|
||||
const b: Bookmark = { path, line: l.line, text: clip(l.text), created: prev?.created ?? Date.now() };
|
||||
if (prev?.list) b.list = prev.list;
|
||||
if (prev?.mnemonic) b.mnemonic = prev.mnemonic;
|
||||
if (prev?.description) b.description = prev.description;
|
||||
moved.push(b);
|
||||
});
|
||||
return sortBookmarks([...list.filter((b) => b.path !== path), ...moved]);
|
||||
}
|
||||
|
||||
export function renameBookmarks(list: readonly Bookmark[], from: string, to: string | null): Bookmark[] {
|
||||
const out: Bookmark[] = [];
|
||||
for (const b of list) {
|
||||
|
||||
@@ -441,6 +441,7 @@ function SearchEverywhereDialog() {
|
||||
// Nothing in the project: retry everywhere (IDEA), unless the user picked the scope.
|
||||
const nothingInProject =
|
||||
!!showEmpty &&
|
||||
tab !== "actions" &&
|
||||
!emptyQuery &&
|
||||
!listing &&
|
||||
!includeNonProject &&
|
||||
@@ -493,7 +494,13 @@ function SearchEverywhereDialog() {
|
||||
)}
|
||||
{showEmpty && (
|
||||
<div className={styles.empty}>
|
||||
{tx(emptyQuery ? "Type to search" : includeNonProject ? "Nothing found" : "Nothing found in project files")}
|
||||
{tx(
|
||||
emptyQuery
|
||||
? "Type to search"
|
||||
: includeNonProject || tab === "actions"
|
||||
? "Nothing found"
|
||||
: "Nothing found in project files",
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -253,8 +253,9 @@ export class SeController {
|
||||
.recentActions()
|
||||
.map((aid) => byId.get(aid))
|
||||
.filter((a): a is Action => !!a && !a.hidden)
|
||||
.slice(0, limit)
|
||||
.map((a) => actionItem(a, this.deps.isEnabled(a)));
|
||||
.map((a) => actionItem(a, this.deps.isEnabled(a)))
|
||||
.filter((a) => a.enabled || req.includeDisabled !== false)
|
||||
.slice(0, limit);
|
||||
this.set(id, gen, items, false, false);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { allActions, type Action } from "@/platform/actions";
|
||||
import { evaluateWhen, type ContextKeys } from "@/platform/context";
|
||||
import { allActions, isActionEnabled } from "@/platform/actions";
|
||||
import type { ContextKeys } from "@/platform/context";
|
||||
import { call, commands, nextRequestId, type LanguageInfo } from "@/platform/ipc";
|
||||
import { inFileSet } from "@/platform/projectRoots";
|
||||
import { searchEndpoints, searchableSettings, useProjectViewRoots } from "@/workbench/contributions";
|
||||
@@ -25,9 +25,9 @@ export function ipcDeps(ctx: ContextKeys): SeDeps {
|
||||
cancel: cancelRequest,
|
||||
nextRequestId,
|
||||
actions: () => allActions(),
|
||||
isEnabled: (a: Action) => {
|
||||
isEnabled: (a) => {
|
||||
try {
|
||||
return evaluateWhen(a.when, ctx);
|
||||
return isActionEnabled(a, ctx);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -311,8 +311,6 @@ export function matchActions(
|
||||
const recentRank = new Map(opts.recent.map((id, i) => [id, i]));
|
||||
for (const a of actions) {
|
||||
if (a.hidden) continue;
|
||||
const enabled = opts.isEnabled(a);
|
||||
if (!enabled && opts.includeDisabled === false) continue;
|
||||
let score: number;
|
||||
let indices: number[] = [];
|
||||
const translated = shown(a, a.title);
|
||||
@@ -333,6 +331,8 @@ export function matchActions(
|
||||
score = Math.max(best, idHit) - 400;
|
||||
if (!Number.isFinite(score)) continue;
|
||||
}
|
||||
const enabled = opts.isEnabled(a);
|
||||
if (!enabled && opts.includeDisabled === false) continue;
|
||||
if (!enabled) score -= 150;
|
||||
const r = recentRank.get(a.id);
|
||||
if (r !== undefined) score += 40 - Math.min(30, r * 3);
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
import { lazyComponent, lazyWhen } from "@/ui";
|
||||
import { activeEditor, registerEditorContribution } from "@/editor/api";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { onFilesMoved, pendingFileMoves } from "@/platform/fileOps";
|
||||
import { call, commands, IpcError, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { EDIT_SCOPES_ACTION } from "@/platform/search";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
@@ -28,7 +30,6 @@ import {
|
||||
updateBookmarks,
|
||||
useBookmarkPopups,
|
||||
useBookmarks,
|
||||
type Bookmark,
|
||||
} from "./bookmarks/store";
|
||||
import { openLocation } from "./common/open";
|
||||
import { maybeToolWindowService } from "./common/services";
|
||||
@@ -49,6 +50,37 @@ import { useFileStructurePopup } from "./structure/popupStore";
|
||||
import { useOutline, useStructureOptions } from "./structure/store";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
async function removeMissingBookmarks(removed: readonly string[]) {
|
||||
const { scope } = useBookmarks.getState();
|
||||
const pending = pendingFileMoves(scope);
|
||||
if (pending) await pending;
|
||||
if (scope !== useBookmarks.getState().scope) return;
|
||||
|
||||
const { items, paths } = useBookmarks.getState();
|
||||
const missing = new Set(
|
||||
[...items, ...paths].map((b) => b.path).filter((path) => removed.some((p) => isSameOrInside(path, p))),
|
||||
);
|
||||
if (!missing.size) return;
|
||||
// A delayed watcher notification can also arrive after a rollback or Undo restored the path.
|
||||
if (isTauri())
|
||||
await Promise.all(
|
||||
[...missing].map(async (path) => {
|
||||
try {
|
||||
await call(commands.fsEntryKind(path));
|
||||
} catch (e) {
|
||||
if (e instanceof IpcError && e.kind === "notFound") return;
|
||||
}
|
||||
missing.delete(path);
|
||||
}),
|
||||
);
|
||||
if (!missing.size || scope !== useBookmarks.getState().scope) return;
|
||||
updateBookmarkData((d) => ({
|
||||
...d,
|
||||
items: d.items.filter((b) => !missing.has(b.path)),
|
||||
paths: d.paths.filter((b) => !missing.has(b.path)),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Single-line editor selection, used to prefill search fields. */
|
||||
function editorSelectionText(): string | null {
|
||||
const view = activeEditor()?.view;
|
||||
@@ -546,15 +578,18 @@ export function activate(): void | (() => void) {
|
||||
if (useFindPopup.getState().scopeTab === "directory")
|
||||
useFindPopup.setState({ scopeTab: "project", directory: "" });
|
||||
}),
|
||||
onFilesMoved((moves) => {
|
||||
if (!moves.length) return;
|
||||
updateBookmarkData((d) => ({
|
||||
...d,
|
||||
items: moves.reduce((items, { from, to }) => renameBookmarks(items, from, to), d.items),
|
||||
paths: moves.reduce((paths, { from, to }) => renamePathBookmarks(paths, from, to), d.paths),
|
||||
}));
|
||||
}),
|
||||
onIdeEvent("fsChanged", (e) => {
|
||||
if (e.ignoreRules?.length)
|
||||
for (const tab of useFindWindow.getState().tabs) if (!tab.editorResults) rerunFindTab(tab.id);
|
||||
if (!e.removed.length) return;
|
||||
updateBookmarks((list) => e.removed.reduce<Bookmark[]>((acc, p) => renameBookmarks(acc, p, null), [...list]));
|
||||
updateBookmarkData((d) => {
|
||||
const paths = e.removed.reduce((acc, p) => renamePathBookmarks(acc, p, null), d.paths);
|
||||
return paths.length === d.paths.length ? d : { ...d, paths };
|
||||
});
|
||||
if (e.removed.length) void removeMissingBookmarks(e.removed);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача