дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 22:32:35 +02:00
Порівняти коміти
22
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
840f258e83 | ||
|
|
485d7bf99d | ||
|
|
53a1e9255e | ||
|
|
40ab249cb8 | ||
|
|
9da3d6d9b5 | ||
|
|
0df7cb1da2 | ||
|
|
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",
|
||||
|
||||
@@ -1975,6 +1975,10 @@ pub struct TypeScriptSettings {
|
||||
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
|
||||
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
pub tsserver_max_memory: u32,
|
||||
/// tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = TsServerLog)]
|
||||
pub tsserver_log: TsServerLog,
|
||||
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
/// `tsconfig.json` reports the errors of files that are not open.
|
||||
pub watch_problems: bool,
|
||||
@@ -1982,10 +1986,27 @@ pub struct TypeScriptSettings {
|
||||
|
||||
impl Default for TypeScriptSettings {
|
||||
fn default() -> Self {
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
|
||||
Self {
|
||||
version: "bundled".into(),
|
||||
tsserver_max_memory: 0,
|
||||
tsserver_log: TsServerLog::Off,
|
||||
watch_problems: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TsServerLog {
|
||||
#[default]
|
||||
Off,
|
||||
Terse,
|
||||
Normal,
|
||||
RequestTime,
|
||||
Verbose,
|
||||
}
|
||||
|
||||
/// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -2168,6 +2189,20 @@ mod tests {
|
||||
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsserver_log_reads_known_levels_and_drops_anything_else() {
|
||||
let log = |v: &str| {
|
||||
let s: Settings =
|
||||
serde_json::from_str(&format!(r#"{{"languages":{{"typescript":{{"tsserverLog":{v}}}}}}}"#)).unwrap();
|
||||
s.languages.typescript.tsserver_log
|
||||
};
|
||||
assert_eq!(log(r#""requestTime""#), TsServerLog::RequestTime);
|
||||
assert_eq!(log(r#""verbose""#), TsServerLog::Verbose);
|
||||
assert_eq!(log(r#""--trace""#), TsServerLog::Off);
|
||||
assert_eq!(log("3"), TsServerLog::Off);
|
||||
assert_eq!(serde_json::to_value(TsServerLog::RequestTime).unwrap(), "requestTime");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_interpreter_may_name_a_run_target() {
|
||||
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
|
||||
|
||||
@@ -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"),
|
||||
],
|
||||
),
|
||||
@@ -484,6 +485,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("navigate.declaration", "Declaration or Usages"),
|
||||
act("navigate.implementation", "Implementation(s)"),
|
||||
act("navigate.typeDeclaration", "Type Declaration"),
|
||||
act("navigate.sourceDefinition", "Source Definition"),
|
||||
act("navigate.superMethod", "Super Method"),
|
||||
act("navigate.gotoTest", "Test"),
|
||||
act("navigate.relatedSymbol", "Related Symbol…"),
|
||||
|
||||
@@ -675,6 +675,53 @@ pub async fn lsp_switch_source_header(
|
||||
Ok(result?.map(|path| path.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
/// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
|
||||
/// instead of its `.d.ts`. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_source_definition(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::select! {
|
||||
result = lsp.source_definition(doc, pos, cancel.clone()) => result,
|
||||
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
|
||||
};
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Has vtsls open the document's `tsconfig.json` / `jsconfig.json` or the TS Server log.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_open_typescript_file(host: &Host, window: &str, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
lsp.open_typescript_file(doc, what).await
|
||||
}
|
||||
|
||||
/// The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_move_to_file_targets(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
command: Command,
|
||||
) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::select! {
|
||||
result = lsp.move_to_file_targets(doc, command, cancel.clone()) => result,
|
||||
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
|
||||
};
|
||||
host.end_request(request);
|
||||
Ok(result?.into_iter().map(ide_core::IpcPath::from).collect())
|
||||
}
|
||||
|
||||
/// Implementations of the symbols at `positions`, one list per position (the
|
||||
/// editor's "is implemented / overridden" gutter markers). Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
@@ -3344,6 +3391,9 @@ ide_command::domain!(
|
||||
lsp_implementation_locations,
|
||||
lsp_file_references,
|
||||
lsp_switch_source_header,
|
||||
lsp_source_definition,
|
||||
lsp_open_typescript_file,
|
||||
lsp_move_to_file_targets,
|
||||
lsp_implementations,
|
||||
lsp_inlay_hints,
|
||||
lsp_inline_completion,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! speak (a WebSocket): direct, or through an HTTP proxy's `CONNECT` tunnel.
|
||||
|
||||
use base64::Engine;
|
||||
use hyper_util::client::proxy::matcher::Matcher;
|
||||
use ide_core::proxy_settings::ProxyRoute;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::time::Duration;
|
||||
@@ -10,30 +11,68 @@ use tokio::net::TcpStream;
|
||||
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// The PAC lookup of the system proxy settings; none outside macOS.
|
||||
#[cfg(target_os = "macos")]
|
||||
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = crate::system_pac_route;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = |_| None;
|
||||
|
||||
/// A connection to `url`'s host and port, through the proxy System Settings › HTTP Proxy
|
||||
/// (or, in Auto mode, the system) routes that host to.
|
||||
pub async fn connect(url: &reqwest::Url) -> IdeResult<TcpStream> {
|
||||
let route = ide_core::proxy_settings::proxy().route(url.host_str());
|
||||
connect_with(url, route, SYSTEM_PAC, Matcher::from_system).await
|
||||
}
|
||||
|
||||
/// The URI the system proxy settings are asked about: the scheme reqwest would use (`ws` → `http`).
|
||||
fn system_uri(url: &reqwest::Url) -> IdeResult<http::Uri> {
|
||||
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
|
||||
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
|
||||
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
|
||||
let proxy = match ide_core::proxy_settings::proxy().route(Some(host)) {
|
||||
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
|
||||
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))
|
||||
}
|
||||
|
||||
/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected.
|
||||
async fn connect_with(
|
||||
url: &reqwest::Url,
|
||||
route: ProxyRoute,
|
||||
pac: impl FnOnce(&str) -> Option<ProxyRoute> + Send + 'static,
|
||||
matcher: impl FnOnce() -> Matcher,
|
||||
) -> IdeResult<TcpStream> {
|
||||
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
|
||||
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
|
||||
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
|
||||
let proxy = match route {
|
||||
ProxyRoute::Direct => None,
|
||||
ProxyRoute::Via(via) => Some(via),
|
||||
ProxyRoute::System => {
|
||||
// The system proxy of the scheme reqwest would use (`ws` → `http`).
|
||||
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
|
||||
let uri: http::Uri =
|
||||
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))?;
|
||||
hyper_util::client::proxy::matcher::Matcher::from_system().intercept(&uri).map(|intercept| {
|
||||
let auth =
|
||||
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
|
||||
let uri = intercept.uri();
|
||||
format!(
|
||||
"{}://{auth}{}",
|
||||
uri.scheme_str().unwrap_or("http"),
|
||||
uri.authority().map(|a| a.as_str()).unwrap_or_default()
|
||||
)
|
||||
})
|
||||
let uri = system_uri(url)?;
|
||||
// On macOS the resolver may run the PAC script (`dnsResolve`), so it stays off the async threads. A
|
||||
// script still loading answers with the matcher's route.
|
||||
let probe = uri.to_string();
|
||||
#[cfg(target_os = "macos")]
|
||||
let pac = tokio::task::spawn_blocking(move || pac(&probe))
|
||||
.await
|
||||
.map_err(|error| IdeError::unavailable(format!("proxy lookup failed: {error}")))?;
|
||||
// Nothing to evaluate outside macOS: no hop to the blocking pool.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let pac = pac(&probe);
|
||||
match pac {
|
||||
Some(ProxyRoute::Via(via)) if via.starts_with("http://") => Some(via),
|
||||
Some(ProxyRoute::Direct) => None,
|
||||
// No PAC applies, or it names a proxy this tunnel cannot speak to (SOCKS): the matcher's route.
|
||||
_ => matcher().intercept(&uri).map(|intercept| {
|
||||
let auth =
|
||||
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
|
||||
let uri = intercept.uri();
|
||||
format!(
|
||||
"{}://{auth}{}",
|
||||
uri.scheme_str().unwrap_or("http"),
|
||||
uri.authority().map(|a| a.as_str()).unwrap_or_default()
|
||||
)
|
||||
}),
|
||||
}
|
||||
}
|
||||
};
|
||||
let connecting = async {
|
||||
@@ -157,6 +196,73 @@ mod tests {
|
||||
assert!(error.message.contains("needs a login"), "{}", error.message);
|
||||
}
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn matcher_via(address: &str) -> impl FnOnce() -> Matcher {
|
||||
let address = address.to_owned();
|
||||
move || Matcher::builder().all(format!("http://{address}")).build()
|
||||
}
|
||||
|
||||
/// The CONNECT line a proxy was asked for, or `None` when nothing connected within a moment.
|
||||
async fn asked(task: tokio::task::JoinHandle<String>) -> Option<String> {
|
||||
tokio::time::timeout(Duration::from_millis(300), task).await.ok().map(|head| head.unwrap())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_pac_route_wins_over_the_matcher_and_ws_is_looked_up_as_http() {
|
||||
let (pac_proxy, pac_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let seen = Arc::new(Mutex::new(String::new()));
|
||||
let recorded = Arc::clone(&seen);
|
||||
let pac = move |probe: &str| {
|
||||
*recorded.lock().unwrap() = probe.to_owned();
|
||||
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
|
||||
};
|
||||
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
|
||||
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
|
||||
assert_eq!(*seen.lock().unwrap(), "http://pac-target.invalid:8080/");
|
||||
assert!(asked(pac_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
|
||||
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wss_is_looked_up_as_https() {
|
||||
let (pac_proxy, _) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let seen = Arc::new(Mutex::new(String::new()));
|
||||
let recorded = Arc::clone(&seen);
|
||||
let pac = move |probe: &str| {
|
||||
*recorded.lock().unwrap() = probe.to_owned();
|
||||
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
|
||||
};
|
||||
let url = reqwest::Url::parse("wss://pac-target.invalid/s").unwrap();
|
||||
connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build()).await.unwrap();
|
||||
assert_eq!(*seen.lock().unwrap(), "https://pac-target.invalid:443/");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_resolved_direct_route_skips_the_matchers_proxy() {
|
||||
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
|
||||
connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy))
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::timeout(Duration::from_millis(300), listener.accept())
|
||||
.await
|
||||
.expect("no direct connection")
|
||||
.unwrap();
|
||||
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_socks_pac_route_keeps_the_matchers_route() {
|
||||
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
|
||||
let pac = |_: &str| Some(ProxyRoute::Via("socks5h://127.0.0.1:1080".into()));
|
||||
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy)).await.unwrap();
|
||||
assert!(asked(matcher_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_credentials_are_percent_decoded() {
|
||||
assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c");
|
||||
|
||||
@@ -2811,6 +2811,79 @@ impl LspManager {
|
||||
Ok(ts_file_moves::file_references(&result))
|
||||
}
|
||||
|
||||
/// Runs vtsls' own `command` for `doc`. typescript-language-server, TypeScript 7 and the
|
||||
/// Vue / Astro servers have none of these commands: they need vtsls.
|
||||
async fn vtsls_command(
|
||||
&self,
|
||||
doc: DocId,
|
||||
command: &str,
|
||||
arguments: impl FnOnce(&DocSnap, &Target) -> Option<Value>,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<(Target, Value)> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let t = self
|
||||
.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == command))
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|t| t.server.name == "vtsls")
|
||||
.ok_or_else(|| IdeError::unavailable("This needs the vtsls TypeScript language server"))?;
|
||||
let arguments =
|
||||
arguments(&snap, &t).ok_or_else(|| IdeError::invalid(format!("invalid `{command}` arguments")))?;
|
||||
let params = json!({ "command": command, "arguments": arguments });
|
||||
let result = self.call(&t, "workspace/executeCommand", params, cancel, LONG_TIMEOUT).await?;
|
||||
Ok((t, result))
|
||||
}
|
||||
|
||||
/// Go to Source Definition: the JavaScript implementation of what `pos` refers to, not its
|
||||
/// `.d.ts` declaration (vtsls' `typescript.goToSourceDefinition`).
|
||||
pub async fn source_definition(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult<Vec<Location>> {
|
||||
let (t, result) = self
|
||||
.vtsls_command(
|
||||
doc,
|
||||
"typescript.goToSourceDefinition",
|
||||
|snap, t| Some(json!([snap.uri, snap.position(t, pos)])),
|
||||
Some(&cancel),
|
||||
)
|
||||
.await?;
|
||||
let locs: Vec<lsp::Location> = serde_json::from_value::<Option<_>>(result)
|
||||
.map_err(|e| IdeError::internal(format!("typescript.goToSourceDefinition: {e}")))?
|
||||
.unwrap_or_default();
|
||||
let conv = self.conv(t.enc());
|
||||
Ok(locs.iter().filter_map(|l| conv.location(l)).collect())
|
||||
}
|
||||
|
||||
/// Opens the `tsconfig.json` / `jsconfig.json` of `doc`'s project, or the TS Server log:
|
||||
/// vtsls answers with `window/showDocument` (or a message when there is none).
|
||||
pub async fn open_typescript_file(&self, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
|
||||
let (command, with_uri) = match what {
|
||||
TypeScriptFile::ProjectConfig => {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let js = snap.language.as_str().starts_with("javascript");
|
||||
(if js { "javascript.goToProjectConfig" } else { "typescript.goToProjectConfig" }, true)
|
||||
}
|
||||
TypeScriptFile::ServerLog => ("typescript.openTsServerLog", false),
|
||||
};
|
||||
self.vtsls_command(doc, command, |snap, _| Some(if with_uri { json!([snap.uri]) } else { json!([]) }), None)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The files tsserver suggests for vtsls' Move to File `command` (from a code action).
|
||||
pub async fn move_to_file_targets(
|
||||
&self,
|
||||
doc: DocId,
|
||||
command: Command,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Vec<PathBuf>> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let request = ts_file_moves::move_to_file_suggestions_request(&snap.path, &command.arguments)
|
||||
.ok_or_else(|| IdeError::invalid("invalid Move to File command"))?;
|
||||
let (_, result) = self
|
||||
.vtsls_command(doc, ts_file_moves::COMMAND, |_, _| request.get("arguments").cloned(), Some(&cancel))
|
||||
.await?;
|
||||
Ok(ts_file_moves::move_to_file_suggestions(&result))
|
||||
}
|
||||
|
||||
/// Whether a server of `doc` (`server`, when given) provides the command `name`. Code actions
|
||||
/// can carry commands other editors' extensions run themselves after the edit (vtsls'
|
||||
/// `_typescript.didOrganizeImports`): no server provides those.
|
||||
|
||||
@@ -87,10 +87,56 @@ pub(crate) fn file_references(result: &Value) -> Vec<ide_core::Location> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `typescript.tsserverRequest` arguments asking where the selection of vtsls' Move to File
|
||||
/// command (`_typescript.moveToFileRefactoring` with `[action, uri, range]`, run with the target
|
||||
/// file appended) can go.
|
||||
pub(crate) fn move_to_file_suggestions_request(file: &std::path::Path, arguments: &[Value]) -> Option<Value> {
|
||||
let range: lsp_types::Range = serde_json::from_value(arguments.get(2)?.clone()).ok()?;
|
||||
// tsserver: 1-based lines and UTF-16 offsets; vtsls speaks UTF-16.
|
||||
Some(json!({
|
||||
"command": COMMAND,
|
||||
"arguments": ["getMoveToRefactoringFileSuggestions", {
|
||||
"file": file,
|
||||
"startLine": range.start.line + 1,
|
||||
"startOffset": range.start.character + 1,
|
||||
"endLine": range.end.line + 1,
|
||||
"endOffset": range.end.character + 1,
|
||||
}],
|
||||
}))
|
||||
}
|
||||
|
||||
/// The files tsserver suggests in its `getMoveToRefactoringFileSuggestions` answer.
|
||||
pub(crate) fn move_to_file_suggestions(result: &Value) -> Vec<PathBuf> {
|
||||
let body = result.get("body").unwrap_or(result);
|
||||
serde_json::from_value(body.get("files").cloned().unwrap_or_default()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn asks_tsserver_where_the_move_to_file_selection_can_go() {
|
||||
let action = json!({ "name": "Move to file", "kind": "refactor.move.file" });
|
||||
let range = json!({ "start": { "line": 6, "character": 16 }, "end": { "line": 8, "character": 1 } });
|
||||
let request = move_to_file_suggestions_request(
|
||||
std::path::Path::new("/p/src/util.ts"),
|
||||
&[action.clone(), json!("file:///p/src/util.ts"), range],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
request["arguments"],
|
||||
json!(["getMoveToRefactoringFileSuggestions", {
|
||||
"file": "/p/src/util.ts", "startLine": 7, "startOffset": 17, "endLine": 9, "endOffset": 2,
|
||||
}])
|
||||
);
|
||||
assert!(move_to_file_suggestions_request(std::path::Path::new("/p/a.ts"), &[action]).is_none());
|
||||
let answer =
|
||||
json!({ "success": true, "body": { "newFileName": "/p/src/greet.ts", "files": ["/p/src/app.ts"] } });
|
||||
assert_eq!(move_to_file_suggestions(&answer), vec![PathBuf::from("/p/src/app.ts")]);
|
||||
assert!(move_to_file_suggestions(&json!({ "success": false })).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_tsserver_file_references() {
|
||||
let result = json!({ "success": true, "body": { "symbolName": "\"./Hello.vue\"", "refs": [
|
||||
|
||||
@@ -109,6 +109,14 @@ pub struct Signature {
|
||||
pub parameters: Vec<(u32, u32)>,
|
||||
}
|
||||
|
||||
/// A file vtsls opens for a document: its project's configuration or the TS Server log.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TypeScriptFile {
|
||||
ProjectConfig,
|
||||
ServerLog,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GotoKind {
|
||||
|
||||
@@ -969,6 +969,135 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// vtsls' own commands (#6922): Go to Source Definition opens a library's JavaScript instead
|
||||
/// of its `.d.ts`, Go to Project Configuration and Open TS Server Log answer with
|
||||
/// `window/showDocument`, JSDoc `{@link}` in hovers is a `file://…#L1,1` link, and Move to File
|
||||
/// suggests the project's files and moves a function with its imports in one applied edit. Set
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/[email protected] typescript@6`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vtsls/language-server and typescript@6 (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn vtsls_commands_open_sources_configs_logs_and_move_to_file() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
for dir in ["src", "node_modules/greeting"] {
|
||||
std::fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
let files = [
|
||||
("package.json", "{\"name\":\"app\",\"private\":true}"),
|
||||
("tsconfig.json", "{\"files\":[],\"references\":[{\"path\":\"./src/tsconfig.app.json\"}]}"),
|
||||
(
|
||||
"src/tsconfig.app.json",
|
||||
"{\"compilerOptions\":{\"strict\":true,\"composite\":true,\"module\":\"ESNext\",\"moduleResolution\":\"Bundler\"},\"include\":[\"./**/*.ts\"]}",
|
||||
),
|
||||
(
|
||||
"node_modules/greeting/package.json",
|
||||
"{\"name\":\"greeting\",\"main\":\"index.js\",\"types\":\"index.d.ts\"}",
|
||||
),
|
||||
("node_modules/greeting/index.d.ts", "export declare function shout(s: string): string;\n"),
|
||||
("node_modules/greeting/index.js", "export function shout(s) {\n return s.toUpperCase();\n}\n"),
|
||||
(
|
||||
"src/main.ts",
|
||||
"import { shout } from \"greeting\";\nimport { greet, Greeter } from \"./util\";\n\n/** Uses {@link Greeter} to say hello. */\nexport function hello(name: string) {\n return shout(greet(name));\n}\n\nexport const g = new Greeter();\n",
|
||||
),
|
||||
(
|
||||
"src/util.ts",
|
||||
"export class Greeter {\n greet(name: string) {\n return `Hello, ${name}`;\n }\n}\n\nexport function greet(name: string) {\n return new Greeter().greet(name);\n}\n",
|
||||
),
|
||||
("src/strings.ts", "export const upper = (s: string) => s.toUpperCase();\n"),
|
||||
("src/app.ts", "import { greet } from \"./util\";\n\nconsole.log(greet(\"app\"));\n"),
|
||||
];
|
||||
for (path, text) in files {
|
||||
std::fs::write(root.join(path), text).unwrap();
|
||||
}
|
||||
// The IDE's settings hook: Move to File on, a TypeScript 6 lib, the log on.
|
||||
let init = serde_json::json!({
|
||||
"vtsls": { "enableMoveToFileCodeAction": true, "autoUseWorkspaceTsdk": true },
|
||||
"typescript": {
|
||||
"tsdk": tools.join("node_modules/typescript/lib").to_string_lossy(),
|
||||
"tsserver": { "log": "verbose" },
|
||||
},
|
||||
});
|
||||
let ts = lang("typescript", "ts", npm_server(&tools, "vtsls", "vtsls", Some(init)));
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![ts]));
|
||||
let applied: Arc<Mutex<Vec<ide_core::WorkspaceEdit>>> = Arc::default();
|
||||
mgr.set_apply_edit_hook(Box::new({
|
||||
let applied = applied.clone();
|
||||
move |edit| {
|
||||
applied.lock().push(edit);
|
||||
true
|
||||
}
|
||||
}));
|
||||
let open = |path: &str| {
|
||||
let doc = DocId::next();
|
||||
let file = root.join(path);
|
||||
mgr.did_open(doc, &file, &LanguageId::new("typescript"), 1, &std::fs::read_to_string(&file).unwrap());
|
||||
doc
|
||||
};
|
||||
let (main, util) = (open("src/main.ts"), open("src/util.ts"));
|
||||
|
||||
// `shout`: Go to Declaration is the `.d.ts`, Go to Source Definition the `.js`.
|
||||
let at = Pos::new(0, 10);
|
||||
// The syntax server answers with the import itself until the project is loaded.
|
||||
let dts = |d: &ide_core::Location| d.path.to_string_lossy().ends_with("greeting/index.d.ts");
|
||||
let declaration = retry("declaration", Duration::from_secs(90), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(main, at, GotoKind::Definition).await.ok().filter(|d| d.iter().any(dts)) }
|
||||
})
|
||||
.await;
|
||||
assert!(declaration.iter().all(dts), "{declaration:?}");
|
||||
let source = mgr.source_definition(main, at, Default::default()).await.unwrap();
|
||||
assert_eq!(source.len(), 1, "{source:?}");
|
||||
assert_eq!(*source[0].path, *root.join("node_modules/greeting/index.js"));
|
||||
assert_eq!(source[0].range.start, Pos::new(0, 16));
|
||||
|
||||
let shown = |events: &Events, suffix: &str| {
|
||||
events
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|e| matches!(e, IdeEvent::LspShowDocument { path: Some(path), .. } if path.to_string_lossy().ends_with(suffix)))
|
||||
};
|
||||
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ProjectConfig).await.unwrap();
|
||||
retry("tsconfig.app.json shown", Duration::from_secs(10), || {
|
||||
let found = shown(&events, "src/tsconfig.app.json").then_some(());
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ServerLog).await.unwrap();
|
||||
retry("tsserver.log shown", Duration::from_secs(10), || {
|
||||
let found = shown(&events, "tsserver.log").then_some(());
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
|
||||
let hover = mgr.hover(main, Pos::new(4, 17), Default::default()).await.unwrap();
|
||||
let hover = format!("{hover:?}");
|
||||
assert!(hover.contains("src/util.ts#L1%2C1"), "{hover}");
|
||||
|
||||
// Move to File on `greet`: tsserver suggests the other files, the move updates the importers.
|
||||
let caret = Pos::new(6, 16);
|
||||
let actions = mgr.code_actions(util, Range::new(caret, caret), vec!["refactor.move".into()]).await.unwrap();
|
||||
let command = actions
|
||||
.iter()
|
||||
.find_map(|a| a.command.clone().filter(|c| c.command == "_typescript.moveToFileRefactoring"))
|
||||
.unwrap_or_else(|| panic!("no Move to File: {actions:?}"));
|
||||
let targets = mgr.move_to_file_targets(util, command.clone(), Default::default()).await.unwrap();
|
||||
let strings = root.join("src/strings.ts");
|
||||
assert!(targets.contains(&strings) && targets.contains(&root.join("src/app.ts")), "{targets:?}");
|
||||
let mut moving = command;
|
||||
moving.arguments.push(serde_json::json!(strings));
|
||||
mgr.execute_command(util, moving).await.unwrap();
|
||||
let edits = applied.lock().clone();
|
||||
assert_eq!(edits.len(), 1, "{edits:?}");
|
||||
let edit = format!("{:?}", edits[0]);
|
||||
for file in ["src/util.ts", "src/strings.ts", "src/app.ts", "src/main.ts"] {
|
||||
assert!(edit.contains(&*root.join(file).to_string_lossy()), "{file}: {edit}");
|
||||
}
|
||||
assert!(edit.contains("export function greet(name: string)"), "{edit}");
|
||||
assert!(edit.contains("import { greet } from \\\"./strings\\\""), "{edit}");
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// CSS Modules Kit (`@css-modules-kit/ts-plugin`) on vtsls, which serves the `.module.css`
|
||||
/// files too (`languages: ["css"]`): definition and completion from TSX, references and rename
|
||||
/// from the stylesheet (#6071), with the settings hook's own plugin configuration. Exactly the
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::exec::{path_with, search_path, which};
|
||||
use crate::npm::{has_ts_api, native_typescript, own_typescript};
|
||||
use crate::{angular, astro, godot, pinned, vue};
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings};
|
||||
use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings, TsServerLog};
|
||||
use ide_core::version_managers::Tool;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_language::{LanguageConfig, LanguageServerConfig};
|
||||
@@ -1508,6 +1508,14 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
if name == "vtsls" && memory > 0 {
|
||||
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "maxTsServerMemory": memory } } }));
|
||||
}
|
||||
if name == "vtsls" {
|
||||
// Move to File asks the IDE for the target file (vtsls hides the action by default).
|
||||
merge_init_options(cfg, json!({ "vtsls": { "enableMoveToFileCodeAction": true } }));
|
||||
let log = s.languages.typescript.tsserver_log;
|
||||
if log != TsServerLog::Off {
|
||||
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "log": log } } }));
|
||||
}
|
||||
}
|
||||
if name == "vtsls"
|
||||
&& cfg.tsserver_project
|
||||
&& !server_root.ancestors().any(|d| d.join("tsconfig.json").is_file() || d.join("jsconfig.json").is_file())
|
||||
@@ -2778,6 +2786,22 @@ mod maven_linkage_tests {
|
||||
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vtsls_offers_move_to_file_and_logs_only_when_asked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
let options = |s: &Settings| {
|
||||
let mut cfg = custom_server("vtsls", &LanguageServerSettings::default());
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), s);
|
||||
serde_json::to_value(cfg.initialization_options).unwrap()
|
||||
};
|
||||
let off = options(&s);
|
||||
assert_eq!(off.pointer("/vtsls/enableMoveToFileCodeAction"), Some(&json!(true)));
|
||||
assert!(off.pointer("/typescript/tsserver/log").is_none());
|
||||
s.languages.typescript.tsserver_log = TsServerLog::Verbose;
|
||||
assert_eq!(options(&s).pointer("/typescript/tsserver/log"), Some(&json!("verbose")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vtsls_probes_the_tsconfig_plugins_but_not_its_global_ones() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -20,7 +20,12 @@ pub(crate) fn gx(e: impl std::fmt::Display) -> IdeError {
|
||||
}
|
||||
|
||||
pub(crate) struct Cache {
|
||||
repo: gix::ThreadSafeRepository,
|
||||
/// `None` after the repository was replaced or went away. gitoxide memory-maps packs, and
|
||||
/// reading a mapping whose volume was unmounted raises SIGBUS, so that handle is never reused.
|
||||
repo: Option<gix::ThreadSafeRepository>,
|
||||
/// The git and common directories `repo` was opened from.
|
||||
dirs: [PathBuf; 2],
|
||||
handles: Option<DirHandles>,
|
||||
files: [PathBuf; 4],
|
||||
stamp: Vec<Option<(SystemTime, u64)>>,
|
||||
/// `objects/pack` directory and its modification time. An external
|
||||
@@ -49,6 +54,49 @@ fn stamp(files: &[PathBuf]) -> Vec<Option<(SystemTime, u64)>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Tells whether the repository's directories are still the ones its handle was opened from.
|
||||
///
|
||||
/// Comparing paths is not enough: a remounted volume can have the same device, inodes and
|
||||
/// modification times. A descriptor opened before the unmount stays invalid after it.
|
||||
#[cfg(unix)]
|
||||
struct DirHandles([std::fs::File; 2]);
|
||||
|
||||
#[cfg(unix)]
|
||||
impl DirHandles {
|
||||
fn open(dirs: &[PathBuf; 2]) -> Option<Self> {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.read(true);
|
||||
// Any other descriptor makes a normal unmount (Eject) fail because the volume is busy.
|
||||
#[cfg(target_os = "macos")]
|
||||
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_EVTONLY);
|
||||
Some(Self([options.open(&dirs[0]).ok()?, options.open(&dirs[1]).ok()?]))
|
||||
}
|
||||
|
||||
fn is_current(&self, dirs: &[PathBuf; 2]) -> bool {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
self.0.iter().zip(dirs).all(|(held, dir)| match (held.metadata(), std::fs::metadata(dir)) {
|
||||
(Ok(held), Ok(now)) => (held.dev(), held.ino()) == (now.dev(), now.ino()),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ponytail: existence only, because an open directory handle blocks renaming it on Windows.
|
||||
// A volume that returns between two calls goes unnoticed; compare file ids if that matters.
|
||||
#[cfg(not(unix))]
|
||||
struct DirHandles;
|
||||
|
||||
#[cfg(not(unix))]
|
||||
impl DirHandles {
|
||||
fn open(dirs: &[PathBuf; 2]) -> Option<Self> {
|
||||
Self.is_current(dirs).then_some(Self)
|
||||
}
|
||||
|
||||
fn is_current(&self, dirs: &[PathBuf; 2]) -> bool {
|
||||
dirs.iter().all(|dir| dir.is_dir())
|
||||
}
|
||||
}
|
||||
|
||||
/// The pack directory's modification time: adding or removing a pack file
|
||||
/// updates it. `None` when the directory can't be read.
|
||||
fn pack_stamp(pack_dir: &Path) -> Option<SystemTime> {
|
||||
@@ -77,7 +125,16 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
let common_dir = absolute(repo.common_dir())?;
|
||||
let files = cache_files(&git_dir, &common_dir);
|
||||
let pack_dir = common_dir.join("objects").join("pack");
|
||||
let cache = Cache { stamp: stamp(&files), files, repo: ts, pack_stamp: pack_stamp(&pack_dir), pack_dir };
|
||||
let dirs = [git_dir.clone(), common_dir];
|
||||
let cache = Cache {
|
||||
stamp: stamp(&files),
|
||||
files,
|
||||
repo: Some(ts),
|
||||
handles: DirHandles::open(&dirs),
|
||||
dirs,
|
||||
pack_stamp: pack_stamp(&pack_dir),
|
||||
pack_dir,
|
||||
};
|
||||
Ok(Some(Repo {
|
||||
execution_allowed: std::sync::atomic::AtomicBool::new(false),
|
||||
git_executable: std::sync::RwLock::new(crate::opening_git_executable()),
|
||||
@@ -141,6 +198,8 @@ impl Repo {
|
||||
|
||||
/// A thread-local gitoxide handle; reopened when configuration or packed refs change.
|
||||
/// gitoxide's packed-ref snapshot only reloads for a newer mtime, which a replacement may preserve.
|
||||
/// A volume lost after this returns can still raise SIGBUS in the caller: gitoxide can't read
|
||||
/// packs without mapping them.
|
||||
pub(crate) fn gix(&self) -> IdeResult<gix::Repository> {
|
||||
let _scope = self.execution_scope();
|
||||
self.check_valid()?;
|
||||
@@ -149,12 +208,20 @@ impl Repo {
|
||||
.map_err(gx);
|
||||
}
|
||||
let mut cache = self.inner.lock().unwrap_or_else(|p| p.into_inner());
|
||||
if !cache.handles.as_ref().is_some_and(|handles| handles.is_current(&cache.dirs)) {
|
||||
cache.repo = None;
|
||||
// Before the repository is opened, so that losing the volume meanwhile is noticed.
|
||||
cache.handles = DirHandles::open(&cache.dirs);
|
||||
if cache.handles.is_none() {
|
||||
return Err(self.stale_error());
|
||||
}
|
||||
}
|
||||
let now = stamp(&cache.files);
|
||||
let pack_now = pack_stamp(&cache.pack_dir);
|
||||
if now != cache.stamp || pack_now != cache.pack_stamp {
|
||||
if cache.repo.is_none() || now != cache.stamp || pack_now != cache.pack_stamp {
|
||||
match gix::ThreadSafeRepository::open(&self.git_dir) {
|
||||
Ok(fresh) => {
|
||||
cache.repo = fresh;
|
||||
cache.repo = Some(fresh);
|
||||
cache.stamp = now;
|
||||
cache.pack_stamp = pack_now;
|
||||
}
|
||||
@@ -163,11 +230,14 @@ impl Repo {
|
||||
cache.stamp = now;
|
||||
cache.pack_stamp = pack_now;
|
||||
self.check_valid()?;
|
||||
if cache.repo.is_none() {
|
||||
return Err(gx(e));
|
||||
}
|
||||
tracing::warn!("reopening repository failed: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut repo = cache.repo.to_thread_local();
|
||||
let mut repo = cache.repo.as_ref().ok_or_else(|| self.stale_error())?.to_thread_local();
|
||||
repo.object_cache_size_if_unset(4 * 1024 * 1024);
|
||||
Ok(repo)
|
||||
}
|
||||
@@ -577,3 +647,44 @@ pub(crate) fn is_ignored(repo: &gix::Repository, rel: &str) -> IdeResult<bool> {
|
||||
pub(crate) fn to_string(b: &BStr) -> String {
|
||||
b.to_str_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(cmd: &mut Command) {
|
||||
assert!(cmd.status().unwrap().success(), "{cmd:?}");
|
||||
}
|
||||
|
||||
/// What a remounted volume looks like: every path and modification time is the same, but
|
||||
/// the files that the old handle mapped are gone. `tests/volume_loss.rs` does it for real.
|
||||
#[test]
|
||||
fn a_replaced_repository_is_reopened_even_when_its_stamps_are_the_same() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("repo");
|
||||
let copy = tmp.path().join("copy");
|
||||
run(Command::new("git").args(["init", "-q"]).arg(&root));
|
||||
let repo = discover(&root).unwrap().unwrap();
|
||||
repo.set_execution_allowed(true);
|
||||
let store = || repo.gix().unwrap().objects.store();
|
||||
let stamps = || {
|
||||
let cache = repo.inner.lock().unwrap();
|
||||
(stamp(&cache.files), pack_stamp(&cache.pack_dir))
|
||||
};
|
||||
let (first, before) = (store(), stamps());
|
||||
assert!(Arc::ptr_eq(&first, &store()), "an unchanged repository keeps its handle");
|
||||
|
||||
run(Command::new("cp").arg("-pR").arg(&root).arg(©));
|
||||
std::fs::rename(&root, tmp.path().join("old")).unwrap();
|
||||
assert!(repo.gix().is_err());
|
||||
assert!(repo.gix().is_err());
|
||||
std::fs::rename(©, &root).unwrap();
|
||||
|
||||
assert_eq!(stamps(), before, "the stamps must not be what triggers the reopen");
|
||||
let second = store();
|
||||
assert!(!Arc::ptr_eq(&first, &second), "the handle to the replaced repository was reused");
|
||||
assert!(Arc::ptr_eq(&second, &store()), "it is reopened once");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Status after the repository's volume disappears. A stale memory-mapped pack index raises
|
||||
//! SIGBUS there, which kills the process instead of failing the call.
|
||||
|
||||
#![cfg(target_os = "macos")]
|
||||
|
||||
use ide_vcs::Repo;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn run(cmd: &mut Command) {
|
||||
let out = cmd.output().unwrap();
|
||||
assert!(out.status.success(), "{cmd:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
run(Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "user.name=t", "-c", "[email protected]", "-c", "commit.gpgsign=false"])
|
||||
.args(args));
|
||||
}
|
||||
|
||||
/// A repository whose objects are all packed, with one staged change so that status has
|
||||
/// to read the `HEAD` tree.
|
||||
fn packed_repo(dir: &Path, files: usize) {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
git(dir, &["init", "-q"]);
|
||||
for i in 0..files {
|
||||
std::fs::write(dir.join(format!("f{i}")), format!("{i}\n")).unwrap();
|
||||
}
|
||||
git(dir, &["add", "."]);
|
||||
git(dir, &["commit", "-qm", "init"]);
|
||||
git(dir, &["repack", "-adq"]);
|
||||
git(dir, &["pack-refs", "--all"]);
|
||||
std::fs::write(dir.join("f0"), "changed\n").unwrap();
|
||||
git(dir, &["add", "f0"]);
|
||||
}
|
||||
|
||||
/// An APFS disk image mounted in a temporary directory, detached when dropped.
|
||||
struct Image {
|
||||
tmp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Image {
|
||||
fn new() -> Self {
|
||||
let image = Self { tmp: tempfile::tempdir().unwrap() };
|
||||
std::fs::create_dir(image.mount()).unwrap();
|
||||
run(Command::new("hdiutil")
|
||||
.args(["create", "-quiet", "-size", "200m", "-fs", "APFS", "-volname", "openidea-test"])
|
||||
.arg(image.file()));
|
||||
image.attach();
|
||||
image
|
||||
}
|
||||
|
||||
fn file(&self) -> PathBuf {
|
||||
self.tmp.path().join("t.dmg")
|
||||
}
|
||||
|
||||
fn mount(&self) -> PathBuf {
|
||||
self.tmp.path().join("mnt")
|
||||
}
|
||||
|
||||
fn attach(&self) {
|
||||
run(Command::new("hdiutil")
|
||||
.args(["attach", "-nobrowse", "-quiet", "-mountpoint"])
|
||||
.arg(self.mount())
|
||||
.arg(self.file()));
|
||||
}
|
||||
|
||||
fn force_detach(&self) {
|
||||
run(Command::new("hdiutil").args(["detach", "-force", "-quiet"]).arg(self.mount()));
|
||||
}
|
||||
|
||||
/// Unmounts like Eject does: refused while a process keeps the volume busy.
|
||||
fn unmount(&self) -> Output {
|
||||
Command::new("diskutil").arg("unmount").arg(self.mount()).output().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Image {
|
||||
fn drop(&mut self) {
|
||||
// After a normal unmount the image is still attached, and only a mounted volume can
|
||||
// be detached by its path.
|
||||
let _ = Command::new("hdiutil")
|
||||
.args(["attach", "-nobrowse", "-quiet", "-mountpoint"])
|
||||
.arg(self.mount())
|
||||
.arg(self.file())
|
||||
.output();
|
||||
let _ = Command::new("hdiutil").args(["detach", "-force", "-quiet"]).arg(self.mount()).output();
|
||||
}
|
||||
}
|
||||
|
||||
/// Run with `cargo test -p ide-vcs --test volume_loss -- --ignored`: needs `hdiutil`.
|
||||
#[test]
|
||||
#[ignore = "mounts and force-detaches a disk image"]
|
||||
fn a_force_detached_volume_does_not_crash_status() {
|
||||
let image = Image::new();
|
||||
let root = image.mount().join("repo");
|
||||
packed_repo(&root, 5000);
|
||||
// Start with cold pages, as after a real reconnect.
|
||||
image.force_detach();
|
||||
image.attach();
|
||||
|
||||
let repo = Repo::discover(&root).unwrap().unwrap();
|
||||
repo.set_execution_allowed(true);
|
||||
assert_eq!(repo.status().unwrap().len(), 1);
|
||||
|
||||
image.force_detach();
|
||||
for _ in 0..2 {
|
||||
assert!(repo.status().is_err());
|
||||
assert!(repo.head().is_err());
|
||||
}
|
||||
image.attach();
|
||||
assert_eq!(repo.status().unwrap().len(), 1);
|
||||
|
||||
// Gone and back between two calls: same path, same modification times.
|
||||
image.force_detach();
|
||||
image.attach();
|
||||
assert_eq!(repo.status().unwrap().len(), 1);
|
||||
assert!(repo.head().unwrap().1.is_some());
|
||||
}
|
||||
|
||||
/// Only the descriptors: this reads nothing, so gitoxide has not mapped any packs yet.
|
||||
#[test]
|
||||
#[ignore = "mounts and unmounts a disk image"]
|
||||
fn the_directory_descriptors_do_not_block_a_normal_unmount() {
|
||||
let image = Image::new();
|
||||
let root = image.mount().join("repo");
|
||||
packed_repo(&root, 3);
|
||||
image.force_detach();
|
||||
image.attach();
|
||||
|
||||
let repo = Repo::discover(&root).unwrap().unwrap();
|
||||
repo.set_execution_allowed(true);
|
||||
let out = image.unmount();
|
||||
assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||
assert!(repo.status().is_err());
|
||||
image.attach();
|
||||
assert_eq!(repo.status().unwrap().len(), 1);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -43,3 +43,48 @@ test("Show Usages distinguishes same-named files without losing the line or snip
|
||||
await expect(checkout.getByTitle("/dev/acme-api/packages/checkout/src/Routes.ts", { exact: true })).toBeVisible();
|
||||
await expect(rows.filter({ hasText: "Worker.ts" }).getByText("src", { exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("Show Usages resizes from its corner, the list fills it, and it reopens at that size", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1200, height: 800 });
|
||||
const show = () =>
|
||||
page.evaluate(async () => {
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ "/src/features/code-insight/usages.ts");
|
||||
const path = "/dev/app/src/Main.ts";
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 30, y: 60 },
|
||||
symbol: "run",
|
||||
groups: [
|
||||
{
|
||||
path,
|
||||
usages: Array.from({ length: 40 }, (_, line) => ({ path, line, col: 0, endCol: 3, text: "run();" })),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
await show();
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
const list = popup.getByRole("listbox", { name: "Usages" });
|
||||
const before = (await popup.boundingBox())!;
|
||||
const listBefore = (await list.boundingBox())!;
|
||||
const corner = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
|
||||
await page.mouse.move(corner.x + corner.width / 2, corner.y + corner.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(corner.x + 200, corner.y + 150, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
const after = (await popup.boundingBox())!;
|
||||
expect(after.width).toBeGreaterThan(before.width + 150);
|
||||
expect(after.height).toBeGreaterThan(before.height + 100);
|
||||
// The list, not empty space, takes the added height.
|
||||
expect((await list.boundingBox())!.height).toBeGreaterThan(listBefore.height + 100);
|
||||
await page.screenshot({ path: test.info().outputPath("usages-resized.png") });
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(popup).toHaveCount(0);
|
||||
await show();
|
||||
const reopened = (await popup.boundingBox())!;
|
||||
expect(Math.abs(reopened.width - after.width)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(reopened.height - after.height)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -440,6 +440,8 @@ lsp_java_move_destinations trusted project_host bin
|
||||
lsp_java_source_types trusted project_host bindings async
|
||||
lsp_library_sources trusted project_host bindings async
|
||||
lsp_message_request_answer trusted project_host bindings sync
|
||||
lsp_move_to_file_targets trusted project_host bindings async
|
||||
lsp_open_typescript_file trusted project_host bindings async
|
||||
lsp_prepare_rename trusted project_host bindings async
|
||||
lsp_prepare_type_hierarchy trusted project_host bindings async
|
||||
lsp_references trusted project_host bindings async
|
||||
@@ -458,6 +460,7 @@ lsp_signature_info trusted project_host bin
|
||||
lsp_snapshot_completion trusted project_host bindings async
|
||||
lsp_snapshot_diagnostics trusted project_host bindings async
|
||||
lsp_source_action_text trusted project_host bindings async
|
||||
lsp_source_definition trusted project_host bindings async
|
||||
lsp_stop trusted project_host bindings async
|
||||
lsp_switch_source_header trusted project_host bindings async
|
||||
lsp_type_hierarchy trusted project_host bindings async
|
||||
@@ -613,6 +616,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
|
||||
|
||||
+89
-5
@@ -1145,6 +1145,13 @@ export const commands = {
|
||||
* language server runs: the question waits in that process, a remote project's server included.
|
||||
*/
|
||||
lspMessageRequestAnswer: (id: number, choice: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_message_request_answer", { id, choice })),
|
||||
/**
|
||||
* The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with
|
||||
* `cancel_request(request)`.
|
||||
*/
|
||||
lspMoveToFileTargets: (request: RequestId, doc: DocId, command: Command) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("lsp_move_to_file_targets", { request, doc, command })),
|
||||
/** Has vtsls open the document's `tsconfig.json` / `jsconfig.json` or the TS Server log. */
|
||||
lspOpenTypescriptFile: (doc: DocId, what: TypeScriptFile) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_open_typescript_file", { doc, what })),
|
||||
lspPrepareRename: (doc: DocId, pos: Pos) => typedError<{
|
||||
start: Pos,
|
||||
end: Pos,
|
||||
@@ -1208,6 +1215,11 @@ export const commands = {
|
||||
lspSnapshotCompletion: (path: string, text: string, pos: Pos, request: RequestId) => typedError<CompletionItem[], IdeError>(__TAURI_INVOKE("lsp_snapshot_completion", { path, text, pos, request })),
|
||||
lspSnapshotDiagnostics: (path: string, text: string, request: RequestId) => typedError<Diagnostic[], IdeError>(__TAURI_INVOKE("lsp_snapshot_diagnostics", { path, text, request })),
|
||||
lspSourceActionText: (path: string, text: string, kind: string, request: RequestId) => typedError<TextEdit[], IdeError>(__TAURI_INVOKE("lsp_source_action_text", { path, text, kind, request })),
|
||||
/**
|
||||
* Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
|
||||
* instead of its `.d.ts`. Cancel with `cancel_request(request)`.
|
||||
*/
|
||||
lspSourceDefinition: (request: RequestId, doc: DocId, pos: Pos) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_source_definition", { request, doc, pos })),
|
||||
/** Stops a language server; it starts again when a file it serves is opened. */
|
||||
lspStop: (server: ServerId) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_stop", { server })),
|
||||
/**
|
||||
@@ -1744,6 +1756,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 +10158,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).
|
||||
@@ -10620,7 +10647,9 @@ export type LanguageServerSettings_Serialize = {
|
||||
codeActionKinds?: string[] | null,
|
||||
};
|
||||
|
||||
export type LanguagesSettings = {
|
||||
export type LanguagesSettings = LanguagesSettings_Serialize | LanguagesSettings_Deserialize;
|
||||
|
||||
export type LanguagesSettings_Deserialize = {
|
||||
/** Explicit plugin formatter, by language id. Empty entries use the normal formatter policy. */
|
||||
pluginFormatters?: { [key in string]: string },
|
||||
python?: PythonSettings,
|
||||
@@ -10628,7 +10657,7 @@ export type LanguagesSettings = {
|
||||
php?: PhpSettings,
|
||||
rust?: RustSettings,
|
||||
go?: GoSettings,
|
||||
typescript?: TypeScriptSettings,
|
||||
typescript?: TypeScriptSettings_Deserialize,
|
||||
prettier?: ExternalFormatterSettings,
|
||||
oxfmt?: ExternalFormatterSettings,
|
||||
biome?: ExternalFormatterSettings,
|
||||
@@ -10644,6 +10673,30 @@ export type LanguagesSettings = {
|
||||
flutter?: FlutterSettings,
|
||||
};
|
||||
|
||||
export type LanguagesSettings_Serialize = {
|
||||
/** Explicit plugin formatter, by language id. Empty entries use the normal formatter policy. */
|
||||
pluginFormatters: { [key in string]: string },
|
||||
python: PythonSettings,
|
||||
node: NodeSettings,
|
||||
php: PhpSettings,
|
||||
rust: RustSettings,
|
||||
go: GoSettings,
|
||||
typescript: TypeScriptSettings_Serialize,
|
||||
prettier: ExternalFormatterSettings,
|
||||
oxfmt: ExternalFormatterSettings,
|
||||
biome: ExternalFormatterSettings,
|
||||
/** dprint formats every file its configuration covers: `languages` is unused. */
|
||||
dprint: ExternalFormatterSettings,
|
||||
ruff: ExternalFormatterSettings,
|
||||
black: ExternalFormatterSettings,
|
||||
java: JavaSettings,
|
||||
ruby: RubySettings,
|
||||
markdown: MarkdownSettings,
|
||||
arduino: ArduinoSettings,
|
||||
zig: ZigSettings,
|
||||
flutter: FlutterSettings,
|
||||
};
|
||||
|
||||
export type LargeCommitFile = {
|
||||
path: IpcPath,
|
||||
size: number,
|
||||
@@ -14718,7 +14771,7 @@ export type Settings_Deserialize = {
|
||||
/** System Settings › HTTP Proxy (global only). */
|
||||
proxy?: ProxySettings,
|
||||
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
|
||||
languages?: LanguagesSettings,
|
||||
languages?: LanguagesSettings_Deserialize,
|
||||
/** Project Structure: source / test / resource / excluded folders (project-relative). */
|
||||
projectStructure?: ProjectStructureSettings,
|
||||
/** Version Control (Git, Commit, Confirmation, Issue Navigation). */
|
||||
@@ -14799,7 +14852,7 @@ export type Settings_Serialize = {
|
||||
/** System Settings › HTTP Proxy (global only). */
|
||||
proxy: ProxySettings,
|
||||
/** Interpreters / toolchains per language (Python, Node.js, Rust, Go, TypeScript). */
|
||||
languages: LanguagesSettings,
|
||||
languages: LanguagesSettings_Serialize,
|
||||
/** Project Structure: source / test / resource / excluded folders (project-relative). */
|
||||
projectStructure: ProjectStructureSettings,
|
||||
/** Version Control (Git, Commit, Confirmation, Issue Navigation). */
|
||||
@@ -15952,7 +16005,15 @@ export type TrustStatus = {
|
||||
decided: boolean,
|
||||
};
|
||||
|
||||
export type TypeScriptSettings = {
|
||||
/** tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it. */
|
||||
export type TsServerLog = "off" | "terse" | "normal" | "requestTime" | "verbose";
|
||||
|
||||
/** A file vtsls opens for a document: its project's configuration or the TS Server log. */
|
||||
export type TypeScriptFile = "projectConfig" | "serverLog";
|
||||
|
||||
export type TypeScriptSettings = TypeScriptSettings_Serialize | TypeScriptSettings_Deserialize;
|
||||
|
||||
export type TypeScriptSettings_Deserialize = {
|
||||
/**
|
||||
* `bundled` (the server's own TypeScript), `workspace` (`node_modules/typescript`),
|
||||
* or a path to a TypeScript `lib` directory.
|
||||
@@ -15964,6 +16025,8 @@ export type TypeScriptSettings = {
|
||||
* vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
*/
|
||||
tsserverMaxMemory?: number,
|
||||
/** tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it. */
|
||||
tsserverLog?: TsServerLog,
|
||||
/**
|
||||
* Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
* `tsconfig.json` reports the errors of files that are not open.
|
||||
@@ -15971,6 +16034,27 @@ export type TypeScriptSettings = {
|
||||
watchProblems?: boolean,
|
||||
};
|
||||
|
||||
export type TypeScriptSettings_Serialize = {
|
||||
/**
|
||||
* `bundled` (the server's own TypeScript), `workspace` (`node_modules/typescript`),
|
||||
* or a path to a TypeScript `lib` directory.
|
||||
*/
|
||||
version: string,
|
||||
/**
|
||||
* tsserver heap limit in MB. `0` = automatic: 8192 when vtsls hosts the Vue
|
||||
* plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
|
||||
* vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
*/
|
||||
tsserverMaxMemory: number,
|
||||
/** tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it. */
|
||||
tsserverLog: TsServerLog,
|
||||
/**
|
||||
* Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
* `tsconfig.json` reports the errors of files that are not open.
|
||||
*/
|
||||
watchProblems: boolean,
|
||||
};
|
||||
|
||||
/** A misspelt word. */
|
||||
export type Typo = {
|
||||
/** UTF-16 range of the word. */
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -627,10 +627,14 @@ describe("EditorController", () => {
|
||||
expect(openFilePaths(useTabs.getState())).toEqual(["/p/a.ts"]);
|
||||
});
|
||||
|
||||
it("offers Find Usages immediately before Go To in the editor context menu", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "one\n" }));
|
||||
// Go to Source Definition is vtsls': only in JavaScript and TypeScript files.
|
||||
it.each([
|
||||
["/p/a.ts", ["navigate.sourceDefinition"]],
|
||||
["/p/a.py", []],
|
||||
])("offers Find Usages immediately before Go To in the editor context menu (%s)", async (path, typescript) => {
|
||||
ctrl = new EditorController(createMemoryBackend({ [path]: "one\n" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
await ctrl.openFile(path, { focus: false });
|
||||
const slot = ctrl.activeSlot!;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
@@ -646,6 +650,7 @@ describe("EditorController", () => {
|
||||
"navigate.declaration",
|
||||
"navigate.implementation",
|
||||
"navigate.typeDeclaration",
|
||||
...typescript,
|
||||
"navigate.superMethod",
|
||||
"navigate.relatedSymbol",
|
||||
"navigate.gotoTest",
|
||||
|
||||
@@ -1007,6 +1007,9 @@ export class EditorController implements SlotHost {
|
||||
{ kind: "action", action: "navigate.declaration", label: "Declaration or Usages" },
|
||||
{ kind: "action", action: "navigate.implementation", label: "Implementation(s)" },
|
||||
{ kind: "action", action: "navigate.typeDeclaration", label: "Type Declaration" },
|
||||
...(/^(java|type)script(react)?$/.test(slot.model.getMeta()?.language ?? "")
|
||||
? [{ kind: "action" as const, action: "navigate.sourceDefinition", label: "Source Definition" }]
|
||||
: []),
|
||||
{ kind: "action", action: "navigate.superMethod", label: "Super Method" },
|
||||
{ kind: "action", action: "navigate.relatedSymbol", label: "Related Symbol…" },
|
||||
{ kind: "action", action: "navigate.gotoTest", label: "Test" },
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** Actions of the LSP editor layer (ids from keymaps/intellij-macos.ts). */
|
||||
import { gotoSourceDefinition, openProjectConfig, openTsServerLog, TYPESCRIPT_WHEN } from "./typescriptCommands";
|
||||
import { generateActionIcon, isGenerateAction } from "./generate";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
@@ -435,6 +436,18 @@ export function registerLspActions(): () => void {
|
||||
editorAction("navigate.typeDeclaration", "Go to Type Declaration", "Navigate", (v) =>
|
||||
gotoTargets(v, "typeDefinition"),
|
||||
),
|
||||
editorAction("navigate.sourceDefinition", "Go to Source Definition", "Navigate", gotoSourceDefinition, {
|
||||
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
|
||||
keywords: ["implementation", "javascript", "node_modules", "d.ts"],
|
||||
}),
|
||||
editorAction("typescript.goToProjectConfig", "Go to Project Configuration", "TypeScript", openProjectConfig, {
|
||||
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
|
||||
keywords: ["tsconfig", "jsconfig"],
|
||||
}),
|
||||
editorAction("typescript.openTsServerLog", "Open TS Server Log", "TypeScript", openTsServerLog, {
|
||||
when: `${EDITOR_WHEN} && (${TYPESCRIPT_WHEN})`,
|
||||
keywords: ["tsserver", "vtsls", "log"],
|
||||
}),
|
||||
editorAction("navigate.nextError", "Next Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, 1)),
|
||||
editorAction("navigate.prevError", "Previous Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, -1)),
|
||||
editorAction("code.showErrorDescription", "Error Description", "View", showErrorDescription, {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { MOVE_TO_FILE_COMMAND, moveToFile } from "./typescriptCommands";
|
||||
import { serverCodeLenses } from "./serverCodeLens";
|
||||
/**
|
||||
* LSP-backed editor features: completion, diagnostics, hover / quick docs,
|
||||
@@ -134,6 +135,7 @@ export function activate(): () => void {
|
||||
registerOverlay({ id: "editor-lsp.extractInterfaceDialog", component: ExtractInterfaceDialog }),
|
||||
registerOverlay({ id: "editor-lsp.memberChooser", component: MemberChooserDialog }),
|
||||
registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand),
|
||||
registerClientCommand(MOVE_TO_FILE_COMMAND, moveToFile),
|
||||
registerEditorBanner(outsideProjectBanner),
|
||||
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
|
||||
// IDEA's Documentation tool window: right side, listed once F1 moved documentation there.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Command } from "@/bindings";
|
||||
|
||||
const lspMoveToFileTargets = vi.fn(async (_request: number, _doc: number, _command: Command) => ({
|
||||
status: "ok" as const,
|
||||
data: ["/p/src/util.ts", "/p/src/strings.ts", "/p/src/app.ts"],
|
||||
}));
|
||||
const lspExecuteCommand = vi.fn(async (_doc: number, _command: Command) => ({ status: "ok" as const, data: null }));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const actual = await orig<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspMoveToFileTargets, lspExecuteCommand } };
|
||||
});
|
||||
vi.mock("@/editor/api", async (orig) => ({
|
||||
...(await orig<typeof import("@/editor/api")>()),
|
||||
whenSynced: async () => {},
|
||||
}));
|
||||
const popups: { items: { label: string; run: () => void }[] }[] = [];
|
||||
vi.mock("./popupStore", async (orig) => ({
|
||||
...(await orig<typeof import("./popupStore")>()),
|
||||
caretAnchor: () => ({ x: 0, y: 0 }),
|
||||
openPopup: (p: (typeof popups)[number]) => popups.push(p),
|
||||
}));
|
||||
vi.mock("./lsp", async (orig) => ({
|
||||
...(await orig<typeof import("./lsp")>()),
|
||||
docOf: () => ({ doc: 7, path: "/p/src/util.ts", language: "typescript" }),
|
||||
}));
|
||||
|
||||
const { moveToFile } = await import("./typescriptCommands");
|
||||
|
||||
describe("Move to File", () => {
|
||||
it("offers tsserver's files but the source, then runs the command with the chosen one", async () => {
|
||||
const action = { name: "Move to file", kind: "refactor.move.file" };
|
||||
const range = { start: { line: 6, character: 16 }, end: { line: 6, character: 16 } };
|
||||
const args = [action, "file:///p/src/util.ts", range];
|
||||
const view = { state: { selection: { main: { head: 0 } } } } as never;
|
||||
expect(await moveToFile(view, args)).toBe(true);
|
||||
expect(lspMoveToFileTargets.mock.calls[0]![2].arguments).toEqual(args);
|
||||
const items = popups[0]!.items;
|
||||
expect(items.map((i) => i.label)).toEqual(["strings.ts", "app.ts", "Choose File…"]);
|
||||
items[0]!.run();
|
||||
await vi.waitFor(() => expect(lspExecuteCommand).toHaveBeenCalled());
|
||||
expect(lspExecuteCommand.mock.calls[0]).toEqual([
|
||||
7,
|
||||
{
|
||||
title: "Move to file",
|
||||
command: "_typescript.moveToFileRefactoring",
|
||||
arguments: [...args, "/p/src/strings.ts"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* vtsls' own TypeScript commands (`workspace/executeCommand`): Go to Source Definition, Go to
|
||||
* Project Configuration, Open TS Server Log and the target file of Move to File. vtsls opens the
|
||||
* configuration and the log itself (`window/showDocument`). typescript-language-server, TypeScript 7
|
||||
* and the Vue / Astro servers have none of them.
|
||||
*/
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import type { Command, Location } from "@/bindings";
|
||||
import { whenSynced } from "@/editor/api";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { basename, dirname, relativePath, useProject } from "@/platform/project";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { fileIconName } from "@/ui";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { showHint } from "./hint";
|
||||
import { docOf, isUnavailable, lspRequest, reportLspError } from "./lsp";
|
||||
import { locationItems, navigateTo } from "./navigation";
|
||||
import { caretAnchor, openPopup } from "./popupStore";
|
||||
import { offsetToPos } from "./positions";
|
||||
|
||||
export const TYPESCRIPT_LANGUAGES = ["typescript", "typescriptreact", "javascript", "javascriptreact"];
|
||||
export const TYPESCRIPT_WHEN = TYPESCRIPT_LANGUAGES.map((id) => `editorLangId == ${id}`).join(" || ");
|
||||
export const MOVE_TO_FILE_COMMAND = "_typescript.moveToFileRefactoring";
|
||||
|
||||
function report(view: EditorView, e: unknown) {
|
||||
if (isUnavailable(e)) showHint(view, "This needs the vtsls TypeScript language server", { tone: "error" });
|
||||
else reportLspError(view, e, true);
|
||||
}
|
||||
|
||||
/** Navigate › Source Definition: the library's JavaScript instead of its `.d.ts`. */
|
||||
export async function gotoSourceDefinition(view: EditorView) {
|
||||
const ctx = docOf(view);
|
||||
if (!ctx) return;
|
||||
const head = view.state.selection.main.head;
|
||||
let locs: Location[];
|
||||
try {
|
||||
await whenSynced(view);
|
||||
const pos = offsetToPos(view.state.doc, head);
|
||||
locs = await lspRequest(() => commands.lspSourceDefinition(nextRequestId(), ctx.doc, pos));
|
||||
} catch (e) {
|
||||
report(view, e);
|
||||
return;
|
||||
}
|
||||
if (!locs.length) {
|
||||
showHint(view, "Cannot find source definition", { tone: "error" });
|
||||
return;
|
||||
}
|
||||
if (locs.length === 1) {
|
||||
await navigateTo(locs[0]!);
|
||||
return;
|
||||
}
|
||||
openPopup({
|
||||
kind: "list",
|
||||
anchor: caretAnchor(view, head),
|
||||
title: tx("Choose Source Definition"),
|
||||
items: await locationItems(locs),
|
||||
});
|
||||
}
|
||||
|
||||
/** Opens the `tsconfig.json` / `jsconfig.json` the file belongs to. */
|
||||
export async function openProjectConfig(view: EditorView) {
|
||||
const ctx = docOf(view);
|
||||
if (!ctx) return;
|
||||
try {
|
||||
await lspRequest(() => commands.lspOpenTypescriptFile(ctx.doc, "projectConfig"));
|
||||
} catch (e) {
|
||||
report(view, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the TS Server log, after offering to turn logging on (which restarts vtsls). */
|
||||
export async function openTsServerLog(view: EditorView) {
|
||||
const ctx = docOf(view);
|
||||
if (!ctx) return;
|
||||
const level = useProject.getState().settings?.languages?.typescript?.tsserverLog ?? "off";
|
||||
if (level === "off") {
|
||||
const ok = await confirm({
|
||||
title: "Open TS Server Log",
|
||||
message: tx("TS Server logging is off. Turn on verbose logging (typescript.tsserver.log) and restart vtsls?"),
|
||||
ok: "Enable Logging",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const settings = await call(commands.settingsSet("global", "languages.typescript.tsserverLog", '"verbose"'));
|
||||
useProject.setState({ settings });
|
||||
} catch (e) {
|
||||
reportLspError(view, e, true);
|
||||
return;
|
||||
}
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: "TS Server logging is on",
|
||||
body: tx("vtsls restarts with logging. Run Open TS Server Log again to open the log."),
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await lspRequest(() => commands.lspOpenTypescriptFile(ctx.doc, "serverLog"));
|
||||
} catch (e) {
|
||||
report(view, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* vtsls' Move to File code action (`[action, uri, range]`): asks for the target file, tsserver's
|
||||
* suggestions first, then runs the command with it appended. vtsls applies the moves and import
|
||||
* updates as one workspace edit (one Undo).
|
||||
*/
|
||||
export async function moveToFile(view: EditorView, args: readonly unknown[]): Promise<boolean> {
|
||||
const ctx = docOf(view);
|
||||
if (!ctx) return false;
|
||||
const command = (target?: string): Command => ({
|
||||
title: "Move to file",
|
||||
command: MOVE_TO_FILE_COMMAND,
|
||||
// The arguments are JSON values (the bindings type them as strings).
|
||||
arguments: (target === undefined ? args : [...args, target]) as string[],
|
||||
});
|
||||
let files: string[];
|
||||
try {
|
||||
await whenSynced(view);
|
||||
files = await lspRequest(() => commands.lspMoveToFileTargets(nextRequestId(), ctx.doc, command()));
|
||||
} catch (e) {
|
||||
report(view, e);
|
||||
return true;
|
||||
}
|
||||
const move = async (target: string) => {
|
||||
try {
|
||||
await whenSynced(view);
|
||||
await lspRequest(() => commands.lspExecuteCommand(ctx.doc, command(target)));
|
||||
} catch (e) {
|
||||
if (!isCancelled(e)) report(view, e);
|
||||
}
|
||||
};
|
||||
const root = useProject.getState().project?.root ?? "";
|
||||
openPopup({
|
||||
kind: "list",
|
||||
anchor: caretAnchor(view, view.state.selection.main.head),
|
||||
title: tx("Move to File"),
|
||||
items: [
|
||||
...files
|
||||
.filter((f) => f !== ctx.path)
|
||||
.map((f, i) => ({
|
||||
id: `${i}`,
|
||||
label: basename(f),
|
||||
detail: relativePath(root, f),
|
||||
icon: fileIconName(basename(f), f),
|
||||
run: () => void move(f),
|
||||
})),
|
||||
{
|
||||
id: "choose",
|
||||
label: tx("Choose File…"),
|
||||
run: () =>
|
||||
void choosePath({ directory: false, title: tx("Move to File"), defaultPath: dirname(ctx.path) }).then((f) => {
|
||||
if (f && f !== ctx.path) void move(f);
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -70,9 +70,20 @@
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: var(--usages-height);
|
||||
min-height: var(--usages-min-height);
|
||||
padding: 2px 0;
|
||||
box-sizing: content-box;
|
||||
}
|
||||
/* Resized: the list takes the height the preview leaves. */
|
||||
.popup[data-resized] .focus {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
.popup[data-resized] .body {
|
||||
flex: 1 1 0;
|
||||
height: auto;
|
||||
min-height: var(--usages-min-height);
|
||||
}
|
||||
.body > * {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* filters), an optional code preview and "Open in Find Window", which moves
|
||||
* the found usages to the Find Usages tool window.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
|
||||
import { create } from "zustand";
|
||||
import clsx from "clsx";
|
||||
import { EditorState, StateEffect, StateField } from "@codemirror/state";
|
||||
@@ -55,6 +55,30 @@ export function setUsagesPopupPreview(preview: boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
const SIZE_KEY = "openidea.usages.popupSize.v1";
|
||||
const MIN_WIDTH = 360;
|
||||
const MIN_HEIGHT = 160;
|
||||
|
||||
/** The size the popup was last resized to, if any (IDEA remembers Show Usages' size). */
|
||||
export function loadUsagesPopupSize(): { w: number; h: number } | null {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(SIZE_KEY) ?? "null") as { w?: unknown; h?: unknown } | null;
|
||||
return typeof saved?.w === "number" && typeof saved.h === "number" && Number.isFinite(saved.w + saved.h)
|
||||
? { w: Math.max(MIN_WIDTH, saved.w), h: Math.max(MIN_HEIGHT, saved.h) }
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveUsagesPopupSize(size: { w: number; h: number }) {
|
||||
try {
|
||||
localStorage.setItem(SIZE_KEY, JSON.stringify(size));
|
||||
} catch {
|
||||
// storage unavailable: the size lasts while the popup is open
|
||||
}
|
||||
}
|
||||
|
||||
/** Usages whose file name or line text contains the typed text (case-insensitive). */
|
||||
export function filterUsages(items: readonly Usage[], filter: string): Usage[] {
|
||||
const q = filter.trim().toLowerCase();
|
||||
@@ -102,6 +126,7 @@ function UsagesPopupInner() {
|
||||
[all, filter, accessOptions],
|
||||
);
|
||||
const [active, setActive] = useState(0);
|
||||
const [initialSize] = useState(loadUsagesPopupSize);
|
||||
const current = Math.min(active, items.length - 1);
|
||||
const total = usageCount(groups);
|
||||
const rowCount = Math.max(1, Math.min(14, items.length));
|
||||
@@ -157,7 +182,18 @@ function UsagesPopupInner() {
|
||||
|
||||
const keys = shortcutLabel("find.usages");
|
||||
return (
|
||||
<Popup open anchor={anchor} onClose={close} aria-label="Usages" className={styles.popup}>
|
||||
<Popup
|
||||
open
|
||||
anchor={anchor}
|
||||
onClose={close}
|
||||
aria-label="Usages"
|
||||
className={styles.popup}
|
||||
resizable="both"
|
||||
minWidth={MIN_WIDTH}
|
||||
minHeight={MIN_HEIGHT}
|
||||
initialSize={initialSize}
|
||||
onResized={saveUsagesPopupSize}
|
||||
>
|
||||
<div
|
||||
className={styles.focus}
|
||||
tabIndex={0}
|
||||
@@ -221,7 +257,12 @@ function UsagesPopupInner() {
|
||||
)}
|
||||
<div
|
||||
className={styles.body}
|
||||
style={{ height: rowCount * rowHeight, minHeight: `min(${Math.min(rowCount, 3) * rowHeight}px, 18vh)` }}
|
||||
style={
|
||||
{
|
||||
"--usages-height": `${rowCount * rowHeight}px`,
|
||||
"--usages-min-height": `min(${Math.min(rowCount, 3) * rowHeight}px, 18vh)`,
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
<List
|
||||
items={items}
|
||||
|
||||
@@ -109,6 +109,21 @@ describe("Show Usages popup", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("is resizable and opens at the size it was left at", () => {
|
||||
localStorage.setItem("openidea.usages.popupSize.v1", JSON.stringify({ w: 900, h: 120 }));
|
||||
try {
|
||||
open();
|
||||
expect(screen.getByRole("separator", { name: "Resize" })).toBeInTheDocument();
|
||||
const popup = screen.getByRole("dialog", { name: "Usages" });
|
||||
expect(popup).toHaveAttribute("data-resized");
|
||||
// Clamped to the minimum height.
|
||||
expect(popup.style.width).toBe("900px");
|
||||
expect(popup.style.height).toBe("160px");
|
||||
} finally {
|
||||
localStorage.removeItem("openidea.usages.popupSize.v1");
|
||||
}
|
||||
});
|
||||
|
||||
it("the preview pane toggles", () => {
|
||||
open();
|
||||
expect(screen.queryByRole("region", { name: "Preview" })).toBeNull();
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -738,9 +738,18 @@ export function MavenPage() {
|
||||
// ---------------------------------------------------------------------------
|
||||
// TypeScript
|
||||
|
||||
const LOG_LEVELS: SelectOption[] = [
|
||||
{ value: "off", label: "Off" },
|
||||
{ value: "terse", label: "Terse" },
|
||||
{ value: "normal", label: "Normal" },
|
||||
{ value: "requestTime", label: "Request time" },
|
||||
{ value: "verbose", label: "Verbose" },
|
||||
];
|
||||
|
||||
export function TypeScriptPage() {
|
||||
const [version, setVersion] = useSetting<string>("languages.typescript.version");
|
||||
const [memory, setMemory] = useSetting<number>("languages.typescript.tsserverMaxMemory");
|
||||
const [log, setLog] = useSetting<string>("languages.typescript.tsserverLog");
|
||||
const { list } = useDetected("typeScript");
|
||||
const workspace = list.find((s) => s.source === "workspace");
|
||||
const options = useMemo<SelectOption[]>(() => {
|
||||
@@ -798,6 +807,12 @@ export function TypeScriptPage() {
|
||||
aria-label="tsserver memory limit"
|
||||
/>
|
||||
</Row>
|
||||
<Row
|
||||
label="tsserver log"
|
||||
hint="tsserver's log (typescript.tsserver.log), opened by TypeScript: Open TS Server Log. Changing it restarts vtsls; Off stops writing it."
|
||||
>
|
||||
<Select value={log ?? "off"} options={LOG_LEVELS} onChange={setLog} aria-label="tsserver log" />
|
||||
</Row>
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -398,7 +398,7 @@ export const LANGUAGE_PAGES: PageSpec[] = [
|
||||
title: "TypeScript",
|
||||
group: LANGUAGES_GROUP,
|
||||
order: 405,
|
||||
keywords: ["typescript version", "tsdk", "tsserver", "node_modules", "vtsls"],
|
||||
keywords: ["typescript version", "tsdk", "tsserver", "node_modules", "vtsls", "tsserver log"],
|
||||
component: TypeScriptPage,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -206,6 +206,7 @@ describe(":action ids", () => {
|
||||
"editor.splitDown",
|
||||
"vcs.update",
|
||||
"vcs.copyBranchName",
|
||||
"navigate.selectInProjectView",
|
||||
]);
|
||||
const missing = Object.entries(IDEA_ACTIONS).filter(([, id]) => !known.has(id));
|
||||
expect(missing).toEqual([]);
|
||||
|
||||
@@ -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"],
|
||||
@@ -513,6 +515,7 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"db.showDiagram": [],
|
||||
"db.showDiagramPopup": [],
|
||||
"db.selectOpened": [],
|
||||
"project.selectOpenedFile": [],
|
||||
"db.expandAll": [],
|
||||
"db.collapseAll": [],
|
||||
// Find in Files popup (findPopupOpen): after the editor's keys, so these win while it is open.
|
||||
@@ -528,6 +531,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"],
|
||||
|
||||
@@ -307,6 +307,7 @@
|
||||
"menu.navigate.showBookmarks": "Show Bookmarks",
|
||||
"menu.navigate.toggleBookmark": "Toggle Bookmark",
|
||||
"menu.navigate.typeDeclaration": "Type Declaration",
|
||||
"menu.navigate.sourceDefinition": "Source Definition",
|
||||
"menu.navigate.typeHierarchy": "Type Hierarchy",
|
||||
"menu.navigate.superMethod": "Super Method",
|
||||
"menu.navigate.gotoTest": "Test",
|
||||
@@ -465,6 +466,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,31 @@
|
||||
"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 中打开",
|
||||
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围"
|
||||
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围",
|
||||
"Source Definition": "源定义",
|
||||
"Go to Source Definition": "转到源定义",
|
||||
"Go to Project Configuration": "转到项目配置",
|
||||
"Open TS Server Log": "打开 TS Server 日志",
|
||||
"This needs the vtsls TypeScript language server": "此功能需要 vtsls TypeScript 语言服务器",
|
||||
"Cannot find source definition": "找不到源定义",
|
||||
"Choose Source Definition": "选择源定义",
|
||||
"TS Server logging is off. Turn on verbose logging (typescript.tsserver.log) and restart vtsls?": "TS Server 日志已关闭。是否开启详细日志(typescript.tsserver.log)并重启 vtsls?",
|
||||
"Enable Logging": "开启日志",
|
||||
"TS Server logging is on": "TS Server 日志已开启",
|
||||
"vtsls restarts with logging. Run Open TS Server Log again to open the log.": "vtsls 将开启日志并重启。再次运行“打开 TS Server 日志”即可打开日志。",
|
||||
"Move to file": "移动到文件",
|
||||
"Move to File": "移动到文件",
|
||||
"Terse": "简略",
|
||||
"Normal": "普通",
|
||||
"Request time": "请求耗时",
|
||||
"Verbose": "详细",
|
||||
"tsserver log": "tsserver 日志",
|
||||
"tsserver's log (typescript.tsserver.log), opened by TypeScript: Open TS Server Log. Changing it restarts vtsls; Off stops writing it.": "tsserver 的日志(typescript.tsserver.log),由“TypeScript: 打开 TS Server 日志”打开。更改后会重启 vtsls;选“关”则停止写入。",
|
||||
"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} 个(文件夹已不存在)"
|
||||
}
|
||||
@@ -307,6 +307,7 @@
|
||||
"menu.navigate.showBookmarks": "显示书签",
|
||||
"menu.navigate.toggleBookmark": "切换书签",
|
||||
"menu.navigate.typeDeclaration": "类型声明",
|
||||
"menu.navigate.sourceDefinition": "源定义",
|
||||
"menu.navigate.typeHierarchy": "类型层次结构",
|
||||
"menu.navigate.superMethod": "super 方法",
|
||||
"menu.navigate.gotoTest": "测试",
|
||||
@@ -465,6 +466,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": "宏",
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getContext } from "./context";
|
||||
import { executeAction, isActionKeyEnabled, registerAction } from "./actions";
|
||||
import { commands } from "./ipc";
|
||||
import { openProject, relativeDir, useProject } from "./project";
|
||||
import { dirname, openProject, relativeDir, useProject } from "./project";
|
||||
import { confirmProjectTrust } from "./projectTrust";
|
||||
|
||||
vi.mock("./projectTrust", () => ({ confirmProjectTrust: vi.fn(async () => {}) }));
|
||||
@@ -78,3 +78,17 @@ describe("relativeDir", () => {
|
||||
expect(relativeDir("/p/app", "/other/x.ts")).toBe("/other");
|
||||
});
|
||||
});
|
||||
|
||||
describe("dirname", () => {
|
||||
it("splits POSIX paths on / only", () => {
|
||||
expect(dirname("/p/src/util.ts")).toBe("/p/src");
|
||||
expect(dirname("/p/a\\b.ts")).toBe("/p");
|
||||
expect(dirname("/util.ts")).toBe("/");
|
||||
});
|
||||
|
||||
it("splits Windows paths on \\ and /", () => {
|
||||
expect(dirname("C:\\p\\src\\util.ts")).toBe("C:\\p\\src");
|
||||
expect(dirname("C:/p/src/util.ts")).toBe("C:/p/src");
|
||||
expect(dirname("\\\\server\\share\\util.ts")).toBe("\\\\server\\share");
|
||||
});
|
||||
});
|
||||
@@ -122,7 +122,9 @@ export function basename(path: string): string {
|
||||
|
||||
export function dirname(path: string): string {
|
||||
if (isVirtualUri(path)) return virtualParent(path);
|
||||
const i = path.lastIndexOf("/");
|
||||
// Windows paths (`C:\p\src`, `\\server\share`) separate with `\` too; on POSIX it is a file-name character.
|
||||
const windows = /^([A-Za-z]:[\\/]|\\\\)/.test(path);
|
||||
const i = windows ? Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) : path.lastIndexOf("/");
|
||||
return i <= 0 ? "/" : path.slice(0, i);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
Заблокувати користувача