дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 14:22:34 +02:00
Порівняти коміти
16
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
ee9b50179e | ||
|
|
baab92c804 | ||
|
|
2b7a18ffd7 | ||
|
|
f47a83828c | ||
|
|
4d5ee2d01c | ||
|
|
2ecb44098a | ||
|
|
b1039bc175 | ||
|
|
182c7c1dbb | ||
|
|
c8dc613485 | ||
|
|
88a6bbca14 | ||
|
|
b9e555300f | ||
|
|
7ff223001b | ||
|
|
cc9279a6d6 | ||
|
|
1cfbb24b31 | ||
|
|
a8a0cdb315 | ||
|
|
8ab776ada6 |
No files matched your search
Створено
@@ -5116,6 +5116,7 @@ dependencies = [
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -618,9 +618,10 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
|
||||
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
|
||||
/// debug info. Opening it would show an error tab; without a path the stop selects the
|
||||
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
|
||||
/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive.
|
||||
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
|
||||
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
|
||||
reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists()
|
||||
reference > 0 && Path::new(path).has_root() && !Path::new(path).exists()
|
||||
}
|
||||
|
||||
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
|
||||
|
||||
@@ -277,6 +277,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("file.exportSettings", "Export Settings…"),
|
||||
act("file.importSettings", "Import Settings…"),
|
||||
act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"),
|
||||
act("file.importJetBrainsRecentProjects", "Import Recent Projects from JetBrains IDE…"),
|
||||
act("file.syncSettings", "Sync Settings Now"),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -613,11 +613,14 @@ impl PluginEngine {
|
||||
pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result<Component, String> {
|
||||
let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?;
|
||||
let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes)));
|
||||
if file.is_file() {
|
||||
// Read into memory rather than `deserialize_file`: that maps the file and makes its pages
|
||||
// executable, which the hardened runtime of the signed macOS app refuses ("failed to make
|
||||
// memory executable"), so the cache never hit and every activation compiled again.
|
||||
if let Ok(precompiled) = std::fs::read(&file) {
|
||||
// SAFETY: the cache directory belongs to the IDE (inside its plugins
|
||||
// directory) and is written only by `store_precompiled` below from
|
||||
// components this engine compiled; a corrupt file fails validation.
|
||||
match unsafe { Component::deserialize_file(&self.engine, &file) } {
|
||||
match unsafe { Component::deserialize(&self.engine, &precompiled) } {
|
||||
Ok(component) => return Ok(component),
|
||||
Err(e) => {
|
||||
tracing::info!("discarding precompiled {}: {e}", file.display());
|
||||
@@ -3035,6 +3038,26 @@ impl Runtime {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The second compile of the same component loads the cached one instead of compiling and
|
||||
/// writing it again (a failed load deletes and rewrites the file).
|
||||
#[test]
|
||||
fn a_precompiled_component_is_loaded_from_the_cache() {
|
||||
let engine = PluginEngine::new().unwrap();
|
||||
let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm");
|
||||
let cache = tempfile::tempdir().unwrap();
|
||||
engine.compile_cached(&wasm, cache.path()).unwrap();
|
||||
let cached = || {
|
||||
let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect();
|
||||
assert_eq!(entries.len(), 1, "{entries:?}");
|
||||
let file = entries[0].clone();
|
||||
(std::fs::metadata(&file).unwrap().modified().unwrap(), file)
|
||||
};
|
||||
let before = cached();
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
engine.compile_cached(&wasm, cache.path()).unwrap();
|
||||
assert_eq!(cached(), before, "loaded, not compiled and stored again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() {
|
||||
let fields = [
|
||||
|
||||
@@ -464,11 +464,16 @@ fn renamed_from(
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The log index, locked only around reads and writes: Git runs without it, so commit
|
||||
/// details and one-commit queries need not wait for a long history walk.
|
||||
fn lock(index: &std::sync::Mutex<crate::log_index::LogIndex>) -> std::sync::MutexGuard<'_, crate::log_index::LogIndex> {
|
||||
index.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut index = r.log_index.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let result = if q.summary_only {
|
||||
let mut all = q.clone();
|
||||
all.skip = 0;
|
||||
@@ -483,14 +488,19 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
|
||||
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
|
||||
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
|
||||
let cached = index.views.get(&key).cloned();
|
||||
let cached = lock(&r.log_index).views.get(&key).cloned();
|
||||
let view = if let Some(cached) = cached {
|
||||
cached
|
||||
} else {
|
||||
// Immutable metadata is reused across roots, filters, merges and ref changes.
|
||||
all.request = q.request;
|
||||
let rows =
|
||||
std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(r, &all, cancel, &mut index)?));
|
||||
let rows = std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(
|
||||
r,
|
||||
&all,
|
||||
cancel,
|
||||
&r.log_index,
|
||||
)?));
|
||||
let mut index = lock(&r.log_index);
|
||||
if index.views.len() >= 4 {
|
||||
index.views.clear();
|
||||
}
|
||||
@@ -512,6 +522,7 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
let retain = q.retain_until.as_ref().and_then(|id| find_pos(id)).map(|i| i + 1).unwrap_or(0);
|
||||
let limit = if q.limit == 0 { usize::MAX } else { (q.limit as usize).max(retain.saturating_sub(start)) };
|
||||
let total = view.rows.len() as u32;
|
||||
let mut index = lock(&r.log_index);
|
||||
let db = index.db().cloned();
|
||||
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
|
||||
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
|
||||
@@ -538,9 +549,9 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
log_indexed(r, q, cancel, &mut index)
|
||||
log_indexed(r, q, cancel, &r.log_index)
|
||||
};
|
||||
index.flush();
|
||||
lock(&r.log_index).flush();
|
||||
result
|
||||
}
|
||||
|
||||
@@ -640,7 +651,7 @@ fn log_indexed(
|
||||
r: &Repo,
|
||||
q: &LogQuery,
|
||||
cancel: &CancellationToken,
|
||||
index: &mut crate::log_index::LogIndex,
|
||||
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
|
||||
) -> IdeResult<Vec<Commit>> {
|
||||
let repo = r.gix()?;
|
||||
let shallow: HashSet<ObjectId> =
|
||||
@@ -676,6 +687,8 @@ fn log_indexed(
|
||||
&& q.since_ms.is_none()
|
||||
&& q.until_ms.is_none()
|
||||
{
|
||||
let mut guard = lock(shared);
|
||||
let index = &mut *guard;
|
||||
update_head_reachable(&repo, index, cancel)?;
|
||||
let id = tips[0];
|
||||
let record = index.get(&repo, id)?;
|
||||
@@ -706,7 +719,9 @@ fn log_indexed(
|
||||
commit.message_truncated = false;
|
||||
return Ok(vec![commit]);
|
||||
}
|
||||
let rows = log_indexed_rows(r, q, cancel, index)?;
|
||||
let rows = log_indexed_rows(r, q, cancel, shared)?;
|
||||
let mut guard = lock(shared);
|
||||
let index = &mut *guard;
|
||||
let db = index.db().cloned();
|
||||
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
|
||||
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
|
||||
@@ -724,7 +739,7 @@ fn log_indexed_rows(
|
||||
r: &Repo,
|
||||
q: &LogQuery,
|
||||
cancel: &CancellationToken,
|
||||
index: &mut crate::log_index::LogIndex,
|
||||
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
|
||||
) -> IdeResult<Vec<crate::log_index::IndexedRow>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -775,7 +790,7 @@ fn log_indexed_rows(
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?)
|
||||
Some(sort_shared(&repo, ids, q, &shallow, cancel, shared)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -802,14 +817,17 @@ fn log_indexed_rows(
|
||||
};
|
||||
let authors: Vec<_> =
|
||||
q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect();
|
||||
update_head_reachable(&repo, index, cancel)?;
|
||||
let mut range_ids_set = range_ids.as_ref().map(|ids| ids.iter().copied().collect::<HashSet<_>>());
|
||||
type Walk<'a> = Box<dyn Iterator<Item = IdeResult<ObjectId>> + 'a>;
|
||||
let walk: Walk<'_> = if let Some(ids) = range_ids {
|
||||
Box::new(ids.into_iter().map(Ok))
|
||||
} else if q.summary_only {
|
||||
let ids = index.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
|
||||
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
|
||||
// One guard for both: a concurrent query with another shallow set resets `nodes`.
|
||||
let mut guard = lock(shared);
|
||||
let ids = guard.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
|
||||
let sorted = sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &guard.nodes)?;
|
||||
drop(guard);
|
||||
Box::new(sorted.into_iter().map(Ok))
|
||||
} else if repo.is_shallow().unwrap_or(false) || q.request.is_some() {
|
||||
// The process can be interrupted even during indegree preparation. Git also
|
||||
// respects shallow boundaries while retaining a topological order.
|
||||
@@ -866,7 +884,7 @@ fn log_indexed_rows(
|
||||
LogOrder::Topo | LogOrder::Standard => topo::Sorting::TopoOrder,
|
||||
LogOrder::Date => topo::Sorting::DateOrder,
|
||||
};
|
||||
let topo = topo::Builder::from_iters(&repo.objects, tips, None::<Vec<ObjectId>>)
|
||||
let topo = topo::Builder::from_iters(&repo.objects, tips.clone(), None::<Vec<ObjectId>>)
|
||||
.sorting(sorting)
|
||||
.parents(if q.first_parent { Parents::First } else { Parents::All })
|
||||
.with_commit_graph(graph)
|
||||
@@ -876,11 +894,20 @@ fn log_indexed_rows(
|
||||
};
|
||||
let walk: Walk<'_> = if q.order == LogOrder::Standard {
|
||||
let ids = walk.collect::<IdeResult<Vec<_>>>()?;
|
||||
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
|
||||
Box::new(sort_shared(&repo, ids, q, &shallow, cancel, shared)?.into_iter().map(Ok))
|
||||
} else {
|
||||
walk
|
||||
};
|
||||
let text = q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten();
|
||||
let mut guard = lock(shared);
|
||||
let index = &mut *guard;
|
||||
// Under the guard that builds the rows: a query run meanwhile (after a branch switch)
|
||||
// may have moved the shared set to another HEAD.
|
||||
update_head_reachable(&repo, index, cancel)?;
|
||||
// A query started before a shallow change may have reset `nodes` to its older set.
|
||||
if index.shallow != shallow {
|
||||
index.ensure_nodes(&repo, &tips, &shallow, cancel)?;
|
||||
}
|
||||
let db = index.db().cloned();
|
||||
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
|
||||
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
|
||||
@@ -952,6 +979,21 @@ fn log_indexed_rows(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sorts with the shared nodes only when they were built for this query's shallow set.
|
||||
fn sort_shared(
|
||||
repo: &gix::Repository,
|
||||
ids: Vec<ObjectId>,
|
||||
q: &LogQuery,
|
||||
shallow: &HashSet<ObjectId>,
|
||||
cancel: &CancellationToken,
|
||||
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
|
||||
) -> IdeResult<Vec<ObjectId>> {
|
||||
let guard = lock(shared);
|
||||
let empty = HashMap::new();
|
||||
let nodes = if &guard.shallow == shallow { &guard.nodes } else { &empty };
|
||||
sort_subset(repo, ids, q.order, q.first_parent, shallow, cancel, nodes)
|
||||
}
|
||||
|
||||
/// A ready-node stack gives incoming merge parents priority, while child counts
|
||||
/// prevent an ancestor shared with another branch from moving ahead of its children.
|
||||
fn sort_subset(
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! A long file history walk must not hold the log index while Git runs: commit details and
|
||||
//! one-commit queries (inline blame, the blame popup) share that index.
|
||||
#![cfg(unix)]
|
||||
|
||||
use ide_vcs::{LogQuery, Repo};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args([
|
||||
"-c",
|
||||
"init.defaultBranch=main",
|
||||
"-c",
|
||||
"user.name=T",
|
||||
"-c",
|
||||
"user.email=t@e",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn details_and_one_commit_queries_do_not_wait_for_a_file_history_walk() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("repo");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
git(&dir, &["init", "-q"]);
|
||||
for i in 0..3 {
|
||||
std::fs::write(dir.join("file"), format!("{i}")).unwrap();
|
||||
git(&dir, &["add", "-A"]);
|
||||
git(&dir, &["commit", "-qm", &format!("c{i}")]);
|
||||
}
|
||||
// A git whose path-limited history walks take seconds.
|
||||
let real = String::from_utf8(Command::new("sh").args(["-c", "command -v git"]).output().unwrap().stdout).unwrap();
|
||||
let started = tmp.path().join("walk-started");
|
||||
let wrapper = tmp.path().join("slow-git");
|
||||
std::fs::write(
|
||||
&wrapper,
|
||||
format!(
|
||||
"#!/bin/sh\ncase \" $* \" in *\" --full-history \"*) : > '{}'; sleep 3;; esac\nexec '{}' \"$@\"\n",
|
||||
started.display(),
|
||||
real.trim()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let repo = Repo::discover(&dir).unwrap().unwrap();
|
||||
repo.set_execution_allowed(true);
|
||||
repo.set_git_executable(Some(&wrapper));
|
||||
std::thread::scope(|scope| {
|
||||
let walk = scope.spawn(|| {
|
||||
repo.log(&LogQuery { path: Some("file".into()), follow: true, ..Default::default() }).unwrap().len()
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
while !started.exists() {
|
||||
assert!(Instant::now() < deadline, "the history walk never started");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let asked = Instant::now();
|
||||
let details = repo.log_details("HEAD").unwrap();
|
||||
let head = repo.log(&LogQuery { branch: Some("HEAD".into()), limit: 1, ..Default::default() }).unwrap();
|
||||
let waited = asked.elapsed();
|
||||
println!("queries waited {waited:?}");
|
||||
assert_eq!(details.message, "c2");
|
||||
assert_eq!(head.len(), 1);
|
||||
assert!(!walk.is_finished(), "the walk ended before the queries ran; the test proves nothing");
|
||||
assert!(waited < Duration::from_secs(2), "queries waited {waited:?} for the walk");
|
||||
assert_eq!(walk.join().unwrap(), 3);
|
||||
});
|
||||
}
|
||||
@@ -24,6 +24,7 @@ globset.workspace = true
|
||||
uuid.workspace = true
|
||||
zip.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
quick-xml = "0.42"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.56"
|
||||
|
||||
@@ -162,6 +162,127 @@ fn is_missing(path: &Path) -> bool {
|
||||
path.is_absolute() && !text.contains("://") && !wsl && !path.exists()
|
||||
}
|
||||
|
||||
fn folder_name(path: &Path) -> String {
|
||||
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string())
|
||||
}
|
||||
|
||||
/// What importing a JetBrains IDE's recent projects did (or, as a preview, would do).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JetBrainsRecentImport {
|
||||
/// Projects added to the recent projects.
|
||||
pub imported: u32,
|
||||
/// Projects left out because their folder no longer exists.
|
||||
pub missing: u32,
|
||||
/// Project groups added.
|
||||
pub groups: u32,
|
||||
}
|
||||
|
||||
/// A recent project as a JetBrains IDE keeps it in `options/recentProjects.xml`.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct JetBrainsRecent {
|
||||
path: String,
|
||||
name: Option<String>,
|
||||
opened_at_ms: f64,
|
||||
/// Opened but not listed (LightEdit, a file opened alone): the IDE does not show it.
|
||||
hidden: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct JetBrainsGroup {
|
||||
name: String,
|
||||
paths: Vec<String>,
|
||||
expanded: bool,
|
||||
}
|
||||
|
||||
/// The `RecentProjectsManager` state: `additionalInfo` entries (path → `RecentProjectMetaInfo`) and
|
||||
/// `groups` (`ProjectGroup` with `name`, `expanded` and its `projects`).
|
||||
fn parse_jetbrains_recent(xml: &str) -> (Vec<JetBrainsRecent>, Vec<JetBrainsGroup>) {
|
||||
use quick_xml::{Reader, XmlVersion, events::Event};
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let (mut projects, mut groups) = (Vec::new(), Vec::new());
|
||||
let mut project: Option<JetBrainsRecent> = None;
|
||||
let mut group: Option<JetBrainsGroup> = None;
|
||||
loop {
|
||||
let (tag, empty) = match reader.read_event() {
|
||||
Ok(Event::Start(tag)) => (tag, false),
|
||||
Ok(Event::Empty(tag)) => (tag, true),
|
||||
Ok(Event::End(tag)) => {
|
||||
match tag.local_name().as_ref() {
|
||||
"entry" => projects.extend(project.take()),
|
||||
"ProjectGroup" => groups.extend(group.take()),
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Ok(Event::Eof) | Err(_) => break,
|
||||
_ => continue,
|
||||
};
|
||||
let attr = |key: &str| {
|
||||
tag.attributes()
|
||||
.flatten()
|
||||
.find(|a| a.key.as_ref() == key)
|
||||
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok().map(|v| v.into_owned()))
|
||||
};
|
||||
match tag.local_name().as_ref() {
|
||||
"entry" if !empty && group.is_none() => {
|
||||
project = attr("key").map(|path| JetBrainsRecent { path, ..Default::default() });
|
||||
}
|
||||
"RecentProjectMetaInfo" => {
|
||||
if let Some(p) = &mut project {
|
||||
p.hidden = attr("hidden").as_deref() == Some("true");
|
||||
}
|
||||
}
|
||||
"ProjectGroup" if !empty => group = Some(JetBrainsGroup::default()),
|
||||
"option" => {
|
||||
let (name, value) = (attr("name"), attr("value"));
|
||||
if let Some(g) = &mut group {
|
||||
match (name.as_deref(), value) {
|
||||
(Some("name"), Some(v)) => g.name = v,
|
||||
(Some("expanded"), Some(v)) => g.expanded = v == "true",
|
||||
// `<option name="projects"><list><option value="…"/>`.
|
||||
(None, Some(v)) => g.paths.push(v),
|
||||
_ => {}
|
||||
}
|
||||
} else if let Some(p) = &mut project {
|
||||
match (name.as_deref(), value) {
|
||||
(Some("customProjectName"), Some(v)) => p.name = Some(v),
|
||||
// Older IDEs.
|
||||
(Some("displayName"), Some(v)) if p.name.is_none() => p.name = Some(v),
|
||||
(Some("projectOpenTimestamp" | "activationTimestamp"), Some(v)) => {
|
||||
p.opened_at_ms = p.opened_at_ms.max(v.parse().unwrap_or(0.0));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(projects, groups)
|
||||
}
|
||||
|
||||
/// A path of `recentProjects.xml`: `$USER_HOME$` is `home`, `$APPLICATION_CONFIG_DIR$` the IDE's settings
|
||||
/// folder `config`; Windows paths are stored with `/`. `None` for other path variables or a relative path.
|
||||
fn expand_jetbrains_path(raw: &str, home: Option<&Path>, config: &Path) -> Option<PathBuf> {
|
||||
let (base, rest) = if let Some(rest) = raw.strip_prefix("$USER_HOME$") {
|
||||
(Some(home?), rest)
|
||||
} else if let Some(rest) = raw.strip_prefix("$APPLICATION_CONFIG_DIR$") {
|
||||
(Some(config), rest)
|
||||
} else {
|
||||
(None, raw)
|
||||
};
|
||||
if rest.contains('$') {
|
||||
return None;
|
||||
}
|
||||
let rest = if cfg!(windows) { rest.replace('/', "\\") } else { rest.to_owned() };
|
||||
let path = match base {
|
||||
Some(base) => base.join(rest.trim_start_matches(['/', '\\'])),
|
||||
None => PathBuf::from(rest),
|
||||
};
|
||||
path.is_absolute().then_some(path)
|
||||
}
|
||||
|
||||
impl RecentProjects {
|
||||
pub fn load(config_dir: &Path) -> Self {
|
||||
let file = config_dir.join("recent.json");
|
||||
@@ -208,8 +329,7 @@ impl RecentProjects {
|
||||
pub fn touch(&self, path: &Path, branch: Option<String>) -> IdeResult<()> {
|
||||
let mut items = self.items.lock();
|
||||
items.retain(|p| p.path != path);
|
||||
let name =
|
||||
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
|
||||
let name = folder_name(path);
|
||||
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch, missing: false });
|
||||
cap(&mut items, &self.groups.lock());
|
||||
self.persist(&items)
|
||||
@@ -219,9 +339,7 @@ impl RecentProjects {
|
||||
pub fn rename(&self, path: &Path, name: Option<&str>) -> IdeResult<()> {
|
||||
let mut items = self.items.lock();
|
||||
let Some(item) = items.iter_mut().find(|p| p.path == path) else { return Ok(()) };
|
||||
let name = name.map(str::to_owned).unwrap_or_else(|| {
|
||||
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string())
|
||||
});
|
||||
let name = name.map(str::to_owned).unwrap_or_else(|| folder_name(path));
|
||||
if item.name == name {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -247,6 +365,91 @@ impl RecentProjects {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds the recent projects and project groups of a JetBrains IDE (`xml`: its
|
||||
/// `options/recentProjects.xml`; `config`: its settings folder). Projects already recent keep their
|
||||
/// entry, folders that are gone are left out, and the groups made here are kept: an imported group
|
||||
/// whose name is taken gets a number, and one whose projects are all grouped already is not added.
|
||||
/// `dry_run` only counts.
|
||||
pub fn import_jetbrains(
|
||||
&self,
|
||||
xml: &str,
|
||||
home: Option<&Path>,
|
||||
config: &Path,
|
||||
dry_run: bool,
|
||||
) -> IdeResult<JetBrainsRecentImport> {
|
||||
let (projects, jetbrains_groups) = parse_jetbrains_recent(xml);
|
||||
let mut summary = JetBrainsRecentImport::default();
|
||||
let mut items = self.items.lock();
|
||||
let mut groups = self.groups.lock();
|
||||
let mut new_items = items.clone();
|
||||
let mut added = Vec::new();
|
||||
for p in projects.into_iter().filter(|p| !p.hidden) {
|
||||
let Some(path) = expand_jetbrains_path(&p.path, home, config).filter(|path| !is_missing(path)) else {
|
||||
summary.missing += 1;
|
||||
continue;
|
||||
};
|
||||
if new_items.iter().any(|i| i.path == path) {
|
||||
continue;
|
||||
}
|
||||
let name = p.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| folder_name(&path));
|
||||
new_items.push(RecentProject {
|
||||
path: path.as_path().into(),
|
||||
name,
|
||||
opened_at_ms: p.opened_at_ms,
|
||||
branch: None,
|
||||
missing: false,
|
||||
});
|
||||
added.push(path);
|
||||
}
|
||||
new_items.sort_by(|a, b| b.opened_at_ms.total_cmp(&a.opened_at_ms));
|
||||
|
||||
let mut new_groups = groups.clone();
|
||||
for g in jetbrains_groups {
|
||||
let base = g.name.trim().to_owned();
|
||||
if base.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut name = base.clone();
|
||||
for n in 2.. {
|
||||
if !new_groups.iter().any(|existing| existing.name == name) {
|
||||
break;
|
||||
}
|
||||
name = format!("{base} {n}");
|
||||
}
|
||||
let paths = g
|
||||
.paths
|
||||
.iter()
|
||||
.filter_map(|raw| expand_jetbrains_path(raw, home, config))
|
||||
.filter(|path| new_items.iter().any(|i| i.path == *path))
|
||||
.map(|path| path.as_path().into())
|
||||
.collect();
|
||||
new_groups.push(RecentProjectGroup { name, paths, expanded: g.expanded });
|
||||
}
|
||||
// Existing groups are normalized already, so they keep their place and their projects.
|
||||
let mut new_groups = normalize(new_groups);
|
||||
let existing = groups.len();
|
||||
let mut index = 0;
|
||||
new_groups.retain(|g| {
|
||||
index += 1;
|
||||
index <= existing || !g.paths.is_empty()
|
||||
});
|
||||
cap(&mut new_items, &new_groups);
|
||||
summary.imported = added.iter().filter(|p| new_items.iter().any(|i| i.path == **p)).count() as u32;
|
||||
summary.groups = (new_groups.len() - existing) as u32;
|
||||
if dry_run {
|
||||
return Ok(summary);
|
||||
}
|
||||
if summary.imported > 0 {
|
||||
self.persist(&new_items)?;
|
||||
*items = new_items;
|
||||
}
|
||||
if summary.groups > 0 {
|
||||
write_json(&self.groups_file, &new_groups)?;
|
||||
*groups = new_groups;
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
pub fn paths(&self) -> Vec<PathBuf> {
|
||||
self.list().into_iter().map(|p| p.path.into_path_buf()).collect()
|
||||
}
|
||||
@@ -344,6 +547,142 @@ mod tests {
|
||||
assert_eq!(recent.list().len(), 1);
|
||||
}
|
||||
|
||||
const JETBRAINS_RECENT: &str = r#"<application>
|
||||
<component name="RecentProjectsManager">
|
||||
<option name="additionalInfo">
|
||||
<map>
|
||||
<entry key="$USER_HOME$/code/alpha">
|
||||
<value>
|
||||
<RecentProjectMetaInfo frameTitle="alpha – main.rs" projectWorkspaceId="w1">
|
||||
<option name="activationTimestamp" value="1700000005000" />
|
||||
<option name="colorInfo"><RecentProjectColorInfo associatedIndex="1" /></option>
|
||||
<option name="customProjectName" value="Alpha Service" />
|
||||
<option name="projectOpenTimestamp" value="1700000001000" />
|
||||
</RecentProjectMetaInfo>
|
||||
</value>
|
||||
</entry>
|
||||
<entry key="$USER_HOME$/code/beta">
|
||||
<value>
|
||||
<RecentProjectMetaInfo>
|
||||
<option name="displayName" value="beta-old-name" />
|
||||
<option name="projectOpenTimestamp" value="1700000003000" />
|
||||
</RecentProjectMetaInfo>
|
||||
</value>
|
||||
</entry>
|
||||
<entry key="$USER_HOME$/code/gone">
|
||||
<value><RecentProjectMetaInfo /></value>
|
||||
</entry>
|
||||
<entry key="$APPLICATION_CONFIG_DIR$/light-edit">
|
||||
<value><RecentProjectMetaInfo hidden="true" /></value>
|
||||
</entry>
|
||||
<entry key="$PROJECT_DIR$/x">
|
||||
<value><RecentProjectMetaInfo /></value>
|
||||
</entry>
|
||||
</map>
|
||||
</option>
|
||||
<option name="groups">
|
||||
<list>
|
||||
<ProjectGroup>
|
||||
<option name="expanded" value="true" />
|
||||
<option name="name" value="Work" />
|
||||
<option name="projects">
|
||||
<list>
|
||||
<option value="$USER_HOME$/code/alpha" />
|
||||
<option value="$USER_HOME$/code/gone" />
|
||||
</list>
|
||||
</option>
|
||||
</ProjectGroup>
|
||||
<ProjectGroup>
|
||||
<option name="name" value="Empty" />
|
||||
</ProjectGroup>
|
||||
</list>
|
||||
</option>
|
||||
<option name="lastOpenedProject" value="$USER_HOME$/code/alpha" />
|
||||
</component>
|
||||
</application>"#;
|
||||
|
||||
#[test]
|
||||
fn parses_jetbrains_recent_projects_and_groups() {
|
||||
let (projects, groups) = parse_jetbrains_recent(JETBRAINS_RECENT);
|
||||
assert_eq!(projects.len(), 5);
|
||||
assert_eq!(
|
||||
projects[0],
|
||||
JetBrainsRecent {
|
||||
path: "$USER_HOME$/code/alpha".into(),
|
||||
name: Some("Alpha Service".into()),
|
||||
opened_at_ms: 1700000005000.0,
|
||||
hidden: false,
|
||||
}
|
||||
);
|
||||
assert_eq!(projects[1].name.as_deref(), Some("beta-old-name"));
|
||||
assert!(projects[3].hidden);
|
||||
assert_eq!(
|
||||
groups,
|
||||
vec![
|
||||
JetBrainsGroup {
|
||||
name: "Work".into(),
|
||||
paths: vec!["$USER_HOME$/code/alpha".into(), "$USER_HOME$/code/gone".into()],
|
||||
expanded: true,
|
||||
},
|
||||
JetBrainsGroup { name: "Empty".into(), paths: vec![], expanded: false },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_jetbrains_path_variables() {
|
||||
let (home, config) = (Path::new("/home/me"), Path::new("/cfg/IDE"));
|
||||
assert_eq!(expand_jetbrains_path("$USER_HOME$/a/b", Some(home), config), Some(home.join("a").join("b")));
|
||||
assert_eq!(expand_jetbrains_path("$APPLICATION_CONFIG_DIR$/x", Some(home), config), Some(config.join("x")));
|
||||
assert_eq!(expand_jetbrains_path("$USER_HOME$", Some(home), config), Some(home.to_path_buf()));
|
||||
assert_eq!(expand_jetbrains_path("$USER_HOME$/a", None, config), None);
|
||||
assert_eq!(expand_jetbrains_path("$PROJECT_DIR$/a", Some(home), config), None);
|
||||
assert_eq!(expand_jetbrains_path("relative/a", Some(home), config), None);
|
||||
#[cfg(windows)]
|
||||
assert_eq!(expand_jetbrains_path("C:/Users/me/a", Some(home), config), Some(PathBuf::from(r"C:\Users\me\a")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jetbrains_import_merges_without_touching_existing_groups() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
for p in ["code/alpha", "code/beta", "mine"] {
|
||||
std::fs::create_dir_all(home.join(p)).unwrap();
|
||||
}
|
||||
let (alpha, beta, mine) = (home.join("code/alpha"), home.join("code/beta"), home.join("mine"));
|
||||
let cfg = tmp.path().join("config");
|
||||
let recent = RecentProjects::load(&cfg);
|
||||
recent.touch(&mine, None).unwrap();
|
||||
recent.touch(&beta, None).unwrap();
|
||||
let own = RecentProjectGroup { name: "Work".into(), paths: vec![mine.as_path().into()], expanded: true };
|
||||
recent.set_groups(vec![own.clone()]).unwrap();
|
||||
let ide = tmp.path().join("IDE");
|
||||
|
||||
let preview = recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, true).unwrap();
|
||||
let expected = JetBrainsRecentImport { imported: 1, missing: 2, groups: 1 };
|
||||
assert_eq!(preview, expected);
|
||||
assert_eq!(recent.list().len(), 2, "a preview changes nothing");
|
||||
|
||||
assert_eq!(recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, false).unwrap(), expected);
|
||||
let reloaded = RecentProjects::load(&cfg);
|
||||
let list = reloaded.list();
|
||||
let item = |p: &Path| list.iter().find(|i| i.path.as_ref() == p).unwrap();
|
||||
assert_eq!(item(&alpha).name, "Alpha Service");
|
||||
assert_eq!(item(&alpha).opened_at_ms, 1700000005000.0);
|
||||
// Already recent: keeps its own entry.
|
||||
assert_eq!(item(&beta).name, "beta");
|
||||
assert_eq!(list.len(), 3);
|
||||
// The group made here stays; the imported one gets a free name and only the imported projects.
|
||||
let imported =
|
||||
RecentProjectGroup { name: "Work 2".into(), paths: vec![alpha.as_path().into()], expanded: true };
|
||||
assert_eq!(reloaded.groups(), vec![own.clone(), imported.clone()]);
|
||||
|
||||
// Importing again adds nothing.
|
||||
let again = recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, false).unwrap();
|
||||
assert_eq!(again, JetBrainsRecentImport { imported: 0, missing: 2, groups: 0 });
|
||||
assert_eq!(RecentProjects::load(&cfg).groups(), vec![own, imported]);
|
||||
}
|
||||
|
||||
fn write_head(git_dir: &Path, contents: &str) {
|
||||
std::fs::create_dir_all(git_dir).unwrap();
|
||||
std::fs::write(git_dir.join("HEAD"), contents).unwrap();
|
||||
|
||||
@@ -145,6 +145,8 @@ Tab placement, the tab limit and what happens when it is reached, the preview ta
|
||||
|
||||
With tabs placed left or right, the tab column is as wide as its longest name, up to a limit. Drag the column's inner edge (or focus it and press `←` / `→`) to change the limit; it applies to every editor group and is remembered.
|
||||
|
||||
Double-click a tab, or the empty part of the tab strip, to maximize the editor: all tool windows are hidden, and doing it again brings them back. Double-clicking a preview tab keeps it open as a regular tab instead.
|
||||
|
||||
## Split editors
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
|
||||
@@ -143,6 +143,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
标签页放在左侧或右侧时,标签页列的宽度随最长的名称变化,但不超过一个上限。拖动该列靠近编辑器的边缘(或聚焦后按 `←` / `→`)可以调整上限;调整对所有编辑器组生效,并会被记住。
|
||||
|
||||
双击标签页或标签页栏的空白处可以最大化编辑器:隐藏所有工具窗口,再双击一次即恢复。双击预览标签页则会把它转为常规标签页。
|
||||
|
||||
## 拆分编辑器
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
|
||||
@@ -99,3 +99,116 @@ test("File History opens its revision and compares only that file with the worki
|
||||
.poll(async () => ipcCalls(page, "vcs_file_at"))
|
||||
.toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION });
|
||||
});
|
||||
|
||||
test("File History creates and copies a patch for only the selected changed file", async ({ workbench: page }) => {
|
||||
const parent = "b".repeat(40);
|
||||
const selectedPath = "src/selected.ts";
|
||||
const otherPath = "src/other.ts";
|
||||
const patch = `diff --git a/${selectedPath} b/${selectedPath}\n`;
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ root, path, revision, parent, selectedPath, otherPath }) => {
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_roots = () => [{ root, head: "main", headCommit: revision, operation: null }];
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: revision,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_branches = () => [];
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_log = ({ query }) =>
|
||||
(query as { path?: string }).path
|
||||
? [
|
||||
{
|
||||
id: revision,
|
||||
shortId: revision.slice(0, 8),
|
||||
parents: [parent],
|
||||
refs: [],
|
||||
author: "Author",
|
||||
email: "[email protected]",
|
||||
timeMs: 1,
|
||||
summary: "Export selected history file",
|
||||
message: "Export selected history file",
|
||||
historyPath: selectedPath,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
h.vcs_log_refs = () => ({});
|
||||
h.vcs_log_users = () => ["Author <[email protected]>"];
|
||||
h.vcs_log_details_batch = () => [];
|
||||
h.vcs_commit_files = () => [
|
||||
{ path: selectedPath, kind: "modified", oldPath: null },
|
||||
{ path: otherPath, kind: "modified", oldPath: null },
|
||||
];
|
||||
h.vcs_create_patch = ({ source }) => {
|
||||
const paths = (source as { paths?: string[] }).paths ?? [];
|
||||
return paths.map((entry) => `diff --git a/${entry} b/${entry}\n`).join("");
|
||||
};
|
||||
h.vcs_write_patch = () => null;
|
||||
h.clipboard_write_text = () => null;
|
||||
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectModule);
|
||||
useProject.setState((state: { settings: Record<string, unknown> }) => ({
|
||||
settings: {
|
||||
...state.settings,
|
||||
vcs: { confirmation: { onPatchCreated: "no" } },
|
||||
},
|
||||
}));
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true, statusLoaded: true });
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.showHistory", { path });
|
||||
},
|
||||
{ root: ROOT, path: `${ROOT}/${selectedPath}`, revision: REVISION, parent, selectedPath, otherPath },
|
||||
);
|
||||
|
||||
const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option", {
|
||||
name: /Export selected history file/,
|
||||
});
|
||||
await expect(row).toBeVisible();
|
||||
await row.click();
|
||||
const tree = page.getByRole("tree", { name: "Changed files" });
|
||||
const selected = tree.getByText("selected.ts", { exact: true });
|
||||
await expect(selected).toBeVisible();
|
||||
await expect(tree.getByText("other.ts", { exact: true })).toBeVisible();
|
||||
const toolbar = page.getByRole("toolbar", { name: "Changed files" });
|
||||
const create = toolbar.getByRole("button", { name: "Create Patch…", exact: true });
|
||||
await expect(create).toBeDisabled();
|
||||
await selected.click();
|
||||
await expect(create).toBeEnabled();
|
||||
await create.click();
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Create Patch", exact: true });
|
||||
await expect(dialog.getByRole("textbox", { name: "Base directory" })).toHaveValue(ROOT);
|
||||
const destination = await dialog.getByRole("textbox", { name: "Patch file" }).inputValue();
|
||||
expect(destination).toBe(`${ROOT}/Export_selected_history_file.patch`);
|
||||
await dialog.getByRole("button", { name: "Create", exact: true }).click();
|
||||
const source = { from: "revisions", before: parent, after: REVISION, paths: [selectedPath] };
|
||||
await expect.poll(() => ipcCalls(page, "vcs_create_patch")).toEqual([{ repo: ROOT, base: ROOT, source }]);
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_write_patch"))
|
||||
.toEqual([expect.objectContaining({ path: destination, patch })]);
|
||||
|
||||
await selected.click({ button: "right" });
|
||||
await page
|
||||
.getByRole("menu", { name: "Context menu" })
|
||||
.getByRole("menuitem", { name: "Copy as Patch to Clipboard", exact: true })
|
||||
.click();
|
||||
await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: patch }]);
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_create_patch"))
|
||||
.toEqual([
|
||||
{ repo: ROOT, base: ROOT, source },
|
||||
{ repo: ROOT, base: null, source },
|
||||
]);
|
||||
});
|
||||
@@ -202,6 +202,93 @@ test("File Structure prefers matches inside the caret symbol", async ({ workbenc
|
||||
await expect(tree.getByRole("treeitem", { name: "load", exact: true })).toHaveAttribute("aria-selected", "false");
|
||||
});
|
||||
|
||||
test("File Structure auto-enables temporary filters without saving them", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const optionsPath = "/src/features/search/structure/store.ts";
|
||||
const { useStructureOptions } = await import(/* @vite-ignore */ optionsPath);
|
||||
useStructureOptions.setState({ showFields: false, showNonPublic: false, showInherited: false, narrowDown: true });
|
||||
const range = { start: { line: 0, col: 0 }, end: { line: 1, col: 1 } };
|
||||
const symbol = (name: string, kind: string, visibility?: string) => ({
|
||||
name,
|
||||
kind,
|
||||
visibility,
|
||||
range,
|
||||
selection_range: range,
|
||||
children: [],
|
||||
});
|
||||
window.__ipc.handlers.doc_outline = () => [
|
||||
{
|
||||
...symbol("Container", "class"),
|
||||
children: [
|
||||
symbol("hiddenField", "field"),
|
||||
symbol("hiddenMethod", "method", "private"),
|
||||
symbol("visible", "method"),
|
||||
],
|
||||
},
|
||||
];
|
||||
window.__ipc.handlers.lsp_type_hierarchy = () => [];
|
||||
const actionsPath = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
|
||||
await executeAction("navigate.fileStructure");
|
||||
});
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "File Structure" });
|
||||
const filter = dialog.getByRole("textbox", { name: "Filter symbols" });
|
||||
const tree = dialog.getByRole("tree", { name: "Symbols" });
|
||||
const fields = dialog.getByRole("checkbox", { name: "Show fields" });
|
||||
const nonPublic = dialog.getByRole("checkbox", { name: "Show non-public" });
|
||||
const readOptions = () =>
|
||||
page.evaluate(async () => {
|
||||
const path = "/src/features/search/structure/store.ts";
|
||||
const { useStructureOptions } = await import(/* @vite-ignore */ path);
|
||||
const { showFields, showNonPublic, showInherited } = useStructureOptions.getState();
|
||||
return { showFields, showNonPublic, showInherited };
|
||||
});
|
||||
|
||||
await expect(fields).not.toBeChecked();
|
||||
await expect(nonPublic).not.toBeChecked();
|
||||
await filter.fill("hiddenField");
|
||||
await expect(fields).toBeChecked();
|
||||
await expect(nonPublic).not.toBeChecked();
|
||||
await expect(tree.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible();
|
||||
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: false, showInherited: false });
|
||||
|
||||
await nonPublic.check();
|
||||
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
|
||||
const saved = await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"));
|
||||
await filter.press("End");
|
||||
await filter.press("Backspace");
|
||||
await expect(filter).toHaveValue("hiddenFiel");
|
||||
await expect(fields).not.toBeChecked();
|
||||
await expect(nonPublic).toBeChecked();
|
||||
await expect(tree.getByRole("treeitem", { name: "hiddenField", exact: true })).toBeHidden();
|
||||
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
|
||||
|
||||
await filter.fill("hiddenField");
|
||||
await expect(fields).toBeChecked();
|
||||
await fields.uncheck();
|
||||
await expect(fields).not.toBeChecked();
|
||||
await filter.press("Escape");
|
||||
await expect(filter).toHaveValue("");
|
||||
await expect(fields).not.toBeChecked();
|
||||
await filter.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
|
||||
expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ path);
|
||||
await executeAction("navigate.fileStructure");
|
||||
});
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(dialog.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
|
||||
await expect(dialog.getByRole("checkbox", { name: "Show non-public" })).toBeChecked();
|
||||
expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved);
|
||||
});
|
||||
|
||||
test("F4 jumps to the filtered File Structure symbol", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
|
||||
@@ -26,6 +26,8 @@ impl ApplicationFocus {
|
||||
pub fn changed(app: &tauri::AppHandle, focused: bool) {
|
||||
let generation = app.state::<ApplicationFocus>().changed(focused);
|
||||
if focused {
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::window_groups::detach_deferred(app);
|
||||
return;
|
||||
}
|
||||
let app = app.clone();
|
||||
|
||||
@@ -382,6 +382,36 @@ pub async fn settings_list_jetbrains_ides() -> IdeResult<Vec<ide_host::plugins::
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Import Recent Projects from JetBrains IDE: merges the recent projects and project groups of the IDE
|
||||
/// whose settings folder is `path` (nothing when it has none); `dry_run` only counts them.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn recent_import_jetbrains(
|
||||
state: State<'_, AppState>,
|
||||
path: PathBuf,
|
||||
dry_run: bool,
|
||||
) -> IdeResult<ide_workspace::recent::JetBrainsRecentImport> {
|
||||
let app = state.app.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let xml = match std::fs::read_to_string(path.join("options").join("recentProjects.xml")) {
|
||||
Ok(xml) => xml,
|
||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory) => {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let state = app.state::<AppState>();
|
||||
let summary = state.recent.import_jetbrains(&xml, dirs::home_dir().as_deref(), &path, dry_run)?;
|
||||
if summary.imported > 0 {
|
||||
crate::jump_list::refresh(&state.app, state.recent.list());
|
||||
}
|
||||
Ok(summary)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
pub(crate) fn project_current(window: Window) -> Option<ProjectInfo> {
|
||||
let state = window.state::<AppState>();
|
||||
state.project(window.label()).ok().filter(|p| !p.light).map(|p| project_info(&p))
|
||||
@@ -466,6 +496,7 @@ ide_command::desktop_domain!(
|
||||
log_frontend,
|
||||
project_rename,
|
||||
project_trust_add_location,
|
||||
recent_import_jetbrains,
|
||||
recent_project_groups,
|
||||
recent_projects,
|
||||
remove_recent_project,
|
||||
|
||||
@@ -114,6 +114,16 @@ pub fn sync_tab_group(
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fullscreen_in_background(window: &WebviewWindow) -> bool {
|
||||
let target = window.clone();
|
||||
on_main(window, move || {
|
||||
let active =
|
||||
MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isActive());
|
||||
!active && native(&target).is_some_and(|w| w.styleMask().contains(objc2_app_kit::NSWindowStyleMask::FullScreen))
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Takes `window` out of its tab group into a window of its own; in full screen, a Space of its own.
|
||||
pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
|
||||
let target = window.clone();
|
||||
|
||||
@@ -1533,6 +1533,7 @@ mod tests {
|
||||
"file.exportSettings",
|
||||
"file.importSettings",
|
||||
"file.importJetBrainsSettings",
|
||||
"file.importJetBrainsRecentProjects",
|
||||
"file.syncSettings",
|
||||
"file.togglePowerSave",
|
||||
"macro.startRecording",
|
||||
|
||||
@@ -201,9 +201,19 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
|
||||
select(app, caller, caller)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
static DEFERRED_DETACH: parking_lot::Mutex<Vec<String>> = parking_lot::Mutex::new(Vec::new());
|
||||
|
||||
pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
|
||||
let err = |e: tauri::Error| IdeError::internal(e.to_string());
|
||||
let state = app.state::<WindowsState>();
|
||||
#[cfg(target_os = "macos")]
|
||||
if state.groups.lock().group(caller).is_some()
|
||||
&& app.get_webview_window(caller).is_some_and(|w| crate::macos::fullscreen_in_background(&w))
|
||||
{
|
||||
DEFERRED_DETACH.lock().push(caller.to_owned());
|
||||
return Ok(());
|
||||
}
|
||||
let Some(next) = state.groups.lock().detach(caller) else {
|
||||
changed(app);
|
||||
return Ok(());
|
||||
@@ -234,6 +244,14 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn detach_deferred(app: &AppHandle) {
|
||||
let labels = std::mem::take(&mut *DEFERRED_DETACH.lock());
|
||||
for label in labels {
|
||||
let _ = detach(app, &label);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn destroyed(app: &AppHandle, caller: &str) {
|
||||
let Some(state) = app.try_state::<WindowsState>() else { return };
|
||||
let next = state.groups.lock().detach(caller);
|
||||
|
||||
@@ -613,6 +613,7 @@ pypi_search outside_restricted project_host bin
|
||||
python_requirements trusted project_host bindings async
|
||||
python_route_sources trusted desktop bindings async
|
||||
recent_files always project_host bindings sync
|
||||
recent_import_jetbrains always desktop bindings async
|
||||
recent_project_groups always desktop bindings sync
|
||||
recent_projects always desktop bindings async
|
||||
redo_workspace_edit always project_host bindings async
|
||||
|
||||
@@ -1744,6 +1744,11 @@ export const commands = {
|
||||
pythonRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("python_route_sources")),
|
||||
/** Recently opened files, most recent first (⌘E). */
|
||||
recentFiles: () => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("recent_files")),
|
||||
/**
|
||||
* Import Recent Projects from JetBrains IDE: merges the recent projects and project groups of the IDE
|
||||
* whose settings folder is `path` (nothing when it has none); `dry_run` only counts them.
|
||||
*/
|
||||
recentImportJetbrains: (path: string, dryRun: boolean) => typedError<JetBrainsRecentImport, IdeError>(__TAURI_INVOKE("recent_import_jetbrains", { path, dryRun })),
|
||||
/** The welcome screen's project groups. */
|
||||
recentProjectGroups: () => __TAURI_INVOKE<RecentProjectGroup[]>("recent_project_groups"),
|
||||
recentProjects: () => __TAURI_INVOKE<RecentProject[]>("recent_projects"),
|
||||
@@ -10141,6 +10146,16 @@ export type JdkVendor = {
|
||||
name: string,
|
||||
};
|
||||
|
||||
/** What importing a JetBrains IDE's recent projects did (or, as a preview, would do). */
|
||||
export type JetBrainsRecentImport = {
|
||||
/** Projects added to the recent projects. */
|
||||
imported: number,
|
||||
/** Projects left out because their folder no longer exists. */
|
||||
missing: number,
|
||||
/** Project groups added. */
|
||||
groups: number,
|
||||
};
|
||||
|
||||
/**
|
||||
* A JetBrains IDE's settings folder or exported archive: every
|
||||
* entry name, and the text of the entries OpenIDEA maps (the frontend does the mapping).
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { insertNewlineAndIndent } from "@codemirror/commands";
|
||||
import { LanguageDescription, type Language } from "@codemirror/language";
|
||||
import { LanguageDescription, indentUnit, type Language } from "@codemirror/language";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getIndentation } from "@codemirror/language";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { logWarning } from "./highlight";
|
||||
import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
|
||||
import { commentTokens, fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
describe("language modes", () => {
|
||||
it("highlights Julia declarations, calls, types, macros and literals without semantic tokens", async () => {
|
||||
@@ -765,3 +765,43 @@ describe("language modes", () => {
|
||||
expect(found).not.toContain("yes:keyword");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Slint indentation", () => {
|
||||
it("indents element blocks by their braces under the C highlighting mode", async () => {
|
||||
const support = await loadSupport(findLanguageDescription("C", "/p/app.slint")!);
|
||||
const slint = commentTokens({
|
||||
id: "slint",
|
||||
name: "Slint",
|
||||
extensions: ["slint"],
|
||||
uiMode: "C",
|
||||
lineComment: "//",
|
||||
blockComment: ["/*", "*/"],
|
||||
indent: { tabSize: 4, insertSpaces: true },
|
||||
});
|
||||
const enter = (doc: string, at = doc.length) => {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
selection: EditorSelection.cursor(at),
|
||||
extensions: [support!, slint, indentUnit.of(" ")],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
insertNewlineAndIndent(view);
|
||||
const out = view.state.doc.toString();
|
||||
view.destroy();
|
||||
return out;
|
||||
};
|
||||
const app = "export component App inherits Window {";
|
||||
expect(enter(app)).toBe(`${app}\n `);
|
||||
expect(enter(`${app}}`, app.length)).toBe(`${app}\n \n}`);
|
||||
expect(enter(`${app}\n width: 100px;`)).toBe(`${app}\n width: 100px;\n `);
|
||||
// After a child element closes, the next line stays at the child's level.
|
||||
expect(enter(`${app}\n Text {\n text: "hi";\n }`)).toBe(
|
||||
`${app}\n Text {\n text: "hi";\n }\n `,
|
||||
);
|
||||
expect(enter(`${app}\n Text {\n }\n Rectangle {`)).toBe(
|
||||
`${app}\n Text {\n }\n Rectangle {\n `,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -740,6 +740,13 @@ const NO_INDENT_LANGS = new Set([
|
||||
"gitattributes",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Languages highlighted by a borrowed mode whose own indentation doesn't fit them: Slint's
|
||||
* element blocks (`Text { … }` without a `;`) read as unfinished C statements, so Enter after
|
||||
* one lands at the wrong column. These use the brace-based fallback indentation instead.
|
||||
*/
|
||||
const BRACE_INDENT_OVER_MODE = new Set(["slint"]);
|
||||
|
||||
function opensBlock(code: string, language: string | undefined): boolean {
|
||||
if (!code) return false;
|
||||
if (/[{([]$/.test(code)) return true;
|
||||
@@ -779,7 +786,7 @@ function indentationCode(text: string, lineComment: string | undefined): string
|
||||
*/
|
||||
export function fallbackIndent(language?: string): Extension {
|
||||
return indentService.of((cx, pos) => {
|
||||
if (cx.state.facet(languageFacet)) return undefined;
|
||||
if (cx.state.facet(languageFacet) && !BRACE_INDENT_OVER_MODE.has(language ?? "")) return undefined;
|
||||
const lineComment = cx.state.languageDataAt<{ line?: string }>("commentTokens", pos)[0]?.line;
|
||||
const stripComment = (text: string) => indentationCode(text, lineComment);
|
||||
|
||||
|
||||
@@ -399,6 +399,8 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
onCloseOthers={(id) => void ctrl.closeOthers(paneId, id)}
|
||||
onTogglePin={(id) => ctrl.togglePin(paneId, id)}
|
||||
closeOnShiftClick
|
||||
// IDEA: a double click on the strip's empty part maximizes the editor, as on a tab.
|
||||
onBlankDoubleClick={() => void executeAction("toolwindow.hideAll")}
|
||||
onDoubleClick={(id) => {
|
||||
// IDEA: a preview tab becomes a regular one; any other tab maximizes the editor.
|
||||
if (pane.tabs.find((t) => t.id === id)?.preview) ctrl.keepTab(paneId, id);
|
||||
|
||||
@@ -162,7 +162,7 @@ describe("Agents selection", () => {
|
||||
vi.mocked(openTask).mockClear();
|
||||
context("two");
|
||||
expect(selectedTasks()).toEqual(["one", "two", "three"]);
|
||||
expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy();
|
||||
expect(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ })).toBeTruthy();
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -298,9 +298,20 @@ describe("Agents docked view", () => {
|
||||
setup();
|
||||
expect(screen.queryByRole("button", { name: "Open in Editor" })).toBeNull();
|
||||
select("two");
|
||||
expect(openTask).toHaveBeenCalledWith("two");
|
||||
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
|
||||
expect(dockTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps focus in the list when a click opens a task, so Delete deletes that task", async () => {
|
||||
setup();
|
||||
const tree = screen.getByRole("tree", { name: "Agent tasks" });
|
||||
tree.focus();
|
||||
select("two");
|
||||
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
|
||||
// The shortcut runs the action without an argument: it takes the list's selection.
|
||||
await taskActions.find((a) => a.id === "agents.deleteTasks")!.run({ ctx: {}, arg: undefined });
|
||||
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("two", false));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Agents bulk actions", () => {
|
||||
@@ -311,7 +322,7 @@ describe("Agents bulk actions", () => {
|
||||
select("one");
|
||||
select("three", { shiftKey: true });
|
||||
context("two");
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Delete (3)…" }));
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ }));
|
||||
await waitFor(() => expect(deleteTask).toHaveBeenCalledTimes(3));
|
||||
expect(confirmChecked).toHaveBeenCalledTimes(1);
|
||||
expect(confirmChecked).toHaveBeenCalledWith(
|
||||
@@ -329,7 +340,7 @@ describe("Agents bulk actions", () => {
|
||||
select("one");
|
||||
select("two", { shiftKey: true });
|
||||
context("four");
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Delete…" }));
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: /^Delete…/ }));
|
||||
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("four", false));
|
||||
});
|
||||
|
||||
@@ -784,6 +795,6 @@ describe("Agents pinned and grouped tasks", () => {
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
fireEvent.pointerUp(window, { button: 0, clientX: 10, clientY: 104 });
|
||||
fireEvent.click(sourceSpan, { button: 0 });
|
||||
expect(openTask).toHaveBeenCalledWith("two");
|
||||
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
|
||||
});
|
||||
});
|
||||
@@ -52,8 +52,8 @@ import {
|
||||
openHome,
|
||||
pinTasks,
|
||||
refreshExternalSessions,
|
||||
reorderTask,
|
||||
reorderTaskGroup,
|
||||
reorderTasks,
|
||||
showImportSessions,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
@@ -238,6 +238,8 @@ export function AgentsView() {
|
||||
searchingRef.current = matches !== null;
|
||||
}, [matches]);
|
||||
const cancelDragRef = useRef<(() => void) | undefined>(undefined);
|
||||
/** Every task the current drag carries, in list order; set when it starts. */
|
||||
const draggedIdsRef = useRef<string[]>([]);
|
||||
const [tasksEl, setTasksEl] = useState<HTMLDivElement | null>(null);
|
||||
const [dropIndicator, setDropIndicator] = useState<DropIndicator | null>(null);
|
||||
useEffect(() => {
|
||||
@@ -266,11 +268,18 @@ export function AgentsView() {
|
||||
const { tasks, organize } = useAgents.getState();
|
||||
const source = tasks.get(data.payload);
|
||||
if (!source) return null;
|
||||
// Dragging a selected task moves the whole selection.
|
||||
const ids = draggedIdsRef.current.includes(source.id) ? draggedIdsRef.current : [source.id];
|
||||
const sources = ids.flatMap((id) => {
|
||||
const task = tasks.get(id);
|
||||
return task ? [task] : [];
|
||||
});
|
||||
const sourceIds = sources.map((t) => t.id);
|
||||
|
||||
if (targetKey === PINNED_SECTION) {
|
||||
return {
|
||||
indicator: { kind: "section", key: targetKey } as DropIndicator,
|
||||
apply: () => pinTasks([source.id], true),
|
||||
apply: () => pinTasks(sourceIds, true),
|
||||
};
|
||||
}
|
||||
if (targetKey.startsWith("ug:")) {
|
||||
@@ -278,23 +287,33 @@ export function AgentsView() {
|
||||
if (!organize.groups.some((g) => g.id === groupId)) return null;
|
||||
return {
|
||||
indicator: { kind: "section", key: targetKey } as DropIndicator,
|
||||
apply: () => moveTasksToGroup([source.id], groupId),
|
||||
apply: () => moveTasksToGroup(sourceIds, groupId),
|
||||
};
|
||||
}
|
||||
if (targetKey.startsWith("g:")) {
|
||||
if (sectionOfTask(source, organize) === targetKey) return null;
|
||||
if (statusSection(taskGroupStatus(source)) !== targetKey) return null;
|
||||
// A status group takes the tasks of its status that are elsewhere.
|
||||
const movable = sources.filter(
|
||||
(t) => sectionOfTask(t, organize) !== targetKey && statusSection(taskGroupStatus(t)) === targetKey,
|
||||
);
|
||||
if (!movable.length) return null;
|
||||
return {
|
||||
indicator: { kind: "section", key: targetKey } as DropIndicator,
|
||||
apply: () => moveTasksToStatusGroup([source.id]),
|
||||
apply: () => moveTasksToStatusGroup(movable.map((t) => t.id)),
|
||||
};
|
||||
}
|
||||
if (searchingRef.current) return null;
|
||||
const target = tasks.get(targetKey);
|
||||
if (!target || !canReorderTask(source, target, organize)) return null;
|
||||
if (!target || sourceIds.includes(target.id)) return null;
|
||||
const movable = sources.filter((t) => canReorderTask(t, target, organize));
|
||||
if (!movable.length) return null;
|
||||
return {
|
||||
indicator: { kind: "row", key: targetKey, position } as DropIndicator,
|
||||
apply: () => reorderTask(source.id, target.id, position),
|
||||
apply: () =>
|
||||
reorderTasks(
|
||||
movable.map((t) => t.id),
|
||||
target.id,
|
||||
position,
|
||||
),
|
||||
};
|
||||
};
|
||||
const update = () => {
|
||||
@@ -383,11 +402,26 @@ export function AgentsView() {
|
||||
setHistoryOpen(false);
|
||||
void executeAction("agents.openTask", task);
|
||||
};
|
||||
// A click or arrow key in the list opens the session but keeps focus in the list, so its
|
||||
// shortcuts (Delete) still act on the selection; Enter and double-click focus the session.
|
||||
const previewTask = (task: string) => {
|
||||
if (inline) showTask(task);
|
||||
else void executeAction("agents.openTask", { task, focus: false });
|
||||
};
|
||||
const dockedTitle = docked ? (tasks.get(docked)?.title ?? docked) : null;
|
||||
const dragTask = (e: ReactPointerEvent<HTMLElement>, task: string, source: HTMLElement = e.currentTarget) => {
|
||||
suppressClickRef.current = false;
|
||||
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
|
||||
cancelDragRef.current?.();
|
||||
// A selected row drags the whole selection, in list order.
|
||||
const current = selectedRef.current;
|
||||
draggedIdsRef.current =
|
||||
current.size > 1 && current.has(task)
|
||||
? roots
|
||||
.flatMap((n) => (n.kind === "group" ? n.group.tasks : n.kind === "task" ? [n.task] : n.tasks))
|
||||
.map((t) => t.id)
|
||||
.filter((id, i, all) => current.has(id) && all.indexOf(id) === i)
|
||||
: [task];
|
||||
cancelDragRef.current = startPointerDrag(
|
||||
e,
|
||||
source,
|
||||
@@ -478,7 +512,7 @@ export function AgentsView() {
|
||||
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
|
||||
if ((e.target as Element).closest("button, input, textarea, [data-tree-toggle]")) return;
|
||||
const key = (e.target as Element).closest<HTMLElement>("[data-tree-key]")?.dataset.treeKey;
|
||||
if (key && tasks.has(key)) showTask(key);
|
||||
if (key && tasks.has(key)) previewTask(key);
|
||||
}}
|
||||
onFocus={() => setFocusedTaskList(() => [...selectedRef.current])}
|
||||
onBlur={(e) => {
|
||||
@@ -554,7 +588,7 @@ export function AgentsView() {
|
||||
lead?.kind === "task" &&
|
||||
sel.has(lead.task.id)
|
||||
)
|
||||
showTask(lead.task.id);
|
||||
previewTask(lead.task.id);
|
||||
}}
|
||||
onActivate={(n) => n.kind === "task" && showTask(n.task.id)}
|
||||
onContextMenu={(n, sel, e) => {
|
||||
|
||||
@@ -57,6 +57,7 @@ import { withQuote } from "./conversation";
|
||||
import {
|
||||
EMPTY_ORGANIZE,
|
||||
PINNED_SECTION,
|
||||
canReorderTask,
|
||||
compactOrder,
|
||||
customSection,
|
||||
loadOrganize,
|
||||
@@ -1184,7 +1185,8 @@ export function useAgentCommands(
|
||||
return extra.length > 0 ? [...filtered, ...extra] : filtered;
|
||||
}
|
||||
|
||||
export function openTask(task: string) {
|
||||
/** Opens the task's session; `focus: false` opens it in the editor without taking focus (a click in the task list). */
|
||||
export function openTask(task: string, options: { focus?: boolean } = {}) {
|
||||
if (routeToWindow(task)) return;
|
||||
forgetClosed(task);
|
||||
if (useAgents.getState().sessionLocation === "toolWindow") {
|
||||
@@ -1192,13 +1194,13 @@ export function openTask(task: string) {
|
||||
return;
|
||||
}
|
||||
useAgents.setState({ lastTask: task, homeOpen: false, lastComposer: task });
|
||||
openTaskInEditor(task);
|
||||
openTaskInEditor(task, options.focus ?? true);
|
||||
}
|
||||
|
||||
function openTaskInEditor(task: string) {
|
||||
function openTaskInEditor(task: string, focus = true) {
|
||||
// The title rides along so a restored tab has it before the tasks load.
|
||||
const title = useAgents.getState().tasks.get(task)?.title;
|
||||
void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus: true });
|
||||
void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus });
|
||||
}
|
||||
|
||||
function showDockedTask(task: string) {
|
||||
@@ -2189,10 +2191,27 @@ export function moveTasksToStatusGroup(tasks: readonly string[]) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Places `sourceId` before or after `targetId` (moving it into the target's section when needed). */
|
||||
export function reorderTask(sourceId: string, targetId: string, position: "before" | "after") {
|
||||
const tasks = useAgents.getState().tasks.values();
|
||||
changeOrganize((organize) => reorderTaskInOrganize(organize, tasks, sourceId, targetId, position));
|
||||
/**
|
||||
* Places `sourceIds` (in list order) before or after `targetId`, keeping their relative order.
|
||||
* Tasks that can't go beside the target (another status than its status group) stay where they are.
|
||||
*/
|
||||
export function reorderTasks(sourceIds: readonly string[], targetId: string, position: "before" | "after") {
|
||||
const tasks = [...useAgents.getState().tasks.values()];
|
||||
changeOrganize((organize) => {
|
||||
let next = organize;
|
||||
// Before: each goes right before the target. After: each goes after the one placed last.
|
||||
let anchor = targetId;
|
||||
const byId = new Map(tasks.map((t) => [t.id, t]));
|
||||
for (const id of sourceIds) {
|
||||
if (id === targetId) continue;
|
||||
const source = byId.get(id);
|
||||
const target = byId.get(anchor);
|
||||
if (!source || !target || !canReorderTask(source, target, next)) continue;
|
||||
next = reorderTaskInOrganize(next, tasks, id, anchor, position);
|
||||
if (position === "after") anchor = id;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
/** Reorders a custom group before or after another custom group. */
|
||||
|
||||
@@ -285,6 +285,11 @@ export const taskActions: Action[] = [
|
||||
hidden: true,
|
||||
run: ({ arg }) => {
|
||||
if (typeof arg === "string") openTask(arg);
|
||||
// `{ task, focus: false }`: a click in the task list opens the session and keeps focus there.
|
||||
else if (arg && typeof arg === "object" && typeof (arg as { task?: unknown }).task === "string") {
|
||||
const { task, focus } = arg as { task: string; focus?: unknown };
|
||||
openTask(task, { focus: focus !== false });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -396,6 +401,8 @@ export const taskActions: Action[] = [
|
||||
title: "Delete Agent Tasks",
|
||||
category: "Agents",
|
||||
hidden: true,
|
||||
// Without an argument the shortcut deletes the task list's selection.
|
||||
keyWhen: "agentTaskListFocus",
|
||||
run: ({ arg }) => confirmDelete(resolveTasks(arg)),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -7,19 +7,28 @@ import listStyles from "@/ui/List.module.css";
|
||||
const listIdes = vi.fn();
|
||||
const importJetBrainsSettings = vi.fn();
|
||||
const notify = vi.fn();
|
||||
const importRecent = vi.fn();
|
||||
const loadRecent = vi.fn();
|
||||
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
call: <T,>(result: Promise<T>) => result,
|
||||
commands: { settingsListJetbrainsIdes: () => listIdes() },
|
||||
commands: {
|
||||
settingsListJetbrainsIdes: () => listIdes(),
|
||||
recentImportJetbrains: (path: string, dryRun: boolean) => importRecent(path, dryRun),
|
||||
},
|
||||
}));
|
||||
vi.mock("../jetbrainsSettings", () => ({ importJetBrainsSettings: (path: string) => importJetBrainsSettings(path) }));
|
||||
vi.mock("../jetbrainsSettings", async (original) => ({
|
||||
...(await original<typeof import("../jetbrainsSettings")>()),
|
||||
importJetBrainsSettings: (path: string) => importJetBrainsSettings(path),
|
||||
}));
|
||||
vi.mock("@/features/welcome/recent", () => ({ loadRecent: () => loadRecent() }));
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify }),
|
||||
}));
|
||||
|
||||
const { importFromJetBrainsIde } = await import("../projectActions");
|
||||
const { importFromJetBrainsIde, importJetBrainsRecentProjects } = await import("../projectActions");
|
||||
|
||||
const idea = {
|
||||
ide: "IntelliJ IDEA 2025.2",
|
||||
@@ -110,3 +119,50 @@ describe("Manage IDE Settings › Import Settings from JetBrains IDE…", () =>
|
||||
expect(importJetBrainsSettings).toHaveBeenCalledExactlyOnceWith(ides[59]!.path);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Import Recent Projects from JetBrains IDE…", () => {
|
||||
async function pickFirst(run: () => Promise<void>) {
|
||||
let done!: Promise<void>;
|
||||
await act(async () => {
|
||||
done = run();
|
||||
});
|
||||
const list = screen.getByRole("listbox", { name: "Import Recent Projects from JetBrains IDE" });
|
||||
await act(async () => {
|
||||
fireEvent.keyDown(list, { key: "Enter" });
|
||||
await done;
|
||||
});
|
||||
}
|
||||
|
||||
it("merges the chosen IDE's recent projects, refreshes the list and says what it did", async () => {
|
||||
listIdes.mockResolvedValue([idea, studio]);
|
||||
importRecent.mockResolvedValue({ imported: 3, missing: 2, groups: 1 });
|
||||
await pickFirst(importJetBrainsRecentProjects);
|
||||
expect(importRecent).toHaveBeenCalledExactlyOnceWith(idea.path, false);
|
||||
expect(loadRecent).toHaveBeenCalled();
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
level: "info",
|
||||
title: "Recent projects imported",
|
||||
body: "Imported 3 recent projects and 1 project groups, skipped 2 whose folder is missing.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("warns when there is nothing new", async () => {
|
||||
listIdes.mockResolvedValue([idea]);
|
||||
importRecent.mockResolvedValue({ imported: 0, missing: 1, groups: 0 });
|
||||
await pickFirst(importJetBrainsRecentProjects);
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ level: "warning", title: "No new recent projects to import" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a failure", async () => {
|
||||
listIdes.mockResolvedValue([idea]);
|
||||
importRecent.mockRejectedValue(new Error("denied"));
|
||||
await pickFirst(importJetBrainsRecentProjects);
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ level: "error", title: "Cannot import recent projects" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,8 @@ const set = vi.fn();
|
||||
const notify = vi.fn();
|
||||
const execute = vi.fn();
|
||||
const marketCall = vi.fn();
|
||||
const importRecent = vi.fn();
|
||||
const loadRecent = vi.fn();
|
||||
const market = [
|
||||
{ id: "ruyimg.codeglance-pro", name: "CodeGlance Pro", installed: null, compatible: true },
|
||||
{ id: "solhovoy.grep-console", name: "Grep Console", installed: null, compatible: true },
|
||||
@@ -22,9 +24,11 @@ vi.mock("@/platform/ipc", async (original) => {
|
||||
settingsGetGlobal: async () => ({ editor }),
|
||||
settingsSet: (scope: string, key: string, value: string) => set(scope, key, value),
|
||||
pluginMarket: () => marketCall(),
|
||||
recentImportJetbrains: (path: string, dryRun: boolean) => importRecent(path, dryRun),
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/features/welcome/recent", () => ({ loadRecent: () => loadRecent() }));
|
||||
vi.mock("@/platform/actions", async (original) => ({
|
||||
...(await original<typeof import("@/platform/actions")>()),
|
||||
executeAction: (id: string, arg?: unknown) => execute(id, arg),
|
||||
@@ -58,6 +62,7 @@ beforeEach(() => {
|
||||
});
|
||||
set.mockResolvedValue({ status: "ok", data: { editor } });
|
||||
marketCall.mockResolvedValue({ status: "ok", data: market });
|
||||
importRecent.mockResolvedValue({ status: "ok", data: { imported: 0, missing: 0, groups: 0 } });
|
||||
// jsdom has no canvas: the import falls back to the font size for the line height.
|
||||
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
|
||||
});
|
||||
@@ -150,3 +155,28 @@ it("says so when the plugin marketplace cannot be reached, without blaming the p
|
||||
expect(screen.getByText(/Plugins without a counterpart/)).not.toHaveTextContent("CodeGlancePro");
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Cancel" })));
|
||||
});
|
||||
|
||||
it("lists an IDE's recent projects and merges them on Import", async () => {
|
||||
read.mockResolvedValue({ status: "ok", data: { entries: [], files: {} } });
|
||||
importRecent.mockResolvedValue({ status: "ok", data: { imported: 4, missing: 1, groups: 2 } });
|
||||
render(<MessagesHost />);
|
||||
let done!: Promise<void>;
|
||||
await act(async () => {
|
||||
done = importJetBrainsSettings("/settings/IDE");
|
||||
});
|
||||
expect(importRecent).toHaveBeenCalledExactlyOnceWith("/settings/IDE", true);
|
||||
expect(screen.getByText("Recent projects")).toBeInTheDocument();
|
||||
expect(screen.getByText("4 new, 2 new project groups, 1 skipped (folder missing)")).toBeInTheDocument();
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Import" }));
|
||||
await done;
|
||||
});
|
||||
expect(importRecent).toHaveBeenLastCalledWith("/settings/IDE", false);
|
||||
expect(loadRecent).toHaveBeenCalled();
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
title: "Settings imported",
|
||||
body: "Imported 4 recent projects and 2 project groups, skipped 1 whose folder is missing.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -27,6 +27,7 @@ vi.mock("@/platform/ipc", async (original) => {
|
||||
settingsGetGlobal: async () => ({ editor }),
|
||||
settingsSet: (scope: string, key: string, value: string) => set(scope, key, value),
|
||||
languages: async () => [python],
|
||||
recentImportJetbrains: async () => ({ status: "ok", data: { imported: 0, missing: 0, groups: 0 } }),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -6,7 +6,13 @@
|
||||
* out). The rest is listed as not imported.
|
||||
*/
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import type { CustomKeymap, JetBrainsSettings, LanguageCodeStyle, LanguageInfo } from "@/bindings";
|
||||
import type {
|
||||
CustomKeymap,
|
||||
JetBrainsRecentImport,
|
||||
JetBrainsSettings,
|
||||
LanguageCodeStyle,
|
||||
LanguageInfo,
|
||||
} from "@/bindings";
|
||||
import { actionToggled, executeAction, getAction } from "@/platform/actions";
|
||||
import { customSchemes } from "@/platform/colorScheme";
|
||||
import { createFontProbeCanvas, fontsLoaded, monoFontFamily } from "@/platform/fonts";
|
||||
@@ -18,6 +24,7 @@ import { guessOs } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { loadRecent } from "@/features/welcome/recent";
|
||||
import { parseJetBrainsTemplates, type JetBrainsTemplateImport } from "@/features/templates/live/jetbrains";
|
||||
import { saveImportedTemplates } from "@/features/templates/live/store";
|
||||
import styles from "./app.module.css";
|
||||
@@ -480,10 +487,25 @@ function Summary({ plan, pending }: { plan: JetBrainsImportPlan; pending?: Promi
|
||||
);
|
||||
}
|
||||
|
||||
/** What importing a JetBrains IDE's recent projects did. */
|
||||
export function recentImportSummary({ imported, groups, missing }: JetBrainsRecentImport): string {
|
||||
return tx`Imported ${imported} recent projects and ${groups} project groups, skipped ${missing} whose folder is missing.`;
|
||||
}
|
||||
|
||||
/** Reads `path`, asks, then writes the mapped settings to the global layer. */
|
||||
export async function importJetBrainsSettings(path: string) {
|
||||
const bundle = await call(commands.settingsReadJetbrains(path));
|
||||
const plan = await planJetBrainsImport(bundle, await commands.settingsGetGlobal());
|
||||
// An IDE's settings folder (not an exported archive) has its recent projects.
|
||||
const recent = await call(commands.recentImportJetbrains(path, true)).catch(() => null);
|
||||
const hasRecent = !!recent && (recent.imported > 0 || recent.groups > 0);
|
||||
if (hasRecent) {
|
||||
const { imported, groups, missing } = recent;
|
||||
plan.rows.push({
|
||||
label: tx("Recent projects"),
|
||||
value: tx`${imported} new, ${groups} new project groups, ${missing} skipped (folder missing)`,
|
||||
});
|
||||
}
|
||||
const plugins = plan.plugins;
|
||||
// Looked up while the confirmation is open; it shows the answer when it comes.
|
||||
const pending = plugins?.candidates.length
|
||||
@@ -491,7 +513,7 @@ export async function importJetBrainsSettings(path: string) {
|
||||
.then((market) => suggestPlugins(plugins.candidates, market))
|
||||
.catch(() => null)
|
||||
: undefined;
|
||||
if (!plan.writes.length && !plan.liveTemplates?.templates.length && !pending && !plugins?.vim) {
|
||||
if (!plan.writes.length && !plan.liveTemplates?.templates.length && !pending && !plugins?.vim && !hasRecent) {
|
||||
const details = [...plan.invalid, ...(plan.liveTemplates?.skipped ?? [])].join(", ");
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
@@ -515,7 +537,14 @@ export async function importJetBrainsSettings(path: string) {
|
||||
if (plan.liveTemplates?.templates.length) saveImportedTemplates(plan.liveTemplates.templates);
|
||||
useProject.setState({ settings });
|
||||
if (plugins?.vim && !actionToggled(getAction("vim.toggle"))) void executeAction("vim.toggle");
|
||||
notifications().notify({ level: "info", title: "Settings imported", body: path, key: "app.settingsImport" });
|
||||
const imported = hasRecent ? await call(commands.recentImportJetbrains(path, false)).catch(() => null) : null;
|
||||
if (imported) void loadRecent();
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: "Settings imported",
|
||||
body: imported ? recentImportSummary(imported) : path,
|
||||
key: "app.settingsImport",
|
||||
});
|
||||
if (useProject.getState().project && plan.inspectionProfiles?.length)
|
||||
offerInspectionProfiles(plan.inspectionProfiles);
|
||||
void pending?.then((s) => s?.install.length && offerPlugins(s.install));
|
||||
|
||||
@@ -9,7 +9,8 @@ import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { notifications, registerEditorBanner } from "@/workbench/contributions";
|
||||
import { pickItems, promptInput } from "@/workbench/inputDialogs";
|
||||
import { importJetBrainsSettings } from "./jetbrainsSettings";
|
||||
import { loadRecent } from "@/features/welcome/recent";
|
||||
import { importJetBrainsSettings, recentImportSummary } from "./jetbrainsSettings";
|
||||
import { showNewProject } from "./NewProject";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -114,24 +115,30 @@ async function importSettings() {
|
||||
}
|
||||
}
|
||||
|
||||
/** The settings folder of the JetBrains IDE the user picks; undefined when none is installed or the pick is cancelled. */
|
||||
async function pickJetBrainsIde(title: string): Promise<string | undefined> {
|
||||
const ides = await call(commands.settingsListJetbrainsIdes());
|
||||
if (!ides.length) {
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
title: "No JetBrains IDE settings were found on this computer",
|
||||
key: "app.settingsImport",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const picked = await pickItems({
|
||||
title,
|
||||
items: ides.map((ide) => ({ key: ide.path, label: ide.ide })),
|
||||
multiple: false,
|
||||
});
|
||||
return picked?.[0];
|
||||
}
|
||||
|
||||
/** Import Settings from a JetBrains IDE installed on this computer, without exporting a `settings.zip` first. */
|
||||
export async function importFromJetBrainsIde() {
|
||||
try {
|
||||
const ides = await call(commands.settingsListJetbrainsIdes());
|
||||
if (!ides.length) {
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
title: "No JetBrains IDE settings were found on this computer",
|
||||
key: "app.settingsImport",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const picked = await pickItems({
|
||||
title: tx("Import Settings from JetBrains IDE"),
|
||||
items: ides.map((ide) => ({ key: ide.path, label: ide.ide })),
|
||||
multiple: false,
|
||||
});
|
||||
if (picked?.[0]) await importJetBrainsSettings(picked[0]);
|
||||
const path = await pickJetBrainsIde(tx("Import Settings from JetBrains IDE"));
|
||||
if (path) await importJetBrainsSettings(path);
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
@@ -142,6 +149,29 @@ export async function importFromJetBrainsIde() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the recent projects and project groups of a JetBrains IDE to the Welcome screen's. */
|
||||
export async function importJetBrainsRecentProjects() {
|
||||
try {
|
||||
const path = await pickJetBrainsIde(tx("Import Recent Projects from JetBrains IDE"));
|
||||
if (!path) return;
|
||||
const result = await call(commands.recentImportJetbrains(path, false));
|
||||
void loadRecent();
|
||||
notifications().notify({
|
||||
level: result.imported || result.groups ? "info" : "warning",
|
||||
title: result.imported || result.groups ? "Recent projects imported" : "No new recent projects to import",
|
||||
body: recentImportSummary(result),
|
||||
key: "app.recentImport",
|
||||
});
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot import recent projects",
|
||||
body: errorText(e),
|
||||
key: "app.recentImport",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function renameProject() {
|
||||
const project = useProject.getState().project;
|
||||
if (!project) return;
|
||||
@@ -219,6 +249,13 @@ export function projectActions(): Action[] {
|
||||
keywords: ["intellij", "pycharm", "webstorm", "android studio", "migrate", "manage ide settings"],
|
||||
run: desktop(importFromJetBrainsIde),
|
||||
},
|
||||
{
|
||||
id: "file.importJetBrainsRecentProjects",
|
||||
title: "Import Recent Projects from JetBrains IDE…",
|
||||
category: "File",
|
||||
keywords: ["intellij", "pycharm", "webstorm", "android studio", "migrate", "project groups"],
|
||||
run: desktop(importJetBrainsRecentProjects),
|
||||
},
|
||||
{
|
||||
id: "file.togglePowerSave",
|
||||
title: "Power Save Mode",
|
||||
|
||||
@@ -100,9 +100,9 @@ export function ProjectHeaderActions() {
|
||||
{!alwaysSelect && (
|
||||
<IconButton
|
||||
icon="locate"
|
||||
action="navigate.selectInProjectView"
|
||||
action="project.selectOpenedFile"
|
||||
title="Select Opened File"
|
||||
shortcut={shortcutLabel("navigate.selectInProjectView")}
|
||||
shortcut={shortcutLabel("project.selectOpenedFile")}
|
||||
size="small"
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -254,6 +254,16 @@ export function registerProjectActions(): () => void {
|
||||
keywords: ["locate", "reveal", "scroll from source", "select opened file"],
|
||||
run: ({ arg }) => void selectInProjectView(typeof arg === "string" ? arg : null),
|
||||
},
|
||||
{
|
||||
// IDEA's SelectOpenedFileInProjectView: the Project view toolbar's locate button.
|
||||
id: "project.selectOpenedFile",
|
||||
title: "Select Opened File",
|
||||
category: "Project View",
|
||||
icon: "locate",
|
||||
when: OPEN,
|
||||
keywords: ["locate", "reveal", "scroll from source", "select in project view"],
|
||||
run: () => void selectInProjectView(null),
|
||||
},
|
||||
{
|
||||
id: "project.reveal",
|
||||
title: "Reveal in Project View",
|
||||
|
||||
@@ -152,6 +152,18 @@ describe("Select In (⌥F1)", () => {
|
||||
expect(useContextMenuStore.getState().menu).toBeNull();
|
||||
});
|
||||
|
||||
it("Select Opened File is a Project View action of its own, as in IDEA's keymap", async () => {
|
||||
const { IDEA_ACTIONS } = await import("@/platform/ideaActions");
|
||||
disposers.push(registerProjectActions(), () => setContext("projectOpen", false));
|
||||
setContext("projectOpen", true);
|
||||
expect(getAction("project.selectOpenedFile")).toMatchObject({
|
||||
title: "Select Opened File",
|
||||
category: "Project View",
|
||||
});
|
||||
expect(IDEA_ACTIONS.SelectOpenedFileInProjectView).toBe("project.selectOpenedFile");
|
||||
expect(IDEA_ACTIONS.SelectInProjectView).toBe("navigate.selectInProjectView");
|
||||
});
|
||||
|
||||
it("expands an in-project folder when expand is true and reveals out-of-project folders in the file manager", async () => {
|
||||
const { useProjectTree } = await import("./store");
|
||||
const prev = useProjectTree.getState();
|
||||
|
||||
@@ -62,6 +62,7 @@ vi.mock("../find/windowStore", async (orig) => ({
|
||||
|
||||
const contributions = await import("@/workbench/contributions");
|
||||
const { commands, emitLocalIdeEvent } = await import("@/platform/ipc");
|
||||
const { ContextMenuHost } = await import("@/ui");
|
||||
const { RecentPopupsOverlay } = await import("../recent/RecentPopups");
|
||||
const { cycleSwitcher, showRecentPopup, hideRecentPopup, useRecentPopup } = await import("../recent/store");
|
||||
const { openLocation } = await import("../common/open");
|
||||
@@ -448,6 +449,39 @@ function clickOption(index: number, modifiers = {}) {
|
||||
fireEvent.click(row, modifiers);
|
||||
}
|
||||
|
||||
describe("Search Everywhere result actions", () => {
|
||||
it.each(["keyboard", "right click"] as const)("selects a file in the Project view from the %s menu", async (how) => {
|
||||
const run = vi.fn();
|
||||
const project = useProject.getState().project;
|
||||
useProject.setState({ project: { root: "/p", name: "p", isGit: false } as never });
|
||||
const dispose = registerAction({
|
||||
id: "navigate.selectInProjectView",
|
||||
title: "Select in Project View",
|
||||
run: ({ arg }) => run(arg),
|
||||
});
|
||||
try {
|
||||
render(
|
||||
<>
|
||||
<SearchEverywhereOverlay />
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
act(() => showSearchEverywhere("files", { query: "order" }));
|
||||
await tick();
|
||||
if (how === "keyboard") fireEvent.keyDown(screen.getByLabelText("Search query"), { key: "Enter", altKey: true });
|
||||
else fireEvent.contextMenu(resultOptions()[0]!);
|
||||
await tick();
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: /Select in Project View/ }));
|
||||
await tick();
|
||||
expect(run).toHaveBeenCalledExactlyOnceWith("/p/src/OrderController.kt");
|
||||
expect(useSearchEverywhere.getState().open).toBe(false);
|
||||
} finally {
|
||||
dispose();
|
||||
useProject.setState({ project });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Search Everywhere multi-selection", () => {
|
||||
it("extends, shrinks, crosses the anchor and clamps Shift selection; plain arrows select one", async () => {
|
||||
const input = await showDuplicateFiles();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { OutlineItem } from "@/platform/ipc";
|
||||
|
||||
@@ -16,10 +16,17 @@ const { FileStructureOverlay, useFileStructurePopup } = await import("../structu
|
||||
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 => ({
|
||||
const item = (
|
||||
name: string,
|
||||
kind: OutlineItem["kind"],
|
||||
line: number,
|
||||
children: OutlineItem[] = [],
|
||||
visibility?: OutlineItem["visibility"],
|
||||
): OutlineItem => ({
|
||||
name,
|
||||
detail: null,
|
||||
kind,
|
||||
visibility,
|
||||
range: { start: { line, col: 0 }, end: { line: line + 1, col: 1 } },
|
||||
selection_range: { start: { line, col: 4 }, end: { line, col: 4 + name.length } },
|
||||
children,
|
||||
@@ -61,6 +68,19 @@ function openFunctions(narrowDown: boolean) {
|
||||
return input;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useStructureOptions.setState({
|
||||
alphabetical: false,
|
||||
narrowDown: true,
|
||||
showFields: true,
|
||||
showNonPublic: true,
|
||||
showInherited: false,
|
||||
sortByVisibility: false,
|
||||
showOnlyWidgets: false,
|
||||
});
|
||||
useOutline.setState({ inheritedSupported: false, inherited: null, flutter: null });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => useFileStructurePopup.setState({ open: false }));
|
||||
useTracking.setState({ caret: null });
|
||||
@@ -186,6 +206,133 @@ describe("File Structure popup", () => {
|
||||
expect(useFileStructurePopup.getState().open).toBe(false);
|
||||
});
|
||||
|
||||
describe("temporary filters", () => {
|
||||
const filteredItems = () => [
|
||||
item("Container", "class", 0, [
|
||||
item("hiddenField", "field", 2),
|
||||
item("hiddenMethod", "method", 4, [], "private"),
|
||||
item("visible", "method", 6),
|
||||
]),
|
||||
];
|
||||
|
||||
it("auto-enables only the applicable filter needed for a match, without persisting it", () => {
|
||||
useStructureOptions.setState({ showFields: false, showNonPublic: false });
|
||||
const saved = localStorage.getItem("openidea.structure.options.v1");
|
||||
const input = open(filteredItems());
|
||||
const fields = screen.getByRole("checkbox", { name: "Show fields" });
|
||||
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
|
||||
expect(fields).not.toBeChecked();
|
||||
expect(nonPublic).not.toBeChecked();
|
||||
|
||||
fireEvent.change(input, { target: { value: "hiddenField" } });
|
||||
expect(fields).toBeChecked();
|
||||
expect(nonPublic).not.toBeChecked();
|
||||
expect(screen.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible();
|
||||
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false });
|
||||
expect(localStorage.getItem("openidea.structure.options.v1")).toBe(saved);
|
||||
|
||||
fireEvent.keyDown(input, { key: "Escape" });
|
||||
expect(fields).not.toBeChecked();
|
||||
fireEvent.keyDown(input, { key: "Escape" });
|
||||
expect(useFileStructurePopup.getState().open).toBe(false);
|
||||
act(() => useFileStructurePopup.setState({ open: true }));
|
||||
expect(screen.getByLabelText("Filter symbols")).toHaveValue("");
|
||||
expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
|
||||
expect(useStructureOptions.getState().showFields).toBe(false);
|
||||
});
|
||||
|
||||
it("tries unchecked filters one at a time until a match appears, then restores all on Escape", () => {
|
||||
useStructureOptions.setState({ showFields: false, showNonPublic: false });
|
||||
const input = open(filteredItems());
|
||||
const fields = screen.getByRole("checkbox", { name: "Show fields" });
|
||||
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
|
||||
|
||||
fireEvent.change(input, { target: { value: "hiddenMethod" } });
|
||||
expect(fields).toBeChecked();
|
||||
expect(nonPublic).toBeChecked();
|
||||
expect(screen.getByRole("treeitem", { name: "hiddenMethod", selected: true })).toBeVisible();
|
||||
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false });
|
||||
|
||||
fireEvent.keyDown(input, { key: "Escape" });
|
||||
expect(input).toHaveValue("");
|
||||
expect(fields).not.toBeChecked();
|
||||
expect(nonPublic).not.toBeChecked();
|
||||
expect(screen.getByRole("treeitem", { name: "visible" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("does not immediately re-enable a restored filter after backspace", () => {
|
||||
useStructureOptions.setState({ showFields: false, showNonPublic: false });
|
||||
const input = open(filteredItems());
|
||||
const fields = screen.getByRole("checkbox", { name: "Show fields" });
|
||||
fireEvent.change(input, { target: { value: "hiddenField" } });
|
||||
expect(fields).toBeChecked();
|
||||
|
||||
fireEvent.change(input, { target: { value: "hiddenFiel" } });
|
||||
expect(fields).not.toBeChecked();
|
||||
expect(screen.getByText("No symbols")).toBeInTheDocument();
|
||||
expect(useStructureOptions.getState().showFields).toBe(false);
|
||||
});
|
||||
|
||||
it("does not auto-enable filters when Narrow down on typing is off", () => {
|
||||
useStructureOptions.setState({ showFields: false, showNonPublic: false });
|
||||
const input = open(filteredItems());
|
||||
act(() => useStructureOptions.setState({ narrowDown: false }));
|
||||
const fields = screen.getByRole("checkbox", { name: "Show fields" });
|
||||
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
|
||||
|
||||
fireEvent.change(input, { target: { value: "hiddenField" } });
|
||||
expect(fields).not.toBeChecked();
|
||||
expect(nonPublic).not.toBeChecked();
|
||||
expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull();
|
||||
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false });
|
||||
});
|
||||
|
||||
it("restores an auto-enabled filter on backspace without reverting a manual checkbox change", () => {
|
||||
useStructureOptions.setState({ showFields: false, showNonPublic: false });
|
||||
const input = open(filteredItems());
|
||||
const fields = screen.getByRole("checkbox", { name: "Show fields" });
|
||||
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
|
||||
fireEvent.change(input, { target: { value: "hiddenField" } });
|
||||
expect(fields).toBeChecked();
|
||||
|
||||
fireEvent.click(nonPublic);
|
||||
expect(useStructureOptions.getState().showNonPublic).toBe(true);
|
||||
fireEvent.change(input, { target: { value: "hiddenFielX" } });
|
||||
expect(fields).toBeChecked(); // Same-length edits do not trigger IDEA's backspace restore.
|
||||
fireEvent.change(input, { target: { value: "visible" } });
|
||||
expect(fields).not.toBeChecked();
|
||||
expect(nonPublic).toBeChecked();
|
||||
expect(screen.getByRole("treeitem", { name: "visible", selected: true })).toBeVisible();
|
||||
expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull();
|
||||
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: true });
|
||||
|
||||
fireEvent.keyDown(input, { key: "Escape" });
|
||||
fireEvent.keyDown(input, { key: "Escape" });
|
||||
act(() => useFileStructurePopup.setState({ open: true }));
|
||||
expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
|
||||
expect(screen.getByRole("checkbox", { name: "Show non-public" })).toBeChecked();
|
||||
});
|
||||
|
||||
it("temporarily enables Show inherited members and restores it when the query gets shorter", () => {
|
||||
const input = open([item("Container", "class", 0, [item("own", "method", 2)])]);
|
||||
const inherited = [{ item: item("inheritedNeedle", "method", 40), path: "/lib/Base.kt", owner: "Base" }];
|
||||
act(() => useOutline.setState({ inheritedSupported: true, inherited: new Map([["0:4", inherited]]) }));
|
||||
const checkbox = screen.getByRole("checkbox", { name: "Show inherited members" });
|
||||
expect(checkbox).not.toBeChecked();
|
||||
|
||||
fireEvent.change(input, { target: { value: "inheritedNeedle" } });
|
||||
expect(checkbox).toBeChecked();
|
||||
expect(screen.getByRole("treeitem", { name: /^inheritedNeedle/, selected: true })).toBeVisible();
|
||||
expect(useStructureOptions.getState().showInherited).toBe(false);
|
||||
|
||||
fireEvent.change(input, { target: { value: "own" } });
|
||||
expect(checkbox).not.toBeChecked();
|
||||
expect(screen.getByRole("treeitem", { name: "own", selected: true })).toBeVisible();
|
||||
expect(screen.queryByRole("treeitem", { name: /^inheritedNeedle/ })).toBeNull();
|
||||
expect(useStructureOptions.getState().showInherited).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("offers Show inherited members only when the server knows type hierarchies", () => {
|
||||
open();
|
||||
expect(screen.queryByLabelText("Show inherited members")).toBeNull();
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { _setActiveEditor, type TextEditorHandle } from "@/editor/api";
|
||||
import { editorSelectionText } from "../index";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
const view = (doc: string, from: number, to: number) => {
|
||||
const v = new EditorView({
|
||||
state: EditorState.create({ doc, selection: EditorSelection.single(from, to) }),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(v);
|
||||
return v;
|
||||
};
|
||||
afterEach(() => {
|
||||
_setActiveEditor(null);
|
||||
views.splice(0).forEach((v) => v.destroy());
|
||||
});
|
||||
|
||||
it("takes the selection of the focused editor, such as the Find in Files preview, over the active one", () => {
|
||||
const main = view("val first = 1", 4, 9);
|
||||
_setActiveEditor({ view: main } as unknown as TextEditorHandle);
|
||||
expect(editorSelectionText()).toBe("first");
|
||||
const preview = view("fun second() {}", 4, 10);
|
||||
preview.contentDOM.focus();
|
||||
expect(editorSelectionText()).toBe("second");
|
||||
preview.contentDOM.blur();
|
||||
expect(editorSelectionText()).toBe("first");
|
||||
});
|
||||
@@ -34,13 +34,14 @@ import {
|
||||
selectRow,
|
||||
selectedRows,
|
||||
rowSelectionMode,
|
||||
showContextMenu,
|
||||
type RowSelection,
|
||||
type MenuItem,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { useFileDecoration } from "@/workbench/contributions";
|
||||
import { highlightTokens, languageForPath, type CodeToken } from "@/editor/lsp/markdown";
|
||||
import { badgeKind, basename, openInListOrder, openLocation, relDir } from "../common/open";
|
||||
import { badgeKind, basename, openInListOrder, openLocation, projectRoot, relDir } from "../common/open";
|
||||
import { parseLocationQuery } from "../common/query";
|
||||
import { setTextSearchOption, useFindPopup } from "../find/store";
|
||||
import { CodePreview, type PreviewHighlight } from "../find/parts";
|
||||
@@ -441,35 +442,67 @@ function SearchEverywhereDialog() {
|
||||
/** IDEA's ⌥↵ on an action: record a shortcut for it (written to the active keymap). */
|
||||
const assignShortcut = (id: string) => closeThen(() => void executeAction("settings.assignShortcut", id));
|
||||
|
||||
/** Actions of a file, symbol or text result: IDEA's ⌥↵ menu and the row's context menu. */
|
||||
const resultMenu = (row: NavigationRow): MenuItem[] => {
|
||||
const copy = (text: string) => void writeClipboardText(text).catch(() => {});
|
||||
const folder = row.kind === "file" && row.folder;
|
||||
const root = projectRoot();
|
||||
const inProject = !!root && (row.path === root || row.path.startsWith(root.endsWith("/") ? root : `${root}/`));
|
||||
const items: MenuItem[] = [
|
||||
{ label: "Open", run: () => activate(row) },
|
||||
{
|
||||
label: "Open to the Side",
|
||||
shortcut: formatBinding("Shift+Enter"),
|
||||
disabled: !!folder,
|
||||
run: () => activate(row, true),
|
||||
},
|
||||
// IDEA's Select in Project View (Select Opened File): shows a result opened in another
|
||||
// application (.doc in WPS) in the Project view, where its place in the project is visible.
|
||||
...(inProject
|
||||
? [
|
||||
{
|
||||
label: "Select in Project View",
|
||||
shortcut: shortcutLabel("navigate.selectInProjectView") ?? undefined,
|
||||
run: () => closeThen(() => void executeActionFrom("search", "navigate.selectInProjectView", row.path)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
];
|
||||
items.push(
|
||||
{ label: "Copy Path", run: () => copy(nativePath(row.path)) },
|
||||
{ label: "Copy Path from Project Root", run: () => copy(row.rel) },
|
||||
...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []),
|
||||
...(row.kind === "file" || row.kind === "text"
|
||||
? [
|
||||
{
|
||||
label: "Find in Directory…",
|
||||
run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
);
|
||||
return items;
|
||||
};
|
||||
|
||||
const openIntentions = () => {
|
||||
const row = activeRow;
|
||||
if (!row || row.kind === "section" || row.kind === "more" || row.kind === "command") return;
|
||||
if (row.kind === "action") return row.run ? undefined : assignShortcut(row.id);
|
||||
const anchor = listRef.current?.querySelector('[data-lead="true"]') ?? inputRef.current;
|
||||
if (!anchor) return;
|
||||
const copy = (text: string) => void writeClipboardText(text).catch(() => {});
|
||||
const items: MenuItem[] =
|
||||
row.kind === "setting"
|
||||
? [{ label: "Open Settings Page", run: () => activate(row) }]
|
||||
: [
|
||||
{ label: "Open", run: () => activate(row) },
|
||||
{ label: "Open to the Side", shortcut: formatBinding("Shift+Enter"), run: () => activate(row, true) },
|
||||
{ kind: "separator" },
|
||||
{ label: "Copy Path", run: () => copy(nativePath(row.path)) },
|
||||
{ label: "Copy Path from Project Root", run: () => copy(row.rel) },
|
||||
...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []),
|
||||
...(row.kind === "file" || row.kind === "text"
|
||||
? [
|
||||
{
|
||||
label: "Find in Directory…",
|
||||
run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
row.kind === "setting" ? [{ label: "Open Settings Page", run: () => activate(row) }] : resultMenu(row);
|
||||
setMenu({ anchor, items, placement: "right-start" });
|
||||
};
|
||||
|
||||
const onRowContextMenu = (row: SeRow, index: number, e: MouseEvent) => {
|
||||
if (row.kind !== "file" && row.kind !== "symbol" && row.kind !== "text") return;
|
||||
e.preventDefault();
|
||||
select(index, e);
|
||||
showContextMenu(e, resultMenu(row));
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (isImeKey(e.nativeEvent)) return;
|
||||
if (tab === "text" && e.altKey && !e.metaKey && !e.ctrlKey && !e.shiftKey) {
|
||||
@@ -574,6 +607,7 @@ function SearchEverywhereDialog() {
|
||||
if (preview && previewOf(r) && e.type === "click" && e.detail !== 2) return;
|
||||
activate(r, e.shiftKey);
|
||||
}}
|
||||
onContextMenu={onRowContextMenu}
|
||||
focusable={false}
|
||||
rowHeight={rowHeight}
|
||||
sectionHeight={rowHeight}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Recent Files / Recent Locations, Find / Replace in Files + the Find tool
|
||||
* window, the Structure tool window + File Structure popup, and bookmarks.
|
||||
*/
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { lazyComponent, lazyWhen } from "@/ui";
|
||||
import { activeEditor, focusedCellEditor, registerEditorContribution } from "@/editor/api";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
@@ -82,8 +83,13 @@ async function removeMissingBookmarks(removed: readonly string[]) {
|
||||
}
|
||||
|
||||
/** Single-line editor selection, used to prefill search fields. */
|
||||
function editorSelectionText(): string | null {
|
||||
const view = activeEditor()?.view;
|
||||
/**
|
||||
* The single-line selection a search starts from: the focused editor's (a Find in Files preview,
|
||||
* a diff pane), else the active editor's, as IDEA reads it from the editor in the action's context.
|
||||
*/
|
||||
export function editorSelectionText(): string | null {
|
||||
const focused = document.activeElement?.closest(".cm-editor");
|
||||
const view = (focused instanceof HTMLElement ? EditorView.findFromDOM(focused) : null) ?? activeEditor()?.view;
|
||||
if (!view) return null;
|
||||
const { from, to } = view.state.selection.main;
|
||||
if (from === to || to - from > 200) return null;
|
||||
|
||||
@@ -33,7 +33,16 @@ import {
|
||||
widgetLetter,
|
||||
type OutlineNode,
|
||||
} from "./outline";
|
||||
import { useCollapsedStructure, useLiveOutline, useOutline, useOutlineNodes, useStructureOptions } from "./store";
|
||||
import {
|
||||
getOutlineNodes,
|
||||
releaseInheritedMembers,
|
||||
requestInheritedMembers,
|
||||
useCollapsedStructure,
|
||||
useLiveOutline,
|
||||
useOutline,
|
||||
useOutlineNodes,
|
||||
useStructureOptions,
|
||||
} from "./store";
|
||||
import styles from "./StructureView.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -301,8 +310,30 @@ export function FileStructureOverlay() {
|
||||
|
||||
const POPUP_ROW = 22;
|
||||
|
||||
type TemporaryFilter = "showFields" | "showNonPublic" | "showInherited";
|
||||
interface AutoFilter {
|
||||
key: TemporaryFilter;
|
||||
queryLength: number;
|
||||
}
|
||||
interface PopupFilters {
|
||||
showFields: boolean;
|
||||
showNonPublic: boolean;
|
||||
showInherited: boolean;
|
||||
}
|
||||
const TEMPORARY_FILTERS: readonly TemporaryFilter[] = ["showFields", "showNonPublic", "showInherited"];
|
||||
|
||||
function effectivePopupFilters(options: PopupFilters, autoFilters: readonly AutoFilter[]): PopupFilters {
|
||||
const enabled = (key: TemporaryFilter) => autoFilters.some((entry) => entry.key === key);
|
||||
return {
|
||||
showFields: options.showFields || enabled("showFields"),
|
||||
showNonPublic: options.showNonPublic || enabled("showNonPublic"),
|
||||
showInherited: options.showInherited || enabled("showInherited"),
|
||||
};
|
||||
}
|
||||
|
||||
function FileStructureDialog() {
|
||||
useLiveOutline();
|
||||
useEffect(() => () => releaseInheritedMembers(), []);
|
||||
const rowHeight = useRowHeight(POPUP_ROW);
|
||||
const path = useOutline((s) => s.path);
|
||||
const items = useOutline((s) => s.items);
|
||||
@@ -313,8 +344,13 @@ function FileStructureDialog() {
|
||||
const showNonPublic = useStructureOptions((s) => s.showNonPublic);
|
||||
const showInherited = useStructureOptions((s) => s.showInherited);
|
||||
const inheritedSupported = useOutline((s) => s.inheritedSupported);
|
||||
const nodes = useOutlineNodes();
|
||||
const [query, setQuery] = useState("");
|
||||
const [autoFilters, setAutoFilters] = useState<AutoFilter[]>([]);
|
||||
const effectiveOptions = useMemo(
|
||||
() => effectivePopupFilters({ showFields, showNonPublic, showInherited }, autoFilters),
|
||||
[showFields, showNonPublic, showInherited, autoFilters],
|
||||
);
|
||||
const nodes = useOutlineNodes(false, effectiveOptions);
|
||||
const [showOptions, setShowOptions] = useState(false);
|
||||
// IDEA opens the popup fully expanded.
|
||||
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
|
||||
@@ -351,7 +387,10 @@ function FileStructureDialog() {
|
||||
else tree.current?.clearSelection();
|
||||
}, [query, hasQuery, caretKey, filter.preferred, filter.nodes]);
|
||||
|
||||
const close = () => useFileStructurePopup.setState({ open: false });
|
||||
const close = () => {
|
||||
releaseInheritedMembers();
|
||||
useFileStructurePopup.setState({ open: false });
|
||||
};
|
||||
const choose = (node: OutlineNode | undefined) => {
|
||||
if (!node || !path) return;
|
||||
close();
|
||||
@@ -365,6 +404,53 @@ function FileStructureDialog() {
|
||||
return next;
|
||||
});
|
||||
|
||||
const availableFilters: Record<TemporaryFilter, boolean> = {
|
||||
showFields: hasFields(items ?? []),
|
||||
showNonPublic: hasVisibility(items ?? []),
|
||||
showInherited: inheritedSupported,
|
||||
};
|
||||
const changeQuery = (nextQuery: string) => {
|
||||
setQuery(nextQuery);
|
||||
setCollapsed(new Set());
|
||||
let nextAuto = autoFilters;
|
||||
if (nextQuery.length < query.length) {
|
||||
// IDEA restores every auto-click whose query was at least this long, newest first.
|
||||
nextAuto = autoFilters.filter((entry) => entry.queryLength < nextQuery.length);
|
||||
if (nextAuto.length !== autoFilters.length) {
|
||||
if (
|
||||
autoFilters.some((entry) => entry.key === "showInherited") &&
|
||||
!nextAuto.some((entry) => entry.key === "showInherited")
|
||||
)
|
||||
releaseInheritedMembers();
|
||||
setAutoFilters(nextAuto);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!nextQuery.trim() || !narrowDown) {
|
||||
setAutoFilters(nextAuto);
|
||||
return;
|
||||
}
|
||||
const persisted = useStructureOptions.getState();
|
||||
let options = effectivePopupFilters(persisted, nextAuto);
|
||||
const hasMatch = () => filterOutline(getOutlineNodes(false, options), nextQuery, narrowDown).best !== null;
|
||||
if (!hasMatch()) {
|
||||
for (const key of TEMPORARY_FILTERS) {
|
||||
if (options[key] || !availableFilters[key]) continue;
|
||||
nextAuto = [{ key, queryLength: nextQuery.length }, ...nextAuto];
|
||||
options = effectivePopupFilters(persisted, nextAuto);
|
||||
if (key === "showInherited") requestInheritedMembers();
|
||||
if (hasMatch()) break;
|
||||
}
|
||||
}
|
||||
setAutoFilters(nextAuto);
|
||||
};
|
||||
const changeFilter = (key: TemporaryFilter, value: boolean) => {
|
||||
// A manual edit takes ownership of the checkbox; later backspaces must not undo it.
|
||||
setAutoFilters((entries) => entries.filter((entry) => entry.key !== key));
|
||||
if (key === "showInherited") releaseInheritedMembers();
|
||||
useStructureOptions.setState({ [key]: value });
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
const lead = tree.current?.leadKey() ?? null;
|
||||
const node = lead ? byKey.get(lead) : undefined;
|
||||
@@ -377,7 +463,7 @@ function FileStructureDialog() {
|
||||
// The first Esc clears the filter, the next one closes the popup.
|
||||
if (!query) return;
|
||||
e.stopPropagation();
|
||||
setQuery("");
|
||||
changeQuery("");
|
||||
break;
|
||||
case "ArrowDown":
|
||||
case "ArrowUp": {
|
||||
@@ -437,22 +523,22 @@ function FileStructureDialog() {
|
||||
{(hasFields(items ?? []) || !showFields) && (
|
||||
<Checkbox
|
||||
label="Show fields"
|
||||
checked={showFields}
|
||||
onChange={(v) => useStructureOptions.setState({ showFields: v })}
|
||||
checked={effectiveOptions.showFields}
|
||||
onChange={(v) => changeFilter("showFields", v)}
|
||||
/>
|
||||
)}
|
||||
{hasVisibility(items ?? []) && (
|
||||
<Checkbox
|
||||
label="Show non-public"
|
||||
checked={showNonPublic}
|
||||
onChange={(v) => useStructureOptions.setState({ showNonPublic: v })}
|
||||
checked={effectiveOptions.showNonPublic}
|
||||
onChange={(v) => changeFilter("showNonPublic", v)}
|
||||
/>
|
||||
)}
|
||||
{inheritedSupported && (
|
||||
<Checkbox
|
||||
label="Show inherited members"
|
||||
checked={showInherited}
|
||||
onChange={(v) => useStructureOptions.setState({ showInherited: v })}
|
||||
checked={effectiveOptions.showInherited}
|
||||
onChange={(v) => changeFilter("showInherited", v)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -496,10 +582,7 @@ function FileStructureDialog() {
|
||||
aria-label={tx("Filter symbols")}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setCollapsed(new Set());
|
||||
}}
|
||||
onChange={(e) => changeQuery(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
{hasQuery && !narrowDown && !filter.best && filter.nodes.length > 0 && (
|
||||
|
||||
@@ -47,6 +47,8 @@ let consumers = 0;
|
||||
let stop: (() => void) | null = null;
|
||||
let seq = 0;
|
||||
let flutterSeq = 0;
|
||||
let reloadOutline: (() => void) | null = null;
|
||||
let inheritedRequest: { doc: number; path: string } | null = null;
|
||||
|
||||
/** A backend document id for `path` while `fn` runs (open editors are reused). */
|
||||
async function withDoc<T>(path: string, fn: (doc: number) => Promise<T>): Promise<T> {
|
||||
@@ -99,16 +101,31 @@ async function loadInherited(doc: number, path: string, items: readonly OutlineI
|
||||
? true
|
||||
: await probeHierarchy(doc, types);
|
||||
if (my !== seq) return;
|
||||
if (!supported || !useStructureOptions.getState().showInherited) {
|
||||
const requested = inheritedRequest?.doc === doc && inheritedRequest.path === path;
|
||||
if (!supported || !(useStructureOptions.getState().showInherited || requested)) {
|
||||
if (requested) inheritedRequest = null;
|
||||
useOutline.setState({ inheritedSupported: supported, inherited: null });
|
||||
return;
|
||||
}
|
||||
useOutline.setState({ inheritedSupported: true });
|
||||
const deps = inheritedDeps(path, doc, language === "python");
|
||||
const entries = await Promise.all(
|
||||
types.map(async (t) => [typeKey(t), await inheritedMembers(path, t, deps).catch(() => [])] as const),
|
||||
);
|
||||
if (my === seq)
|
||||
useOutline.setState({ inheritedSupported: true, inherited: new Map(entries.filter(([, m]) => m.length)) });
|
||||
if (my === seq) useOutline.setState({ inherited: new Map(entries.filter(([, m]) => m.length)) });
|
||||
}
|
||||
|
||||
/** Loads inherited members for a temporary popup filter without changing persisted options. */
|
||||
export function requestInheritedMembers() {
|
||||
const { doc, path, inherited } = useOutline.getState();
|
||||
if (doc === null || path === null) return;
|
||||
inheritedRequest = { doc, path };
|
||||
if (inherited === null) reloadOutline?.();
|
||||
}
|
||||
|
||||
/** Ends a popup's temporary inherited-member request when its filter is restored or it closes. */
|
||||
export function releaseInheritedMembers() {
|
||||
inheritedRequest = null;
|
||||
}
|
||||
|
||||
async function loadFlutter(doc: number, language: string) {
|
||||
@@ -153,6 +170,7 @@ function start(): () => void {
|
||||
if (!ctx) {
|
||||
seq++;
|
||||
flutterSeq++;
|
||||
inheritedRequest = null;
|
||||
useOutline.setState({
|
||||
path: null,
|
||||
doc: null,
|
||||
@@ -167,6 +185,7 @@ function start(): () => void {
|
||||
}
|
||||
void load(ctx.doc, ctx.path, ctx.language);
|
||||
};
|
||||
reloadOutline = reloadNow;
|
||||
reloadNow();
|
||||
const unsubActive = useEditorRegistry.subscribe((s, prev) => {
|
||||
if (s.active?.ctx.doc !== prev.active?.ctx.doc || s.active?.ctx.path !== prev.active?.ctx.path) reloadNow();
|
||||
@@ -188,6 +207,8 @@ function start(): () => void {
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
flutterSeq++;
|
||||
if (reloadOutline === reloadNow) reloadOutline = null;
|
||||
inheritedRequest = null;
|
||||
unsubFlutter();
|
||||
unsubActive();
|
||||
unsubInherited();
|
||||
@@ -268,6 +289,8 @@ const outlinePreferences = (s: StructureOptions) => ({
|
||||
showOnlyWidgets: s.showOnlyWidgets,
|
||||
});
|
||||
|
||||
type OutlinePreferences = ReturnType<typeof outlinePreferences>;
|
||||
|
||||
function outlineNodes(
|
||||
items: OutlineState["items"],
|
||||
flutter: OutlineState["flutter"],
|
||||
@@ -285,12 +308,20 @@ function outlineNodes(
|
||||
return flutter && options.showOnlyWidgets ? onlyWidgets(nodes) : nodes;
|
||||
}
|
||||
|
||||
export function useOutlineNodes(widgets = false) {
|
||||
/** Snapshot builder for query-event transitions, which cannot call hooks. */
|
||||
export function getOutlineNodes(widgets = false, overrides?: Partial<OutlinePreferences>) {
|
||||
const { items, flutter, inheritedSupported, inherited } = useOutline.getState();
|
||||
const options = { ...outlinePreferences(useStructureOptions.getState()), ...overrides };
|
||||
return outlineNodes(items, widgets ? flutter : null, inheritedSupported ? inherited : null, options);
|
||||
}
|
||||
|
||||
export function useOutlineNodes(widgets = false, overrides?: Partial<OutlinePreferences>) {
|
||||
const items = useOutline((s) => s.items);
|
||||
const flutter = useOutline((s) => (widgets ? s.flutter : null));
|
||||
const inherited = useOutline((s) => (s.inheritedSupported ? s.inherited : null));
|
||||
const options = useStructureOptions(useShallow(outlinePreferences));
|
||||
return useMemo(() => outlineNodes(items, flutter, inherited, options), [items, flutter, inherited, options]);
|
||||
const effective = useMemo(() => (overrides ? { ...options, ...overrides } : options), [options, overrides]);
|
||||
return useMemo(() => outlineNodes(items, flutter, inherited, effective), [items, flutter, inherited, effective]);
|
||||
}
|
||||
|
||||
function collapseStructure() {
|
||||
|
||||
@@ -308,6 +308,13 @@ describe("Git Log commit actions", () => {
|
||||
"Fix_crash_on_start.patch",
|
||||
);
|
||||
expect(suggestedPatchName({ kind: "commits", commits: [commit("a"), commit("b")] }, "x")).toBe("2_commits.patch");
|
||||
expect(
|
||||
suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("Fix: historical file!")] }, "x"),
|
||||
).toBe("Fix_historical_file.patch");
|
||||
expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("a"), commit("b")] }, "x")).toBe(
|
||||
"2_commits.patch",
|
||||
);
|
||||
expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [] }, "Changes")).toBe("0_files.patch");
|
||||
expect(suggestedPatchName({ kind: "changes", files: [] }, "///")).toBe("changes.patch");
|
||||
});
|
||||
});
|
||||
@@ -42,10 +42,12 @@ import { graphOptionsMenu } from "../log/FilterBar";
|
||||
import {
|
||||
EMPTY_TREE,
|
||||
assignLineStats,
|
||||
canCreatePatchFromLogChanges,
|
||||
filesUnder,
|
||||
filterPatch,
|
||||
flatFileNodes,
|
||||
lineStatRanges,
|
||||
logPatchRanges,
|
||||
toLogChanges,
|
||||
useLogChanges,
|
||||
} from "../logChanges";
|
||||
@@ -122,6 +124,78 @@ describe("changed files model", () => {
|
||||
expect(rootFile!.statsFrom).toBe(EMPTY_TREE);
|
||||
});
|
||||
|
||||
it("builds path-filtered historical patch ranges, including empty trees and both rename paths", () => {
|
||||
const previous = useVcs.getState();
|
||||
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
|
||||
try {
|
||||
const older: Commit = { ...commit, id: "a".repeat(40), parents: ["9".repeat(40)], timeMs: 1 };
|
||||
const newer: Commit = { ...commit, id: "b".repeat(40), parents: [older.id], timeMs: 2 };
|
||||
const changes = [
|
||||
...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"),
|
||||
...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"),
|
||||
...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"),
|
||||
...toLogChanges([{ path: "deleted.ts", kind: "deleted", oldPath: null }], newer, "/repo"),
|
||||
];
|
||||
const paths = ["edited.ts", "new.ts", "old.ts"];
|
||||
expect(canCreatePatchFromLogChanges(changes)).toBe(true);
|
||||
expect(logPatchRanges(changes)).toEqual([
|
||||
{ repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] },
|
||||
{ repo: "/repo", before: older.id, after: newer.id, paths },
|
||||
{ repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["deleted.ts"] },
|
||||
]);
|
||||
expect(logPatchRanges(changes, true)).toEqual([
|
||||
{ repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["added.ts"] },
|
||||
{ repo: "/repo", before: newer.id, after: older.id, paths },
|
||||
{ repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["deleted.ts"] },
|
||||
]);
|
||||
|
||||
const other = { ...changes[1]!, repo: "/other" };
|
||||
useVcs.setState({ roots: ["/repo", "/other"] });
|
||||
expect(canCreatePatchFromLogChanges([changes[0]!, other])).toBe(false);
|
||||
expect(logPatchRanges([changes[0]!, other])).toEqual([]);
|
||||
const ambiguous = { ...changes[0]!, repo: null };
|
||||
expect(canCreatePatchFromLogChanges([ambiguous])).toBe(false);
|
||||
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, readOnly: true }])).toBe(true);
|
||||
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, repo: "/external", readOnly: true }])).toBe(false);
|
||||
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, oldPath: 42 as unknown as string }])).toBe(false);
|
||||
expect(canCreatePatchFromLogChanges([{ ...changes[0]!, before: newer.id, after: newer.id }])).toBe(false);
|
||||
expect(canCreatePatchFromLogChanges([])).toBe(false);
|
||||
} finally {
|
||||
useVcs.setState(previous);
|
||||
}
|
||||
});
|
||||
|
||||
it("enables changed-file patch actions and menu rows only for an applicable selection", () => {
|
||||
const previous = useVcs.getState();
|
||||
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo", "/other"] });
|
||||
const files = toLogChanges(
|
||||
[
|
||||
{ path: "a.ts", kind: "modified", oldPath: null },
|
||||
{ path: "b.ts", kind: "modified", oldPath: null },
|
||||
],
|
||||
commit,
|
||||
"/repo",
|
||||
);
|
||||
const dispose = registerLogPaneActions();
|
||||
try {
|
||||
for (const id of ["vcs.log.changes.createPatch", "vcs.log.changes.copyPatch"]) {
|
||||
const action = getAction(id)!;
|
||||
expect(action.enabled!({ ctx: {}, arg: [] })).toBe(false);
|
||||
expect(action.enabled!({ ctx: {}, arg: files })).toBe(true);
|
||||
expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/other" }] })).toBe(true);
|
||||
expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/external" }] })).toBe(false);
|
||||
const item = (changes: ReturnType<typeof toLogChanges>) =>
|
||||
changesMenu(changes).find((entry) => "action" in entry && entry.action === id);
|
||||
expect(item(files)).toMatchObject({ arg: files, disabled: false });
|
||||
expect(item([])).toMatchObject({ disabled: true });
|
||||
expect(item([{ ...files[0]!, repo: "/external" }])).toMatchObject({ disabled: true });
|
||||
}
|
||||
} finally {
|
||||
dispose();
|
||||
useVcs.setState(previous);
|
||||
}
|
||||
});
|
||||
|
||||
it("asks for one numstat per revision pair and matches a rename by either name", () => {
|
||||
const files = toLogChanges(
|
||||
[
|
||||
@@ -265,6 +339,8 @@ describe("rename label", () => {
|
||||
|
||||
describe("changed files pane", () => {
|
||||
it("shows the files flat or by directory and shares the selection with its actions", async () => {
|
||||
const previous = useVcs.getState();
|
||||
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
|
||||
vcsCommitFiles.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
@@ -275,10 +351,16 @@ describe("changed files pane", () => {
|
||||
useGitLog.setState({ commits: [commit], selected: commit.id, selection: [commit.id] });
|
||||
const { unmount } = render(<CommitDetails commits={[commit]} />);
|
||||
expect(await screen.findByText("src")).toBeInTheDocument();
|
||||
const createPatch = screen.getByRole("button", { name: "Create Patch…" });
|
||||
const copyPatch = screen.getByRole("button", { name: "Copy as Patch to Clipboard" });
|
||||
expect(createPatch).toBeDisabled();
|
||||
expect(copyPatch).toBeDisabled();
|
||||
fireEvent.mouseDown(screen.getByText("a.ts"));
|
||||
expect(useLogChanges.getState().selected.map((c) => c.path)).toEqual(["src/a.ts"]);
|
||||
expect(useLogChanges.getState().commits).toEqual([commit]);
|
||||
expect(screen.getByRole("button", { name: "Show Diff" })).toBeEnabled();
|
||||
expect(createPatch).toBeEnabled();
|
||||
expect(copyPatch).toBeEnabled();
|
||||
|
||||
useLogOptions.setState({ groupByDirectory: false });
|
||||
expect(await screen.findByText("b.ts")).toBeInTheDocument();
|
||||
@@ -286,6 +368,7 @@ describe("changed files pane", () => {
|
||||
expect(screen.getAllByText("src")).toHaveLength(2);
|
||||
unmount();
|
||||
expect(useLogChanges.getState().selected).toEqual([]);
|
||||
useVcs.setState(previous);
|
||||
});
|
||||
|
||||
it("shows added and deleted lines when the log option is on", async () => {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { Commit, PatchSource } from "@/bindings";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createPatch: vi.fn(),
|
||||
writeClipboardText: vi.fn(),
|
||||
openDialog: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsCreatePatch: (repo: string | null, source: PatchSource, base: string | null) =>
|
||||
mocks.createPatch(repo, source, base),
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/platform/clipboard", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/clipboard")>()),
|
||||
writeClipboardText: mocks.writeClipboardText,
|
||||
}));
|
||||
vi.mock("../dialogs", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../dialogs")>()),
|
||||
openDialog: mocks.openDialog,
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify: mocks.notify }),
|
||||
}));
|
||||
|
||||
import { EMPTY_TREE, toLogChanges } from "../logChanges";
|
||||
import { copyLogChangesAsPatch } from "../patches";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const commit = (id: string, parents: string[], timeMs: number): Commit => ({
|
||||
id: id.repeat(40),
|
||||
shortId: id.repeat(8),
|
||||
parents,
|
||||
author: "A",
|
||||
email: "[email protected]",
|
||||
timeMs,
|
||||
summary: `Commit ${id}`,
|
||||
message: `Commit ${id}`,
|
||||
refs: [],
|
||||
});
|
||||
|
||||
const originalVcs = useVcs.getState();
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.createPatch.mockReset();
|
||||
mocks.writeClipboardText.mockReset();
|
||||
mocks.openDialog.mockReset();
|
||||
mocks.notify.mockReset();
|
||||
mocks.writeClipboardText.mockResolvedValue(undefined);
|
||||
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] });
|
||||
});
|
||||
|
||||
afterEach(() => useVcs.setState(originalVcs));
|
||||
|
||||
describe("Git Log changed-file patches", () => {
|
||||
it("copies exactly the selected revision/path ranges, with both names of a rename", async () => {
|
||||
const older = commit("a", ["9".repeat(40)], 1);
|
||||
const newer = commit("b", [older.id], 2);
|
||||
const changes = [
|
||||
...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"),
|
||||
...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"),
|
||||
...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"),
|
||||
];
|
||||
mocks.createPatch.mockImplementation(async (_repo: string, source: PatchSource) => ({
|
||||
status: "ok" as const,
|
||||
data: source.from === "revisions" ? `patch ${source.before} ${source.after} ${source.paths.join(",")}\n` : "",
|
||||
}));
|
||||
await copyLogChangesAsPatch(changes);
|
||||
|
||||
expect(mocks.createPatch.mock.calls).toEqual([
|
||||
["/repo", { from: "revisions", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] }, null],
|
||||
[
|
||||
"/repo",
|
||||
{
|
||||
from: "revisions",
|
||||
before: older.id,
|
||||
after: newer.id,
|
||||
paths: ["edited.ts", "new.ts", "old.ts"],
|
||||
},
|
||||
null,
|
||||
],
|
||||
]);
|
||||
expect(mocks.writeClipboardText).toHaveBeenCalledExactlyOnceWith(
|
||||
`patch ${EMPTY_TREE} ${older.id} added.ts\npatch ${older.id} ${newer.id} edited.ts,new.ts,old.ts\n`,
|
||||
);
|
||||
expect(mocks.openDialog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not touch the clipboard for empty, mixed-repository or external read-only selections", async () => {
|
||||
const c = commit("c", ["9".repeat(40)], 1);
|
||||
const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo");
|
||||
await copyLogChangesAsPatch([]);
|
||||
await copyLogChangesAsPatch([files[0]!, { ...files[0]!, repo: "/other" }]);
|
||||
await copyLogChangesAsPatch([{ ...files[0]!, repo: "/external", readOnly: true }]);
|
||||
expect(mocks.createPatch).not.toHaveBeenCalled();
|
||||
expect(mocks.writeClipboardText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves the clipboard untouched when Git returns an empty patch", async () => {
|
||||
const c = commit("c", ["9".repeat(40)], 1);
|
||||
const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo");
|
||||
mocks.createPatch.mockResolvedValue({ status: "ok", data: "" });
|
||||
await copyLogChangesAsPatch(files);
|
||||
expect(mocks.writeClipboardText).not.toHaveBeenCalled();
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ group: "vcs", level: "info", title: "No changes to create a patch from" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,7 @@ import { buildFileTree, dirKeys, type FileTreeNode } from "../fileTree";
|
||||
import styles from "../GitLog.module.css";
|
||||
import {
|
||||
canApplySelectedChanges,
|
||||
canCreatePatchFromLogChanges,
|
||||
canOpenRepositoryVersion,
|
||||
absolutePath,
|
||||
changesArg,
|
||||
@@ -412,6 +413,22 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
|
||||
actionArg={chosenChanges}
|
||||
disabled={!chosenChanges.length}
|
||||
/>
|
||||
<IconButton
|
||||
icon="patch"
|
||||
size="small"
|
||||
title="Create Patch…"
|
||||
action="vcs.log.changes.createPatch"
|
||||
actionArg={chosenChanges}
|
||||
disabled={!canCreatePatchFromLogChanges(chosenChanges)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="copy"
|
||||
size="small"
|
||||
title="Copy as Patch to Clipboard"
|
||||
action="vcs.log.changes.copyPatch"
|
||||
actionArg={chosenChanges}
|
||||
disabled={!canCreatePatchFromLogChanges(chosenChanges)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="revert"
|
||||
size="small"
|
||||
@@ -590,6 +607,19 @@ export function changesMenu(changes: LogChange[], source?: { commit: Commit; tot
|
||||
disabled: !canOpenRepositoryVersion(changes),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.createPatch",
|
||||
arg: changes,
|
||||
disabled: !canCreatePatchFromLogChanges(changes),
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.copyPatch",
|
||||
arg: changes,
|
||||
disabled: !canCreatePatchFromLogChanges(changes),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
kind: "action",
|
||||
action: "vcs.log.changes.apply",
|
||||
|
||||
@@ -23,7 +23,7 @@ import type { FileTreeNode } from "./fileTree";
|
||||
import { baseName } from "./model";
|
||||
import { readWorkingText, runOp, saveAll, writeFileText } from "./ops";
|
||||
import { reportApply } from "./shelf";
|
||||
import { currentRepoRoot } from "./store";
|
||||
import { currentRepoRoot, useVcs } from "./store";
|
||||
import { commitRepo } from "./multiRoot";
|
||||
import { repositoryPath } from "./repositoryPaths";
|
||||
import { confirmDialog } from "./dialogs";
|
||||
@@ -156,6 +156,66 @@ export async function withLineStats(files: LogChange[]): Promise<LogChange[]> {
|
||||
return assignLineStats(files, loaded);
|
||||
}
|
||||
|
||||
/** One repository's selected historical files between the same two revisions. */
|
||||
export interface LogPatchRange {
|
||||
repo: string;
|
||||
before: string;
|
||||
after: string;
|
||||
paths: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The repository a historical patch can safely use. A missing row repository is
|
||||
* unambiguous only when the project has one root; otherwise callers must retain it.
|
||||
*/
|
||||
export function logPatchRepository(changes: readonly LogChange[]): string | null {
|
||||
if (!changes.length) return null;
|
||||
const state = useVcs.getState();
|
||||
const fallback = state.roots.length === 1 ? state.roots[0]! : state.roots.length ? null : (state.repo ?? state.root);
|
||||
const repo = changes[0]!.repo ?? fallback;
|
||||
if (!repo || changes.some((change) => (change.repo ?? fallback) !== repo)) return null;
|
||||
return state.roots.length && !state.roots.includes(repo) ? null : repo;
|
||||
}
|
||||
|
||||
/** Create Patch is an export: empty, malformed, read-only external and mixed-repository selections cannot use it. */
|
||||
export function canCreatePatchFromLogChanges(changes: readonly LogChange[]): boolean {
|
||||
if (!changes.length || !logPatchRepository(changes)) return false;
|
||||
return (
|
||||
changes.every(
|
||||
(change) =>
|
||||
typeof change.path === "string" &&
|
||||
change.path.length > 0 &&
|
||||
(change.oldPath === null || (typeof change.oldPath === "string" && change.oldPath.length > 0)) &&
|
||||
(change.before === null || (typeof change.before === "string" && change.before.length > 0)) &&
|
||||
(change.after === null || (typeof change.after === "string" && change.after.length > 0)) &&
|
||||
(change.before !== null || change.after !== null),
|
||||
) && changes.some((change) => (change.before ?? EMPTY_TREE) !== (change.after ?? EMPTY_TREE))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Path-filtered revision diffs for exactly the selected rows. Added and deleted
|
||||
* files use Git's empty tree on their missing side; renames include both names.
|
||||
* Reversing swaps each range's endpoints, including the empty tree.
|
||||
*/
|
||||
export function logPatchRanges(changes: readonly LogChange[], reverse = false): LogPatchRange[] {
|
||||
if (!canCreatePatchFromLogChanges(changes)) return [];
|
||||
const repo = logPatchRepository(changes)!;
|
||||
const ranges = new Map<string, LogPatchRange>();
|
||||
for (const change of changes) {
|
||||
const before = (reverse ? change.after : change.before) ?? EMPTY_TREE;
|
||||
const after = (reverse ? change.before : change.after) ?? EMPTY_TREE;
|
||||
if (before === after) continue;
|
||||
const key = `${before}\0${after}`;
|
||||
let range = ranges.get(key);
|
||||
if (!range) ranges.set(key, (range = { repo, before, after, paths: [] }));
|
||||
for (const path of change.oldPath ? [change.path, change.oldPath] : [change.path]) {
|
||||
if (path && !range.paths.includes(path)) range.paths.push(path);
|
||||
}
|
||||
}
|
||||
return [...ranges.values()];
|
||||
}
|
||||
|
||||
/** Files without directory grouping: by name, each node's path shown next to it. */
|
||||
export function flatFileNodes<F>(files: readonly F[], relPath: (f: F) => string): FileTreeNode<F>[] {
|
||||
return files
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { isFavoriteBranch } from "./branches";
|
||||
import {
|
||||
applySelectedChanges,
|
||||
canCreatePatchFromLogChanges,
|
||||
canOpenRepositoryVersion,
|
||||
changesArg,
|
||||
compareChangesWithLocal,
|
||||
@@ -32,6 +33,7 @@ import { logOptions } from "./logOptions";
|
||||
import { goToRef, selectedCommits, toggleCherryHighlight, updateLogOptions, useGitLog } from "./logStore";
|
||||
import { commitKey, commitRepo } from "./multiRoot";
|
||||
import { dropSelectedChanges, extractSelectedChanges } from "./rebase";
|
||||
import { copyLogChangesAsPatch, showCreatePatchForLogChanges } from "./patches";
|
||||
import { openRevisionFile } from "./revisionInput";
|
||||
import { currentRepoRoot, focusRepo } from "./store";
|
||||
import { showCompareBranches, type BranchComparisonTarget, type BranchComparisonData } from "./CompareBranches";
|
||||
@@ -301,6 +303,28 @@ export function registerLogPaneActions(): () => void {
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vcs.log.changes.createPatch",
|
||||
title: "Create Patch…",
|
||||
category: "Git Log",
|
||||
icon: "patch",
|
||||
when: LOG,
|
||||
hidden: true,
|
||||
keyWhen: "vcsLogChangesFocus",
|
||||
enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)),
|
||||
run: ({ arg }) => showCreatePatchForLogChanges(changesArg(arg), useLogChanges.getState().commits),
|
||||
},
|
||||
{
|
||||
id: "vcs.log.changes.copyPatch",
|
||||
title: "Copy as Patch to Clipboard",
|
||||
category: "Git Log",
|
||||
icon: "copy",
|
||||
when: LOG,
|
||||
hidden: true,
|
||||
keyWhen: "vcsLogChangesFocus",
|
||||
enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)),
|
||||
run: ({ arg }) => copyLogChangesAsPatch(changesArg(arg)),
|
||||
},
|
||||
{
|
||||
id: "vcs.log.changes.getFromRevision",
|
||||
title: "Get from Revision",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard";
|
||||
import { commitRepo } from "./multiRoot";
|
||||
import { canCreatePatchFromLogChanges, logPatchRanges, logPatchRepository, type LogChange } from "./logChanges";
|
||||
/** Create Patch… (from local changes or commits) and Apply Patch… (file or clipboard, with a preview). */
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
||||
import type {
|
||||
@@ -68,15 +69,20 @@ import { useDiffSource } from "./diffSource";
|
||||
export type PatchOrigin =
|
||||
| { kind: "changes"; files: FileStatus[]; staging?: readonly StagingPatchEntry[] }
|
||||
| { kind: "commits"; commits: Commit[] }
|
||||
| { kind: "logChanges"; changes: LogChange[]; commits: Commit[] }
|
||||
| { kind: "shelf"; entry: ShelvedChangeList; path?: string };
|
||||
|
||||
/** File name IDEA suggests: the change list or commit subject, sanitised. */
|
||||
export function suggestedPatchName(origin: PatchOrigin, listName: string): string {
|
||||
const base =
|
||||
origin.kind === "commits"
|
||||
origin.kind === "commits" || origin.kind === "logChanges"
|
||||
? origin.commits.length === 1
|
||||
? origin.commits[0]!.summary
|
||||
: `${origin.commits.length} commits`
|
||||
: origin.commits.length > 1
|
||||
? `${origin.commits.length} commits`
|
||||
: origin.kind === "logChanges"
|
||||
? `${origin.changes.length} files`
|
||||
: "0 commits"
|
||||
: origin.kind === "shelf"
|
||||
? origin.entry.name
|
||||
: listName;
|
||||
@@ -160,6 +166,38 @@ export function showCreatePatchForCommits(commits: Commit[]) {
|
||||
openDialog((close) => <CreatePatchDialog origin={{ kind: "commits", commits }} onClose={close} />);
|
||||
}
|
||||
|
||||
async function createLogChangesPatch(changes: readonly LogChange[], reverse: boolean, base: string | null) {
|
||||
const patches = await Promise.all(
|
||||
logPatchRanges(changes, reverse).map(({ repo, before, after, paths }) =>
|
||||
call(commands.vcsCreatePatch(repo, { from: "revisions", before, after, paths }, base)),
|
||||
),
|
||||
);
|
||||
return patches.join("");
|
||||
}
|
||||
|
||||
export function showCreatePatchForLogChanges(changes: LogChange[], commits: Commit[]) {
|
||||
if (!canCreatePatchFromLogChanges(changes)) return;
|
||||
openDialog((close) => <CreatePatchDialog origin={{ kind: "logChanges", changes, commits }} onClose={close} />);
|
||||
}
|
||||
|
||||
/** Copy the selected historical files as a patch directly, without the Create Patch dialog. */
|
||||
export async function copyLogChangesAsPatch(changes: readonly LogChange[]) {
|
||||
if (!canCreatePatchFromLogChanges(changes)) return;
|
||||
await runOp(
|
||||
tx("Create patch"),
|
||||
async () => {
|
||||
const patch = await createLogChangesPatch(changes, false, null);
|
||||
if (!patch) {
|
||||
noPatchChanges();
|
||||
return false;
|
||||
}
|
||||
await writeClipboardText(patch);
|
||||
return true;
|
||||
},
|
||||
{ success: (copied) => (copied ? "Patch copied to the clipboard" : ""), refresh: false },
|
||||
);
|
||||
}
|
||||
|
||||
export function showCreatePatchForShelf(entry: ShelvedChangeList, path?: string) {
|
||||
openDialog((close) => <CreatePatchDialog origin={{ kind: "shelf", entry, path }} onClose={close} />);
|
||||
}
|
||||
@@ -220,7 +258,11 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
|
||||
const root = useVcs((s) => s.root) ?? "";
|
||||
const roots = useVcs((s) => s.roots);
|
||||
const [repo] = useState(() =>
|
||||
origin.kind === "commits" ? (commitRepo(origin.commits[0]!) ?? currentRepoRoot()) : currentRepoRoot(),
|
||||
origin.kind === "commits"
|
||||
? (commitRepo(origin.commits[0]!) ?? currentRepoRoot())
|
||||
: origin.kind === "logChanges"
|
||||
? (logPatchRepository(origin.changes) ?? currentRepoRoot())
|
||||
: currentRepoRoot(),
|
||||
);
|
||||
const listName = useChangelists((s) => activeList(s.state).name);
|
||||
const [selected, setSelected] = useState(
|
||||
@@ -254,7 +296,7 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
|
||||
setPending(true);
|
||||
setError("");
|
||||
const source: PatchSource | null =
|
||||
origin.kind === "shelf"
|
||||
origin.kind === "shelf" || origin.kind === "logChanges"
|
||||
? null
|
||||
: origin.kind === "changes"
|
||||
? localPatchSource(origin, selected, reverse)
|
||||
@@ -273,7 +315,9 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
|
||||
? await call(
|
||||
commands.vcsShelfPatch(origin.entry.id, origin.path ?? null, baseInput === null ? null : directory),
|
||||
)
|
||||
: await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory));
|
||||
: origin.kind === "logChanges"
|
||||
? await createLogChangesPatch(origin.changes, reverse, directory)
|
||||
: await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory));
|
||||
if (!patch) {
|
||||
noPatchChanges();
|
||||
return false;
|
||||
|
||||
@@ -70,6 +70,13 @@ function HeaderButtons() {
|
||||
const secondary: MenuItem[] = [
|
||||
{ kind: "action", action: "file.newUntitled", label: "New File", disabled: opening },
|
||||
{ kind: "action", action: "file.openFile", label: "Open File", disabled: opening },
|
||||
{ kind: "separator" },
|
||||
{
|
||||
kind: "action",
|
||||
action: "file.importJetBrainsRecentProjects",
|
||||
label: "Import Recent Projects from JetBrains IDE…",
|
||||
disabled: opening,
|
||||
},
|
||||
];
|
||||
return (
|
||||
<div className={styles.headerButtons} role="group" aria-label={tx("Project actions")}>
|
||||
|
||||
@@ -101,6 +101,29 @@ describe("resolveMonoFont", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a chosen family that isn't installed", () => {
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("puts the bundled face before the fallback, so Latin text doesn't take the fallback's proportional letters", async () => {
|
||||
const fonts = await import("./fonts");
|
||||
// Before the native catalog loads nothing is known to be missing.
|
||||
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(`"Fira Code", "PingFang SC", ${BASE}`);
|
||||
fonts.noteInstalledFonts(["PingFang SC", "Menlo"]);
|
||||
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(
|
||||
`"Fira Code", "JetBrains Mono", "JetBrains Mono Variable", "PingFang SC", ${BASE}`,
|
||||
);
|
||||
// Installed, bundled and generic families keep the fallback right after them; so does no fallback.
|
||||
expect(fonts.monoFontFamily("menlo", "PingFang SC", BASE)).toBe(`"menlo", "PingFang SC", ${BASE}`);
|
||||
expect(fonts.monoFontFamily("Inter", "PingFang SC", BASE)).toBe(
|
||||
`"Inter", "Inter Variable", "PingFang SC", ${BASE}`,
|
||||
);
|
||||
expect(fonts.monoFontFamily("monospace", "PingFang SC", BASE)).toBe(`"monospace", "PingFang SC", ${BASE}`);
|
||||
expect(fonts.monoFontFamily("Fira Code", "", BASE)).toBe(`"Fira Code", ${BASE}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("discovered Nerd Font fallbacks (#3723)", () => {
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
|
||||
@@ -98,12 +98,15 @@ async function loadUserFont(name: string, alias: string): Promise<void> {
|
||||
* face is named alone unless the native catalog lists an installed JetBrains Mono.
|
||||
*/
|
||||
let monoInstalled: boolean | null = null;
|
||||
/** Lower-cased installed family names from the native catalog, once it has loaded. */
|
||||
let installedFamilies: ReadonlySet<string> | null = null;
|
||||
const bundledMonoOnly = () => guessOs() === "linux" && monoInstalled !== true;
|
||||
const BUNDLED_MONO_STACK = '"JetBrains Mono Variable", ui-monospace, monospace';
|
||||
|
||||
/** Records whether the system has JetBrains Mono installed (`installed`: the native catalog, not the bundled list). */
|
||||
export function noteInstalledFonts(installed: readonly string[], root?: HTMLElement): void {
|
||||
monoInstalled = installed.some((name) => name.trim().toLowerCase() === BUNDLED_MONO_FAMILY.toLowerCase());
|
||||
installedFamilies = new Set(installed.map((name) => name.trim().toLowerCase()));
|
||||
monoInstalled = installedFamilies.has(BUNDLED_MONO_FAMILY.toLowerCase());
|
||||
installMonoStack(root);
|
||||
}
|
||||
|
||||
@@ -256,7 +259,22 @@ export function monoFontFamily(family: string | undefined, fallback = "", base =
|
||||
const name = familyName(family ?? "");
|
||||
const fb = familyName(fallback);
|
||||
const head = familyFaces(name || BUNDLED_MONO_FAMILY);
|
||||
return [...head, ...(fb ? familyFaces(fb) : []), base].join(", ");
|
||||
// A chosen family that isn't installed leaves every glyph to the fallback, often a CJK face
|
||||
// whose Latin letters are proportional: a grid measures its cells by the widest of them and
|
||||
// the text comes out spread apart. The bundled face stands in for the missing one, and the
|
||||
// fallback still covers what that lacks.
|
||||
const standIn = fb && name && familyMissing(name) ? familyFaces(BUNDLED_MONO_FAMILY) : [];
|
||||
return [...head, ...standIn, ...(fb ? familyFaces(fb) : []), base].join(", ");
|
||||
}
|
||||
|
||||
const GENERIC_FAMILIES =
|
||||
/^(?:monospace|ui-monospace|sans-serif|serif|system-ui|ui-sans-serif|ui-serif|cursive|fantasy)$/i;
|
||||
|
||||
/** Whether the native catalog has loaded and doesn't list `name` (bundled and generic families always count as present). */
|
||||
function familyMissing(name: string): boolean {
|
||||
if (!installedFamilies) return false;
|
||||
const key = name.toLowerCase();
|
||||
return !installedFamilies.has(key) && !BUNDLED_FACES.has(key) && !GENERIC_FAMILIES.test(name);
|
||||
}
|
||||
|
||||
/** Tools › Terminal › Font, shared by the terminal and the Run console. */
|
||||
|
||||
@@ -6,6 +6,8 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
|
||||
GotoDeclaration: "navigate.declaration",
|
||||
GotoImplementation: "navigate.implementation",
|
||||
GotoTypeDeclaration: "navigate.typeDeclaration",
|
||||
SelectInProjectView: "navigate.selectInProjectView",
|
||||
SelectOpenedFileInProjectView: "project.selectOpenedFile",
|
||||
GotoSuperMethod: "navigate.superMethod",
|
||||
GotoTest: "navigate.gotoTest",
|
||||
GotoRelated: "navigate.relatedSymbol",
|
||||
|
||||
@@ -49,6 +49,22 @@ describe("IntelliJ IDEA keymap import", () => {
|
||||
expect(k.overrides).toEqual({});
|
||||
});
|
||||
|
||||
it("bases a keymap derived from Emacs on $default, not macOS", () => {
|
||||
for (const parent of ["Emacs", "Emacs copy"]) {
|
||||
const k = parseIdeaKeymap(`<keymap name="E" parent="${parent}"></keymap>`);
|
||||
expect(k.parent).toBe("intellij-windows");
|
||||
}
|
||||
for (const [parent, preset] of [
|
||||
["Mac OS X", "intellij-macos"],
|
||||
["macOS System Shortcuts", "intellij-macos"],
|
||||
["Eclipse (Mac OS X)", "eclipse-macos"],
|
||||
["VSCode (macOS)", "vscode-macos"],
|
||||
["Default for KDE", "intellij-windows"],
|
||||
]) {
|
||||
expect(parseIdeaKeymap(`<keymap name="K" parent="${parent}"></keymap>`).parent).toBe(preset);
|
||||
}
|
||||
});
|
||||
|
||||
it("maps Duplicate Entire Lines, which has no shortcut in the presets", () => {
|
||||
const k = parseIdeaKeymap(
|
||||
`<keymap name="M" parent="Mac OS X 10.5+"><action id="EditorDuplicateLines"><keyboard-shortcut first-keystroke="shift meta D"/></action></keymap>`,
|
||||
|
||||
@@ -31,11 +31,13 @@ export interface ImportedIdeaKeymap {
|
||||
/** IDEA's bundled keymap names (`<keymap name=…>`) → our presets. */
|
||||
function presetOf(parent: string | null): string {
|
||||
const p = parent ?? "";
|
||||
const mac = /mac/i.test(p);
|
||||
// "Mac OS X 10.5+", "Eclipse (Mac OS X)", "VSCode (macOS)"; not the "mac" inside "Emacs".
|
||||
const mac = /\bmac(?: ?os)?\b/i.test(p);
|
||||
if (/^eclipse/i.test(p)) return mac ? "eclipse-macos" : "eclipse-windows";
|
||||
if (/^vs ?code/i.test(p)) return mac ? "vscode-macos" : "vscode-windows";
|
||||
if (mac) return "intellij-macos";
|
||||
if (p === "$default" || /^default for/i.test(p)) return "intellij-windows";
|
||||
// IDEA's Emacs keymap (and copies of it) inherits $default.
|
||||
if (p === "$default" || /^default for/i.test(p) || /^emacs\b/i.test(p)) return "intellij-windows";
|
||||
return defaultPreset();
|
||||
}
|
||||
|
||||
|
||||
@@ -122,6 +122,8 @@ describe("IDEA keymap parity", () => {
|
||||
// Vcs.Log.GoToRef: Find in the Git Log table.
|
||||
["vcs.log.goToRef", ["Meta+F"], ["Ctrl+F"]],
|
||||
["vcs.log.maximizeCommitMessage", [], []],
|
||||
["vcs.log.changes.createPatch", [], []],
|
||||
["vcs.log.changes.copyPatch", [], []],
|
||||
["vcs.log.refresh", ["Meta+R"], ["Ctrl+F5"]],
|
||||
["vcs.log.focusTextFilter", ["Ctrl+L"], ["Ctrl+L"]],
|
||||
// Back / Forward also carry the mouse side buttons (`<mouse-shortcut keystroke="button4"/>`).
|
||||
|
||||
@@ -389,6 +389,8 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"vcs.addToVcs": ["Meta+Alt+A"],
|
||||
"vcs.showDiff": ["Meta+D"],
|
||||
"vcs.log.changes.showDiff": ["Meta+D"],
|
||||
"vcs.log.changes.createPatch": [],
|
||||
"vcs.log.changes.copyPatch": [],
|
||||
"vcs.showDiffInNewWindow": [],
|
||||
"vcs.nextChange": ["Ctrl+Alt+Shift+Down"],
|
||||
"vcs.prevChange": ["Ctrl+Alt+Shift+Up"],
|
||||
@@ -495,6 +497,7 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"agents.sendToAgent": [],
|
||||
// Agents task list (when it has focus)
|
||||
"agents.archiveTasks": ["Meta+Shift+E"],
|
||||
"agents.deleteTasks": ["Delete", "Meta+Backspace"],
|
||||
// Database tool window (when the tree has focus; `db.openConsole` anywhere).
|
||||
"db.openConsole": ["Meta+Shift+L"],
|
||||
"db.newDataSource": [],
|
||||
@@ -531,6 +534,7 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"db.showDiagram": ["Meta+Alt+Shift+U"],
|
||||
"db.showDiagramPopup": ["Meta+Alt+U"],
|
||||
"db.selectOpened": [],
|
||||
"project.selectOpenedFile": [],
|
||||
"db.expandAll": [],
|
||||
"db.collapseAll": [],
|
||||
// Terminal (keyWhen: terminalFocus); after VCS Update / Go to Test so it wins there.
|
||||
|
||||
@@ -383,6 +383,8 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"vcs.addToVcs": ["Ctrl+Alt+A"],
|
||||
"vcs.showDiff": ["Ctrl+D"],
|
||||
"vcs.log.changes.showDiff": ["Ctrl+D"],
|
||||
"vcs.log.changes.createPatch": [],
|
||||
"vcs.log.changes.copyPatch": [],
|
||||
"vcs.showDiffInNewWindow": [],
|
||||
"vcs.nextChange": ["Ctrl+Alt+Shift+Down"],
|
||||
"vcs.prevChange": ["Ctrl+Alt+Shift+Up"],
|
||||
@@ -493,6 +495,7 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"agents.sendToAgent": [],
|
||||
// Agents task list (when it has focus)
|
||||
"agents.archiveTasks": ["Ctrl+Shift+E"],
|
||||
"agents.deleteTasks": ["Delete"],
|
||||
// Database tool window (when the tree has focus; `db.openConsole` anywhere).
|
||||
"db.openConsole": ["Ctrl+Shift+Q"],
|
||||
"db.newDataSource": [],
|
||||
@@ -529,6 +532,7 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"db.showDiagram": ["Ctrl+Alt+Shift+U"],
|
||||
"db.showDiagramPopup": ["Ctrl+Alt+U"],
|
||||
"db.selectOpened": [],
|
||||
"project.selectOpenedFile": [],
|
||||
"db.expandAll": [],
|
||||
"db.collapseAll": [],
|
||||
// Terminal (keyWhen: terminalFocus); after VCS Update / Go to Test so it wins there.
|
||||
|
||||
@@ -402,6 +402,8 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"vcs.addToVcs": [],
|
||||
"vcs.showDiff": [],
|
||||
"vcs.log.changes.showDiff": [],
|
||||
"vcs.log.changes.createPatch": [],
|
||||
"vcs.log.changes.copyPatch": [],
|
||||
"vcs.showDiffInNewWindow": [],
|
||||
"vcs.nextChange": ["Alt+F5"],
|
||||
"vcs.prevChange": ["Alt+Shift+F5"],
|
||||
@@ -528,6 +530,7 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"agents.sendToAgent": [],
|
||||
// Agents task list (when it has focus)
|
||||
"agents.archiveTasks": ["Meta+Shift+E"],
|
||||
"agents.deleteTasks": ["Meta+Backspace"],
|
||||
// Python Console: VS Code's Shift+Enter would shadow typing in Python files, so unbound.
|
||||
"python.console.executeSelection": [],
|
||||
// Search fields (find bar, Find in Files): last, so they win over editor keys while one is focused.
|
||||
|
||||
@@ -45,6 +45,7 @@ export const vscodeWindows: Record<string, string[]> = {
|
||||
"project.rename": ["F2"],
|
||||
"project.delete": ["Delete"],
|
||||
"db.drop": ["Delete"],
|
||||
"agents.deleteTasks": ["Delete"],
|
||||
"project.copyAbsolutePath": ["Alt+Shift+C"],
|
||||
"project.open": [],
|
||||
"project.openInRightSplit": ["Ctrl+Enter"],
|
||||
|
||||
@@ -465,6 +465,7 @@
|
||||
"menu.file.exportSettings": "Export Settings…",
|
||||
"menu.file.importSettings": "Import Settings…",
|
||||
"menu.file.importJetBrainsSettings": "Import Settings from JetBrains IDE…",
|
||||
"menu.file.importJetBrainsRecentProjects": "Import Recent Projects from JetBrains IDE…",
|
||||
"menu.file.syncSettings": "Sync Settings Now",
|
||||
"menu.file.togglePowerSave": "Power Save Mode",
|
||||
"menu.macros": "Macros",
|
||||
|
||||
@@ -3740,6 +3740,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.",
|
||||
"Hot reload on save failed: {0}": "Hot reload on save failed: {0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?",
|
||||
"New Tab": "New Tab",
|
||||
"New tab in current window": "New tab in current window",
|
||||
"Show Only Widgets": "Show Only Widgets",
|
||||
@@ -4811,5 +4812,13 @@
|
||||
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.",
|
||||
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.",
|
||||
"Open in Xcode": "Open in Xcode",
|
||||
"Import Recent Projects from JetBrains IDE": "Import Recent Projects from JetBrains IDE",
|
||||
"Import Recent Projects from JetBrains IDE…": "Import Recent Projects from JetBrains IDE…",
|
||||
"Recent projects imported": "Recent projects imported",
|
||||
"No new recent projects to import": "No new recent projects to import",
|
||||
"Cannot import recent projects": "Cannot import recent projects",
|
||||
"Recent projects": "Recent projects",
|
||||
"Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.": "Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.",
|
||||
"{imported} new, {groups} new project groups, {missing} skipped (folder missing)": "{imported} new, {groups} new project groups, {missing} skipped (folder missing)",
|
||||
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it"
|
||||
}
|
||||
@@ -9762,6 +9762,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Сохранение файла Dart во время запущенной сессии отладки Flutter перезагружает приложение, если в файле нет ошибок.",
|
||||
"Hot reload on save failed: {0}": "Ошибка горячей перезагрузки при сохранении: {0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта, присоединять к уже открытым проектам или открывать как новую вкладку в этом окне.\nКак открыть «{name}»?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта или как новую вкладку в этом окне.\nКак открыть «{name}»?",
|
||||
"Show Only Widgets": "Показывать только виджеты",
|
||||
"Update failed": "Не удалось выполнить обновление",
|
||||
"Updating branches": "Обновление веток",
|
||||
|
||||
@@ -2668,6 +2668,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Çalışan Flutter hata ayıklama oturumunda Dart dosyası kaydedildiğinde, dosyada hata yoksa uygulama yeniden yüklenir.",
|
||||
"Hot reload on save failed: {0}": "Kaydetmede sıcak yeniden yükleme başarısız: {0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir, açık projelere bağlanabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?",
|
||||
"New Tab": "Yeni sekme",
|
||||
"New tab in current window": "Geçerli pencerede yeni sekme",
|
||||
"Show Only Widgets": "Yalnızca Bileşenleri Göster",
|
||||
|
||||
@@ -9195,6 +9195,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "儲存正在執行的 Flutter 偵錯工作階段裡的 Dart 檔案時重新載入應用,檔案有錯誤時跳過。",
|
||||
"Hot reload on save failed: {0}": "儲存時熱過載失敗:{0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案、附加到已開啟的專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?",
|
||||
"Show Only Widgets": "僅顯示 Widget",
|
||||
"Update failed": "更新失敗",
|
||||
"Updating branches": "正在更新分支",
|
||||
|
||||
@@ -10315,6 +10315,7 @@
|
||||
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "保存正在运行的 Flutter 调试会话里的 Dart 文件时重新加载应用,文件有错误时跳过。",
|
||||
"Hot reload on save failed: {0}": "保存时热重载失败:{0}",
|
||||
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目、附加到已打开的项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?",
|
||||
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?",
|
||||
"Show Only Widgets": "仅显示 Widget",
|
||||
"Update failed": "更新失败",
|
||||
"Updating branches": "正在更新分支",
|
||||
@@ -11464,5 +11465,12 @@
|
||||
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译它。请在 Xcode 中添加,或把该组转换为文件夹。",
|
||||
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译 {files}。请在 Xcode 中添加,或把该组转换为文件夹。",
|
||||
"Open in Xcode": "在 Xcode 中打开",
|
||||
"Import Recent Projects from JetBrains IDE": "从 JetBrains IDE 导入最近项目",
|
||||
"Import Recent Projects from JetBrains IDE…": "从 JetBrains IDE 导入最近项目…",
|
||||
"Recent projects imported": "已导入最近项目",
|
||||
"No new recent projects to import": "没有可导入的新最近项目",
|
||||
"Cannot import recent projects": "无法导入最近项目",
|
||||
"Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.": "已导入 {imported} 个最近项目和 {groups} 个项目分组,跳过 {missing} 个文件夹已不存在的项目。",
|
||||
"{imported} new, {groups} new project groups, {missing} skipped (folder missing)": "新增 {imported} 个,新增 {groups} 个项目分组,跳过 {missing} 个(文件夹已不存在)",
|
||||
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围"
|
||||
}
|
||||
@@ -465,6 +465,7 @@
|
||||
"menu.file.exportSettings": "导出设置…",
|
||||
"menu.file.importSettings": "导入设置…",
|
||||
"menu.file.importJetBrainsSettings": "从 JetBrains IDE 导入设置…",
|
||||
"menu.file.importJetBrainsRecentProjects": "从 JetBrains IDE 导入最近项目…",
|
||||
"menu.file.syncSettings": "立即同步设置",
|
||||
"menu.file.togglePowerSave": "省电模式",
|
||||
"menu.macros": "宏",
|
||||
|
||||
@@ -103,6 +103,16 @@ describe("Tabs interactions", () => {
|
||||
expect(onClose).toHaveBeenCalledWith("b");
|
||||
});
|
||||
|
||||
it("double click on the empty strip calls onBlankDoubleClick, not on a tab", () => {
|
||||
const onBlank = vi.fn();
|
||||
const { container } = render(<Tabs items={items} activeId="a" onSelect={() => {}} onBlankDoubleClick={onBlank} />);
|
||||
fireEvent.doubleClick(screen.getByRole("tab", { name: "A" }));
|
||||
expect(onBlank).not.toHaveBeenCalled();
|
||||
fireEvent.doubleClick(screen.getByRole("tablist"));
|
||||
fireEvent.doubleClick(container.firstElementChild!);
|
||||
expect(onBlank).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("Shift+left-click closes an editor tab without selecting it", () => {
|
||||
const onClose = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
|
||||
+15
-1
@@ -136,6 +136,8 @@ export interface TabsProps {
|
||||
/** Shift+left-click a tab closes it (editor tabs; plain clicks still select). */
|
||||
closeOnShiftClick?: boolean;
|
||||
onDoubleClick?: (id: string) => void;
|
||||
/** Double click on the empty part of the strip (not on a tab or button), e.g. to maximize the editor. */
|
||||
onBlankDoubleClick?: () => void;
|
||||
onContextMenu?: (id: string, e: MouseEvent) => void;
|
||||
/** `editor`: 30px with separators (editor tabs); `compact`: 28px plain (popups, tool window sub-tabs). */
|
||||
variant?: "editor" | "compact";
|
||||
@@ -176,6 +178,7 @@ export function Tabs({
|
||||
onTogglePin,
|
||||
closeOnShiftClick,
|
||||
onDoubleClick,
|
||||
onBlankDoubleClick,
|
||||
onContextMenu,
|
||||
variant = "editor",
|
||||
trailing,
|
||||
@@ -397,7 +400,18 @@ export function Tabs({
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={stripClass} ref={stripRef}>
|
||||
<div
|
||||
className={stripClass}
|
||||
ref={stripRef}
|
||||
onDoubleClick={
|
||||
onBlankDoubleClick
|
||||
? (e) => {
|
||||
// Only the strip's own background counts: tabs, buttons and trailing content handle their own clicks.
|
||||
if (e.target === e.currentTarget || e.target === scrollRef.current) onBlankDoubleClick();
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{vertical && trailing && <div className={styles.trailing}>{trailing}</div>}
|
||||
<div
|
||||
ref={scrollRef}
|
||||
|
||||
+11
-1
@@ -749,7 +749,17 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
endSearch();
|
||||
if (e.shiftKey) selectIndex(i, "range");
|
||||
else if (e.metaKey || e.ctrlKey) selectIndex(i, "toggle");
|
||||
else selectIndex(i);
|
||||
else if (multiSelect && selected.size > 1 && selected.has(rows[i]!.key)) {
|
||||
// Pressing a row of a multi-selection keeps the selection so a drag carries all of it;
|
||||
// a release without moving (a plain click) narrows it to the row.
|
||||
const x0 = e.clientX;
|
||||
const y0 = e.clientY;
|
||||
const up = (u: globalThis.MouseEvent) => {
|
||||
window.removeEventListener("mouseup", up, true);
|
||||
if (Math.abs(u.clientX - x0) < 4 && Math.abs(u.clientY - y0) < 4) selectIndex(i);
|
||||
};
|
||||
window.addEventListener("mouseup", up, true);
|
||||
} else selectIndex(i);
|
||||
};
|
||||
|
||||
const leadRow = leadIndex >= 0 ? rows[leadIndex] : undefined;
|
||||
|
||||
@@ -7,9 +7,11 @@ import { ask } from "./messages";
|
||||
import { commands } from "@/platform/ipc";
|
||||
|
||||
const windowOpenRemote = vi.fn();
|
||||
const windowGroupJoin = vi.fn();
|
||||
const remoteWindow = vi.hoisted(() => ({ value: false }));
|
||||
vi.mock("./messages", () => ({ ask: vi.fn() }));
|
||||
vi.mock("@/platform/remote", () => ({
|
||||
isRemoteWindow: () => false,
|
||||
isRemoteWindow: () => remoteWindow.value,
|
||||
connectRemote: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
@@ -18,10 +20,12 @@ vi.mock("@/platform/ipc", () => ({
|
||||
commands: {
|
||||
settingsSet: vi.fn(async () => ({ general: { openProjectIn: "attach" } })),
|
||||
windowOpenRemote: (...a: unknown[]) => windowOpenRemote(...a),
|
||||
windowGroupJoin: (...a: unknown[]) => windowGroupJoin(...a),
|
||||
},
|
||||
}));
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
remoteWindow.value = false;
|
||||
useProject.setState({
|
||||
project: { root: "/a", name: "A", settings: {}, trusted: true, isGit: false },
|
||||
settings: {},
|
||||
@@ -40,14 +44,20 @@ it("offers attach for this open without remembering it", async () => {
|
||||
expect(await chooseProjectWindow("C")).toBe(button);
|
||||
expect(ask).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("does not attach without a project or when opening a remote project", async () => {
|
||||
it("offers a new tab but no attach for a remote project or from a remote window", async () => {
|
||||
useProject.setState({
|
||||
settings: { general: { openProjectIn: "attach" } } as never,
|
||||
});
|
||||
vi.mocked(ask).mockResolvedValue({ button: "cancel", checked: false });
|
||||
expect(await chooseProjectWindow("remote", false)).toBeNull();
|
||||
expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]);
|
||||
useProject.setState({ project: null });
|
||||
expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]);
|
||||
remoteWindow.value = true;
|
||||
expect(await chooseProjectWindow("B")).toBeNull();
|
||||
expect(vi.mocked(ask).mock.calls[1]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]);
|
||||
useProject.setState({ project: null, lightEdit: true });
|
||||
expect(await chooseProjectWindow("B")).toBeNull();
|
||||
expect(vi.mocked(ask).mock.calls[2]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]);
|
||||
useProject.setState({ project: null, lightEdit: false });
|
||||
expect(await chooseProjectWindow("B")).toBe("same");
|
||||
});
|
||||
|
||||
@@ -65,7 +75,7 @@ it("opens a project tab by policy, or a new window when this one can't take one"
|
||||
useProject.setState({ settings: { general: { openProjectIn: "tab" } } } as never);
|
||||
expect(openPolicy()).toBe("tab");
|
||||
expect(await chooseProjectWindow("B")).toBe("tab");
|
||||
expect(await chooseProjectWindow("remote", false)).toBe("new");
|
||||
expect(await chooseProjectWindow("remote", false)).toBe("tab");
|
||||
useProject.setState({ project: null, lightEdit: true });
|
||||
expect(await chooseProjectWindow("B")).toBe("new");
|
||||
expect(ask).not.toHaveBeenCalled();
|
||||
@@ -91,6 +101,16 @@ describe("a recent project opened with a modifier key", () => {
|
||||
usePlatform.setState({ os });
|
||||
});
|
||||
|
||||
it("opens a remote project as a project tab of this window", async () => {
|
||||
windowOpenRemote.mockResolvedValueOnce({ kind: "current" }).mockResolvedValueOnce({ kind: "opened", label: "w2" });
|
||||
const here = vi.fn(async () => {});
|
||||
useProject.setState({ settings: { general: { openProjectIn: "tab" } } as never });
|
||||
expect(await openRemoteProject(target, "/home/me/app", here)).toBe(true);
|
||||
expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", true);
|
||||
expect(windowGroupJoin).toHaveBeenCalledWith("w2");
|
||||
expect(here).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("opens a remote project in that window without asking", async () => {
|
||||
windowOpenRemote.mockResolvedValue({ kind: "opened" });
|
||||
const here = vi.fn(async () => {});
|
||||
|
||||
@@ -40,26 +40,26 @@ export async function chooseProjectWindow(
|
||||
): Promise<"new" | "same" | "attach" | "tab" | null> {
|
||||
const { project, lightEdit } = useProject.getState();
|
||||
if (!project && !lightEdit) return "same";
|
||||
// Both ways of keeping this window's project: a workspace folder, or a project tab of this window.
|
||||
const canAdd = allowAttach && !!project && !isRemoteWindow();
|
||||
// Attach adds a local folder to this local window's workspace; a project tab is a window of its
|
||||
// own joined to this one's group, so it takes remote projects and remote windows too.
|
||||
const canTab = !!project;
|
||||
const canAttach = allowAttach && canTab && !isRemoteWindow();
|
||||
const mode = openPolicy();
|
||||
// A project tab needs this window's project beside it; without one, a new window is the closest.
|
||||
if (mode === "tab") return canAdd ? "tab" : "new";
|
||||
if (mode === "tab") return canTab ? "tab" : "new";
|
||||
if (mode !== "ask") return mode;
|
||||
const r = await ask({
|
||||
title: t("app.window.askTitle"),
|
||||
width: canAdd ? 640 : undefined,
|
||||
body: canAdd
|
||||
width: canAttach ? 640 : undefined,
|
||||
body: canAttach
|
||||
? tx`Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open "${name}"?`
|
||||
: t("app.window.askBody", { name }),
|
||||
: canTab
|
||||
? tx`Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open "${name}"?`
|
||||
: t("app.window.askBody", { name }),
|
||||
buttons: [
|
||||
{ id: "cancel", label: t("common.cancel") },
|
||||
...(canAdd
|
||||
? [
|
||||
{ id: "attach", label: t("app.window.askAttach") },
|
||||
{ id: "tab", label: tx`New Tab` },
|
||||
]
|
||||
: []),
|
||||
...(canAttach ? [{ id: "attach", label: t("app.window.askAttach") }] : []),
|
||||
...(canTab ? [{ id: "tab", label: tx`New Tab` }] : []),
|
||||
{ id: "new", label: t("app.window.askNew") },
|
||||
{ id: "same", label: t("app.window.askThis"), primary: true },
|
||||
],
|
||||
@@ -81,8 +81,8 @@ export async function chooseProjectWindow(
|
||||
|
||||
/**
|
||||
* Opens folder `path` of `target` (an SSH host or a WSL distribution): focuses the
|
||||
* window that has it, else opens it in a new window or (`here`) this one per
|
||||
* "Open project in", or where `override` says. `false`: cancelled.
|
||||
* window that has it, else opens it in a new window, a project tab of this window or
|
||||
* (`here`) this one per "Open project in", or where `override` says. `false`: cancelled.
|
||||
*/
|
||||
export async function openRemoteProject(
|
||||
target: RemoteTarget,
|
||||
@@ -93,8 +93,10 @@ export async function openRemoteProject(
|
||||
if ((await call(commands.windowOpenRemote(target, path, false))).kind === "focused") return true;
|
||||
const mode = override ?? (await chooseProjectWindow(path.replace(/\/+$/, "").split("/").pop() || path, false));
|
||||
if (!mode) return false;
|
||||
if (mode === "new") {
|
||||
await call(commands.windowOpenRemote(target, path, true));
|
||||
if (mode === "new" || mode === "tab") {
|
||||
const outcome = await call(commands.windowOpenRemote(target, path, true));
|
||||
// As a local project tab: the window holding the project, new or focused, joins this one's group.
|
||||
if (mode === "tab" && outcome.kind !== "current") await call(commands.windowGroupJoin(outcome.label));
|
||||
return true;
|
||||
}
|
||||
// The remote host's project doesn't take this window's untitled buffers.
|
||||
|
||||
Reference in new issue
Заблокувати користувача