дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 11:18:20 +02:00
Порівняти коміти
21
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1375620b99 | ||
|
|
217bd29860 | ||
|
|
25d6e8ac7c | ||
|
|
280760a5d4 | ||
|
|
b3008be32b | ||
|
|
577193d387 | ||
|
|
449db6baa7 | ||
|
|
ea1f1e54d0 | ||
|
|
4201aad9f9 | ||
|
|
678407f4c0 | ||
|
|
7392bd2547 | ||
|
|
b1f73e3920 | ||
|
|
e8b12dfb51 | ||
|
|
fd828c0ade | ||
|
|
ebc879dc8b | ||
|
|
7096a1c374 | ||
|
|
a1d4d6fb7f | ||
|
|
7596e95b76 | ||
|
|
cc471029d2 | ||
|
|
ee8afe39a2 | ||
|
|
5f606219b2 |
No files matched your search
@@ -222,13 +222,26 @@ impl Shared {
|
||||
if builtin_off { Vec::new() } else { mcp_servers_for(init.mcp_stdio(), &self.paths.project_root) };
|
||||
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
servers.extend(mcp::acp_mcp_servers(&configured, provider, init, overrides));
|
||||
let mut off = mcp::servers_off(&configured, overrides);
|
||||
if builtin_off {
|
||||
off.push(BUILTIN_SERVER.to_owned());
|
||||
}
|
||||
let off = Self::mcp_off(&configured, provider, overrides);
|
||||
McpForSession { servers, off }
|
||||
}
|
||||
|
||||
fn mcp_servers_off_for_session(&self, provider: &str, overrides: &BTreeMap<String, bool>) -> Vec<String> {
|
||||
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
Self::mcp_off(&configured, provider, overrides)
|
||||
}
|
||||
|
||||
fn mcp_off(configured: &[McpServer], provider: &str, overrides: &BTreeMap<String, bool>) -> Vec<String> {
|
||||
let mut off = mcp::servers_off(configured, provider, overrides);
|
||||
if overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false) {
|
||||
off.push(BUILTIN_SERVER.to_owned());
|
||||
off.push(mcp::BUILTIN_MCP_NAME.to_owned());
|
||||
off.sort();
|
||||
off.dedup();
|
||||
}
|
||||
off
|
||||
}
|
||||
|
||||
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
|
||||
let config = self.paths.catalogs.cached(self, provider).config;
|
||||
self.config_for_new_task(config, provider)
|
||||
@@ -1618,6 +1631,26 @@ impl AgentManager {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Recycles idle resumable live sessions (or schedules reload after the running turn) when
|
||||
/// global, workspace, or built-in IDE MCP server settings change.
|
||||
pub fn notify_mcp_servers_changed(&self) {
|
||||
let tasks: Vec<Arc<Task>> = self.tasks.read().values().cloned().collect();
|
||||
for task in tasks {
|
||||
let (archived, busy, has_bg) = {
|
||||
let s = task.state.lock();
|
||||
(s.task.status == AgentStatus::Archived, s.busy, !s.background_tasks.is_empty())
|
||||
};
|
||||
if archived {
|
||||
continue;
|
||||
}
|
||||
if busy || has_bg || !task.permissions.lock().is_empty() {
|
||||
task.mcp_reload_pending.store(true, Ordering::Release);
|
||||
} else {
|
||||
task.recycle_resumable_session();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops every agent (project closed).
|
||||
pub fn shutdown(&self) {
|
||||
for task in self.tasks.read().values() {
|
||||
@@ -2218,9 +2251,16 @@ impl Task {
|
||||
saved: Option<String>,
|
||||
) -> Result<Live, SessionOpenError> {
|
||||
let launch_cwd = cwd.to_path_buf();
|
||||
let spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
|
||||
let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
|
||||
.await
|
||||
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
|
||||
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
|
||||
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
|
||||
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
|
||||
spec.args.push("--disable-mcp-server".into());
|
||||
spec.args.push(name);
|
||||
}
|
||||
}
|
||||
self.stderr.lock().clear();
|
||||
self.config_sent.lock().clear();
|
||||
let weak = Arc::downgrade(self);
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::{
|
||||
};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -89,24 +89,61 @@ fn matches_agent(agents: &[String], provider: &str) -> bool {
|
||||
/// The configured servers off for this session: off by default and not switched on for it, or
|
||||
/// switched off for it. Named so an agent that also loads its own configuration can keep a
|
||||
/// same-named server of it off too. Workspace entries take precedence, as in [`acp_mcp_servers`].
|
||||
pub(crate) fn servers_off(all: &[McpServer], overrides: &BTreeMap<String, bool>) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
let ordered =
|
||||
all.iter().filter(|s| s.scope == McpScope::Workspace).chain(all.iter().filter(|s| s.scope == McpScope::User));
|
||||
let configured: Vec<String> = ordered
|
||||
.filter(|s| seen.insert(s.name.as_str()))
|
||||
.filter(|s| !overrides.get(&s.name).copied().unwrap_or(s.enabled))
|
||||
.map(|s| s.name.clone())
|
||||
.collect();
|
||||
// A server switched off that the IDE doesn't configure may still be the agent's own.
|
||||
let switched = overrides
|
||||
pub(crate) fn servers_off(all: &[McpServer], provider: &str, overrides: &BTreeMap<String, bool>) -> Vec<String> {
|
||||
let mut seen_configured = HashSet::new();
|
||||
let mut enabled_names = HashSet::new();
|
||||
let mut off = BTreeSet::new();
|
||||
|
||||
let ordered = all
|
||||
.iter()
|
||||
.filter(|(name, on)| !**on && name.as_str() != BUILTIN_MCP_NAME && !seen.contains(name.as_str()))
|
||||
.map(|(name, _)| name.clone());
|
||||
let mut off: Vec<String> = configured.into_iter().chain(switched).collect();
|
||||
off.sort();
|
||||
off.dedup();
|
||||
off
|
||||
.filter(|s| s.scope == McpScope::Workspace && !s.unapproved)
|
||||
.chain(all.iter().filter(|s| s.scope == McpScope::User));
|
||||
|
||||
for srv in ordered {
|
||||
if !seen_configured.insert(srv.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let explicit = overrides.get(&srv.name).copied();
|
||||
let matches = explicit == Some(true) || matches_agent(&srv.agents, provider);
|
||||
let active = explicit.unwrap_or(srv.enabled) && matches;
|
||||
if active {
|
||||
enabled_names.insert(srv.name.as_str());
|
||||
} else {
|
||||
off.insert(srv.name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
for srv in all.iter().filter(|s| s.scope == McpScope::Workspace && s.unapproved) {
|
||||
if !enabled_names.contains(srv.name.as_str()) {
|
||||
off.insert(srv.name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// A server switched off that the IDE doesn't configure may still be the agent's own.
|
||||
for (name, &on) in overrides {
|
||||
if !on && name.as_str() != BUILTIN_MCP_NAME && !enabled_names.contains(name.as_str()) {
|
||||
off.insert(name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
off.into_iter().collect()
|
||||
}
|
||||
|
||||
/// Names of MCP servers present in Codex's own TOML configuration files (`~/.codex/config.toml`
|
||||
/// and `<workspace_root>/.codex/config.toml`).
|
||||
pub(crate) fn codex_external_server_names(home_dir: Option<&Path>, workspace_root: &Path) -> BTreeSet<String> {
|
||||
let mut names = BTreeSet::new();
|
||||
let mut paths = Vec::new();
|
||||
if let Some(home) = home_dir {
|
||||
paths.push(home.join(".codex").join("config.toml"));
|
||||
}
|
||||
paths.push(workspace_root.join(".codex").join("config.toml"));
|
||||
for path in paths {
|
||||
if let Ok(text) = std::fs::read_to_string(&path) {
|
||||
names.extend(parse_codex_toml_servers(&text).into_keys());
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Builds the ACP `mcpServers` array for `session/new`, `session/load`, and `session/fork`.
|
||||
@@ -1058,6 +1095,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn servers_off_follow_the_effective_state() {
|
||||
let mut claude_only = configured("claude-only", McpScope::User, true);
|
||||
claude_only.agents = vec!["claude".into()];
|
||||
let mut unapproved_ws = configured("unapproved-ws", McpScope::Workspace, false);
|
||||
unapproved_ws.unapproved = true;
|
||||
|
||||
let all = [
|
||||
configured("default-off", McpScope::User, false),
|
||||
configured("switched-on", McpScope::User, false),
|
||||
@@ -1066,6 +1108,8 @@ mod tests {
|
||||
// The workspace entry decides for its name.
|
||||
configured("both", McpScope::User, true),
|
||||
configured("both", McpScope::Workspace, false),
|
||||
claude_only,
|
||||
unapproved_ws,
|
||||
];
|
||||
let overrides = BTreeMap::from([
|
||||
("switched-on".to_owned(), true),
|
||||
@@ -1073,8 +1117,11 @@ mod tests {
|
||||
("agent-own".to_owned(), false),
|
||||
(BUILTIN_MCP_NAME.to_owned(), false),
|
||||
]);
|
||||
assert_eq!(servers_off(&all, &overrides), ["agent-own", "both", "default-off", "switched-off"]);
|
||||
assert_eq!(servers_off(&all[2..4], &BTreeMap::new()), Vec::<String>::new());
|
||||
assert_eq!(
|
||||
servers_off(&all, "copilot", &overrides),
|
||||
["agent-own", "both", "claude-only", "default-off", "switched-off", "unapproved-ws"]
|
||||
);
|
||||
assert_eq!(servers_off(&all[2..4], "copilot", &BTreeMap::new()), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1671,6 +1671,17 @@ fn session_mcp_servers_become_thread_configuration() {
|
||||
json!({"mcp_servers":{"OpenIDEA":{"command":"/app/openidea","args":["--mcp-stdio","--project","/project"],"env":{"K":"V"}}}})
|
||||
)
|
||||
);
|
||||
let external = std::collections::BTreeSet::from(["linear".to_owned()]);
|
||||
assert_eq!(
|
||||
super::translate::mcp_config_with_external(
|
||||
&json!({
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "mcpServersOff": ["linear", "not-in-codex"] } }
|
||||
}),
|
||||
&external,
|
||||
),
|
||||
Some(json!({ "mcp_servers": { "linear": { "enabled": false } } }))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -923,8 +923,18 @@ fn str_of(v: &Value, key: &str) -> Option<String> {
|
||||
|
||||
/// Session-scoped MCP configuration, carried in thread/start, resume and fork.
|
||||
pub(super) fn mcp_config(params: &Value) -> Option<Value> {
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(std::path::PathBuf::from);
|
||||
let cwd = params.get("cwd").and_then(Value::as_str).map_or_else(|| std::path::Path::new("."), std::path::Path::new);
|
||||
let external = crate::mcp::codex_external_server_names(home.as_deref(), cwd);
|
||||
mcp_config_with_external(params, &external)
|
||||
}
|
||||
|
||||
pub(super) fn mcp_config_with_external(
|
||||
params: &Value,
|
||||
external_names: &std::collections::BTreeSet<String>,
|
||||
) -> Option<Value> {
|
||||
let mut servers = serde_json::Map::new();
|
||||
for server in params.get("mcpServers")?.as_array()? {
|
||||
for server in params.get("mcpServers").and_then(Value::as_array).into_iter().flatten() {
|
||||
if server.get("type").and_then(Value::as_str).is_some_and(|t| t != "stdio") {
|
||||
continue;
|
||||
}
|
||||
@@ -946,5 +956,16 @@ pub(super) fn mcp_config(params: &Value) -> Option<Value> {
|
||||
"args":server.get("args").cloned().unwrap_or_else(||json!([])),"env":env}),
|
||||
);
|
||||
}
|
||||
for name in params
|
||||
.pointer("/_meta/openidea/mcpServersOff")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
{
|
||||
if !servers.contains_key(name) && external_names.contains(name) {
|
||||
servers.insert(name.to_owned(), json!({ "enabled": false }));
|
||||
}
|
||||
}
|
||||
(!servers.is_empty()).then(|| json!({"mcp_servers":servers}))
|
||||
}
|
||||
@@ -471,6 +471,9 @@ impl CopilotShim {
|
||||
if let Some(mcp) = translate::wire_mcp_servers(params.get("mcpServers")) {
|
||||
req["mcpServers"] = mcp;
|
||||
}
|
||||
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
|
||||
let created = self.call("session.create", req).await?;
|
||||
let session_id = created
|
||||
@@ -527,6 +530,9 @@ impl CopilotShim {
|
||||
if let Some(mcp) = translate::wire_mcp_servers(params.get("mcpServers")) {
|
||||
req["mcpServers"] = mcp;
|
||||
}
|
||||
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
|
||||
|
||||
@@ -355,6 +355,8 @@ impl Handler for FakeCopilotServer {
|
||||
"commands.list" => Ok(json!({ "commands": [{ "name": "compact", "description": "Compact context" }] })),
|
||||
"skills.discover" => Ok(json!({ "skills": [] })),
|
||||
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
|
||||
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
|
||||
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
|
||||
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
|
||||
"session.mode.set" => Ok(json!({})),
|
||||
"session.permissions.setApproveAll" => {
|
||||
@@ -538,3 +540,53 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
|
||||
.any(|u| u["sessionUpdate"] == "usage_update" && u["size"] == 200_000 && u["used"] == 42_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
|
||||
let server = Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()) });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let disabled = json!(["datadog", "github-mcp-server", "linear", "playwright", "slack-official"]);
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/new",
|
||||
json!({
|
||||
"cwd": "/tmp",
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "mcpServersOff": disabled } }
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/load",
|
||||
json!({
|
||||
"sessionId": "cop-sess-1",
|
||||
"cwd": "/tmp",
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "mcpServersOff": disabled } }
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = server.calls.lock();
|
||||
let (_, create_params) = calls.iter().find(|(m, _)| m == "session.create").unwrap();
|
||||
assert_eq!(create_params["disabledMcpServers"], disabled);
|
||||
let (_, resume_params) = calls.iter().find(|(m, _)| m == "session.resume").unwrap();
|
||||
assert_eq!(resume_params["disabledMcpServers"], disabled);
|
||||
}
|
||||
@@ -522,6 +522,14 @@ pub(super) fn wire_mcp_servers(acp_servers: Option<&Value>) -> Option<Value> {
|
||||
(!out.is_empty()).then_some(Value::Object(out))
|
||||
}
|
||||
|
||||
/// Extracts `_meta.openidea.mcpServersOff` into Copilot's `disabledMcpServers` string array.
|
||||
pub(super) fn wire_disabled_mcp_servers(params: &Value) -> Option<Value> {
|
||||
let list = params.pointer("/_meta/openidea/mcpServersOff")?.as_array()?;
|
||||
let names: Vec<Value> =
|
||||
list.iter().filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(|s| json!(s))).collect();
|
||||
(!names.is_empty()).then_some(Value::Array(names))
|
||||
}
|
||||
|
||||
/// Converts `commands.list` + `skills.discover` results into ACP `availableCommands`.
|
||||
pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Option<&Value>) -> Vec<Value> {
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
@@ -47,13 +47,20 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
fs::write(
|
||||
&script,
|
||||
format!(
|
||||
r#"gradle.projectsEvaluated {{
|
||||
r#"import org.gradle.util.GradleVersion
|
||||
|
||||
gradle.projectsEvaluated {{
|
||||
def p = gradle.rootProject.project({})
|
||||
def resources = p.tasks.named('processResources')
|
||||
p.tasks.register('openideaUpdateResources') {{
|
||||
dependsOn resources
|
||||
doLast {{ new File({}).setText(resources.get().destinationDir.absolutePath, 'UTF-8') }}
|
||||
def update = {{ t ->
|
||||
t.dependsOn 'processResources'
|
||||
// Resolved here so the action holds no task or project (configuration cache).
|
||||
def dir = p.tasks.getByName('processResources').destinationDir
|
||||
def manifest = new File({})
|
||||
t.doLast {{ manifest.setText(dir.absolutePath, 'UTF-8') }}
|
||||
}}
|
||||
// `register` is Gradle 4.9+.
|
||||
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update)
|
||||
else p.tasks.create('openideaUpdateResources', update)
|
||||
}}
|
||||
"#,
|
||||
literal(&p.path),
|
||||
@@ -172,7 +179,16 @@ mod tests {
|
||||
assert_eq!(gradle.command, "/tools/gradlew");
|
||||
assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources");
|
||||
let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap();
|
||||
assert!(script.contains("processResources") && script.contains("destinationDir.absolutePath"));
|
||||
assert!(
|
||||
script.contains("processResources")
|
||||
&& script.contains(".destinationDir\n")
|
||||
&& script.contains("setText(dir.absolutePath")
|
||||
);
|
||||
// `register` is Gradle 4.9+ (#3864).
|
||||
assert!(script.contains("else p.tasks.create('openideaUpdateResources', update)"), "{script}");
|
||||
// The configuration cache can't serialize a task or project the action refers to.
|
||||
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
|
||||
assert!(!action.contains("p.") && !action.contains("tasks"), "{action}");
|
||||
assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,8 @@ def processedResources = { Project p, s ->
|
||||
def describe = { Project p ->
|
||||
def m = [path: identity(p), dir: canon(p.projectDir), buildDir: canon(p.layout.buildDirectory.get().asFile)]
|
||||
if (p.gradle.parent != null) m.build = identity(p.rootProject)
|
||||
def sets = p.extensions.findByName('sourceSets')
|
||||
// Gradle 4.x has it as a convention property, not an extension.
|
||||
def sets = p.extensions.findByName('sourceSets') ?: p.findProperty('sourceSets')
|
||||
if (sets != null) {
|
||||
// Test source sets as IDEA classifies them: `test`, test fixtures, JVM test suites,
|
||||
// and sets whose folders the `idea` plugin lists as test sources.
|
||||
@@ -51,9 +52,12 @@ def describe = { Project p ->
|
||||
}
|
||||
}
|
||||
try {
|
||||
// `java` is Gradle 4.10+ (a convention before), its toolchain 6.7+.
|
||||
def java = p.extensions.findByName('java')
|
||||
def lv = java?.toolchain?.languageVersion?.getOrNull()
|
||||
m.java = lv != null ? lv.asInt() : (java?.targetCompatibility?.majorVersion as Integer)
|
||||
def lv = null
|
||||
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
|
||||
def target = java != null ? java.targetCompatibility : p.findProperty('targetCompatibility')
|
||||
m.java = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
|
||||
} catch (ignored) {}
|
||||
println '@openidea-model\t' + JsonOutput.toJson(m)
|
||||
}
|
||||
|
||||
@@ -172,13 +172,25 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
fs::write(
|
||||
&script,
|
||||
format!(
|
||||
r#"gradle.projectsEvaluated {{
|
||||
r#"import org.gradle.util.GradleVersion
|
||||
|
||||
gradle.projectsEvaluated {{
|
||||
def p = gradle.rootProject.project({})
|
||||
def warTask = p.tasks.named('war')
|
||||
p.tasks.register('openideaTomcatArtifact') {{
|
||||
dependsOn warTask
|
||||
doLast {{ new File({}).setText(warTask.get().archiveFile.get().asFile.absolutePath, 'UTF-8') }}
|
||||
def artifact = {{ t ->
|
||||
t.dependsOn 'war'
|
||||
// Resolved here so the action holds no task or project (configuration cache).
|
||||
def war = p.tasks.getByName('war')
|
||||
// `archiveFile` is Gradle 5.1+, `archivePath` is gone in 8.0.
|
||||
def archive = war.hasProperty('archiveFile') ? war.archiveFile : war.archivePath
|
||||
def manifest = new File({})
|
||||
t.doLast {{
|
||||
def file = archive instanceof File ? archive : archive.get().asFile
|
||||
manifest.setText(file.absolutePath, 'UTF-8')
|
||||
}}
|
||||
}}
|
||||
// `register` is Gradle 4.9+.
|
||||
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact)
|
||||
else p.tasks.create('openideaTomcatArtifact', artifact)
|
||||
}}
|
||||
"#,
|
||||
groovy_literal(path),
|
||||
@@ -270,7 +282,7 @@ mod tests {
|
||||
assert_eq!(a.len(), 1);
|
||||
let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap();
|
||||
assert!(plan.args.contains(&":openideaTomcatArtifact".into()));
|
||||
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("archiveFile.get()"));
|
||||
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("? war.archiveFile :"));
|
||||
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
|
||||
}
|
||||
|
||||
@@ -297,7 +309,14 @@ mod tests {
|
||||
assert!(plan.args.contains(&format!("{}:openideaTomcatArtifact", module.trim_end_matches(':'))));
|
||||
let script = fs::read_to_string(cache.join("war.init.gradle")).unwrap();
|
||||
assert!(script.contains(&format!("rootProject.project('{}')", module)));
|
||||
assert!(script.contains("archiveFile.get().asFile.absolutePath, 'UTF-8'"));
|
||||
assert!(script.contains("manifest.setText(file.absolutePath, 'UTF-8')"));
|
||||
// `archiveFile` is Gradle 5.1+, `register` 4.9+ (#3864).
|
||||
assert!(
|
||||
script.contains(": war.archivePath") && script.contains("else p.tasks.create('openideaTomcatArtifact'")
|
||||
);
|
||||
// The configuration cache can't serialize a task or project the action refers to.
|
||||
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
|
||||
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -348,6 +348,35 @@ mod imp {
|
||||
paths
|
||||
}
|
||||
|
||||
/// `Preferred DropEffect`: a `DWORD` saying whether the files were copied or cut.
|
||||
/// Explorer writes it with every file list, and paste targets that move files
|
||||
/// between machines (Remote Desktop's clipboard redirection, #3863) read it.
|
||||
fn drop_effect_format() -> u32 {
|
||||
let name: Vec<u16> = "Preferred DropEffect\0".encode_utf16().collect();
|
||||
unsafe { RegisterClipboardFormatW(name.as_ptr()) }
|
||||
}
|
||||
|
||||
/// `DROPEFFECT_COPY`.
|
||||
const DROPEFFECT_COPY: u32 = 1;
|
||||
|
||||
/// An `HGLOBAL` holding a copy of `bytes`. Null when the allocation failed.
|
||||
fn global_bytes(bytes: &[u8]) -> Handle {
|
||||
unsafe {
|
||||
let memory = GlobalAlloc(GMEM_MOVEABLE, bytes.len());
|
||||
if memory.is_null() {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
let data = GlobalLock(memory);
|
||||
if data.is_null() {
|
||||
GlobalFree(memory);
|
||||
return ptr::null_mut();
|
||||
}
|
||||
ptr::copy_nonoverlapping(bytes.as_ptr(), data as *mut u8, bytes.len());
|
||||
GlobalUnlock(memory);
|
||||
memory
|
||||
}
|
||||
}
|
||||
|
||||
/// An `HGLOBAL` holding `text` as UTF-16 with a terminating NUL, and its
|
||||
/// byte size. Null when the allocation failed.
|
||||
fn global_text(text: &str) -> (Handle, usize) {
|
||||
@@ -430,6 +459,13 @@ mod imp {
|
||||
if !taken {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
let effect = drop_effect_format();
|
||||
if effect != 0 {
|
||||
let effect_memory = global_bytes(&DROPEFFECT_COPY.to_le_bytes());
|
||||
if !effect_memory.is_null() && SetClipboardData(effect, effect_memory).is_null() {
|
||||
GlobalFree(effect_memory);
|
||||
}
|
||||
}
|
||||
let (text_memory, _) = global_text(&text);
|
||||
if !text_memory.is_null() {
|
||||
// The text alone still pastes somewhere useful.
|
||||
|
||||
@@ -167,10 +167,11 @@ const GRADLE: &[&str] = &["gradle", "gradlew"];
|
||||
/// Gradle's own JVM and the compiler's source encoding are untouched.
|
||||
pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\
|
||||
// Written by OpenIDEA: a UTF-8 default charset for applications run by Gradle, as the Run console decodes UTF-8.
|
||||
import org.gradle.util.GradleVersion
|
||||
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
|
||||
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
|
||||
allprojects {
|
||||
tasks.withType(JavaExec).configureEach {
|
||||
defaultCharacterEncoding = 'UTF-8'
|
||||
}
|
||||
each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
|
||||
}
|
||||
";
|
||||
|
||||
@@ -621,10 +622,12 @@ mod tests {
|
||||
#[test]
|
||||
fn gradle_script_respects_the_builds_own_file_encoding() {
|
||||
let s = GRADLE_FILE_ENCODING_SCRIPT;
|
||||
assert!(s.contains("tasks.withType(JavaExec).configureEach"), "{s}");
|
||||
assert!(s.contains("defaultCharacterEncoding = 'UTF-8'"), "{s}");
|
||||
assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}");
|
||||
assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}");
|
||||
assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}");
|
||||
assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}");
|
||||
// Gradle before 4.9 has no `configureEach` (#3864).
|
||||
assert!(s.contains("? tasks.configureEach(action) : tasks.all(action)"), "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -6,11 +6,16 @@ use ide_run::wrap::{self, program_name};
|
||||
use std::path::Path;
|
||||
|
||||
const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage.
|
||||
allprojects {
|
||||
plugins.withId('java') {
|
||||
apply plugin: 'jacoco'
|
||||
tasks.withType(Test).configureEach { t -> t.finalizedBy(tasks.named('jacocoTestReport')) }
|
||||
tasks.named('jacocoTestReport') { r -> r.reports { xml.required.set(true) } }
|
||||
import org.gradle.util.GradleVersion
|
||||
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
|
||||
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
|
||||
allprojects { p ->
|
||||
p.plugins.withId('java') {
|
||||
p.apply plugin: 'jacoco'
|
||||
each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') }
|
||||
def xml = p.tasks.getByName('jacocoTestReport').reports.xml
|
||||
// `Report.required` is Gradle 6.1+, `enabled` is gone in 8.0.
|
||||
if (xml.hasProperty('required')) xml.required.set(true) else xml.enabled = true
|
||||
}
|
||||
}
|
||||
"#;
|
||||
@@ -391,7 +396,10 @@ mod tests {
|
||||
let p = prepare(dir.path(), &cfg("gradle", "./gradlew", &[":app:test", "--tests", "*Calc"]), dir.path());
|
||||
let (l, report) = launch(&p);
|
||||
assert_eq!(l.args[0], "--init-script");
|
||||
assert!(std::fs::read_to_string(&l.args[1]).unwrap().contains("jacoco"));
|
||||
let script = std::fs::read_to_string(&l.args[1]).unwrap();
|
||||
assert!(script.contains("p.apply plugin: 'jacoco'"), "{script}");
|
||||
// `Report.required` is Gradle 6.1+, `configureEach` 4.9+ (#3864).
|
||||
assert!(script.contains("else xml.enabled = true") && script.contains(": tasks.all(action)"), "{script}");
|
||||
assert!(matches!(report, CoverageReportSpec::Jacoco { .. }));
|
||||
}
|
||||
|
||||
|
||||
@@ -191,6 +191,12 @@ impl Host {
|
||||
};
|
||||
host.apply_proxy();
|
||||
host.apply_added_jdks();
|
||||
// Before any project starts jdtls; the deleting itself can take a while.
|
||||
let unused =
|
||||
ide_sdk::jdtls_workspaces::take_unused(&host.local_data_dir, ide_sdk::jdtls_workspaces::UNUSED_FOR);
|
||||
if !unused.is_empty() {
|
||||
std::thread::spawn(move || ide_sdk::jdtls_workspaces::remove(unused));
|
||||
}
|
||||
ops::agent::move_user_mcp_values(&host);
|
||||
host
|
||||
}
|
||||
|
||||
@@ -457,6 +457,7 @@ fn persist_mcp_map(
|
||||
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.mcpServers", value)?;
|
||||
for p in host.projects() {
|
||||
p.settings.reload();
|
||||
p.agents.notify_mcp_servers_changed();
|
||||
p.sink.emit(event.clone());
|
||||
if kept == Kept::LocalFile {
|
||||
host.agent_secrets.notify_kept_locally(&p.sink);
|
||||
@@ -466,6 +467,7 @@ fn persist_mcp_map(
|
||||
McpScope::Workspace => {
|
||||
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace MCP servers"))?;
|
||||
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.mcpServers", value)?;
|
||||
p.agents.notify_mcp_servers_changed();
|
||||
p.sink.emit(event);
|
||||
}
|
||||
}
|
||||
@@ -533,9 +535,17 @@ pub(crate) fn session_mcp_servers(
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
let mut user = settings.layer(SettingsScope::Global).agents.mcp_servers;
|
||||
fill_mcp_values(secrets, &mut user);
|
||||
let mut workspace = settings.layer(SettingsScope::Project).agents.mcp_servers;
|
||||
workspace.retain(|name, srv| approvals.approved(root, name, srv));
|
||||
ide_agent::mcp::servers_from_settings(&user, &workspace)
|
||||
let raw_workspace = settings.layer(SettingsScope::Project).agents.mcp_servers;
|
||||
let workspace = approvals.apply(root, raw_workspace.clone());
|
||||
let mut out = ide_agent::mcp::servers_from_settings(&user, &workspace);
|
||||
for srv in &mut out {
|
||||
if srv.scope == McpScope::Workspace
|
||||
&& let Some(raw) = raw_workspace.get(&srv.name)
|
||||
{
|
||||
srv.unapproved = !approvals.approved(root, &srv.name, raw);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Lists configured MCP servers across User (`settings.toml`) and Workspace (`.openidea/settings.toml`) scopes.
|
||||
|
||||
@@ -238,6 +238,11 @@ pub fn set_settings(
|
||||
if is_proxy {
|
||||
host.apply_proxy();
|
||||
}
|
||||
if key == "agents" || key == "agents.mcpServers" || key.starts_with("agents.mcpServers.") {
|
||||
for project in affected() {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
// A new interpreter / toolchain / server executable restarts the language servers it affects.
|
||||
// So do inspections that are compiler options (`ide-sdk` `configure_java_compiler`).
|
||||
let code_style = key == "editor"
|
||||
|
||||
@@ -65,6 +65,7 @@ pub async fn spell_check(
|
||||
end: r.end,
|
||||
kind: match r.kind {
|
||||
SpellingKind::Comment => RegionKind::Comment,
|
||||
SpellingKind::String if r.raw => RegionKind::RawString,
|
||||
SpellingKind::String => RegionKind::String,
|
||||
SpellingKind::Name => RegionKind::Name,
|
||||
},
|
||||
|
||||
@@ -286,6 +286,7 @@ impl Host {
|
||||
lsp.set_prepare_hook(Box::new(move |cfg, _, cancel| {
|
||||
let effective = settings.effective();
|
||||
if cfg.name == "jdtls" {
|
||||
ide_sdk::jdtls_workspaces::mark_used(cfg);
|
||||
crate::java_runtime::prepare(
|
||||
cfg,
|
||||
&data_dir,
|
||||
|
||||
@@ -73,6 +73,33 @@ pub struct SpellingRegion {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub kind: SpellingKind,
|
||||
/// A raw / verbatim string: backslashes are literal text, not escapes
|
||||
/// (`r"\user"`, `r#"…"#`, `` `…` ``, `@"…"`). The spelling layer must not
|
||||
/// skip the character after a `\` in one of these.
|
||||
pub raw: bool,
|
||||
}
|
||||
|
||||
/// Whether `node` is a string literal whose backslashes are not escapes.
|
||||
fn is_raw_string(node: &Node<'_>, text: &str) -> bool {
|
||||
let kind = node.kind();
|
||||
// Rust/C++/C# grammars name the node directly.
|
||||
if kind == "raw_string_literal" || kind == "verbatim_string_literal" || kind.contains("raw_string") {
|
||||
return true;
|
||||
}
|
||||
// Go backtick strings and Python `r`/`fr`/`rb` prefixes: the grammar uses
|
||||
// the generic `string` node, so inspect the literal's own prefix.
|
||||
if kind == "string" || kind == "string_literal" {
|
||||
let literal = &text[node.start_byte()..node.end_byte()];
|
||||
if literal.starts_with('`') {
|
||||
return true;
|
||||
}
|
||||
let quote = literal.find(['"', '\'']);
|
||||
let prefix = quote.map_or("", |i| &literal[..i]);
|
||||
return !prefix.is_empty()
|
||||
&& prefix.chars().any(|c| c == 'r' || c == 'R')
|
||||
&& prefix.chars().all(|c| matches!(c, 'r' | 'R' | 'b' | 'B' | 'f' | 'F' | 'u' | 'U'));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn is_name_leaf(kind: &str) -> bool {
|
||||
@@ -101,16 +128,20 @@ fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
|
||||
}
|
||||
|
||||
/// Comments, string literals and declared names, for spell checking.
|
||||
pub(crate) fn spelling_regions(tree: &Tree) -> Vec<SpellingRegion> {
|
||||
pub(crate) fn spelling_regions(tree: &Tree, text: &str) -> Vec<SpellingRegion> {
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = tree.walk();
|
||||
loop {
|
||||
let node = cursor.node();
|
||||
let literal = kind_of(&node);
|
||||
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind };
|
||||
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind, raw: false };
|
||||
match literal {
|
||||
Some(LiteralKind::Comment) => out.push(region(SpellingKind::Comment)),
|
||||
Some(LiteralKind::String) => out.push(region(SpellingKind::String)),
|
||||
Some(LiteralKind::String) => {
|
||||
let mut r = region(SpellingKind::String);
|
||||
r.raw = is_raw_string(&node, text);
|
||||
out.push(r);
|
||||
}
|
||||
None if node.is_named()
|
||||
&& node.child_count() == 0
|
||||
&& is_name_leaf(node.kind())
|
||||
|
||||
@@ -294,7 +294,7 @@ impl Syntax {
|
||||
/// Comments, string literals and declared names (byte ranges, document
|
||||
/// order) for the Typo inspection; `None` like [`Self::literals`].
|
||||
pub fn spelling_regions(&self, lang: &LanguageId, text: &str) -> Option<Vec<SpellingRegion>> {
|
||||
self.analyze(lang, text, |_, tree, _| Some(literals::spelling_regions(tree)))
|
||||
self.analyze(lang, text, |_, tree, text| Some(literals::spelling_regions(tree, text)))
|
||||
}
|
||||
|
||||
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
|
||||
|
||||
@@ -1422,6 +1422,35 @@ fn spelling_regions_cover_declared_names_only() {
|
||||
assert_eq!(names, ["Bird", "fly", "text"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spelling_regions_mark_raw_strings() {
|
||||
let py = r#"a = r"\user" + R'\mesage' + fr"\wrd" + rb"\foo" + "\user""#;
|
||||
let found: Vec<(&str, bool)> = syntax()
|
||||
.spelling_regions(&lang("python"), py)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|r| r.kind == SpellingKind::String)
|
||||
.map(|r| (&py[r.start..r.end], r.raw))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
vec![
|
||||
(r#"r"\user""#, true),
|
||||
(r"R'\mesage'", true),
|
||||
(r#"fr"\wrd""#, true),
|
||||
(r#"rb"\foo""#, true),
|
||||
(r#""\user""#, false),
|
||||
]
|
||||
);
|
||||
// C# verbatim / Rust raw literals are named by the grammar itself.
|
||||
let cs = r#"var s = @"C:\mesage";"#;
|
||||
let raw = syntax().spelling_regions(&lang("csharp"), cs).unwrap().iter().any(|r| r.raw);
|
||||
assert!(raw, "C# verbatim string should be raw");
|
||||
let rs = r#"let s = r"\mesage";"#;
|
||||
let raw = syntax().spelling_regions(&lang("rust"), rs).unwrap().iter().any(|r| r.raw);
|
||||
assert!(raw, "Rust raw string should be raw");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Script regions of Vue SFCs and HTML documents
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
doctrine-mapping.xsd is from Doctrine ORM (https://github.com/doctrine/orm),
|
||||
MIT License. Copyright (c) Doctrine Project.
|
||||
The copy published at https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd
|
||||
is broken (wrong targetNamespace / XMLSchema URI after an http→https rewrite);
|
||||
this file is the upstream schema with the correct namespace.
|
||||
@@ -0,0 +1,643 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
|
||||
targetNamespace="http://doctrine-project.org/schemas/orm/doctrine-mapping"
|
||||
xmlns:orm="http://doctrine-project.org/schemas/orm/doctrine-mapping"
|
||||
elementFormDefault="qualified">
|
||||
|
||||
<xs:annotation>
|
||||
<xs:documentation><![CDATA[
|
||||
This is the XML Schema for the object/relational
|
||||
mapping file used by the Doctrine ORM.
|
||||
]]></xs:documentation>
|
||||
</xs:annotation>
|
||||
|
||||
<xs:element name="doctrine-mapping">
|
||||
<xs:complexType>
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="mapped-superclass" type="orm:mapped-superclass" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="entity" type="orm:entity" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="embeddable" type="orm:embeddable" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
|
||||
<xs:complexType name="emptyType">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="cascade-type">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="cascade-all" type="orm:emptyType" minOccurs="0"/>
|
||||
<xs:element name="cascade-persist" type="orm:emptyType" minOccurs="0"/>
|
||||
<xs:element name="cascade-merge" type="orm:emptyType" minOccurs="0"/>
|
||||
<xs:element name="cascade-remove" type="orm:emptyType" minOccurs="0"/>
|
||||
<xs:element name="cascade-refresh" type="orm:emptyType" minOccurs="0"/>
|
||||
<xs:element name="cascade-detach" type="orm:emptyType" minOccurs="0"/>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:simpleType name="lifecycle-callback-type">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:enumeration value="prePersist"/>
|
||||
<xs:enumeration value="postPersist"/>
|
||||
<xs:enumeration value="preUpdate"/>
|
||||
<xs:enumeration value="postUpdate"/>
|
||||
<xs:enumeration value="preRemove"/>
|
||||
<xs:enumeration value="postRemove"/>
|
||||
<xs:enumeration value="postLoad"/>
|
||||
<xs:enumeration value="preFlush"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="cache-usage-type">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:enumeration value="READ_ONLY"/>
|
||||
<xs:enumeration value="READ_WRITE"/>
|
||||
<xs:enumeration value="NONSTRICT_READ_WRITE"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:complexType name="lifecycle-callback">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="type" type="orm:lifecycle-callback-type" use="required" />
|
||||
<xs:attribute name="method" type="xs:NMTOKEN" use="required" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="lifecycle-callbacks">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="1" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="named-query">
|
||||
<xs:attribute name="name" type="xs:string" use="required" />
|
||||
<xs:attribute name="query" type="xs:string" use="required" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="named-queries">
|
||||
<xs:sequence>
|
||||
<xs:element name="named-query" type="orm:named-query" minOccurs="1" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="named-native-query">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="query" type="xs:string" minOccurs="1" maxOccurs="1"/>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:string" use="required" />
|
||||
<xs:attribute name="result-class" type="orm:fqcn" />
|
||||
<xs:attribute name="result-set-mapping" type="xs:string" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="named-native-queries">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="named-native-query" type="orm:named-native-query" minOccurs="1" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="entity-listener">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="0" maxOccurs="unbounded"/>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="class" type="orm:fqcn"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="entity-listeners">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="entity-listener" type="orm:entity-listener" minOccurs="1" maxOccurs="unbounded" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="column-result">
|
||||
<xs:attribute name="name" type="xs:string" use="required" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="field-result">
|
||||
<xs:attribute name="name" type="xs:string" use="required" />
|
||||
<xs:attribute name="column" type="xs:string" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="entity-result">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="field-result" type="orm:field-result" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:choice>
|
||||
<xs:attribute name="entity-class" type="orm:fqcn" use="required" />
|
||||
<xs:attribute name="discriminator-column" type="xs:string" use="optional" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="sql-result-set-mapping">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="entity-result" type="orm:entity-result"/>
|
||||
<xs:element name="column-result" type="orm:column-result"/>
|
||||
</xs:choice>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:string" use="required" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="sql-result-set-mappings">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="sql-result-set-mapping" type="orm:sql-result-set-mapping" minOccurs="1" maxOccurs="unbounded" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="cache">
|
||||
<xs:attribute name="usage" type="orm:cache-usage-type" />
|
||||
<xs:attribute name="region" type="xs:string" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="entity">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
|
||||
<xs:element name="options" type="orm:options" minOccurs="0" />
|
||||
<xs:element name="indexes" type="orm:indexes" minOccurs="0"/>
|
||||
<xs:element name="unique-constraints" type="orm:unique-constraints" minOccurs="0"/>
|
||||
<xs:element name="discriminator-column" type="orm:discriminator-column" minOccurs="0"/>
|
||||
<xs:element name="discriminator-map" type="orm:discriminator-map" minOccurs="0"/>
|
||||
<xs:element name="lifecycle-callbacks" type="orm:lifecycle-callbacks" minOccurs="0" maxOccurs="1" />
|
||||
<xs:element name="entity-listeners" type="orm:entity-listeners" minOccurs="0" maxOccurs="1" />
|
||||
<xs:element name="named-queries" type="orm:named-queries" minOccurs="0" maxOccurs="1" />
|
||||
<xs:element name="named-native-queries" type="orm:named-native-queries" minOccurs="0" maxOccurs="1" />
|
||||
<xs:element name="sql-result-set-mappings" type="orm:sql-result-set-mappings" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="id" type="orm:id" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="field" type="orm:field" minOccurs="0" maxOccurs="unbounded"/>
|
||||
<xs:element name="embedded" type="orm:embedded" minOccurs="0" maxOccurs="unbounded"/>
|
||||
<xs:element name="one-to-one" type="orm:one-to-one" minOccurs="0" maxOccurs="unbounded"/>
|
||||
<xs:element name="one-to-many" type="orm:one-to-many" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="many-to-one" type="orm:many-to-one" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="many-to-many" type="orm:many-to-many" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="association-overrides" type="orm:association-overrides" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="attribute-overrides" type="orm:attribute-overrides" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:string" use="required" />
|
||||
<xs:attribute name="table" type="orm:tablename" />
|
||||
<xs:attribute name="schema" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="repository-class" type="orm:fqcn"/>
|
||||
<xs:attribute name="inheritance-type" type="orm:inheritance-type"/>
|
||||
<xs:attribute name="change-tracking-policy" type="orm:change-tracking-policy" />
|
||||
<xs:attribute name="read-only" type="xs:boolean" default="false" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:simpleType name="tablename" id="tablename">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:pattern value="[a-zA-Z_u01-uff.]+" id="tablename.pattern">
|
||||
</xs:pattern>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:complexType name="option" mixed="true">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="option" type="orm:option"/>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="required"/>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="options">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="option" type="orm:option" minOccurs="0" maxOccurs="unbounded"/>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="mapped-superclass" >
|
||||
<xs:complexContent>
|
||||
<xs:extension base="orm:entity"/>
|
||||
</xs:complexContent>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="embeddable">
|
||||
<xs:complexContent>
|
||||
<xs:extension base="orm:entity"/>
|
||||
</xs:complexContent>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:simpleType name="change-tracking-policy">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:enumeration value="DEFERRED_IMPLICIT"/>
|
||||
<xs:enumeration value="DEFERRED_EXPLICIT"/>
|
||||
<xs:enumeration value="NOTIFY"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="inheritance-type">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:enumeration value="SINGLE_TABLE"/>
|
||||
<xs:enumeration value="JOINED"/>
|
||||
<xs:enumeration value="TABLE_PER_CLASS"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="generator-strategy">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:enumeration value="NONE"/>
|
||||
<xs:enumeration value="SEQUENCE"/>
|
||||
<xs:enumeration value="IDENTITY"/>
|
||||
<xs:enumeration value="AUTO"/>
|
||||
<xs:enumeration value="UUID"/>
|
||||
<xs:enumeration value="CUSTOM" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="fk-action">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:enumeration value="CASCADE"/>
|
||||
<xs:enumeration value="RESTRICT"/>
|
||||
<xs:enumeration value="SET NULL"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="fetch-type">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:enumeration value="EAGER"/>
|
||||
<xs:enumeration value="LAZY"/>
|
||||
<xs:enumeration value="EXTRA_LAZY"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="generated-type">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:enumeration value="NEVER"/>
|
||||
<xs:enumeration value="INSERT"/>
|
||||
<xs:enumeration value="ALWAYS"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:complexType name="field">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="options" type="orm:options" minOccurs="0" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="type" type="orm:type" default="string" />
|
||||
<xs:attribute name="column" type="orm:columntoken" />
|
||||
<xs:attribute name="length" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="unique" type="xs:boolean" default="false" />
|
||||
<xs:attribute name="nullable" type="xs:boolean" default="false" />
|
||||
<xs:attribute name="insertable" type="xs:boolean" default="true" />
|
||||
<xs:attribute name="updatable" type="xs:boolean" default="true" />
|
||||
<xs:attribute name="generated" type="orm:generated-type" default="NEVER" />
|
||||
<xs:attribute name="enum-type" type="xs:string" />
|
||||
<xs:attribute name="version" type="xs:boolean" />
|
||||
<xs:attribute name="column-definition" type="xs:string" />
|
||||
<xs:attribute name="precision" type="xs:integer" use="optional" />
|
||||
<xs:attribute name="scale" type="xs:integer" use="optional" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="embedded">
|
||||
<xs:sequence>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:sequence>
|
||||
<xs:attribute name="name" type="xs:string" use="required" />
|
||||
<xs:attribute name="class" type="orm:fqcn" use="optional" />
|
||||
<xs:attribute name="column-prefix" type="xs:string" use="optional" />
|
||||
<xs:attribute name="use-column-prefix" type="xs:boolean" default="true" use="optional" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="discriminator-column">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="options" type="orm:options" minOccurs="0" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="type" type="xs:NMTOKEN"/>
|
||||
<xs:attribute name="field-name" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="length" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="column-definition" type="xs:string" />
|
||||
<xs:attribute name="enum-type" type="xs:string" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="unique-constraint">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="options" type="orm:options" minOccurs="0" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
|
||||
<xs:attribute name="columns" type="xs:string" use="optional"/>
|
||||
<xs:attribute name="fields" type="xs:string" use="optional"/>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="unique-constraints">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="unique-constraint" type="orm:unique-constraint" minOccurs="1" maxOccurs="unbounded"/>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="index">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="options" type="orm:options" minOccurs="0" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
|
||||
<xs:attribute name="columns" type="xs:string" use="optional"/>
|
||||
<xs:attribute name="fields" type="xs:string" use="optional"/>
|
||||
<xs:attribute name="flags" type="xs:string" use="optional"/>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="indexes">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="index" type="orm:index" minOccurs="1" maxOccurs="unbounded"/>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="discriminator-mapping">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="value" type="orm:type" use="required"/>
|
||||
<xs:attribute name="class" type="orm:fqcn" use="required"/>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="discriminator-map">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="discriminator-mapping" type="orm:discriminator-mapping" minOccurs="1" maxOccurs="unbounded"/>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="generator">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="strategy" type="orm:generator-strategy" use="optional" default="AUTO" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="id">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="generator" type="orm:generator" minOccurs="0" />
|
||||
<xs:element name="sequence-generator" type="orm:sequence-generator" minOccurs="0" maxOccurs="1" />
|
||||
<xs:element name="custom-id-generator" type="orm:custom-id-generator" minOccurs="0" maxOccurs="1" />
|
||||
<xs:element name="options" type="orm:options" minOccurs="0" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="type" type="orm:type" />
|
||||
<xs:attribute name="column" type="orm:columntoken" />
|
||||
<xs:attribute name="length" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="association-key" type="xs:boolean" default="false" />
|
||||
<xs:attribute name="column-definition" type="xs:string" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="sequence-generator">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="sequence-name" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="allocation-size" type="xs:integer" use="optional" default="1" />
|
||||
<xs:attribute name="initial-value" type="xs:integer" use="optional" default="1" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="custom-id-generator">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="class" type="orm:fqcn" use="required" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:simpleType name="fqcn" id="fqcn">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:pattern value="[a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+" id="fqcn.pattern">
|
||||
</xs:pattern>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="type" id="type">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:pattern value="([a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+)|(\c+)" id="type.class.pattern">
|
||||
</xs:pattern>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:complexType name="inverse-join-columns">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="join-column">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="optional" />
|
||||
<xs:attribute name="referenced-column-name" type="xs:NMTOKEN" use="optional" default="id" />
|
||||
<xs:attribute name="unique" type="xs:boolean" default="false" />
|
||||
<xs:attribute name="nullable" type="xs:boolean" default="true" />
|
||||
<xs:attribute name="on-delete" type="orm:fk-action" />
|
||||
<xs:attribute name="column-definition" type="xs:string" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="join-columns">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="join-table">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="join-columns" type="orm:join-columns" />
|
||||
<xs:element name="inverse-join-columns" type="orm:join-columns" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="schema" type="xs:NMTOKEN" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="order-by">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="order-by-field" type="orm:order-by-field" minOccurs="1" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="order-by-field">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="direction" type="orm:order-by-direction" default="ASC" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:simpleType name="order-by-direction">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:enumeration value="ASC"/>
|
||||
<xs:enumeration value="DESC"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="columntoken" id="columntoken">
|
||||
<xs:restriction base="xs:token">
|
||||
<xs:pattern value="[-._:A-Za-z0-9`]+" id="columntoken.pattern"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:complexType name="many-to-many">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
|
||||
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
|
||||
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
|
||||
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="target-entity" type="xs:string" use="required" />
|
||||
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="index-by" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
|
||||
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="one-to-many">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
|
||||
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
|
||||
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="target-entity" type="xs:string" use="required" />
|
||||
<xs:attribute name="mapped-by" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="index-by" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
|
||||
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="many-to-one">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
|
||||
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
|
||||
<xs:choice minOccurs="0" maxOccurs="1">
|
||||
<xs:element name="join-column" type="orm:join-column"/>
|
||||
<xs:element name="join-columns" type="orm:join-columns"/>
|
||||
</xs:choice>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="target-entity" type="xs:string" />
|
||||
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="one-to-one">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
|
||||
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
|
||||
<xs:choice minOccurs="0" maxOccurs="1">
|
||||
<xs:element name="join-column" type="orm:join-column"/>
|
||||
<xs:element name="join-columns" type="orm:join-columns"/>
|
||||
</xs:choice>
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="target-entity" type="xs:string" />
|
||||
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
|
||||
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="association-overrides">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="association-override" type="orm:association-override" minOccurs="1" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="association-override">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
|
||||
<xs:element name="join-columns" type="orm:join-columns" minOccurs="0" />
|
||||
<xs:element name="inversed-by" type="orm:inversed-by-override" minOccurs="0" maxOccurs="1" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
|
||||
<xs:attribute name="fetch" type="orm:fetch-type" use="optional" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="inversed-by-override">
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="attribute-overrides">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="attribute-override" type="orm:attribute-override" minOccurs="1" maxOccurs="unbounded" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="attribute-override">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="field" type="orm:attribute-override-field" minOccurs="1" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="attribute-override-field">
|
||||
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:element name="options" type="orm:options" minOccurs="0" />
|
||||
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
|
||||
</xs:choice>
|
||||
<xs:attribute name="type" type="orm:type" default="string" />
|
||||
<xs:attribute name="column" type="orm:columntoken" />
|
||||
<xs:attribute name="length" type="xs:NMTOKEN" />
|
||||
<xs:attribute name="unique" type="xs:boolean" default="false" />
|
||||
<xs:attribute name="nullable" type="xs:boolean" default="false" />
|
||||
<xs:attribute name="insertable" type="xs:boolean" default="true" />
|
||||
<xs:attribute name="updateable" type="xs:boolean" default="true" />
|
||||
<xs:attribute name="version" type="xs:boolean" />
|
||||
<xs:attribute name="column-definition" type="xs:string" />
|
||||
<xs:attribute name="precision" type="xs:integer" use="optional" />
|
||||
<xs:attribute name="scale" type="xs:integer" use="optional" />
|
||||
<xs:anyAttribute namespace="##other"/>
|
||||
</xs:complexType>
|
||||
|
||||
</xs:schema>
|
||||
@@ -40,6 +40,7 @@ mod uri;
|
||||
mod virtual_doc;
|
||||
mod vue_navigation;
|
||||
mod vue_refs;
|
||||
mod xml_catalog;
|
||||
|
||||
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
|
||||
pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions};
|
||||
@@ -3795,6 +3796,9 @@ impl LspManager {
|
||||
if cfg.name == compose::SERVER {
|
||||
compose::configure_yaml_compose_schemas(&mut cfg, &self.open_compose_files());
|
||||
}
|
||||
if cfg.name == xml_catalog::SERVER {
|
||||
xml_catalog::configure_lemminx_catalogs(&mut cfg);
|
||||
}
|
||||
cfg
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! Bundled XML catalogs for LemMinX so known-broken remote XSDs resolve locally.
|
||||
//!
|
||||
//! Doctrine's hosted `doctrine-mapping.xsd` advertises the wrong `targetNamespace`
|
||||
//! (the schema URL itself) after an http→https rewrite, so any mapping file that
|
||||
//! points `xsi:schemaLocation` at that URL fails with `TargetNamespace.1` /
|
||||
//! `cvc-elt.1.a`. An OASIS catalog maps the namespace and those system IDs to the
|
||||
//! correct upstream schema we ship.
|
||||
|
||||
use ide_language::LanguageServerConfig;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const SERVER: &str = "lemminx";
|
||||
|
||||
const DOCTRINE_XSD: &str = include_str!("../schemas/xml/doctrine-mapping.xsd");
|
||||
|
||||
const CATALOG_TEMPLATE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
|
||||
<uri name="http://doctrine-project.org/schemas/orm/doctrine-mapping" uri="doctrine-mapping.xsd"/>
|
||||
<uri name="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
|
||||
<system systemId="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
|
||||
<system systemId="http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
|
||||
</catalog>
|
||||
"#;
|
||||
|
||||
/// Writes the bundled catalog (idempotent) and prepends it to LemMinX `xml.catalogs`.
|
||||
pub fn configure_lemminx_catalogs(cfg: &mut LanguageServerConfig) {
|
||||
if cfg.name != SERVER {
|
||||
return;
|
||||
}
|
||||
let Some(catalog) = ensure_catalog() else { return };
|
||||
let catalog = path_for_settings(&catalog);
|
||||
let mut settings = cfg.settings.take().filter(Value::is_object).unwrap_or_else(|| json!({}));
|
||||
let Some(root) = settings.as_object_mut() else {
|
||||
cfg.settings = Some(settings);
|
||||
return;
|
||||
};
|
||||
let Some(xml) = root.entry("xml").or_insert_with(|| json!({})).as_object_mut() else {
|
||||
cfg.settings = Some(settings);
|
||||
return;
|
||||
};
|
||||
let Some(catalogs) = xml.entry("catalogs").or_insert_with(|| json!([])).as_array_mut() else {
|
||||
cfg.settings = Some(settings);
|
||||
return;
|
||||
};
|
||||
if catalogs.iter().any(|v| v.as_str() == Some(catalog.as_str())) {
|
||||
cfg.settings = Some(settings);
|
||||
return;
|
||||
}
|
||||
catalogs.insert(0, Value::String(catalog));
|
||||
cfg.settings = Some(settings);
|
||||
}
|
||||
|
||||
fn ensure_catalog() -> Option<PathBuf> {
|
||||
// Per-pid directory: shared `/tmp/openidea-xml-catalog` would let another
|
||||
// local user plant a catalog that remaps arbitrary schema URIs.
|
||||
let dir = std::env::temp_dir().join(format!("openidea-xml-catalog-{}", std::process::id()));
|
||||
if let Err(e) = ide_vfs::create_private_dir(&dir) {
|
||||
tracing::warn!("xml catalog: cannot create {}: {e}", dir.display());
|
||||
return None;
|
||||
}
|
||||
let xsd = dir.join("doctrine-mapping.xsd");
|
||||
if !write_if_changed(&xsd, DOCTRINE_XSD.as_bytes()) {
|
||||
tracing::warn!("xml catalog: cannot write {}", xsd.display());
|
||||
return None;
|
||||
}
|
||||
let catalog = dir.join("catalog.xml");
|
||||
if !write_if_changed(&catalog, CATALOG_TEMPLATE.as_bytes()) {
|
||||
tracing::warn!("xml catalog: cannot write {}", catalog.display());
|
||||
return None;
|
||||
}
|
||||
Some(catalog)
|
||||
}
|
||||
|
||||
fn write_if_changed(path: &Path, bytes: &[u8]) -> bool {
|
||||
if std::fs::read(path).ok().as_deref() == Some(bytes) {
|
||||
return true;
|
||||
}
|
||||
ide_vfs::write_atomic_private(path, bytes).is_ok()
|
||||
}
|
||||
|
||||
fn path_for_settings(path: &Path) -> String {
|
||||
path.to_string_lossy().replace('\\', "/")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_language::LanguageRegistry;
|
||||
|
||||
const DOCTRINE_NS: &str = "http://doctrine-project.org/schemas/orm/doctrine-mapping";
|
||||
const DOCTRINE_SCHEMA_HTTPS: &str = "https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
|
||||
const DOCTRINE_SCHEMA_HTTP: &str = "http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
|
||||
|
||||
#[test]
|
||||
fn bundled_xsd_keeps_http_namespace() {
|
||||
assert!(DOCTRINE_XSD.contains(&format!("targetNamespace=\"{DOCTRINE_NS}\"")));
|
||||
assert!(!DOCTRINE_XSD.contains("xmlns:xs=\"https://www.w3.org/2001/XMLSchema\""));
|
||||
assert!(!DOCTRINE_XSD.contains("targetNamespace=\"https://www.doctrine-project.org"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_maps_namespace_and_system_ids() {
|
||||
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
|
||||
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_SCHEMA_HTTPS}""#)));
|
||||
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTPS}""#)));
|
||||
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTP}""#)));
|
||||
assert_eq!(CATALOG_TEMPLATE.matches(r#"uri="doctrine-mapping.xsd""#).count(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepends_catalog_without_dropping_user_entries() {
|
||||
let reg = LanguageRegistry::load(None).unwrap();
|
||||
let xml = reg.get(&ide_core::LanguageId::new("xml")).unwrap();
|
||||
let mut cfg = xml.language_servers[0].clone();
|
||||
cfg.settings = Some(json!({"xml": {"catalogs": ["/user/catalog.xml"]}}));
|
||||
configure_lemminx_catalogs(&mut cfg);
|
||||
let list: Vec<String> = cfg.settings.as_ref().unwrap()["xml"]["catalogs"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
assert_eq!(list.len(), 2);
|
||||
assert!(list[0].ends_with("catalog.xml"));
|
||||
assert!(list[0].contains(&format!("openidea-xml-catalog-{}", std::process::id())));
|
||||
assert_eq!(list[1], "/user/catalog.xml");
|
||||
configure_lemminx_catalogs(&mut cfg);
|
||||
assert_eq!(cfg.settings.as_ref().unwrap()["xml"]["catalogs"].as_array().unwrap().len(), 2);
|
||||
|
||||
let catalog = PathBuf::from(&list[0]);
|
||||
let body = std::fs::read_to_string(&catalog).unwrap();
|
||||
assert_eq!(body, CATALOG_TEMPLATE);
|
||||
assert!(body.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
|
||||
let xsd = catalog.with_file_name("doctrine-mapping.xsd");
|
||||
assert_eq!(std::fs::read_to_string(xsd).unwrap(), DOCTRINE_XSD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_other_servers() {
|
||||
let reg = LanguageRegistry::load(None).unwrap();
|
||||
let yaml = reg.get(&ide_core::LanguageId::new("yaml")).unwrap();
|
||||
let mut cfg = yaml.language_servers[0].clone();
|
||||
let before = cfg.settings.clone();
|
||||
configure_lemminx_catalogs(&mut cfg);
|
||||
assert_eq!(cfg.settings, before);
|
||||
}
|
||||
}
|
||||
+105
-13
@@ -21,9 +21,11 @@
|
||||
<body>
|
||||
<canvas id="map"></canvas>
|
||||
<script>
|
||||
// A minimal minimap over `openidea.editor`: each line 2px high, each character 1px wide,
|
||||
// in its highlight colour; the visible area as a frame that can be dragged; the wheel
|
||||
// scrolls the editor.
|
||||
// A minimal minimap over `openidea.editor`: each line 2px high, each character 1px wide (tabs
|
||||
// as wide as the editor draws them), in its highlight colour; the visible area as a frame that
|
||||
// can be dragged; the wheel scrolls the editor; the marker bar's problems as bars at the right
|
||||
// edge; folded lines left out; the selected lines tinted and the caret's line marked; VCS
|
||||
// changes at the left edge.
|
||||
const editor = window.openidea.editor;
|
||||
const canvas = document.getElementById("map");
|
||||
const ctx = canvas.getContext("2d");
|
||||
@@ -33,6 +35,13 @@
|
||||
let colors = new Map();
|
||||
let loading = new Set();
|
||||
let view = null;
|
||||
let problems = [];
|
||||
let folds = [];
|
||||
let selections = [];
|
||||
let changes = [];
|
||||
let tabSize = 4;
|
||||
const PROBLEM_COLOR = { error: "--openidea-danger", warning: "--openidea-warning" };
|
||||
const PROBLEM_RANK = { error: 2, warning: 1 };
|
||||
let drag = null;
|
||||
let queued = false;
|
||||
|
||||
@@ -40,19 +49,48 @@
|
||||
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(color);
|
||||
return !!m && Math.max(m[1], m[2], m[3]) - Math.min(m[1], m[2], m[3]) < 24;
|
||||
};
|
||||
// Column → x, with tabs expanded to the editor's tab stops.
|
||||
const xOf = (line) => {
|
||||
if (!line.includes("\t")) return (c) => c;
|
||||
const xs = [0];
|
||||
for (let i = 0, x = 0; i < line.length; i++) xs.push((x += line[i] === "\t" ? tabSize - (x % tabSize) : 1));
|
||||
return (c) => xs[Math.min(c, line.length)];
|
||||
};
|
||||
const cssVar = (name) => (window.openidea.theme && window.openidea.theme.vars[name]) || "";
|
||||
|
||||
// Document lines ↔ minimap rows, without the lines folds hide (fractional within a fold's row).
|
||||
const rowOf = (line) => {
|
||||
let hidden = 0;
|
||||
for (const f of folds) {
|
||||
if (line >= f.toLine + 1) hidden += f.toLine - f.fromLine;
|
||||
else if (line > f.fromLine) return f.fromLine - hidden + (line - f.fromLine) / (f.toLine + 1 - f.fromLine);
|
||||
else break;
|
||||
}
|
||||
return line - hidden;
|
||||
};
|
||||
const lineOfRow = (row) => {
|
||||
let hidden = 0;
|
||||
for (const f of folds) {
|
||||
const r = f.fromLine - hidden;
|
||||
if (row >= r + 1) hidden += f.toLine - f.fromLine;
|
||||
else if (row > r) return f.fromLine + (row - r) * (f.toLine + 1 - f.fromLine);
|
||||
else break;
|
||||
}
|
||||
return row + hidden;
|
||||
};
|
||||
|
||||
function layout() {
|
||||
const H = canvas.clientHeight;
|
||||
if (!view) return { H, offset: 0, top: 0, height: 0, range: 1, visible: 0 };
|
||||
const L = Math.max(1, view.lineCount);
|
||||
const visible = Math.max(0, view.lastLine - view.firstLine);
|
||||
const L = Math.max(1, rowOf(view.lineCount));
|
||||
const firstRow = rowOf(view.firstLine);
|
||||
const visible = Math.max(0, rowOf(view.lastLine) - firstRow);
|
||||
const scrollable = Math.max(1, view.scrollHeight - view.clientHeight);
|
||||
const p = Math.min(1, Math.max(0, view.scrollTop / scrollable));
|
||||
const mapH = L * LINE;
|
||||
const offset = p * Math.max(0, mapH - H);
|
||||
const range = Math.max(1, Math.min(H, mapH) - visible * LINE);
|
||||
return { H, offset, top: view.firstLine * LINE - offset, height: visible * LINE, range, visible, L };
|
||||
return { H, offset, top: firstRow * LINE - offset, height: visible * LINE, range, visible, L };
|
||||
}
|
||||
|
||||
function redraw() {
|
||||
@@ -65,7 +103,7 @@
|
||||
queued = false;
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const W = canvas.clientWidth;
|
||||
const { H, offset, top, height } = layout();
|
||||
const { H, offset, top, height, L } = layout();
|
||||
if (canvas.width !== Math.round(W * dpr) || canvas.height !== Math.round(H * dpr)) {
|
||||
canvas.width = Math.round(W * dpr);
|
||||
canvas.height = Math.round(H * dpr);
|
||||
@@ -74,16 +112,28 @@
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
if (!view) return;
|
||||
const first = Math.floor(offset / LINE);
|
||||
const last = Math.min(text.length, Math.ceil((offset + H) / LINE));
|
||||
const last = Math.min(L, Math.ceil((offset + H) / LINE));
|
||||
const missing = [];
|
||||
const muted = cssVar("--openidea-fg-muted");
|
||||
for (let i = first; i < last; i++) {
|
||||
const y = i * LINE - offset;
|
||||
// Selections under the text: the lines they cover tinted, a caret's line a stronger strip.
|
||||
ctx.fillStyle = cssVar("--openidea-accent");
|
||||
for (const s of selections) {
|
||||
const caret = s.anchor.line === s.head.line && s.anchor.column === s.head.column;
|
||||
const from = Math.floor(rowOf(Math.min(s.anchor.line, s.head.line)));
|
||||
const to = Math.floor(rowOf(Math.max(s.anchor.line, s.head.line)));
|
||||
ctx.globalAlpha = caret ? 0.6 : 0.3;
|
||||
ctx.fillRect(0, from * LINE - offset, W, (to - from + 1) * LINE);
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
for (let row = first; row < last; row++) {
|
||||
const i = lineOfRow(row);
|
||||
const y = row * LINE - offset;
|
||||
const line = text[i] || "";
|
||||
const x = xOf(line);
|
||||
// Text without a syntax colour: faint, so the coloured spans stand out.
|
||||
ctx.globalAlpha = 0.2;
|
||||
ctx.fillStyle = muted;
|
||||
for (const m of line.matchAll(/\S+/g)) ctx.fillRect(m.index, y, m[0].length, LINE - 0.5);
|
||||
for (const m of line.matchAll(/\S+/g)) ctx.fillRect(x(m.index), y, m[0].length, LINE - 0.5);
|
||||
ctx.globalAlpha = 1;
|
||||
const spans = colors.get(i);
|
||||
if (!spans) missing.push(i);
|
||||
@@ -92,9 +142,23 @@
|
||||
// Greys (the plain text colour, comments) stay as faint as uncoloured text.
|
||||
if (grey(s.color)) continue;
|
||||
ctx.fillStyle = s.color;
|
||||
ctx.fillRect(s.from, y, s.to - s.from, LINE - 0.5);
|
||||
ctx.fillRect(x(s.from), y, x(s.to) - x(s.from), LINE - 0.5);
|
||||
}
|
||||
}
|
||||
// Changes in the gutter's colours: a bar over changed lines, a notch where lines were deleted.
|
||||
for (const c of changes) {
|
||||
ctx.fillStyle = cssVar(`--openidea-change-${c.kind}`);
|
||||
const y = Math.floor(rowOf(c.line)) * LINE - offset;
|
||||
if (c.kind === "deleted") ctx.fillRect(0, y - 1, 4, 2);
|
||||
else ctx.fillRect(0, y, 2, (Math.floor(rowOf(c.lastLine)) - Math.floor(rowOf(c.line)) + 1) * LINE);
|
||||
}
|
||||
// Problems: errors drawn last, on top; weak warnings in the muted colour.
|
||||
const ranked = [...problems].sort((a, b) => (PROBLEM_RANK[a.severity] || 0) - (PROBLEM_RANK[b.severity] || 0));
|
||||
for (const p of ranked) {
|
||||
ctx.fillStyle = cssVar(PROBLEM_COLOR[p.severity] || "--openidea-fg-muted");
|
||||
const y = Math.floor(rowOf(p.line));
|
||||
ctx.fillRect(W - 3, y * LINE - offset, 3, Math.max(LINE, (Math.floor(rowOf(p.lastLine)) - y + 1) * LINE));
|
||||
}
|
||||
// The visible area: a light accent tint and a 1px border, stronger while dragged.
|
||||
const frameH = Math.max(height, 4);
|
||||
ctx.fillStyle = cssVar("--openidea-accent");
|
||||
@@ -132,8 +196,15 @@
|
||||
view = null;
|
||||
return redraw();
|
||||
}
|
||||
// `tabSize` is API 1.10.
|
||||
tabSize = target.tabSize || 4;
|
||||
const doc = await editor.document.get();
|
||||
text = doc.text.split("\n");
|
||||
// `problems` is API 1.10.
|
||||
problems = editor.problems ? await editor.problems() : [];
|
||||
folds = editor.folded ? await editor.folded() : [];
|
||||
selections = editor.selections ? await editor.selections() : [];
|
||||
changes = editor.changes ? await editor.changes() : [];
|
||||
view = Object.assign(await editor.viewport(), { version: target.version });
|
||||
redraw();
|
||||
}
|
||||
@@ -151,6 +222,27 @@
|
||||
for (const k of [...colors.keys()]) if (k >= fromLine && k < toLine) colors.delete(k);
|
||||
redraw();
|
||||
});
|
||||
if (editor.onProblems)
|
||||
editor.onProblems((p) => {
|
||||
problems = p;
|
||||
redraw();
|
||||
});
|
||||
// `onLayout` is API 1.10.
|
||||
if (editor.onLayout)
|
||||
editor.onLayout((l) => {
|
||||
folds = l.folded;
|
||||
redraw();
|
||||
});
|
||||
if (editor.onSelections)
|
||||
editor.onSelections((s) => {
|
||||
selections = s;
|
||||
redraw();
|
||||
});
|
||||
if (editor.onChanges)
|
||||
editor.onChanges((c) => {
|
||||
changes = c;
|
||||
redraw();
|
||||
});
|
||||
window.openidea.onThemeChange(redraw);
|
||||
new ResizeObserver(redraw).observe(canvas);
|
||||
|
||||
@@ -158,7 +250,7 @@
|
||||
const scrollToFrameTop = (frameTop) => {
|
||||
const { range, visible, L } = layout();
|
||||
const p = Math.min(1, Math.max(0, frameTop / range));
|
||||
void editor.scrollTo(p * Math.max(0, L - visible));
|
||||
void editor.scrollTo(lineOfRow(p * Math.max(0, L - visible)));
|
||||
};
|
||||
canvas.addEventListener("pointerdown", (e) => {
|
||||
if (!view) return;
|
||||
|
||||
@@ -26,9 +26,13 @@ pub fn init_script(jvm_args: &[String]) -> String {
|
||||
let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", ");
|
||||
format!(
|
||||
"// Written by OpenIDEA: VM options of the run configuration.\n\
|
||||
import org.gradle.util.GradleVersion\n\
|
||||
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.\n\
|
||||
def each = {{ tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? \
|
||||
tasks.configureEach(action) : tasks.all(action) }}\n\
|
||||
allprojects {{\n \
|
||||
tasks.withType(JavaExec).configureEach {{ jvmArgs([{list}]) }}\n \
|
||||
tasks.withType(Test).configureEach {{ jvmArgs([{list}]) }}\n\
|
||||
each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
|
||||
each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
|
||||
}}\n"
|
||||
)
|
||||
}
|
||||
@@ -75,8 +79,10 @@ mod tests {
|
||||
fn adds_each_argument_to_java_exec_and_test_tasks() {
|
||||
let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]));
|
||||
let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']";
|
||||
assert!(script.contains(&format!("tasks.withType(JavaExec).configureEach {{ jvmArgs({list}) }}")), "{script}");
|
||||
assert!(script.contains(&format!("tasks.withType(Test).configureEach {{ jvmArgs({list}) }}")), "{script}");
|
||||
assert!(script.contains(&format!("each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
|
||||
assert!(script.contains(&format!("each(tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
|
||||
// Gradle before 4.9 has no `configureEach` (#3864).
|
||||
assert!(script.contains("? tasks.configureEach(action) : tasks.all(action)"), "{script}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
//! jdtls workspaces (`<local data>/lsp/jdtls/<key>`) that no project uses any more.
|
||||
//!
|
||||
//! A workspace is keyed by the project folder and by the settings that need a clean import
|
||||
//! (source paths, output folder, libraries, linked Gradle projects, unlinked Maven poms), so
|
||||
//! each change of those, and each moved or deleted project, leaves the previous workspace
|
||||
//! behind: 50–200 MB of imported model and indexes. Like a cache, one unused for a month is
|
||||
//! removed at start-up; a project that comes back imports again.
|
||||
|
||||
use ide_language::LanguageServerConfig;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
/// Touched each time jdtls starts on a workspace.
|
||||
const USED_MARKER: &str = ".openidea-last-used";
|
||||
/// Workspaces being removed (renamed first, so a server never starts on a half-deleted one).
|
||||
const TRASH_PREFIX: &str = ".removed-";
|
||||
/// How long a workspace may go unused before start-up removes it.
|
||||
pub const UNUSED_FOR: Duration = Duration::from_secs(30 * 24 * 60 * 60);
|
||||
|
||||
fn root(data_dir: &Path) -> PathBuf {
|
||||
data_dir.join("lsp").join("jdtls")
|
||||
}
|
||||
|
||||
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
|
||||
pub fn mark_used(cfg: &LanguageServerConfig) {
|
||||
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
|
||||
let dir = Path::new(dir);
|
||||
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| std::fs::write(dir.join(USED_MARKER), b"")) {
|
||||
tracing::debug!("jdtls: cannot mark {} as used: {e}", dir.display());
|
||||
}
|
||||
}
|
||||
|
||||
/// When a workspace was last used: the latest of our marker (written when jdtls starts) and what
|
||||
/// jdtls itself touches while it runs and when it saves on exit (a server can run for weeks).
|
||||
fn last_used(dir: &Path) -> Option<SystemTime> {
|
||||
let metadata = dir.join(".metadata");
|
||||
[
|
||||
dir.join(USED_MARKER),
|
||||
metadata.join(".log"),
|
||||
metadata.join(".plugins").join("org.eclipse.core.resources"),
|
||||
metadata,
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
|
||||
.max()
|
||||
}
|
||||
|
||||
/// Moves the workspaces unused for longer than `max_age` aside, before any server starts, and
|
||||
/// returns what [`remove`] deletes. Quick: only renames.
|
||||
pub fn take_unused(data_dir: &Path, max_age: Duration) -> Vec<PathBuf> {
|
||||
let root = root(data_dir);
|
||||
let Ok(entries) = std::fs::read_dir(&root) else { return Vec::new() };
|
||||
let now = SystemTime::now();
|
||||
let mut taken = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if name.starts_with(TRASH_PREFIX) {
|
||||
// Left by a start-up that quit before deleting it.
|
||||
taken.push(path);
|
||||
continue;
|
||||
}
|
||||
let unused = last_used(&path).and_then(|t| now.duration_since(t).ok()).is_some_and(|age| age > max_age);
|
||||
if !unused {
|
||||
continue;
|
||||
}
|
||||
let trash = root.join(format!("{TRASH_PREFIX}{name}"));
|
||||
match std::fs::rename(&path, &trash) {
|
||||
Ok(()) => taken.push(trash),
|
||||
Err(e) => tracing::debug!("jdtls: cannot move unused workspace {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
taken
|
||||
}
|
||||
|
||||
/// Deletes what [`take_unused`] moved aside; slow for large workspaces, so off the start-up path.
|
||||
pub fn remove(taken: Vec<PathBuf>) {
|
||||
for dir in taken {
|
||||
match std::fs::remove_dir_all(&dir) {
|
||||
Ok(()) => tracing::info!("jdtls: removed unused workspace {}", dir.display()),
|
||||
Err(e) => tracing::warn!("jdtls: cannot remove unused workspace {}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn days_ago(days: u64) -> SystemTime {
|
||||
SystemTime::now() - Duration::from_secs(days * 24 * 60 * 60)
|
||||
}
|
||||
|
||||
/// Back-dates a file, or (on Unix, where a folder opens as a file) a folder.
|
||||
fn age(path: &Path, days: u64) {
|
||||
let file =
|
||||
if path.is_dir() { std::fs::File::open(path) } else { std::fs::File::options().write(true).open(path) };
|
||||
file.unwrap().set_modified(days_ago(days)).unwrap();
|
||||
}
|
||||
|
||||
fn cfg(data: &Path) -> LanguageServerConfig {
|
||||
let languages = ide_language::LanguageRegistry::load(None).unwrap();
|
||||
let mut cfg = languages.get(&ide_core::LanguageId::new("java")).unwrap().language_servers.remove(0);
|
||||
cfg.args = vec!["-data".into(), data.to_string_lossy().into_owned()];
|
||||
cfg
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removes_workspaces_unused_for_longer_than_the_limit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = root(tmp.path());
|
||||
let (old, recent) = (root.join("old"), root.join("recent"));
|
||||
mark_used(&cfg(&old));
|
||||
mark_used(&cfg(&recent));
|
||||
age(&old.join(USED_MARKER), 40);
|
||||
age(&recent.join(USED_MARKER), 5);
|
||||
std::fs::write(root.join("defaults.prefs"), "").unwrap();
|
||||
|
||||
let taken = take_unused(tmp.path(), UNUSED_FOR);
|
||||
assert_eq!(taken.len(), 1, "{taken:?}");
|
||||
assert!(!old.exists() && recent.exists() && root.join("defaults.prefs").exists());
|
||||
remove(taken);
|
||||
let mut left: Vec<_> = std::fs::read_dir(&root).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
left.sort();
|
||||
assert_eq!(left, ["defaults.prefs", "recent"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_started_server_marks_its_workspace_again() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = root(tmp.path()).join("p");
|
||||
mark_used(&cfg(&ws));
|
||||
age(&ws.join(USED_MARKER), 40);
|
||||
mark_used(&cfg(&ws));
|
||||
assert!(take_unused(tmp.path(), UNUSED_FOR).is_empty());
|
||||
assert!(ws.exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = root(tmp.path()).join("legacy");
|
||||
std::fs::create_dir_all(ws.join(".metadata")).unwrap();
|
||||
std::fs::write(ws.join(".metadata/.log"), "").unwrap();
|
||||
for p in [ws.join(".metadata/.log"), ws.join(".metadata")] {
|
||||
age(&p, 90);
|
||||
}
|
||||
assert_eq!(take_unused(tmp.path(), UNUSED_FOR).len(), 1);
|
||||
// The log alone being recent keeps it.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = root(tmp.path()).join("legacy");
|
||||
std::fs::create_dir_all(ws.join(".metadata")).unwrap();
|
||||
std::fs::write(ws.join(".metadata/.log"), "").unwrap();
|
||||
age(&ws.join(".metadata"), 90);
|
||||
assert!(take_unused(tmp.path(), UNUSED_FOR).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leftovers_of_an_interrupted_removal_are_removed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let trash = root(tmp.path()).join(format!("{TRASH_PREFIX}gone"));
|
||||
std::fs::create_dir_all(trash.join(".metadata")).unwrap();
|
||||
let taken = take_unused(tmp.path(), UNUSED_FOR);
|
||||
assert_eq!(taken, std::slice::from_ref(&trash));
|
||||
remove(taken);
|
||||
assert!(!trash.exists());
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ pub mod go;
|
||||
pub mod godot;
|
||||
pub mod java;
|
||||
pub mod jdtls;
|
||||
pub mod jdtls_workspaces;
|
||||
pub mod libraries;
|
||||
pub mod locate;
|
||||
pub mod lombok;
|
||||
|
||||
@@ -24,6 +24,8 @@ pub use words::{MIN_WORD_CHARS, WordSpan, words};
|
||||
pub enum RegionKind {
|
||||
Comment,
|
||||
String,
|
||||
/// A raw / verbatim string: `\` is literal text, not an escape (`r"\user"`).
|
||||
RawString,
|
||||
/// A declared identifier (`camelCase` / `snake_case` split).
|
||||
Name,
|
||||
/// Plain text / Markdown prose.
|
||||
@@ -53,7 +55,7 @@ impl From<RegionKind> for TypoContext {
|
||||
fn from(kind: RegionKind) -> Self {
|
||||
match kind {
|
||||
RegionKind::Name => Self::Code,
|
||||
RegionKind::String => Self::Literal,
|
||||
RegionKind::String | RegionKind::RawString => Self::Literal,
|
||||
RegionKind::Comment => Self::Comment,
|
||||
RegionKind::Prose => Self::Prose,
|
||||
}
|
||||
@@ -89,7 +91,7 @@ impl SpellScope {
|
||||
pub fn includes(&self, kind: RegionKind) -> bool {
|
||||
match kind {
|
||||
RegionKind::Name => self.code,
|
||||
RegionKind::String => self.literals,
|
||||
RegionKind::String | RegionKind::RawString => self.literals,
|
||||
RegionKind::Comment => self.comments,
|
||||
RegionKind::Prose => true,
|
||||
}
|
||||
@@ -678,6 +680,15 @@ mod tests {
|
||||
assert_eq!(found, [("mesage", TypoContext::Code)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_strings_do_not_lose_the_letter_after_a_backslash() {
|
||||
let s = Speller::default();
|
||||
let text = r#"r"\user \mesage""#;
|
||||
let regions = [Region { start: 0, end: text.len(), kind: RegionKind::RawString }];
|
||||
let typos = s.check(text, ®ions, &|| false).unwrap();
|
||||
assert_eq!(typos.iter().map(|t| t.word.as_str()).collect::<Vec<_>>(), ["mesage"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_filters_region_kinds() {
|
||||
let comments_only = SpellScope { code: false, literals: false, comments: true };
|
||||
|
||||
@@ -18,7 +18,7 @@ pub struct WordSpan {
|
||||
pub fn words(text: &str, start: usize, end: usize, kind: RegionKind, out: &mut Vec<WordSpan>) {
|
||||
let Some(slice) = text.get(start..end) else { return };
|
||||
let escapes = match kind {
|
||||
RegionKind::Name => Escapes::None,
|
||||
RegionKind::Name | RegionKind::RawString => Escapes::None,
|
||||
RegionKind::String => Escapes::Char,
|
||||
RegionKind::Comment | RegionKind::Prose => Escapes::Word,
|
||||
};
|
||||
@@ -186,6 +186,17 @@ mod tests {
|
||||
assert_eq!(split("// 中文注释 naïve", RegionKind::Comment), ["naïve"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_strings_keep_the_letter_after_a_backslash() {
|
||||
// `\u` in a normal string is an escape: the letter is consumed and only
|
||||
// `ser` is prose. In a raw string the backslash is literal, so `user`
|
||||
// must be checked whole (issue: r"\user" flagged as typo 'ser').
|
||||
assert_eq!(split(r#""\user""#, RegionKind::String), ["ser"]);
|
||||
assert_eq!(split(r#""\user""#, RegionKind::RawString), ["user"]);
|
||||
assert_eq!(split(r"\n\t \wrd", RegionKind::RawString), ["wrd"]);
|
||||
assert_eq!(split(r"C:\Users\mesage", RegionKind::RawString), ["Users", "mesage"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_backslash_commands_in_comments() {
|
||||
assert_eq!(split("/// \\brief Returns the sum.", RegionKind::Comment), ["Returns", "the", "sum"]);
|
||||
|
||||
@@ -125,11 +125,11 @@ const discoveredSources: McpExternalSource[] = [
|
||||
nativeProvider: "copilot",
|
||||
servers: [
|
||||
{
|
||||
name: "workiq",
|
||||
name: "playwright",
|
||||
transport: "stdio",
|
||||
enabled: true,
|
||||
command: "npx",
|
||||
args: ["-y", "@microsoft/workiq", "mcp"],
|
||||
args: ["-y", "@playwright/mcp@latest"],
|
||||
url: null,
|
||||
envKeys: [],
|
||||
headerKeys: [],
|
||||
@@ -290,16 +290,18 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
|
||||
await expect(sessionPopup).toContainText("openidea");
|
||||
await expect(sessionPopup).toContainText("postgres-local");
|
||||
await expect(sessionPopup).toContainText("github-mcp-server");
|
||||
await expect(sessionPopup).toContainText("workiq");
|
||||
await expect(sessionPopup).toContainText("playwright");
|
||||
|
||||
// Disable `slack-official` for this session only and verify IPC call + `Session` badge.
|
||||
// Disable `slack-official` (Global) and `playwright` (Agent Config) for this session only.
|
||||
await sessionPopup.getByRole("switch", { name: "Enable slack-official for this session" }).click();
|
||||
await expect(sessionPopup).toContainText("Session");
|
||||
await sessionPopup.getByRole("switch", { name: "Enable playwright for this session" }).click();
|
||||
await expect(sessionPopup).toContainText("Disabled for this session (GitHub Copilot CLI)");
|
||||
const overrideCalls = await ipcCalls(page, "agent_set_mcp_overrides");
|
||||
expect(overrideCalls.at(-1)?.overrides).toEqual({ "slack-official": false });
|
||||
expect(overrideCalls.at(-1)?.overrides).toEqual({ "slack-official": false, playwright: false });
|
||||
|
||||
const screenshotDir = process.env.CAPTURE_MCP_SCREENSHOTS;
|
||||
if (screenshotDir) {
|
||||
await page.waitForTimeout(250);
|
||||
await page.screenshot({ path: `${screenshotDir}/mcp-session-picker.png` });
|
||||
}
|
||||
|
||||
|
||||
+51
-14
@@ -447,6 +447,29 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
|
||||
required `when`: the command runs on a plain Escape in a focused editor once the
|
||||
IDE's own Escape handling (popups, completion, rename, selection, extra carets,
|
||||
Vim) found nothing to do.
|
||||
- **The marker bar's problems in editor panels.** An editor panel's page reads
|
||||
the problems its group's marker bar shows with `openidea.editor.problems()`
|
||||
and hears them change through `onProblems`. See _Editor panels_.
|
||||
- **Semantic highlighting in editor panels.** `openidea.editor.highlights()`
|
||||
returns the colours the editor shows, semantic highlighting from the language
|
||||
server layered over the syntax colours, and `onHighlights` reports the lines
|
||||
whose colours change when semantic tokens arrive. See _Editor panels_.
|
||||
- **Folds and soft wrap in editor panels.** An editor panel's page reads which
|
||||
lines are folded with `openidea.editor.folded()`, how many rows each line takes
|
||||
with soft wrap on with `wrapped(fromLine, toLine)`, and hears both change
|
||||
through `onLayout`. See _Editor panels_.
|
||||
- **The caret and selections in editor panels.** An editor panel's page reads
|
||||
the caret and every selection of its group's editor with
|
||||
`openidea.editor.selections()` and hears them move through `onSelections`. See
|
||||
_Editor panels_.
|
||||
- **VCS changes in editor panels.** An editor panel's page reads the added,
|
||||
modified and deleted lines its group's change-marker lane shows with
|
||||
`openidea.editor.changes()` and hears them change through `onChanges`. Frames
|
||||
get the lane's colours as `--openidea-change-added`, `--openidea-change-modified`
|
||||
and `--openidea-change-deleted`. See _Editor panels_.
|
||||
- **The tab size in editor panels.** `openidea.editor.get()` includes the
|
||||
`tabSize` the editor expands tabs with for the group's file, and `onTarget`
|
||||
reports it again when it changes. See _Editor panels_.
|
||||
|
||||
### API 1.9
|
||||
|
||||
@@ -1751,6 +1774,7 @@ values (the body already uses the text colour, UI font and size):
|
||||
| `--openidea-border`, `--openidea-focus-ring`, `--openidea-link` | Lines, focus, links |
|
||||
| `--openidea-accent`, `--openidea-fg-on-accent` | Accent and text on it |
|
||||
| `--openidea-danger`, `--openidea-warning`, `--openidea-success`, `--openidea-info` | Status colours |
|
||||
| `--openidea-change-added`, `--openidea-change-modified`, `--openidea-change-deleted` | API 1.10: the editor's VCS change markers |
|
||||
| `--openidea-font-ui`, `--openidea-font-mono`, `--openidea-font-size` | Fonts (web fonts the IDE bundles are not available in the frame) |
|
||||
|
||||
Scripts get the same as `openidea.theme` (`{ dark, vars }`) and
|
||||
@@ -1912,22 +1936,35 @@ sit side by side.
|
||||
The page gets `openidea.editor` (only an editor panel's page has it). Lines are
|
||||
0-based, columns UTF-16:
|
||||
|
||||
| `openidea.editor` | What it does |
|
||||
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `get()` | `{ path, language, version, lineCount }` of the group's file, or `null` |
|
||||
| `onTarget(fn)` | Called with `get()` when the group shows another file, or none |
|
||||
| `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame |
|
||||
| `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame |
|
||||
| `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging |
|
||||
| `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel |
|
||||
| `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the syntax colour in the current scheme (a CSS colour) |
|
||||
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed |
|
||||
| `openidea.editor` | What it does |
|
||||
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `get()` | `{ path, language, version, lineCount, tabSize }` of the group's file, or `null`; `tabSize` (API 1.10) is the columns a tab takes in the editor (Code Style, `.editorconfig`, indent detection) |
|
||||
| `onTarget(fn)` | Called with `get()` when the group shows another file, or none, and (API 1.10) when the file's tab size changes |
|
||||
| `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame |
|
||||
| `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame |
|
||||
| `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging |
|
||||
| `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel |
|
||||
| `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the colour the editor shows in the current scheme (a CSS colour; API 1.10: semantic highlighting included) |
|
||||
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed, semantic tokens arrived (API 1.10) |
|
||||
| `problems()` | API 1.10: the problems the marker bar shows, in file order: `[{ line, lastLine, severity }]`, `lastLine` the last line a problem covers, `severity` `error`, `warning` or `weakWarning` |
|
||||
| `onProblems(fn)` | API 1.10: called with `problems()` when a problem appears or goes away, when edits move them, and when the group shows another file; at most once a frame |
|
||||
| `folded()` | API 1.10: the folded ranges, in file order: `[{ fromLine, toLine }]`, `fromLine` the line that stays visible (with the placeholder), `toLine` the last line hidden. Folds inside a fold are part of it |
|
||||
| `wrapped(fromLine, toLine)` | API 1.10: the visual rows of each line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): 1 for a line that fits, 0 for a line a fold hides; `null` while soft wrap is off |
|
||||
| `onLayout(fn)` | API 1.10: called with `{ folded, softWrap }` (`folded()`, and whether soft wrap is on) when folds change, soft wrap turns on or off, wrapped rows may have changed, and the group shows another file; at most once a frame |
|
||||
| `selections()` | API 1.10: the caret and selections: `[{ anchor: { line, column }, head: { line, column } }]`, the main selection first, the others in file order; a caret is a selection whose `anchor` equals `head` |
|
||||
| `onSelections(fn)` | API 1.10: called with `selections()` when the caret moves, a selection changes, and the group shows another file; at most once a frame |
|
||||
| `changes()` | API 1.10: the VCS changes beside the line numbers, in file order: `[{ line, lastLine, kind }]`, `kind` `added`, `modified` or `deleted`; a deletion's `line` is the line below the deleted text. `[]` outside version control |
|
||||
| `onChanges(fn)` | API 1.10: called with `changes()` when the changes are recomputed or edits move them, and when the group shows another file; at most once a frame |
|
||||
|
||||
Colours come from syntax highlighting only (no semantic highlighting yet); the
|
||||
Colours are the editor's: syntax highlighting and, from API 1.10, the semantic
|
||||
highlighting over it (a semantic colour wins where both apply). The
|
||||
panel's other colours are the frame's theme variables (`openidea.theme`,
|
||||
`onThemeChange`). Not there yet: the caret and selections, and the marker bar's
|
||||
problems and changes. `crates/ide-plugin/tests/fixtures/editor-panel` is a
|
||||
minimal minimap (each line 2 px, its frame draggable) to install and try.
|
||||
`onThemeChange`). Before API 1.10 there is no `problems`, `folded`, `wrapped`,
|
||||
`onLayout`, `selections` or `changes`: check for them (`if (editor.problems)`) when the page also runs in
|
||||
older IDEs. Outside the visible area the editor estimates wrapped rows from the
|
||||
line's length until it lays the line out; `onLayout` follows when it does.
|
||||
`crates/ide-plugin/tests/fixtures/editor-panel` is a minimal minimap (each line
|
||||
2 px, its frame draggable, problems marked at its right edge, folded lines left out, the selected lines and the caret's line tinted, VCS changes at its left edge) to install and try.
|
||||
|
||||
### Web frame PTYs (API 1.3)
|
||||
|
||||
|
||||
@@ -37,13 +37,21 @@ pub fn apply(state: &AppState) {
|
||||
let settings = state.global_settings.effective().mcp_server;
|
||||
let mut server = state.mcp.server.lock();
|
||||
if !settings.enabled {
|
||||
if let Some(running) = server.take() {
|
||||
let was_running = server.take();
|
||||
let stopped = was_running.is_some();
|
||||
if let Some(running) = was_running {
|
||||
running.stop();
|
||||
}
|
||||
*state.mcp.running_with.lock() = None;
|
||||
ide_agent::set_mcp_executable(None);
|
||||
state.host.set_mcp_executable(None);
|
||||
*state.mcp.error.lock() = None;
|
||||
drop(server);
|
||||
if stopped {
|
||||
for project in state.host.projects() {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Ok(address) = settings.address.trim().parse::<IpAddr>() else {
|
||||
@@ -96,6 +104,10 @@ pub fn apply(state: &AppState) {
|
||||
*server = Some(started);
|
||||
*state.mcp.running_with.lock() = Some(wanted);
|
||||
*state.mcp.error.lock() = None;
|
||||
drop(server);
|
||||
for project in state.host.projects() {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("MCP server: {e}");
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
} from "@codemirror/state";
|
||||
import { GutterMarker, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import type { LanguageDescription } from "@codemirror/language";
|
||||
import type { HunkKind } from "@/bindings";
|
||||
import type { LineEnding } from "@/platform/ipc";
|
||||
import { create } from "zustand";
|
||||
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
|
||||
@@ -374,6 +375,21 @@ export const scrollbarMarks = Facet.define<readonly ScrollbarMark[], readonly Sc
|
||||
*/
|
||||
export const gutterLaneMarkers = Facet.define<RangeSet<GutterMarker>>();
|
||||
|
||||
/**
|
||||
* The VCS changes the change-marker lane shows, as document offsets of this state (mapped
|
||||
* through edits), in file order. `to <= from` draws a deletion notch on the line at `from`.
|
||||
* Editor panels read them (`openidea.editor.changes()`).
|
||||
*/
|
||||
export interface LineChange {
|
||||
kind: HunkKind;
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
export const lineChanges = Facet.define<readonly LineChange[], readonly LineChange[]>({
|
||||
combine: (values) => values[0] ?? [],
|
||||
});
|
||||
|
||||
/** Marker for `gutterLaneMarkers`: a solid 3px bar (or a small wedge for `deleted`). */
|
||||
export class LaneMarker extends GutterMarker {
|
||||
constructor(
|
||||
|
||||
@@ -20,7 +20,7 @@ import { countColumn, Facet, RangeSetBuilder, type EditorState, type Extension }
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { getIndentUnit, matchBrackets, syntaxTree } from "@codemirror/language";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { BRACKET_COLORS, bracketScanner, type BracketScanner } from "./rainbowBrackets";
|
||||
import { BRACKET_COLORS, LONG_LINE, bracketScanner, type BracketScanner } from "./rainbowBrackets";
|
||||
|
||||
/** How far (px) a guide sits left of its column, so a caret in that column is right of it (IDEA's indent guide shift). */
|
||||
const GUIDE_SHIFT = 2;
|
||||
@@ -188,9 +188,6 @@ export function braceGuide(state: EditorState, step: number): Guide | null {
|
||||
return blockGuide(state, openLine.number, col, step);
|
||||
}
|
||||
|
||||
/** Lines at least this long get no guides, and open no bracket block for them. */
|
||||
const LONG_LINE = 10_000;
|
||||
|
||||
/**
|
||||
* Bracket colour (depth within the palette) per guide level on each of the lines `first`..`last` (index `n - first`).
|
||||
* The guide at `level` belongs to the block opened by the nearest line above indented
|
||||
|
||||
@@ -17,6 +17,40 @@ async function tokens(mode: string, source: string) {
|
||||
return result;
|
||||
}
|
||||
|
||||
describe("Kotlin soft keywords", () => {
|
||||
const styleOf = (out: Awaited<ReturnType<typeof tokens>>, text: string, nth = 0) =>
|
||||
out.filter((t) => t.text === text)[nth]?.style ?? "";
|
||||
|
||||
it("colours a soft keyword only where it acts as one", async () => {
|
||||
const source = [
|
||||
"import top.ttb.data.Model",
|
||||
"data class Point(val x: Int)",
|
||||
"open class Base { val data = result.data; private fun f() {} }",
|
||||
"val open: Int get() = 1",
|
||||
"fun g(data: String) = try { } catch (e: Exception) { } finally { }",
|
||||
].join("\n");
|
||||
const out = await tokens("Kotlin", source);
|
||||
// Package path, property access and names.
|
||||
expect(styleOf(out, "data", 0)).not.toContain("tok-keyword");
|
||||
expect(styleOf(out, "data", 2)).not.toContain("tok-keyword");
|
||||
expect(styleOf(out, "data", 3)).not.toContain("tok-keyword");
|
||||
expect(styleOf(out, "data", 4)).not.toContain("tok-keyword");
|
||||
expect(styleOf(out, "open", 1)).not.toContain("tok-keyword");
|
||||
// Modifiers and accessors.
|
||||
expect(styleOf(out, "import")).toContain("tok-keyword");
|
||||
expect(styleOf(out, "data", 1)).toContain("tok-keyword");
|
||||
expect(styleOf(out, "open", 0)).toContain("tok-keyword");
|
||||
expect(styleOf(out, "private")).toContain("tok-keyword");
|
||||
expect(styleOf(out, "get")).toContain("tok-keyword");
|
||||
expect(styleOf(out, "catch")).toContain("tok-keyword");
|
||||
expect(styleOf(out, "finally")).toContain("tok-keyword");
|
||||
// Hard keywords stay keywords.
|
||||
expect(styleOf(out, "class")).toContain("tok-keyword");
|
||||
expect(styleOf(out, "val")).toContain("tok-keyword");
|
||||
expect(styleOf(out, "fun")).toContain("tok-keyword");
|
||||
});
|
||||
});
|
||||
|
||||
describe("frontend string interpolation", () => {
|
||||
it.each([
|
||||
["Kotlin", 'println("$i + 1 = ${i + 1}")'],
|
||||
|
||||
@@ -152,7 +152,34 @@ export function interpolationParser<S>(base: StreamParser<S>, dialect: Interpola
|
||||
frame.doc = depth > 0 && doc;
|
||||
return doc ? "docComment" : result;
|
||||
}
|
||||
if (dialect === "Kotlin" && result === "keyword" && !kotlinKeywordAt(stream.string, from, stream.pos))
|
||||
return "variable";
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Kotlin's hard keywords: never names, wherever they appear (except after a dot). */
|
||||
const KOTLIN_HARD_KEYWORDS = new Set(
|
||||
"as as? break class continue do else false for fun if in !in interface is !is null object package return super this throw true try typealias typeof val var when while".split(
|
||||
" ",
|
||||
),
|
||||
);
|
||||
/** Soft keywords that open a block or a parameter list rather than precede a name. */
|
||||
const KOTLIN_BLOCK_SOFT_KEYWORDS = new Set(["catch", "finally", "init", "constructor", "get", "set"]);
|
||||
|
||||
/**
|
||||
* Whether the word the base mode calls a keyword is one here. A word after `.` is a member or
|
||||
* package name (`import a.data.b`, `result.data`). Soft keywords (`data`, `open`, `get`…) are
|
||||
* keywords only where they act as one, before a declaration or another modifier (`data class`,
|
||||
* `get() = …`); elsewhere they are ordinary names (`val data = …`), as IDEA colours them.
|
||||
*/
|
||||
function kotlinKeywordAt(line: string, from: number, to: number): boolean {
|
||||
if (/\??\.\s*$/.test(line.slice(0, from))) return false;
|
||||
const word = line.slice(from, to);
|
||||
if (KOTLIN_HARD_KEYWORDS.has(word)) return true;
|
||||
const next = line.slice(to).match(/^\s*(.)/u)?.[1];
|
||||
if (next === undefined) return false;
|
||||
if (/[\p{L}_`@]/u.test(next)) return true;
|
||||
return KOTLIN_BLOCK_SOFT_KEYWORDS.has(word) && (next === "(" || next === "{");
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import { languages } from "@codemirror/language-data";
|
||||
import {
|
||||
BracketScanner,
|
||||
DEFAULT_RAINBOW_OPTIONS,
|
||||
LONG_LINE,
|
||||
bracketClass,
|
||||
bracketScanner,
|
||||
rainbowBrackets,
|
||||
type RainbowBracketOptions,
|
||||
} from "./rainbowBrackets";
|
||||
@@ -157,7 +159,13 @@ describe("rainbow brackets", () => {
|
||||
});
|
||||
|
||||
it("keeps interpolation depth across chunks, viewports and edits", async () => {
|
||||
const doc = "f(`" + "literal ([ ".repeat(500) + "${g([1])}" + " tail ) ".repeat(700) + "`); h()";
|
||||
// Newlines keep every line under `LONG_LINE`; the template still crosses chunk boundaries.
|
||||
const doc =
|
||||
"f(`" +
|
||||
("literal ([ ".repeat(20) + "\n").repeat(30) +
|
||||
"${g([1])}" +
|
||||
(" tail ) ".repeat(20) + "\n").repeat(40) +
|
||||
"`); h()";
|
||||
const ext = await javascript();
|
||||
const scanner = new BracketScanner();
|
||||
const from = doc.indexOf("[1]");
|
||||
@@ -225,6 +233,44 @@ describe("rainbow brackets", () => {
|
||||
expect(new BracketScanner().openAt(js, [js.doc.length]).map((m) => m?.depth)).toEqual([1]);
|
||||
});
|
||||
|
||||
it("jumps over minified lines, keeping the nesting across them", async () => {
|
||||
// The long line starts inside a scan chunk; one of its brackets is never closed.
|
||||
const pad = "y()\n".repeat(1100);
|
||||
const long = `f(${"x({a:[1,2]});".repeat(Math.ceil(LONG_LINE / 13))}`;
|
||||
const doc = `{\n${pad}${long}\n[z]\n}`;
|
||||
const from = doc.indexOf(long);
|
||||
for (const ext of [cStyle, await javascript()]) expect(marks(doc, ext, from)).toEqual(["[1", "]1", "}0"]);
|
||||
// One character shorter, it is scanned like any other line.
|
||||
const short = "x({a:[1,2]});".repeat(Math.floor((LONG_LINE - 1) / 13));
|
||||
expect(marks(`{\n${short}\n[z]\n}`, cStyle).slice(0, 7)).toEqual(["{0", "(1", "{2", "[3", "]3", "}2", ")1"]);
|
||||
const state = EditorState.create({ doc, extensions: cStyle });
|
||||
expect(new BracketScanner().openAt(state, [doc.indexOf("[z]") + 1]).map((m) => m?.depth)).toEqual([1]);
|
||||
});
|
||||
|
||||
it("drops a line's brackets once it grows past the limit and brings them back when it shrinks", () => {
|
||||
// Checkpoints fall inside the line while it is short; its open `f(` must not leak past it once long.
|
||||
const line = `f(${"x({a:[1,2]});".repeat(Math.floor((LONG_LINE - 100) / 13))}`;
|
||||
const doc = `${"y()\n".repeat(1100)}${line}\n[z]\n`;
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, extensions: [cStyle, rainbowBrackets()] }),
|
||||
parent: document.body,
|
||||
});
|
||||
const depthOfZ = () => {
|
||||
const state = view.state;
|
||||
const at = state.doc.toString().indexOf("[z]");
|
||||
return bracketScanner(view)!
|
||||
.marks(state, at, state.doc.length)
|
||||
.map((m) => m.depth);
|
||||
};
|
||||
expect(depthOfZ()).toEqual([1, 1]);
|
||||
const end = doc.indexOf("\n[z]");
|
||||
view.dispatch({ changes: { from: end, insert: "x".repeat(200) } });
|
||||
expect(depthOfZ()).toEqual([0, 0]);
|
||||
view.dispatch({ changes: { from: end, to: end + 200 } });
|
||||
expect(depthOfZ()).toEqual([1, 1]);
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it("is installed by the Rainbow brackets setting", () => {
|
||||
const render = (rainbowBrackets: boolean) => {
|
||||
const view = new EditorView({
|
||||
|
||||
@@ -64,6 +64,12 @@ const CHUNK = 4096;
|
||||
const LOOKAHEAD = 64_000;
|
||||
/** Longest comment / quote token the lexical scanner needs to see past a chunk end. */
|
||||
const TOKEN_SLACK = 8;
|
||||
/**
|
||||
* Lines at least this long (minified code) are jumped over: their brackets are neither
|
||||
* coloured nor counted, and they get no indent guides. Scanning one would cost time in
|
||||
* proportion to its length after every keystroke, since the viewport always holds all of it.
|
||||
*/
|
||||
export const LONG_LINE = 10_000;
|
||||
|
||||
/** Closer char code of each opener char code: `(` `[` `{`. */
|
||||
const CLOSER: Record<number, number> = { 40: 41, 91: 93, 123: 125 };
|
||||
@@ -347,7 +353,19 @@ export class BracketScanner {
|
||||
const blockFirst = comments.block ? comments.block.open.charCodeAt(0) : -1;
|
||||
const angles: AngleEvents | undefined = tree && this.angleNames ? { doc, kindOf: this.kindOf, out: [] } : undefined;
|
||||
while (s.pos < end) {
|
||||
const chunkEnd = Math.min(end, (Math.floor(s.pos / CHUNK) + 1) * CHUNK);
|
||||
const line = doc.lineAt(s.pos);
|
||||
if (line.length >= LONG_LINE && s.pos < line.to) {
|
||||
// Intentionally leave minified lines unmarked and exclude their brackets from nesting.
|
||||
// Resume at its line break, which ends a line comment or string as on a short line.
|
||||
s.pos = line.to;
|
||||
continue;
|
||||
}
|
||||
let chunkEnd = Math.min(end, (Math.floor(s.pos / CHUNK) + 1) * CHUNK);
|
||||
// A long line can start inside this chunk only on the chunk's last line: stop before it.
|
||||
if (chunkEnd < doc.length) {
|
||||
const last = doc.lineAt(chunkEnd);
|
||||
if (last.from > s.pos && last.length >= LONG_LINE) chunkEnd = last.from;
|
||||
}
|
||||
const base = s.pos;
|
||||
const text = doc.sliceString(base, Math.min(doc.length, chunkEnd + TOKEN_SLACK));
|
||||
const stop = chunkEnd - base;
|
||||
@@ -552,7 +570,9 @@ const plugin = ViewPlugin.fromClass(
|
||||
if (reconfigured) this.scanner = new BracketScanner(options);
|
||||
else if (u.docChanged) {
|
||||
let first = Infinity;
|
||||
u.changes.iterChangedRanges((fromA) => (first = Math.min(first, fromA)));
|
||||
// From the line start: a line grown past `LONG_LINE` must not keep checkpoints inside it.
|
||||
const old = u.startState.doc;
|
||||
u.changes.iterChangedRanges((fromA) => (first = Math.min(first, old.lineAt(fromA).from)));
|
||||
this.scanner.invalidate(first);
|
||||
}
|
||||
if (reconfigured || u.docChanged || u.viewportChanged || syntaxTree(u.startState) !== syntaxTree(u.state))
|
||||
|
||||
@@ -67,7 +67,7 @@ export function installColorScheme(): () => void {
|
||||
: null;
|
||||
observer?.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["data-theme", "data-contrast", "data-color-theme", "data-plugin-theme"],
|
||||
attributeFilter: ["data-theme", "data-contrast", "data-color-theme", "data-plugin-theme", "data-red-green"],
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* path through `@codemirror/lint` (wavy underlines, no gutter, no lint
|
||||
* tooltip — `hover.ts` renders diagnostics together with documentation).
|
||||
*/
|
||||
import type { Text } from "@codemirror/state";
|
||||
import type { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorSelection, StateEffect, StateField } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { forEachDiagnostic, linter, setDiagnostics, type Diagnostic as LintDiagnostic } from "@codemirror/lint";
|
||||
@@ -165,32 +165,52 @@ const MARK_COLOR: Partial<Record<Severity, string>> = {
|
||||
info: "var(--info)",
|
||||
};
|
||||
|
||||
/** A diagnostic's mark on the overview lane (the marker bar). */
|
||||
export interface ProblemMark extends ScrollbarMark {
|
||||
to: number;
|
||||
severity: Severity;
|
||||
}
|
||||
|
||||
/** Overview-lane (scrollbar) marks for diagnostics, errors on top. */
|
||||
export function diagnosticMarks(diags: readonly LintDiagnostic[]): ScrollbarMark[] {
|
||||
const out: ScrollbarMark[] = [];
|
||||
export function diagnosticMarks(diags: readonly LintDiagnostic[]): ProblemMark[] {
|
||||
const out: ProblemMark[] = [];
|
||||
for (const d of diags) {
|
||||
const color = MARK_COLOR[d.severity];
|
||||
if (!color || d.markClass?.includes("cm-lsp-unnecessary") || d.markClass?.includes("cm-lsp-typo")) continue;
|
||||
out.push({ from: d.from, to: d.to, color, tooltip: d.message, priority: 3 - SEVERITY_RANK[d.severity] });
|
||||
out.push({
|
||||
from: d.from,
|
||||
to: d.to,
|
||||
color,
|
||||
tooltip: d.message,
|
||||
priority: 3 - SEVERITY_RANK[d.severity],
|
||||
severity: d.severity,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const setMarks = StateEffect.define<readonly ScrollbarMark[]>();
|
||||
const setMarks = StateEffect.define<readonly ProblemMark[]>();
|
||||
|
||||
const marksField = StateField.define<readonly ScrollbarMark[]>({
|
||||
const marksField = StateField.define<readonly ProblemMark[]>({
|
||||
create: () => [],
|
||||
update(marks, tr) {
|
||||
for (const e of tr.effects) if (e.is(setMarks)) return e.value;
|
||||
if (!tr.docChanged || !marks.length) return marks;
|
||||
return marks.map((m) => {
|
||||
const from = tr.changes.mapPos(m.from);
|
||||
return { ...m, from, to: Math.max(from, tr.changes.mapPos(m.to ?? m.from)) };
|
||||
return { ...m, from, to: Math.max(from, tr.changes.mapPos(m.to)) };
|
||||
});
|
||||
},
|
||||
provide: (f) => scrollbarMarks.from(f),
|
||||
});
|
||||
|
||||
const NO_MARKS: readonly ProblemMark[] = [];
|
||||
|
||||
/** The problems the marker bar shows for `state`'s document, in document order; positions follow edits. */
|
||||
export function markerBarProblems(state: EditorState): readonly ProblemMark[] {
|
||||
return state.field(marksField, false) ?? NO_MARKS;
|
||||
}
|
||||
|
||||
const diagnosticsSync = ViewPlugin.fromClass(
|
||||
class {
|
||||
private unsubscribe: () => void;
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
*/
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import type { Tree } from "@lezer/common";
|
||||
import { Prec, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
|
||||
import { Prec, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { commands, type SemanticTokens } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
@@ -207,6 +207,11 @@ const semanticField = StateField.define<DecorationSet>({
|
||||
},
|
||||
});
|
||||
|
||||
/** The semantic marks the editor shows over the syntax colours (empty without semantic highlighting). */
|
||||
export function semanticHighlights(state: EditorState): DecorationSet {
|
||||
return state.field(semanticField, false) ?? Decoration.none;
|
||||
}
|
||||
|
||||
const semanticPlugin = ViewPlugin.fromClass(
|
||||
class {
|
||||
private refresh = debounce(() => void this.run(), 600);
|
||||
|
||||
@@ -210,7 +210,10 @@
|
||||
}
|
||||
/* Imported sessions below the task list: compact rows, not growing space. */
|
||||
.external {
|
||||
flex: none;
|
||||
/* Many imported sessions must not squeeze the task list out of the popup. */
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 40%;
|
||||
overflow-y: auto;
|
||||
padding: 4px 12px 8px;
|
||||
display: flex;
|
||||
|
||||
@@ -59,11 +59,11 @@ const SOURCES: McpExternalSource[] = [
|
||||
nativeProvider: "copilot",
|
||||
servers: [
|
||||
{
|
||||
name: "workiq",
|
||||
name: "playwright",
|
||||
transport: "stdio",
|
||||
enabled: true,
|
||||
command: "npx",
|
||||
args: ["-y", "@microsoft/workiq", "mcp"],
|
||||
args: ["-y", "@playwright/mcp@latest"],
|
||||
url: null,
|
||||
envKeys: [],
|
||||
headerKeys: [],
|
||||
@@ -102,31 +102,37 @@ describe("McpPicker", () => {
|
||||
it("resolves IDE, Project override over Global, agent-scoped defaults, and native CLI configs", async () => {
|
||||
render(<Harness provider="copilot" />);
|
||||
|
||||
// Active by default for copilot: openidea (IDE) + shared (Project) + workiq (Copilot CLI) = 3 of 4 (claude-only is off).
|
||||
// Active by default for copilot: openidea (IDE) + shared (Project) + playwright (Copilot CLI) = 3 of 4 (claude-only is off).
|
||||
const trigger = screen.getByRole("button", { name: "MCP servers" });
|
||||
expect(trigger).toHaveTextContent("MCP3/4");
|
||||
|
||||
fireEvent.click(trigger);
|
||||
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
|
||||
expect(screen.getByText("Overrides Global")).toBeInTheDocument();
|
||||
expect(screen.getByText("workiq")).toBeInTheDocument();
|
||||
expect(screen.getByText("playwright")).toBeInTheDocument();
|
||||
expect(screen.getByText("Active via GitHub Copilot CLI")).toBeInTheDocument();
|
||||
|
||||
// Toggle `shared` off and `claude-only` on for this session only, then Reset.
|
||||
// Toggle `shared` off, `playwright` (native CLI) off, and `claude-only` on for this session only, then Reset.
|
||||
const sharedSwitch = screen.getByRole("switch", { name: "Enable shared for this session" });
|
||||
const claudeSwitch = screen.getByRole("switch", { name: "Enable claude-only for this session" });
|
||||
const playwrightSwitch = screen.getByRole("switch", { name: "Enable playwright for this session" });
|
||||
expect(sharedSwitch).toHaveAttribute("aria-checked", "true");
|
||||
expect(claudeSwitch).toHaveAttribute("aria-checked", "false");
|
||||
expect(playwrightSwitch).toHaveAttribute("aria-checked", "true");
|
||||
|
||||
fireEvent.click(sharedSwitch);
|
||||
fireEvent.click(claudeSwitch);
|
||||
fireEvent.click(playwrightSwitch);
|
||||
expect(sharedSwitch).toHaveAttribute("aria-checked", "false");
|
||||
expect(claudeSwitch).toHaveAttribute("aria-checked", "true");
|
||||
expect(screen.getAllByText("Session")).toHaveLength(2);
|
||||
expect(playwrightSwitch).toHaveAttribute("aria-checked", "false");
|
||||
expect(screen.getByText("Disabled for this session (GitHub Copilot CLI)")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("Session")).toHaveLength(3);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
|
||||
expect(sharedSwitch).toHaveAttribute("aria-checked", "true");
|
||||
expect(claudeSwitch).toHaveAttribute("aria-checked", "false");
|
||||
expect(playwrightSwitch).toHaveAttribute("aria-checked", "true");
|
||||
expect(screen.queryByRole("button", { name: "Reset" })).toBeNull();
|
||||
});
|
||||
|
||||
@@ -149,7 +155,7 @@ describe("McpPicker", () => {
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Import" }));
|
||||
await waitFor(() =>
|
||||
expect(importSelected).toHaveBeenCalledWith("user", [{ sourceId: "copilot-cli", name: "workiq" }], false),
|
||||
expect(importSelected).toHaveBeenCalledWith("user", [{ sourceId: "copilot-cli", name: "playwright" }], false),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -120,7 +120,7 @@ export function McpPicker({
|
||||
? String(resolved.activeCount)
|
||||
: `${resolved.activeCount}/${resolved.totalCount}`;
|
||||
|
||||
const handleToggleItem = (item: SessionMcpItem, nextEnabled: boolean) => {
|
||||
const handleToggleItem = (item: Pick<SessionMcpItem, "name" | "defaultEnabled">, nextEnabled: boolean) => {
|
||||
onChange(nextSessionOverrides(overrides, item, nextEnabled));
|
||||
};
|
||||
|
||||
@@ -317,9 +317,17 @@ export function McpPicker({
|
||||
<div className={styles.rowTitle}>
|
||||
<span className={styles.name}>{item.name}</span>
|
||||
<span className={styles.pill}>{item.server.transport.toUpperCase()}</span>
|
||||
{item.overridden && (
|
||||
<span className={clsx(styles.pill, styles.pillSession)}>
|
||||
<T>Session</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className={styles.sub} title={item.sourcePath}>
|
||||
{formatMessage(tx("Active via {source}"), { source: item.sourceLabel })}
|
||||
{formatMessage(
|
||||
tx(item.enabled ? "Active via {source}" : "Disabled for this session ({source})"),
|
||||
{ source: item.sourceLabel },
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.rowControls}>
|
||||
@@ -334,7 +342,12 @@ export function McpPicker({
|
||||
<T>Import</T>
|
||||
</button>
|
||||
)}
|
||||
<span className={clsx(styles.dot, styles.dotOn)} aria-hidden />
|
||||
<Toggle
|
||||
checked={item.enabled}
|
||||
aria-label={formatMessage(tx("Enable {name} for this session"), { name: item.name })}
|
||||
onChange={(on) => handleToggleItem(item, on)}
|
||||
/>
|
||||
<span className={clsx(styles.dot, item.enabled && styles.dotOn)} aria-hidden />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -80,6 +80,9 @@ export interface NativeCliMcpItem {
|
||||
sourceLabel: string;
|
||||
sourcePath: string;
|
||||
server: McpDiscoveredServer;
|
||||
defaultEnabled: boolean;
|
||||
enabled: boolean;
|
||||
overridden: boolean;
|
||||
}
|
||||
|
||||
export interface ResolvedSessionMcp {
|
||||
@@ -166,20 +169,25 @@ export function resolveSessionMcp(
|
||||
for (const srv of src.servers) {
|
||||
if (seenNames.has(srv.name) || !srv.enabled) continue;
|
||||
seenNames.add(srv.name);
|
||||
const explicit = overrides[srv.name];
|
||||
const enabled = explicit ?? true;
|
||||
nativeCli.push({
|
||||
name: srv.name,
|
||||
sourceId: src.id,
|
||||
sourceLabel: src.label,
|
||||
sourcePath: src.path,
|
||||
server: srv,
|
||||
defaultEnabled: true,
|
||||
enabled,
|
||||
overridden: explicit !== undefined && explicit !== true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const controllable = [...(ideMcpEnabled ? [ide] : []), ...workspace.filter((i) => !i.lockedReason), ...user];
|
||||
const activeCount = controllable.filter((i) => i.enabled).length + nativeCli.length;
|
||||
const activeCount = controllable.filter((i) => i.enabled).length + nativeCli.filter((i) => i.enabled).length;
|
||||
const totalCount = controllable.length + nativeCli.length;
|
||||
const overrideCount = controllable.filter((i) => i.overridden).length;
|
||||
const overrideCount = controllable.filter((i) => i.overridden).length + nativeCli.filter((i) => i.overridden).length;
|
||||
|
||||
return { ide, workspace, user, nativeCli, activeCount, totalCount, overrideCount };
|
||||
}
|
||||
@@ -187,7 +195,7 @@ export function resolveSessionMcp(
|
||||
/** Computes the minimal `mcpOverrides` map after toggling `name` to `nextEnabled`. */
|
||||
export function nextSessionOverrides(
|
||||
current: Readonly<Record<string, boolean>> | undefined,
|
||||
item: SessionMcpItem,
|
||||
item: Pick<SessionMcpItem, "name" | "defaultEnabled">,
|
||||
nextEnabled: boolean,
|
||||
): Record<string, boolean> {
|
||||
const next = { ...(current ?? {}) };
|
||||
|
||||
@@ -1,21 +1,35 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { syntaxHighlighting } from "@codemirror/language";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { codeFolding, foldEffect, syntaxHighlighting, unfoldEffect } from "@codemirror/language";
|
||||
import { Compartment, EditorSelection, EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { PluginInfo } from "@/bindings";
|
||||
import type { Diagnostic, LineHunk, PluginInfo } from "@/bindings";
|
||||
import type { TextEditorHandle } from "@/editor/api";
|
||||
import { diagnosticsExtension, setFileDiagnostics } from "@/editor/lsp/diagnostics";
|
||||
import { lspDoc } from "@/editor/lsp/lsp";
|
||||
import { hunkField, setHunksEffect } from "@/features/vcs/gutter";
|
||||
import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { useEditorGroupPanels } from "@/workbench/contributions";
|
||||
import type { SemanticTokens } from "@/platform/ipc";
|
||||
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
|
||||
import { usePlugins } from "../store";
|
||||
import { FRAME_TAG, frameDocument } from "../views/frame";
|
||||
import { PanelEditor, editorPanelUpdates, projectEditorPanel } from "../views/editorPanel";
|
||||
import { WebView, type FrameEditor, type FrameEditorEvent } from "../views/WebView";
|
||||
|
||||
// The language server's semantic tokens, for the editor's semantic highlighting.
|
||||
const lsp = vi.hoisted(() => ({ tokens: { data: [], tokenTypes: [], tokenModifiers: [] } as SemanticTokens }));
|
||||
const lspSemanticTokens = vi.hoisted(() => async () => ({ status: "ok" as const, data: lsp.tokens }));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const actual = await orig<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspSemanticTokens } };
|
||||
});
|
||||
const { semanticExtension } = await import("@/editor/lsp/semantic");
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
setPluginsBackend(null);
|
||||
usePlugins.setState({ plugins: [] });
|
||||
});
|
||||
@@ -64,9 +78,18 @@ describe("frame bridge: openidea.editor", () => {
|
||||
scrollTo(line: number): Promise<unknown>;
|
||||
scrollBy(pixels: number): Promise<unknown>;
|
||||
highlights(from: number, to: number): Promise<unknown>;
|
||||
problems(): Promise<unknown>;
|
||||
folded(): Promise<unknown>;
|
||||
wrapped(from: number, to: number): Promise<unknown>;
|
||||
selections(): Promise<unknown>;
|
||||
changes(): Promise<unknown>;
|
||||
onTarget(fn: (v: unknown) => void): void;
|
||||
onViewport(fn: (v: unknown) => void): void;
|
||||
onHighlights(fn: (v: unknown) => void): void;
|
||||
onProblems(fn: (v: unknown) => void): void;
|
||||
onLayout(fn: (v: unknown) => void): void;
|
||||
onSelections(fn: (v: unknown) => void): void;
|
||||
onChanges(fn: (v: unknown) => void): void;
|
||||
document: unknown;
|
||||
};
|
||||
expect(editor.document).toBe(api.document);
|
||||
@@ -86,19 +109,43 @@ describe("frame bridge: openidea.editor", () => {
|
||||
expect(sent.at(-1)).toMatchObject({ op: "editor.highlights", args: { fromLine: 0, toLine: 3000 } });
|
||||
send({ reply: sent.at(-1)!.call, error: "at most 2000 lines at a time" });
|
||||
await expect(lines).rejects.toThrow("2000");
|
||||
const problems = editor.problems();
|
||||
expect(sent.at(-1)).toMatchObject({ op: "editor.problems" });
|
||||
send({ reply: sent.at(-1)!.call, value: [{ line: 2, lastLine: 2, severity: "error" }] });
|
||||
await expect(problems).resolves.toEqual([{ line: 2, lastLine: 2, severity: "error" }]);
|
||||
void editor.folded();
|
||||
expect(sent.at(-1)).toMatchObject({ op: "editor.folded" });
|
||||
void editor.wrapped(4, 9);
|
||||
expect(sent.at(-1)).toMatchObject({ op: "editor.wrapped", args: { fromLine: 4, toLine: 9 } });
|
||||
void editor.selections();
|
||||
expect(sent.at(-1)).toMatchObject({ op: "editor.selections" });
|
||||
void editor.changes();
|
||||
expect(sent.at(-1)).toMatchObject({ op: "editor.changes" });
|
||||
|
||||
const events: unknown[] = [];
|
||||
editor.onTarget((v) => events.push(["target", v]));
|
||||
editor.onViewport((v) => events.push(["viewport", v]));
|
||||
editor.onHighlights((v) => events.push(["highlights", v]));
|
||||
editor.onProblems((v) => events.push(["problems", v]));
|
||||
editor.onLayout((v) => events.push(["layout", v]));
|
||||
editor.onSelections((v) => events.push(["selections", v]));
|
||||
editor.onChanges((v) => events.push(["changes", v]));
|
||||
send({ editor: "target", value: null });
|
||||
send({ editor: "viewport", value: { firstLine: 1.5 } });
|
||||
send({ editor: "highlights", value: { fromLine: 0, toLine: 4 } });
|
||||
send({ editor: "problems", value: [] });
|
||||
send({ editor: "layout", value: { folded: [], softWrap: true } });
|
||||
send({ editor: "selections", value: [] });
|
||||
send({ editor: "changes", value: [] });
|
||||
send({ editor: "constructor", value: 1 });
|
||||
expect(events).toEqual([
|
||||
["target", null],
|
||||
["viewport", { firstLine: 1.5 }],
|
||||
["highlights", { fromLine: 0, toLine: 4 }],
|
||||
["problems", []],
|
||||
["layout", { folded: [], softWrap: true }],
|
||||
["selections", []],
|
||||
["changes", []],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -116,7 +163,7 @@ describe("WebView as an editor panel", () => {
|
||||
const listeners = new Set<(e: FrameEditorEvent) => void>();
|
||||
const calls: unknown[] = [];
|
||||
const editor: FrameEditor & { fire(e: FrameEditorEvent): void } = {
|
||||
get: () => ({ path: "/p/a.ts", language: "typescript", version: 2, lineCount: 3 }),
|
||||
get: () => ({ path: "/p/a.ts", language: "typescript", version: 2, lineCount: 3, tabSize: 4 }),
|
||||
viewport: () => ({ firstLine: 0, lastLine: 2.5, lineCount: 3, scrollTop: 0, scrollHeight: 60, clientHeight: 50 }),
|
||||
scrollTo: (line) => void calls.push(["scrollTo", line]),
|
||||
scrollBy: (px) => void calls.push(["scrollBy", px]),
|
||||
@@ -124,6 +171,14 @@ describe("WebView as an editor panel", () => {
|
||||
calls.push(["highlights", from, to]);
|
||||
return [[{ from: 0, to: 5, color: "rgb(1, 2, 3)" }]];
|
||||
},
|
||||
problems: () => [{ line: 1, lastLine: 2, severity: "warning" }],
|
||||
folded: () => [{ fromLine: 0, toLine: 2 }],
|
||||
selections: () => [{ anchor: { line: 1, column: 0 }, head: { line: 1, column: 4 } }],
|
||||
changes: () => [{ line: 0, lastLine: 1, kind: "added" }],
|
||||
wrapped: (from, to) => {
|
||||
calls.push(["wrapped", from, to]);
|
||||
return [1, 3];
|
||||
},
|
||||
subscribe: (l) => {
|
||||
listeners.add(l);
|
||||
return () => void listeners.delete(l);
|
||||
@@ -157,7 +212,13 @@ describe("WebView as an editor panel", () => {
|
||||
});
|
||||
|
||||
send({ call: 1, op: "editor.get" });
|
||||
expect((await reply(1)).value).toEqual({ path: "/p/a.ts", language: "typescript", version: 2, lineCount: 3 });
|
||||
expect((await reply(1)).value).toEqual({
|
||||
path: "/p/a.ts",
|
||||
language: "typescript",
|
||||
version: 2,
|
||||
lineCount: 3,
|
||||
tabSize: 4,
|
||||
});
|
||||
send({ call: 2, op: "editor.highlights", args: { fromLine: 0, toLine: 1 } });
|
||||
expect((await reply(2)).value).toEqual([[{ from: 0, to: 5, color: "rgb(1, 2, 3)" }]]);
|
||||
send({ call: 3, op: "editor.highlights", args: { fromLine: 0, toLine: 2001 } });
|
||||
@@ -178,6 +239,21 @@ describe("WebView as an editor panel", () => {
|
||||
// Read-only: the page cannot edit the group's file.
|
||||
send({ call: 8, op: "document.edit", args: { version: 0, edits: [] } });
|
||||
expect((await reply(8)).error).toBeDefined();
|
||||
send({ call: 9, op: "editor.problems" });
|
||||
expect((await reply(9)).value).toEqual([{ line: 1, lastLine: 2, severity: "warning" }]);
|
||||
send({ call: 10, op: "editor.folded" });
|
||||
expect((await reply(10)).value).toEqual([{ fromLine: 0, toLine: 2 }]);
|
||||
send({ call: 11, op: "editor.wrapped", args: { fromLine: 1, toLine: 3 } });
|
||||
expect((await reply(11)).value).toEqual([1, 3]);
|
||||
send({ call: 12, op: "editor.wrapped", args: { fromLine: 0, toLine: 2001 } });
|
||||
expect(String((await reply(12)).error)).toContain("2000");
|
||||
send({ call: 13, op: "editor.wrapped", args: { fromLine: 0.5, toLine: 2 } });
|
||||
expect((await reply(13)).error).toBeDefined();
|
||||
expect(calls.at(-1)).toEqual(["wrapped", 1, 3]);
|
||||
send({ call: 14, op: "editor.selections" });
|
||||
expect((await reply(14)).value).toEqual([{ anchor: { line: 1, column: 0 }, head: { line: 1, column: 4 } }]);
|
||||
send({ call: 15, op: "editor.changes" });
|
||||
expect((await reply(15)).value).toEqual([{ line: 0, lastLine: 1, kind: "added" }]);
|
||||
|
||||
editor.fire({ editor: "highlights", value: { fromLine: 0, toLine: 3 } });
|
||||
expect(posted.at(-1)).toEqual({ tag: FRAME_TAG, editor: "highlights", value: { fromLine: 0, toLine: 3 } });
|
||||
@@ -226,7 +302,7 @@ describe("PanelEditor", () => {
|
||||
panel.bind(handle);
|
||||
expect(events[0]).toEqual({
|
||||
editor: "target",
|
||||
value: { path: "/p/src/a.js", language: "javascript", version: 1, lineCount: 3 },
|
||||
value: { path: "/p/src/a.js", language: "javascript", version: 1, lineCount: 3, tabSize: 4 },
|
||||
});
|
||||
expect(panel.document.read()).toMatchObject({ readOnly: true, name: "a.js", text: view.state.doc.toString() });
|
||||
expect(() => panel.document.edit(0, [])).toThrow("read-only");
|
||||
@@ -273,6 +349,438 @@ describe("PanelEditor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("PanelEditor semantic highlights", () => {
|
||||
it("layers the semantic colours over the syntax colours and follows the tokens", async () => {
|
||||
vi.useFakeTimers();
|
||||
const PATH = "/p/src/semantic.js";
|
||||
lsp.tokens = { data: [1, 0, 5, 0, 0], tokenTypes: ["property"], tokenModifiers: [] };
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({
|
||||
doc: "let total = 1;\ntotal;\nend",
|
||||
extensions: [
|
||||
lspDoc.of({ doc: 1, path: PATH, language: "javascript", uiMode: null, readOnly: false }),
|
||||
javascript(),
|
||||
syntaxHighlighting(openideaHighlightStyle),
|
||||
semanticExtension(),
|
||||
EditorView.theme({ ".cm-sem-property": { color: "rgb(1, 2, 3)" } }),
|
||||
editorPanelUpdates,
|
||||
],
|
||||
}),
|
||||
});
|
||||
const handle: TextEditorHandle = {
|
||||
view,
|
||||
tabId: "t1",
|
||||
ctx: { doc: 1, path: PATH, language: "javascript", uiMode: "JavaScript", readOnly: false },
|
||||
};
|
||||
const panel = new PanelEditor();
|
||||
const events: FrameEditorEvent[] = [];
|
||||
panel.subscribe((e) => events.push(e));
|
||||
panel.bind(handle);
|
||||
const syntaxOnly = panel.highlights(0, 3);
|
||||
const semantic = "rgb(1, 2, 3)";
|
||||
expect(syntaxOnly.flat().map((s) => s.color)).not.toContain(semantic);
|
||||
|
||||
// The tokens arrive: line 1's `total` takes the semantic colour; the other lines keep theirs.
|
||||
events.length = 0;
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(view.contentDOM.querySelector(".cm-sem-property")).not.toBeNull();
|
||||
expect(events).toContainEqual({ editor: "highlights", value: { fromLine: 1, toLine: 2 } });
|
||||
const lines = panel.highlights(0, 3);
|
||||
expect(lines[1]).toContainEqual({ from: 0, to: 5, color: semantic });
|
||||
expect(lines[1]!.filter((s) => s.from < 5)).toHaveLength(1);
|
||||
expect(lines[0]).toEqual(syntaxOnly[0]);
|
||||
expect(lines[2]).toEqual(syntaxOnly[2]);
|
||||
|
||||
// Refreshed after an edit at the end: the token moved to line 0, whose colours are reported.
|
||||
lsp.tokens = { data: [0, 4, 5, 0, 0], tokenTypes: ["property"], tokenModifiers: [] };
|
||||
view.dispatch({ changes: { from: view.state.doc.length, insert: "!" } });
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
events.length = 0;
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(events).toContainEqual({ editor: "highlights", value: { fromLine: 0, toLine: 2 } });
|
||||
expect(panel.highlights(0, 1)[0]).toContainEqual({ from: 4, to: 9, color: semantic });
|
||||
expect(panel.highlights(1, 2)).toEqual([syntaxOnly[1]]);
|
||||
|
||||
panel.dispose();
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PanelEditor layout", () => {
|
||||
it("reports the folded lines and the rows of wrapped lines, and follows them", async () => {
|
||||
const long = "x".repeat(200);
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({
|
||||
doc: `function f() {\n a;\n b;\n}\n${long}\nend`,
|
||||
extensions: [codeFolding(), editorPanelUpdates],
|
||||
}),
|
||||
});
|
||||
const handle: TextEditorHandle = {
|
||||
view,
|
||||
tabId: "t1",
|
||||
ctx: { doc: 1, path: "/p/src/a.js", language: "javascript", uiMode: "JavaScript", readOnly: false },
|
||||
};
|
||||
const panel = new PanelEditor();
|
||||
const events: FrameEditorEvent[] = [];
|
||||
panel.subscribe((e) => events.push(e));
|
||||
panel.bind(handle);
|
||||
await nextFrame();
|
||||
// Neither: no folds, no rows (switching to a file says so).
|
||||
expect(panel.folded()).toEqual([]);
|
||||
expect(panel.wrapped(0, 6)).toBeNull();
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: [], softWrap: false } },
|
||||
]);
|
||||
|
||||
// Folding lines 1–2 (the `{` line stays, `}` joins it), and a fold inside it.
|
||||
events.length = 0;
|
||||
const open = view.state.doc.line(1).to;
|
||||
const close = view.state.doc.line(4).from;
|
||||
view.dispatch({
|
||||
effects: [foldEffect.of({ from: open, to: close }), foldEffect.of({ from: open + 3, to: open + 6 })],
|
||||
});
|
||||
await nextFrame();
|
||||
const folds = [{ fromLine: 0, toLine: 3 }];
|
||||
expect(panel.folded()).toEqual(folds);
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: folds, softWrap: false } },
|
||||
]);
|
||||
|
||||
// Soft wrap on: the long line takes several rows, the folded ones none. jsdom lays nothing
|
||||
// out, so the measured state stands in: wrapping on, the long line's block three rows high.
|
||||
events.length = 0;
|
||||
let wrapping = false;
|
||||
Object.defineProperty(view, "lineWrapping", { get: () => wrapping });
|
||||
const lineBlockAt = view.lineBlockAt.bind(view);
|
||||
vi.spyOn(view, "lineBlockAt").mockImplementation((pos) => {
|
||||
const b = lineBlockAt(pos);
|
||||
return b.from === view.state.doc.line(5).from
|
||||
? Object.assign(Object.create(b), { height: 3 * view.defaultLineHeight })
|
||||
: b;
|
||||
});
|
||||
wrapping = true;
|
||||
view.dispatch({ effects: StateEffect.appendConfig.of(EditorView.lineWrapping) });
|
||||
await nextFrame();
|
||||
const rows = panel.wrapped(0, 6)!;
|
||||
expect(rows).toEqual([1, 0, 0, 0, 3, 1]);
|
||||
expect(panel.wrapped(4, 99)).toEqual(rows.slice(4));
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: folds, softWrap: true } },
|
||||
]);
|
||||
|
||||
// The outer fold opened: the lines come back, but for the inner fold's.
|
||||
events.length = 0;
|
||||
view.dispatch({ effects: unfoldEffect.of({ from: open, to: close }) });
|
||||
await nextFrame();
|
||||
const inner = [{ fromLine: 1, toLine: 2 }];
|
||||
expect(panel.folded()).toEqual(inner);
|
||||
expect(panel.wrapped(0, 4)).toEqual([1, 1, 0, 1]);
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: inner, softWrap: true } },
|
||||
]);
|
||||
|
||||
// Soft wrap off: no rows.
|
||||
events.length = 0;
|
||||
wrapping = false;
|
||||
view.dispatch({ effects: StateEffect.reconfigure.of([codeFolding(), editorPanelUpdates]) });
|
||||
await nextFrame();
|
||||
expect(panel.wrapped(0, 4)).toBeNull();
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([
|
||||
{ editor: "layout", value: { folded: inner, softWrap: false } },
|
||||
]);
|
||||
|
||||
// Selecting alone says nothing.
|
||||
events.length = 0;
|
||||
view.dispatch({ selection: { anchor: 2 } });
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "layout")).toEqual([]);
|
||||
|
||||
panel.dispose();
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PanelEditor problems", () => {
|
||||
const PATH = "/p/src/problems.js";
|
||||
const at = (line: number, col: number, endLine = line, endCol = col + 1) => ({
|
||||
start: { line, col },
|
||||
end: { line: endLine, col: endCol },
|
||||
});
|
||||
const diag = (range: ReturnType<typeof at>, severity: Diagnostic["severity"], extra: Partial<Diagnostic> = {}) =>
|
||||
({ range, severity, message: severity, source: null, code: null, ...extra }) as Diagnostic;
|
||||
|
||||
it("reports the marker bar's problems by line and follows them", async () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({
|
||||
doc: "let a = 1;\nlet b = 2;\nfoo(\n bar);\nend",
|
||||
extensions: [
|
||||
lspDoc.of({ doc: 1, path: PATH, language: "javascript", uiMode: null, readOnly: false }),
|
||||
diagnosticsExtension(),
|
||||
editorPanelUpdates,
|
||||
],
|
||||
}),
|
||||
});
|
||||
const handle: TextEditorHandle = {
|
||||
view,
|
||||
tabId: "t1",
|
||||
ctx: { doc: 1, path: PATH, language: "javascript", uiMode: "JavaScript", readOnly: false },
|
||||
};
|
||||
const panel = new PanelEditor();
|
||||
const events: FrameEditorEvent[] = [];
|
||||
panel.subscribe((e) => events.push(e));
|
||||
panel.bind(handle);
|
||||
await nextFrame();
|
||||
// Switching to a file: its problems (none yet).
|
||||
expect(events).toContainEqual({ editor: "problems", value: [] });
|
||||
|
||||
events.length = 0;
|
||||
setFileDiagnostics(PATH, "test", [
|
||||
diag(at(2, 0, 3, 6), "error"),
|
||||
diag(at(0, 4), "warning"),
|
||||
diag(at(1, 4), "info"),
|
||||
// Not on the marker bar: hints, unused code.
|
||||
diag(at(4, 0), "hint"),
|
||||
diag(at(0, 0), "warning", { unnecessary: true }),
|
||||
]);
|
||||
await Promise.resolve();
|
||||
await nextFrame();
|
||||
const shown = [
|
||||
{ line: 0, lastLine: 0, severity: "warning" },
|
||||
{ line: 1, lastLine: 1, severity: "weakWarning" },
|
||||
{ line: 2, lastLine: 3, severity: "error" },
|
||||
];
|
||||
expect(panel.problems()).toEqual(shown);
|
||||
expect(events.filter((e) => e.editor === "problems")).toEqual([{ editor: "problems", value: shown }]);
|
||||
|
||||
// An edit above moves them.
|
||||
events.length = 0;
|
||||
view.dispatch({ changes: { from: 0, insert: "\n" } });
|
||||
await nextFrame();
|
||||
expect(events).toContainEqual({
|
||||
editor: "problems",
|
||||
value: shown.map((p) => ({ ...p, line: p.line + 1, lastLine: p.lastLine + 1 })),
|
||||
});
|
||||
|
||||
// Fixed: gone.
|
||||
events.length = 0;
|
||||
setFileDiagnostics(PATH, "test", []);
|
||||
await Promise.resolve();
|
||||
await nextFrame();
|
||||
expect(events).toEqual([{ editor: "problems", value: [] }]);
|
||||
|
||||
// Scrolling or selecting alone says nothing.
|
||||
events.length = 0;
|
||||
view.dispatch({ selection: { anchor: 2 } });
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "problems")).toEqual([]);
|
||||
|
||||
panel.dispose();
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PanelEditor selections", () => {
|
||||
const view = (doc: string) => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
return new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
extensions: [EditorState.allowMultipleSelections.of(true), editorPanelUpdates],
|
||||
}),
|
||||
});
|
||||
};
|
||||
const handleOf = (v: EditorView, path: string): TextEditorHandle => ({
|
||||
view: v,
|
||||
tabId: path,
|
||||
ctx: { doc: 1, path, language: "javascript", uiMode: "JavaScript", readOnly: false },
|
||||
});
|
||||
const at = (line: number, column: number) => ({ line, column });
|
||||
|
||||
it("reports the caret and every selection, the main one first, and follows them", async () => {
|
||||
// Line 0 is "é😀ab": the emoji takes two UTF-16 columns.
|
||||
const a = view("é😀ab\nsecond\nthird");
|
||||
const panel = new PanelEditor();
|
||||
const events: FrameEditorEvent[] = [];
|
||||
panel.subscribe((e) => events.push(e));
|
||||
panel.bind(handleOf(a, "/p/a.js"));
|
||||
await nextFrame();
|
||||
// Showing a file: its caret (at the start).
|
||||
expect(events).toContainEqual({ editor: "selections", value: [{ anchor: at(0, 0), head: at(0, 0) }] });
|
||||
|
||||
// Two selections and a caret; the main one (the last) comes first, the others in file order.
|
||||
events.length = 0;
|
||||
const three = EditorSelection.create(
|
||||
[EditorSelection.range(1, 3), EditorSelection.range(12, 7), EditorSelection.cursor(15)],
|
||||
2,
|
||||
);
|
||||
a.dispatch({ selection: three });
|
||||
const shown = [
|
||||
{ anchor: at(2, 2), head: at(2, 2) },
|
||||
{ anchor: at(0, 1), head: at(0, 3) },
|
||||
{ anchor: at(1, 6), head: at(1, 1) },
|
||||
];
|
||||
expect(panel.selections()).toEqual(shown);
|
||||
// Several moves in one frame: one event.
|
||||
a.dispatch({ selection: EditorSelection.cursor(0) });
|
||||
a.dispatch({ selection: three });
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "selections")).toEqual([{ editor: "selections", value: shown }]);
|
||||
|
||||
// An edit above moves the caret to another line.
|
||||
events.length = 0;
|
||||
a.dispatch({ changes: { from: 0, insert: "\n" }, selection: EditorSelection.cursor(1) });
|
||||
await nextFrame();
|
||||
expect(events).toContainEqual({ editor: "selections", value: [{ anchor: at(1, 0), head: at(1, 0) }] });
|
||||
|
||||
// Scrolling alone says nothing.
|
||||
events.length = 0;
|
||||
a.scrollDOM.dispatchEvent(new Event("scroll"));
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "selections")).toEqual([]);
|
||||
|
||||
// Another file: its selections.
|
||||
const b = view("x\ny");
|
||||
b.dispatch({ selection: EditorSelection.range(0, 3) });
|
||||
events.length = 0;
|
||||
panel.bind(handleOf(b, "/p/b.js"));
|
||||
await nextFrame();
|
||||
expect(events).toContainEqual({ editor: "selections", value: [{ anchor: at(0, 0), head: at(1, 1) }] });
|
||||
|
||||
panel.bind(null);
|
||||
expect(panel.selections()).toEqual([]);
|
||||
panel.dispose();
|
||||
a.destroy();
|
||||
b.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PanelEditor changes", () => {
|
||||
const hunk = (kind: LineHunk["kind"], start: number, lines: number): LineHunk => ({
|
||||
kind,
|
||||
start,
|
||||
lines,
|
||||
oldStart: start,
|
||||
oldLines: kind === "added" ? 0 : 1,
|
||||
oldText: kind === "added" ? "" : "old\n",
|
||||
});
|
||||
|
||||
it("reports the change lane's hunks by line and follows them", async () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({ doc: "a\nb\nc\nd\ne\nf", extensions: [hunkField, editorPanelUpdates] }),
|
||||
});
|
||||
const handle: TextEditorHandle = {
|
||||
view,
|
||||
tabId: "t1",
|
||||
ctx: { doc: 1, path: "/p/src/a.js", language: "javascript", uiMode: "JavaScript", readOnly: false },
|
||||
};
|
||||
const panel = new PanelEditor();
|
||||
const events: FrameEditorEvent[] = [];
|
||||
panel.subscribe((e) => events.push(e));
|
||||
panel.bind(handle);
|
||||
await nextFrame();
|
||||
// Showing a file: its changes (none yet, as outside version control).
|
||||
expect(events).toContainEqual({ editor: "changes", value: [] });
|
||||
|
||||
events.length = 0;
|
||||
view.dispatch({ effects: setHunksEffect.of([hunk("added", 0, 1), hunk("modified", 2, 2), hunk("deleted", 5, 0)]) });
|
||||
const shown = [
|
||||
{ line: 0, lastLine: 0, kind: "added" },
|
||||
{ line: 2, lastLine: 3, kind: "modified" },
|
||||
// Deleted above line 5: marked on line 5.
|
||||
{ line: 5, lastLine: 5, kind: "deleted" },
|
||||
];
|
||||
expect(panel.changes()).toEqual(shown);
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "changes")).toEqual([{ editor: "changes", value: shown }]);
|
||||
|
||||
// An edit above moves them; deleting the added line leaves a deletion, as the lane shows it.
|
||||
events.length = 0;
|
||||
view.dispatch({ changes: { from: 0, to: 2 } });
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "changes")).toEqual([
|
||||
{
|
||||
editor: "changes",
|
||||
value: [
|
||||
{ line: 0, lastLine: 0, kind: "deleted" },
|
||||
{ line: 1, lastLine: 2, kind: "modified" },
|
||||
{ line: 4, lastLine: 4, kind: "deleted" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
// Moving the caret alone says nothing.
|
||||
events.length = 0;
|
||||
view.dispatch({ selection: { anchor: 1 } });
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "changes")).toEqual([]);
|
||||
|
||||
// No changes any more.
|
||||
events.length = 0;
|
||||
view.dispatch({ effects: setHunksEffect.of([]) });
|
||||
await nextFrame();
|
||||
expect(events).toEqual([{ editor: "changes", value: [] }]);
|
||||
|
||||
panel.dispose();
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("PanelEditor tab size", () => {
|
||||
it("reports the editor's tab size and the new one when it changes", async () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const indent = new Compartment();
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({ doc: "\tx", extensions: [indent.of(EditorState.tabSize.of(2)), editorPanelUpdates] }),
|
||||
});
|
||||
const handle: TextEditorHandle = {
|
||||
view,
|
||||
tabId: "t1",
|
||||
ctx: { doc: 1, path: "/p/src/a.go", language: "go", uiMode: "Go", readOnly: false },
|
||||
};
|
||||
const panel = new PanelEditor();
|
||||
const events: FrameEditorEvent[] = [];
|
||||
panel.subscribe((e) => events.push(e));
|
||||
panel.bind(handle);
|
||||
expect(panel.get()).toMatchObject({ path: "/p/src/a.go", tabSize: 2 });
|
||||
await nextFrame();
|
||||
|
||||
// A settings or `.editorconfig` change: `onTarget` again, once a frame.
|
||||
events.length = 0;
|
||||
view.dispatch({ effects: indent.reconfigure(EditorState.tabSize.of(8)) });
|
||||
view.dispatch({ effects: indent.reconfigure(EditorState.tabSize.of(3)) });
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "target")).toEqual([
|
||||
{ editor: "target", value: { path: "/p/src/a.go", language: "go", version: 1, lineCount: 1, tabSize: 3 } },
|
||||
]);
|
||||
|
||||
// The same size again, or an edit: no new target.
|
||||
events.length = 0;
|
||||
view.dispatch({ effects: indent.reconfigure(EditorState.tabSize.of(3)) });
|
||||
view.dispatch({ changes: { from: 0, insert: "y" } });
|
||||
await nextFrame();
|
||||
expect(events.filter((e) => e.editor === "target")).toEqual([]);
|
||||
|
||||
panel.dispose();
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("editorPanels projection", () => {
|
||||
it("shows the panel only while `editor.read` is granted and `when` holds", () => {
|
||||
const plugin = (granted: boolean) =>
|
||||
|
||||
@@ -73,6 +73,8 @@ export interface EditorTarget {
|
||||
language: string;
|
||||
version: number;
|
||||
lineCount: number;
|
||||
/** The columns a tab takes, as the editor expands it. */
|
||||
tabSize: number;
|
||||
}
|
||||
|
||||
/** What `openidea.editor.viewport()` returns: 0-based lines, fractional within a line. */
|
||||
@@ -91,10 +93,56 @@ export interface HighlightSpan {
|
||||
color: string;
|
||||
}
|
||||
|
||||
/** One problem of the marker bar, as `openidea.editor.problems()` returns it: 0-based lines. */
|
||||
export interface EditorProblem {
|
||||
line: number;
|
||||
/** The last line the problem covers (`line` for most). */
|
||||
lastLine: number;
|
||||
severity: "error" | "warning" | "weakWarning";
|
||||
}
|
||||
|
||||
/** A fold, as `openidea.editor.folded()` returns it: 0-based lines. */
|
||||
export interface EditorFold {
|
||||
/** The line that stays visible, showing the placeholder. */
|
||||
fromLine: number;
|
||||
/** The last line the fold hides. */
|
||||
toLine: number;
|
||||
}
|
||||
|
||||
/** A VCS change of the change-marker lane, as `openidea.editor.changes()` returns it: 0-based lines. */
|
||||
export interface EditorChange {
|
||||
line: number;
|
||||
/** The last changed line; `line` for a deletion, marked on the line the deleted text was above. */
|
||||
lastLine: number;
|
||||
kind: "added" | "modified" | "deleted";
|
||||
}
|
||||
|
||||
/** A position in the document: 0-based line, UTF-16 column. */
|
||||
export interface EditorPosition {
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
/** A selection, as `openidea.editor.selections()` returns it; the caret is one whose `anchor` equals `head`. */
|
||||
export interface EditorSelection {
|
||||
anchor: EditorPosition;
|
||||
head: EditorPosition;
|
||||
}
|
||||
|
||||
/** What `openidea.editor.onLayout` hears: the folds, and whether long lines wrap. */
|
||||
export interface EditorLayout {
|
||||
folded: EditorFold[];
|
||||
softWrap: boolean;
|
||||
}
|
||||
|
||||
export type FrameEditorEvent =
|
||||
| { editor: "target"; value: EditorTarget | null }
|
||||
| { editor: "viewport"; value: EditorViewport }
|
||||
| { editor: "highlights"; value: { fromLine: number; toLine: number } };
|
||||
| { editor: "highlights"; value: { fromLine: number; toLine: number } }
|
||||
| { editor: "problems"; value: EditorProblem[] }
|
||||
| { editor: "layout"; value: EditorLayout }
|
||||
| { editor: "selections"; value: EditorSelection[] }
|
||||
| { editor: "changes"; value: EditorChange[] };
|
||||
|
||||
/** The text editor an editor panel's frame follows (`openidea.editor`). */
|
||||
export interface FrameEditor {
|
||||
@@ -104,6 +152,13 @@ export interface FrameEditor {
|
||||
scrollBy(pixels: number): void;
|
||||
/** Lines `fromLine` up to `toLine` (exclusive); throws over {@link MAX_HIGHLIGHT_LINES}. */
|
||||
highlights(fromLine: number, toLine: number): HighlightSpan[][];
|
||||
problems(): EditorProblem[];
|
||||
folded(): EditorFold[];
|
||||
/** Visual rows of lines `fromLine` up to `toLine` (0 for lines folds hide), or null without soft wrap. */
|
||||
wrapped(fromLine: number, toLine: number): number[] | null;
|
||||
/** The main selection first, then the others in file order. */
|
||||
selections(): EditorSelection[];
|
||||
changes(): EditorChange[];
|
||||
subscribe(listener: (event: FrameEditorEvent) => void): () => void;
|
||||
}
|
||||
|
||||
@@ -372,9 +427,18 @@ export function WebView({
|
||||
case "editor.viewport":
|
||||
case "editor.scrollTo":
|
||||
case "editor.scrollBy":
|
||||
case "editor.highlights": {
|
||||
case "editor.highlights":
|
||||
case "editor.problems":
|
||||
case "editor.folded":
|
||||
case "editor.selections":
|
||||
case "editor.changes":
|
||||
case "editor.wrapped": {
|
||||
if (!editor) throw new Error("this view is not an editor panel");
|
||||
if (op === "editor.get") return [editor.get()];
|
||||
if (op === "editor.problems") return [editor.problems()];
|
||||
if (op === "editor.folded") return [editor.folded()];
|
||||
if (op === "editor.selections") return [editor.selections()];
|
||||
if (op === "editor.changes") return [editor.changes()];
|
||||
if (op === "editor.viewport") return [editor.viewport()];
|
||||
if (op === "editor.scrollTo") return [editor.scrollTo(finite(args.line, "line"))];
|
||||
if (op === "editor.scrollBy") return [editor.scrollBy(finite(args.pixels, "pixels"))];
|
||||
@@ -383,7 +447,7 @@ export function WebView({
|
||||
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to < from)
|
||||
throw new Error("lines are 0 ≤ fromLine ≤ toLine, whole numbers");
|
||||
if (to - from > MAX_HIGHLIGHT_LINES) throw new Error(`at most ${MAX_HIGHLIGHT_LINES} lines at a time`);
|
||||
return [editor.highlights(from, to)];
|
||||
return [op === "editor.wrapped" ? editor.wrapped(from, to) : editor.highlights(from, to)];
|
||||
}
|
||||
case "saveFile":
|
||||
case "openFile": {
|
||||
|
||||
@@ -2,15 +2,19 @@
|
||||
* Plugin editor panels (`[[contributes.editorPanels]]`): a web page at the right edge of every
|
||||
* editor group, following the group's text editor (a minimap, say). Each group has one frame,
|
||||
* kept while the group switches tabs: the page hears `onTarget` instead of reloading. Through
|
||||
* `openidea.editor` it reads the file (read-only), the viewport and the syntax colours, and
|
||||
* scrolls the editor — straight from the editor, not through the plugin's code, since a minimap
|
||||
* follows every frame of a scroll.
|
||||
* `openidea.editor` it reads the file (read-only), the viewport, the colours (syntax and semantic), the
|
||||
* marker bar's problems, the folds and the rows of wrapped lines, the caret and selections, the VCS changes, and scrolls the editor — straight
|
||||
* from the editor, not through the plugin's code, since a minimap follows every frame of a scroll.
|
||||
*/
|
||||
import { highlightingFor, syntaxTree } from "@codemirror/language";
|
||||
import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { foldedRanges, highlightingFor, syntaxTree } from "@codemirror/language";
|
||||
import { RangeSet, type Range } from "@codemirror/state";
|
||||
import { BlockType, Decoration, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { highlightTree } from "@lezer/highlight";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import type { Severity } from "@/bindings";
|
||||
import { lineChanges, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import { markerBarProblems } from "@/editor/lsp/diagnostics";
|
||||
import { semanticHighlights } from "@/editor/lsp/semantic";
|
||||
import { evaluateWhen, useContextKeys } from "@/platform/context";
|
||||
import { subscribeTheme } from "@/platform/themeWatch";
|
||||
import { registerEditorGroupPanel } from "@/workbench/contributions";
|
||||
@@ -19,6 +23,10 @@ import { basename } from "./customEditor";
|
||||
import {
|
||||
WebView,
|
||||
type DocumentState,
|
||||
type EditorFold,
|
||||
type EditorChange,
|
||||
type EditorProblem,
|
||||
type EditorSelection,
|
||||
type EditorTarget,
|
||||
type EditorViewport,
|
||||
type FrameDocument,
|
||||
@@ -35,6 +43,17 @@ export interface EditorPanelDecl {
|
||||
when?: string | null;
|
||||
}
|
||||
|
||||
/** The marker bar's levels (IDEA's): `info` is a weak warning; hints have no mark. */
|
||||
const problemLevel = (severity: Severity): EditorProblem["severity"] =>
|
||||
severity === "error" || severity === "warning" ? severity : "weakWarning";
|
||||
|
||||
const syntaxMarks = new Map<string, Decoration>();
|
||||
const syntaxMark = (classes: string) => {
|
||||
let m = syntaxMarks.get(classes);
|
||||
if (!m) syntaxMarks.set(classes, (m = Decoration.mark({ class: classes })));
|
||||
return m;
|
||||
};
|
||||
|
||||
/** View updates of the editors that panels follow. */
|
||||
const updateListeners = new Map<EditorView, Set<(u: ViewUpdate) => void>>();
|
||||
|
||||
@@ -56,6 +75,18 @@ function lineAtHeight(view: EditorView, height: number): number {
|
||||
return Math.min(doc.lines, first + frac * span);
|
||||
}
|
||||
|
||||
/** What the next frame sends: nothing yet. */
|
||||
const nothingPending = () => ({
|
||||
target: false,
|
||||
viewport: false,
|
||||
document: false,
|
||||
problems: false,
|
||||
layout: false,
|
||||
selections: false,
|
||||
changes: false,
|
||||
lines: null as [number, number] | null,
|
||||
});
|
||||
|
||||
/** One panel frame's view of its group's text editor. */
|
||||
export class PanelEditor implements FrameEditor {
|
||||
private handle: TextEditorHandle | null = null;
|
||||
@@ -67,11 +98,7 @@ export class PanelEditor implements FrameEditor {
|
||||
/** Highlight classes → their colour in the current scheme. */
|
||||
private readonly colors = new Map<string, string>();
|
||||
private frame = 0;
|
||||
private pending: { viewport: boolean; document: boolean; lines: [number, number] | null } = {
|
||||
viewport: false,
|
||||
document: false,
|
||||
lines: null,
|
||||
};
|
||||
private pending = nothingPending();
|
||||
|
||||
readonly document: FrameDocument = {
|
||||
read: () => {
|
||||
@@ -96,9 +123,12 @@ export class PanelEditor implements FrameEditor {
|
||||
this.unbind = () => {};
|
||||
this.handle = handle;
|
||||
this.version++;
|
||||
// Sent below.
|
||||
this.pending.target = false;
|
||||
if (handle) {
|
||||
const { view } = handle;
|
||||
const onScroll = () => this.schedule({ viewport: true });
|
||||
let softWrap = view.lineWrapping;
|
||||
const onUpdate = (u: ViewUpdate) => {
|
||||
const lines = u.state.doc.lines;
|
||||
if (u.docChanged) {
|
||||
@@ -117,6 +147,28 @@ export class PanelEditor implements FrameEditor {
|
||||
}
|
||||
}
|
||||
if (u.geometryChanged || u.heightChanged || u.viewportChanged) this.schedule({ viewport: true });
|
||||
if (markerBarProblems(u.startState) !== markerBarProblems(u.state)) this.schedule({ problems: true });
|
||||
// An edit can move a caret to another line without changing its offset.
|
||||
if (u.docChanged || !u.state.selection.eq(u.startState.selection)) this.schedule({ selections: true });
|
||||
if (u.startState.facet(lineChanges) !== u.state.facet(lineChanges)) this.schedule({ changes: true });
|
||||
// Settings or `.editorconfig` changed the file's indentation: `get()` changed.
|
||||
if (u.startState.tabSize !== u.state.tabSize) this.schedule({ target: true });
|
||||
// Wrapped rows follow the line blocks' heights.
|
||||
const wrap = u.view.lineWrapping;
|
||||
if (foldedRanges(u.startState) !== foldedRanges(u.state) || wrap !== softWrap || (wrap && u.heightChanged)) {
|
||||
softWrap = wrap;
|
||||
this.schedule({ layout: true });
|
||||
}
|
||||
const semBefore = semanticHighlights(u.startState);
|
||||
const semAfter = semanticHighlights(u.state);
|
||||
if (semBefore !== semAfter) {
|
||||
// New semantic tokens: the lines whose marks differ (in the new document).
|
||||
const changed = (from: number, to: number) => {
|
||||
const doc = u.state.doc;
|
||||
this.schedule({ lines: [doc.lineAt(from).number - 1, doc.lineAt(Math.max(from, to - 1)).number] });
|
||||
};
|
||||
RangeSet.compare([semBefore], [semAfter], u.changes, { compareRange: changed, comparePoint: changed });
|
||||
}
|
||||
};
|
||||
view.scrollDOM.addEventListener("scroll", onScroll, { passive: true });
|
||||
let set = updateListeners.get(view);
|
||||
@@ -127,7 +179,7 @@ export class PanelEditor implements FrameEditor {
|
||||
set.delete(onUpdate);
|
||||
if (!set.size) updateListeners.delete(view);
|
||||
};
|
||||
this.schedule({ viewport: true });
|
||||
this.schedule({ viewport: true, problems: true, layout: true, selections: true, changes: true });
|
||||
}
|
||||
this.emit({ editor: "target", value: this.get() });
|
||||
}
|
||||
@@ -153,7 +205,14 @@ export class PanelEditor implements FrameEditor {
|
||||
get(): EditorTarget | null {
|
||||
const h = this.handle;
|
||||
if (!h) return null;
|
||||
return { path: h.ctx.path, language: h.ctx.language, version: this.version, lineCount: h.view.state.doc.lines };
|
||||
const { state } = h.view;
|
||||
return {
|
||||
path: h.ctx.path,
|
||||
language: h.ctx.language,
|
||||
version: this.version,
|
||||
lineCount: state.doc.lines,
|
||||
tabSize: state.tabSize,
|
||||
};
|
||||
}
|
||||
|
||||
viewport(): EditorViewport | null {
|
||||
@@ -201,38 +260,131 @@ export class PanelEditor implements FrameEditor {
|
||||
const out: HighlightSpan[][] = Array.from({ length: to - fromLine }, () => []);
|
||||
const start = doc.line(fromLine + 1).from;
|
||||
const end = doc.line(to).to;
|
||||
const syntax: Range<Decoration>[] = [];
|
||||
highlightTree(
|
||||
syntaxTree(state),
|
||||
{ style: (tags) => highlightingFor(state, tags) },
|
||||
(from, until, classes) => {
|
||||
const color = this.color(view, classes);
|
||||
(from, until, classes) => void syntax.push(syntaxMark(classes).range(from, until)),
|
||||
start,
|
||||
end,
|
||||
);
|
||||
// As the editor layers them: semantic marks inside the syntax spans, so their colour wins.
|
||||
RangeSet.spans([semanticHighlights(state), Decoration.set(syntax)], start, end, {
|
||||
span: (from, until, active) => {
|
||||
if (!active.length) return;
|
||||
// `active` runs innermost first.
|
||||
const color = this.color(view, active.map((d) => (d.spec.class as string | undefined) ?? "").reverse());
|
||||
if (!color) return;
|
||||
// A token can run over several lines (a block comment): one span per line.
|
||||
for (let pos = Math.max(from, start); pos < Math.min(until, end);) {
|
||||
for (let pos = from; pos < until;) {
|
||||
const line = doc.lineAt(pos);
|
||||
const stop = Math.min(until, end, line.to);
|
||||
const stop = Math.min(until, line.to);
|
||||
if (stop > pos) out[line.number - 1 - fromLine]!.push({ from: pos - line.from, to: stop - line.from, color });
|
||||
pos = line.to + 1;
|
||||
}
|
||||
},
|
||||
start,
|
||||
end,
|
||||
);
|
||||
point: () => {},
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The text colour `classes` give in the editor, as the current scheme resolves it. */
|
||||
private color(view: EditorView, classes: string): string {
|
||||
let color = this.colors.get(classes);
|
||||
problems(): EditorProblem[] {
|
||||
const view = this.handle?.view;
|
||||
if (!view) return [];
|
||||
const doc = view.state.doc;
|
||||
return markerBarProblems(view.state).map((m) => ({
|
||||
line: doc.lineAt(m.from).number - 1,
|
||||
lastLine: doc.lineAt(Math.max(m.from, m.to - 1)).number - 1,
|
||||
severity: problemLevel(m.severity),
|
||||
}));
|
||||
}
|
||||
|
||||
folded(): EditorFold[] {
|
||||
const view = this.handle?.view;
|
||||
if (!view) return [];
|
||||
const doc = view.state.doc;
|
||||
const out: EditorFold[] = [];
|
||||
foldedRanges(view.state).between(0, doc.length, (from, to) => {
|
||||
const fromLine = doc.lineAt(from).number - 1;
|
||||
const toLine = doc.lineAt(to).number - 1;
|
||||
const last = out.at(-1);
|
||||
// Folds inside a fold, or starting on the row it ends on, are part of it.
|
||||
if (last && fromLine <= last.toLine) last.toLine = Math.max(last.toLine, toLine);
|
||||
else if (toLine > fromLine) out.push({ fromLine, toLine });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
wrapped(fromLine: number, toLine: number): number[] | null {
|
||||
const view = this.handle?.view;
|
||||
if (!view?.lineWrapping) return null;
|
||||
const doc = view.state.doc;
|
||||
const out: number[] = [];
|
||||
for (let n = fromLine + 1; n <= Math.min(toLine, doc.lines); n++) {
|
||||
const line = doc.line(n);
|
||||
// The editor's own line blocks: measured in the viewport, estimated elsewhere.
|
||||
const block = view.lineBlockAt(line.from);
|
||||
if (block.from < line.from) {
|
||||
out.push(0);
|
||||
continue;
|
||||
}
|
||||
// Block widgets (above or below the line) are not rows of its text.
|
||||
const height = Array.isArray(block.type)
|
||||
? block.type.reduce((h, b) => (b.type === BlockType.Text ? h + b.height : h), 0)
|
||||
: block.height;
|
||||
out.push(Math.max(1, Math.round(height / view.defaultLineHeight)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
selections(): EditorSelection[] {
|
||||
const view = this.handle?.view;
|
||||
if (!view) return [];
|
||||
const { doc, selection } = view.state;
|
||||
const position = (pos: number) => {
|
||||
const line = doc.lineAt(pos);
|
||||
return { line: line.number - 1, column: pos - line.from };
|
||||
};
|
||||
const main = selection.main;
|
||||
return [main, ...selection.ranges.filter((_, i) => i !== selection.mainIndex)].map((r) => ({
|
||||
anchor: position(r.anchor),
|
||||
head: position(r.head),
|
||||
}));
|
||||
}
|
||||
|
||||
changes(): EditorChange[] {
|
||||
const view = this.handle?.view;
|
||||
if (!view) return [];
|
||||
const doc = view.state.doc;
|
||||
return view.state.facet(lineChanges).map((c) => {
|
||||
// As the lane draws them: a hunk whose lines were all deleted is a deletion.
|
||||
if (c.kind === "deleted" || c.to <= c.from) {
|
||||
const line = doc.lineAt(Math.min(c.from, doc.length)).number - 1;
|
||||
return { line, lastLine: line, kind: "deleted" };
|
||||
}
|
||||
return {
|
||||
line: doc.lineAt(c.from).number - 1,
|
||||
lastLine: doc.lineAt(Math.max(c.from, c.to - 1)).number - 1,
|
||||
kind: c.kind,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** The text colour of spans nested with these classes (outermost first), as the current scheme resolves it. */
|
||||
private color(view: EditorView, nested: string[]): string {
|
||||
const key = nested.join("\n");
|
||||
let color = this.colors.get(key);
|
||||
if (color === undefined) {
|
||||
// Outside the content DOM, which the editor observes; inside the editor, for its variables.
|
||||
const probe = document.createElement("span");
|
||||
probe.className = classes;
|
||||
probe.style.cssText = "position:absolute;visibility:hidden";
|
||||
let inner = probe;
|
||||
for (const classes of nested)
|
||||
inner = inner.appendChild(Object.assign(document.createElement("span"), { className: classes }));
|
||||
view.dom.appendChild(probe);
|
||||
color = getComputedStyle(probe).color;
|
||||
color = getComputedStyle(inner).color;
|
||||
probe.remove();
|
||||
this.colors.set(classes, color);
|
||||
this.colors.set(key, color);
|
||||
}
|
||||
return color;
|
||||
}
|
||||
@@ -241,10 +393,24 @@ export class PanelEditor implements FrameEditor {
|
||||
for (const l of this.listeners) l(e);
|
||||
}
|
||||
|
||||
private schedule(p: { viewport?: boolean; document?: boolean; lines?: [number, number] }) {
|
||||
private schedule(p: {
|
||||
target?: boolean;
|
||||
viewport?: boolean;
|
||||
document?: boolean;
|
||||
problems?: boolean;
|
||||
layout?: boolean;
|
||||
selections?: boolean;
|
||||
changes?: boolean;
|
||||
lines?: [number, number];
|
||||
}) {
|
||||
const q = this.pending;
|
||||
q.target ||= !!p.target;
|
||||
q.viewport ||= !!p.viewport;
|
||||
q.document ||= !!p.document;
|
||||
q.problems ||= !!p.problems;
|
||||
q.layout ||= !!p.layout;
|
||||
q.selections ||= !!p.selections;
|
||||
q.changes ||= !!p.changes;
|
||||
if (p.lines) q.lines = q.lines ? [Math.min(q.lines[0], p.lines[0]), Math.max(q.lines[1], p.lines[1])] : p.lines;
|
||||
if (!this.frame) this.frame = requestAnimationFrame(() => this.flush());
|
||||
}
|
||||
@@ -252,9 +418,10 @@ export class PanelEditor implements FrameEditor {
|
||||
private flush() {
|
||||
this.frame = 0;
|
||||
const q = this.pending;
|
||||
this.pending = { viewport: false, document: false, lines: null };
|
||||
this.pending = nothingPending();
|
||||
const view = this.handle?.view;
|
||||
if (!view) return;
|
||||
if (q.target) this.emit({ editor: "target", value: this.get() });
|
||||
if (q.document && this.documentListeners.size) {
|
||||
const state = { version: this.version, text: view.state.doc.toString() };
|
||||
for (const l of this.documentListeners) l(state);
|
||||
@@ -265,6 +432,10 @@ export class PanelEditor implements FrameEditor {
|
||||
this.emit({ editor: "highlights", value: { fromLine, toLine: Math.min(q.lines[1], lines) } });
|
||||
}
|
||||
if (q.viewport) this.emit({ editor: "viewport", value: this.viewport()! });
|
||||
if (q.problems) this.emit({ editor: "problems", value: this.problems() });
|
||||
if (q.layout) this.emit({ editor: "layout", value: { folded: this.folded(), softWrap: view.lineWrapping } });
|
||||
if (q.selections) this.emit({ editor: "selections", value: this.selections() });
|
||||
if (q.changes) this.emit({ editor: "changes", value: this.changes() });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,15 @@
|
||||
const listeners = [];
|
||||
const themeListeners = [];
|
||||
const documentListeners = [];
|
||||
const editorListeners = { target: [], viewport: [], highlights: [] };
|
||||
const editorListeners = {
|
||||
target: [],
|
||||
viewport: [],
|
||||
highlights: [],
|
||||
problems: [],
|
||||
layout: [],
|
||||
selections: [],
|
||||
changes: [],
|
||||
};
|
||||
const editorPanel = /(?:^|[?&])openidea=editor-panel(?:&|$)/.test(location.search.slice(1));
|
||||
const pending = new Map();
|
||||
const root = document.documentElement;
|
||||
@@ -99,7 +107,7 @@
|
||||
} else if (m.document) {
|
||||
for (const l of documentListeners) safely(l, m.document);
|
||||
} else if (editorPanel && typeof m.editor === "string") {
|
||||
// Only the three lists: not `constructor` and the like.
|
||||
// Only those lists: not `constructor` and the like.
|
||||
const list = editorListeners[m.editor];
|
||||
if (Array.isArray(list)) for (const l of list) safely(l, m.value);
|
||||
} else if (typeof m.text === "string") {
|
||||
@@ -131,9 +139,9 @@
|
||||
};
|
||||
/** The text editor of the editor group the panel is in. */
|
||||
const editorApi = Object.freeze({
|
||||
/** `{ path, language, version, lineCount }` of the group's file, or null. */
|
||||
/** `{ path, language, version, lineCount, tabSize }` of the group's file, or null. */
|
||||
get: () => call("editor.get"),
|
||||
/** Called with the new `get()` value when the group shows another file, or none. */
|
||||
/** Called with the new `get()` value when the group shows another file, or none, or the file's tab size changes. */
|
||||
onTarget: listen(editorListeners.target),
|
||||
/** The group's document, read-only (`edit` / `replace` reject). */
|
||||
document: documentApi,
|
||||
@@ -149,6 +157,24 @@
|
||||
highlights: (fromLine, toLine) => call("editor.highlights", { fromLine: Number(fromLine), toLine: Number(toLine) }),
|
||||
/** Called with `{ fromLine, toLine }` when those lines' colours may have changed. */
|
||||
onHighlights: listen(editorListeners.highlights),
|
||||
/** The marker bar's problems: `[{ line, lastLine, severity }]`, severity `error`, `warning` or `weakWarning`. */
|
||||
problems: () => call("editor.problems"),
|
||||
/** Called with `problems()` when a problem appears or goes away, or its lines move, at most once a frame. */
|
||||
onProblems: listen(editorListeners.problems),
|
||||
/** The folded ranges: `[{ fromLine, toLine }]`, the line that stays visible and the last one hidden. */
|
||||
folded: () => call("editor.folded"),
|
||||
/** Visual rows of lines `fromLine` up to `toLine` (exclusive), at most 2000; 0 for folded-away lines. Null without soft wrap. */
|
||||
wrapped: (fromLine, toLine) => call("editor.wrapped", { fromLine: Number(fromLine), toLine: Number(toLine) }),
|
||||
/** Called with `{ folded, softWrap }` when folds change, soft wrap turns on or off, or wrapped rows may have changed, at most once a frame. */
|
||||
onLayout: listen(editorListeners.layout),
|
||||
/** The caret and selections: `[{ anchor: { line, column }, head: { line, column } }]`, the main one first; a caret has `anchor` equal to `head`. */
|
||||
selections: () => call("editor.selections"),
|
||||
/** Called with `selections()` when the caret moves, a selection changes, or the group shows another file, at most once a frame. */
|
||||
onSelections: listen(editorListeners.selections),
|
||||
/** The VCS changes beside the line numbers: `[{ line, lastLine, kind }]`, kind `added`, `modified` or `deleted` (`lastLine` equals `line`, the line below the deleted text). */
|
||||
changes: () => call("editor.changes"),
|
||||
/** Called with `changes()` when the changes are recomputed or edits move them, or the group shows another file, at most once a frame. */
|
||||
onChanges: listen(editorListeners.changes),
|
||||
});
|
||||
|
||||
window.openidea = Object.freeze({
|
||||
|
||||
@@ -48,6 +48,9 @@ export const FRAME_THEME_TOKENS = {
|
||||
"--openidea-warning": "--warning",
|
||||
"--openidea-success": "--success",
|
||||
"--openidea-info": "--info",
|
||||
"--openidea-change-added": "--gutter-added",
|
||||
"--openidea-change-modified": "--gutter-modified",
|
||||
"--openidea-change-deleted": "--gutter-deleted",
|
||||
} as const;
|
||||
|
||||
/** Non-colour variables: public name → IDE token. */
|
||||
|
||||
@@ -651,6 +651,37 @@ export function ProjectView() {
|
||||
// uses and the editor leaves them out.
|
||||
let files: DragSession | null = null;
|
||||
let endDrag: (() => void) | null = null;
|
||||
// While dragging, the tree scrolls only when the pointer is near its top or bottom edge
|
||||
// (IDEA's DnD autoscroll). Leaving the tree toward a drop target elsewhere (the terminal,
|
||||
// an editor) keeps it where it is: WebKit's own autoscroll of the pressed scroll container
|
||||
// would otherwise keep scrolling it toward the pointer.
|
||||
const scroller = containerRef.current?.querySelector<HTMLElement>('[role="tree"]') ?? null;
|
||||
let held = scroller?.scrollTop ?? 0;
|
||||
let pointer: { x: number; y: number } | null = null;
|
||||
let frame = 0;
|
||||
const inside = (p: { x: number; y: number }) => {
|
||||
const r = scroller?.getBoundingClientRect();
|
||||
return !!r && p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
|
||||
};
|
||||
const keep = () => {
|
||||
if (!scroller) return;
|
||||
if (pointer && !inside(pointer)) scroller.scrollTop = held;
|
||||
else held = scroller.scrollTop;
|
||||
};
|
||||
const edgeScroll = () => {
|
||||
frame = 0;
|
||||
if (!scroller || !pointer || !inside(pointer)) return;
|
||||
const r = scroller.getBoundingClientRect();
|
||||
const delta = pointer.y < r.top + 24 ? -8 : pointer.y > r.bottom - 24 ? 8 : 0;
|
||||
const before = scroller.scrollTop;
|
||||
scroller.scrollTop = Math.max(0, Math.min(scroller.scrollHeight - scroller.clientHeight, before + delta));
|
||||
held = scroller.scrollTop;
|
||||
if (held !== before) {
|
||||
const target = folderAt(containerRef.current, pointer.x, pointer.y);
|
||||
setDropTarget(target && !paths.some((p) => target.path === p || isInside(target.path, p)) ? target.key : null);
|
||||
frame = requestAnimationFrame(edgeScroll);
|
||||
}
|
||||
};
|
||||
const move = (ev: PointerEvent) => {
|
||||
// A press with no button held is a reordered macOS tap, not a drag (see pointerDrag.ts).
|
||||
if (!(ev.buttons & 1)) {
|
||||
@@ -673,6 +704,10 @@ export function ProjectView() {
|
||||
payload: nodes.map((n) => (n.dir ? `${n.path}/` : n.path)).join("\n"),
|
||||
});
|
||||
}
|
||||
if (!pointer) scroller?.addEventListener("scroll", keep, { passive: true });
|
||||
pointer = { x: ev.clientX, y: ev.clientY };
|
||||
keep();
|
||||
if (!frame) frame = requestAnimationFrame(edgeScroll);
|
||||
const target = folderAt(containerRef.current, ev.clientX, ev.clientY);
|
||||
const valid = target && !paths.some((p) => target.path === p || isInside(target.path, p));
|
||||
setDropTarget(valid ? target.key : null);
|
||||
@@ -703,6 +738,10 @@ export function ProjectView() {
|
||||
}
|
||||
};
|
||||
const cleanup = () => {
|
||||
scroller?.removeEventListener("scroll", keep);
|
||||
cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
pointer = null;
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", up);
|
||||
window.removeEventListener("pointercancel", cleanup);
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// OpenIDEA: BootRun is a JavaExec task; give its forked application JVM a dynamic
|
||||
// JDWP port instead of Gradle's fixed 5005. The property is added by jdwpLaunch.
|
||||
import org.gradle.util.GradleVersion
|
||||
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
|
||||
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
|
||||
gradle.projectsEvaluated {
|
||||
allprojects {
|
||||
tasks.matching { it.name == 'bootRun' }.configureEach { task ->
|
||||
each(tasks.matching { it.name == 'bootRun' }) { task ->
|
||||
if (System.getProperty('openidea.run.debug') == 'true') {
|
||||
task.debugOptions.enabled = false
|
||||
task.debug = false
|
||||
task.doFirst {
|
||||
task.setJvmArgs(task.jvmArgs.findAll {
|
||||
!it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:')
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
// OpenIDEA: runs a main class on its Gradle source set's runtime classpath, like IntelliJ
|
||||
// IDEA's "Build and run using: Gradle" (ApplicationTaskInitScript.gradle). Parameters come
|
||||
// as system properties so this file never changes: see `gradleRun.ts`.
|
||||
// as system properties so this file never changes: see `gradleRun.ts`. Works from Gradle 4.6,
|
||||
// the oldest IDEA supports: `register` is Gradle 4.9+, `JavaExec.mainClass` 6.4+.
|
||||
import groovy.json.JsonSlurper
|
||||
import org.gradle.util.GradleVersion
|
||||
|
||||
def lazyTasks = GradleVersion.current() >= GradleVersion.version('4.9')
|
||||
|
||||
def target = System.getProperty('openidea.run.project')
|
||||
if (target != null) {
|
||||
@@ -12,10 +16,11 @@ if (target != null) {
|
||||
p.plugins.withId('java') {
|
||||
def json = new JsonSlurper()
|
||||
def list = { String key -> (List) json.parseText(System.getProperty(key, '[]')) }
|
||||
p.tasks.register('openideaRun', JavaExec) { t ->
|
||||
def configure = { JavaExec t ->
|
||||
t.description = 'Runs a main class for OpenIDEA.'
|
||||
t.classpath = p.sourceSets.getByName(System.getProperty('openidea.run.sourceSet', 'main')).runtimeClasspath
|
||||
t.mainClass.set(System.getProperty('openidea.run.main'))
|
||||
def main = System.getProperty('openidea.run.main')
|
||||
if (t.hasProperty('mainClass')) t.mainClass.set(main) else t.main = main
|
||||
t.args(list('openidea.run.args'))
|
||||
t.jvmArgs(list('openidea.run.jvmArgs'))
|
||||
// The IDE attaches to this JVM, not to the Gradle daemon; port 0 prints the one picked.
|
||||
@@ -31,6 +36,8 @@ if (target != null) {
|
||||
if (dir) t.workingDir = dir
|
||||
t.standardInput = System.in
|
||||
}
|
||||
if (lazyTasks) p.tasks.register('openideaRun', JavaExec, configure)
|
||||
else p.tasks.create('openideaRun', JavaExec, configure)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -190,6 +190,27 @@ describe("Build and run using: Gradle", () => {
|
||||
expect(guard).toContain("list('openidea.run.jvmArgs')");
|
||||
expect(guard).toContain("StartAttachListener|DisableAttachMechanism");
|
||||
});
|
||||
|
||||
// Gradle 4.6 is the oldest IDEA supports: `register`, `named` and `configureEach` are 4.9+,
|
||||
// `debugOptions` 5.6+, `JavaExec.mainClass` 6.4+. Each use needs a guard on its line (#3864).
|
||||
it.each([
|
||||
["gradleRun", RUN_SCRIPT],
|
||||
["gradleTests", TESTS_SCRIPT],
|
||||
["gradleBoot", BOOT_SCRIPT],
|
||||
])("%s guards Gradle API newer than 4.6", (_, script) => {
|
||||
const unguarded = script
|
||||
.split("\n")
|
||||
.filter((l) => !l.trim().startsWith("//"))
|
||||
.filter((l) => /\.register\(|\.named\(|configureEach|debugOptions|mainClass/.test(l))
|
||||
.filter((l) => !/GradleVersion|lazyTasks|hasProperty/.test(l));
|
||||
expect(unguarded).toEqual([]);
|
||||
});
|
||||
|
||||
it("sets the main class with `main` and creates the task eagerly on old Gradle (#3864)", () => {
|
||||
expect(RUN_SCRIPT).toContain("if (t.hasProperty('mainClass')) t.mainClass.set(main) else t.main = main");
|
||||
expect(RUN_SCRIPT).toContain("else p.tasks.create('openideaRun', JavaExec, configure)");
|
||||
expect(RUN_SCRIPT).toContain("import org.gradle.util.GradleVersion");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Gradle test runs", () => {
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
// build's output, for the Run window's test tree: Gradle itself prints only failures (or a
|
||||
// project's own format), and writes its XML reports when a task ends. Test tasks always run,
|
||||
// so a rerun never ends UP-TO-DATE without results.
|
||||
import org.gradle.util.GradleVersion
|
||||
|
||||
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
|
||||
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
|
||||
|
||||
def tc = { String s ->
|
||||
s == null ? '' : s.replace('|', '||').replace("'", "|'").replace('\n', '|n').replace('\r', '|r')
|
||||
@@ -9,7 +13,7 @@ def tc = { String s ->
|
||||
}
|
||||
|
||||
allprojects {
|
||||
tasks.withType(Test).configureEach { Test task ->
|
||||
each(tasks.withType(Test)) { Test task ->
|
||||
task.outputs.upToDateWhen { false }
|
||||
task.addTestListener(new TestListener() {
|
||||
void beforeSuite(TestDescriptor suite) {}
|
||||
@@ -48,9 +52,9 @@ allprojects {
|
||||
// Replace build-configured agents only for this debug launch, after project configuration.
|
||||
gradle.projectsEvaluated {
|
||||
allprojects {
|
||||
tasks.withType(Test).configureEach { Test task ->
|
||||
each(tasks.withType(Test)) { Test task ->
|
||||
if (System.getProperty('openidea.run.debug') == 'true') {
|
||||
task.debugOptions.enabled = false
|
||||
task.debug = false
|
||||
task.doFirst {
|
||||
task.setJvmArgs(task.jvmArgs.findAll {
|
||||
!it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:')
|
||||
|
||||
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { CLEAR_COLOR } from "@/platform/colorScheme";
|
||||
import { CLEAR_COLOR, _setSchemeSource } from "@/platform/colorScheme";
|
||||
import { setLocale } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { DEFAULT_SETTINGS } from "../model/schema";
|
||||
@@ -260,6 +260,23 @@ describe("Go scheme attributes", () => {
|
||||
|
||||
describe("scheme attribute state", () => {
|
||||
beforeEach(() => schemePage("editor.colorScheme.language-defaults"));
|
||||
it("shows the red-green colours the editor uses and the setting behind them (#3851)", () => {
|
||||
_setSchemeSource(readFileSync("src/styles/tokens.css", "utf8"));
|
||||
try {
|
||||
act(() => {
|
||||
stage("editor.colorScheme", "global", "editor.colorScheme", "dark");
|
||||
stage("appearance", "global", "appearance.redGreenVision", true);
|
||||
});
|
||||
expect(screen.getByRole("textbox", { name: "Foreground hex" })).toHaveValue("#597cc2");
|
||||
const preview = screen.getByLabelText("Color scheme preview");
|
||||
expect(preview.style.getPropertyValue("--syn-keyword")).toBe("#597cc2");
|
||||
act(() => fireEvent.click(screen.getByRole("button", { name: "Appearance settings" })));
|
||||
expect(useSettingsDialog.getState().pageId).toBe("appearance");
|
||||
} finally {
|
||||
_setSchemeSource("");
|
||||
}
|
||||
});
|
||||
|
||||
it("shows checked attributes and inherited colours from the selected scheme", () => {
|
||||
act(() => {
|
||||
stage("editor.colorScheme", "global", "editor.customSchemes", {
|
||||
|
||||
@@ -113,9 +113,10 @@ function previewVars(
|
||||
o: Record<string, TextAttributesOverride> | undefined,
|
||||
customs: CustomColorSchemes,
|
||||
language?: string,
|
||||
redGreen = false,
|
||||
): CSSProperties {
|
||||
const vars: Record<string, string> = {};
|
||||
const tokens = resolvedSchemeTokens(id, customs);
|
||||
const tokens = resolvedSchemeTokens(id, customs, redGreen);
|
||||
for (const [k, v] of tokens)
|
||||
if (
|
||||
k.startsWith("--syn-") ||
|
||||
@@ -1341,6 +1342,7 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
|
||||
const [overrides, setOverrides] = useSetting<Overrides>("editor.colorOverrides", "global");
|
||||
const [weight] = useSetting<number>("editor.fontWeight");
|
||||
const [boldFontWeight] = useSetting<number>("editor.boldFontWeight");
|
||||
const [redGreen = false] = useSetting<boolean>("appearance.redGreenVision", "global");
|
||||
const [rawCustoms, setCustoms] = useSetting<CustomColorSchemes>("editor.customSchemes", "global");
|
||||
const customs = useMemo(() => customSchemes(rawCustoms), [rawCustoms]);
|
||||
const [report, setReport] = useState("");
|
||||
@@ -1404,19 +1406,26 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
|
||||
}, [mine]);
|
||||
const attr = ATTRIBUTES.find((a) => a.id === selected);
|
||||
const language = attr?.language;
|
||||
const inherited = useMemo(() => (attr ? resolvedAttribute(id, attr.id, customs) : {}), [id, attr, customs]);
|
||||
const inherited = useMemo(
|
||||
() => (attr ? resolvedAttribute(id, attr.id, customs, redGreen) : {}),
|
||||
[id, attr, customs, redGreen],
|
||||
);
|
||||
const vars = useMemo(() => {
|
||||
const next = {
|
||||
...previewVars(id, mine, customs, language),
|
||||
...previewVars(id, mine, customs, language, redGreen),
|
||||
...fontWeightVars(weight, boldFontWeight),
|
||||
} as CSSProperties & Record<string, string>;
|
||||
// Console preview sits on the console background, not the editor surface.
|
||||
if (scopes[0] === "Console Colors" && next["--bg-console"]) next["--bg-editor"] = next["--bg-console"];
|
||||
return next;
|
||||
}, [id, mine, customs, language, weight, boldFontWeight, scopes]);
|
||||
}, [id, mine, customs, language, weight, boldFontWeight, scopes, redGreen]);
|
||||
const baseVars = useMemo(
|
||||
() => ({ ...previewVars(id, mine, customs), ...fontWeightVars(weight, boldFontWeight) }) as CSSProperties,
|
||||
[id, mine, customs, weight, boldFontWeight],
|
||||
() =>
|
||||
({
|
||||
...previewVars(id, mine, customs, undefined, redGreen),
|
||||
...fontWeightVars(weight, boldFontWeight),
|
||||
}) as CSSProperties,
|
||||
[id, mine, customs, weight, boldFontWeight, redGreen],
|
||||
);
|
||||
const update = (attrId: string, v: TextAttributesOverride | undefined) => {
|
||||
const next: Overrides = { ...(overrides ?? {}) };
|
||||
@@ -1573,6 +1582,14 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
|
||||
{scheme === "theme-default" && (
|
||||
<div className={styles.note}>{tx`Follows the IDE theme: currently ${schemeName}.`}</div>
|
||||
)}
|
||||
{redGreen && (id === "dark" || id === "light") && (
|
||||
<div className={styles.note}>
|
||||
<T>Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.</T>{" "}
|
||||
<button type="button" className={styles.schemeLink} onClick={() => selectPage("appearance")}>
|
||||
<T>Appearance settings</T>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{landing ? (
|
||||
<nav className={styles.schemeLinks} aria-label={tx("Color scheme pages")}>
|
||||
{SCHEME_SUBPAGES.map((p) => (
|
||||
|
||||
@@ -35,7 +35,8 @@
|
||||
flex: none;
|
||||
height: var(--h-row);
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
/* The panes' columns, so each title sits over its pane. */
|
||||
grid-template-columns: 1fr 30px 1fr 30px 1fr;
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
@@ -45,14 +46,17 @@
|
||||
align-items: center;
|
||||
padding: 0 12px;
|
||||
}
|
||||
.labels > span + span {
|
||||
border-left: 1px solid var(--border);
|
||||
.labels > span:nth-child(2) {
|
||||
grid-column: 3;
|
||||
}
|
||||
.labels > span:nth-child(3) {
|
||||
grid-column: 5;
|
||||
}
|
||||
.panes {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
grid-template-columns: 1fr 30px 1fr 30px 1fr;
|
||||
}
|
||||
.panes[hidden] {
|
||||
display: none;
|
||||
@@ -63,8 +67,34 @@
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
}
|
||||
.pane + .pane {
|
||||
/* Between two panes, as the diff viewer's divider: the bands of the changes on either side. */
|
||||
.divider {
|
||||
position: relative;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
background: var(--bg-app);
|
||||
border-left: 1px solid var(--border);
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.divider > svg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
.divider :global(.cm-mergeBand-conflict) {
|
||||
--band: color-mix(in srgb, var(--vcs-conflict) 14%, transparent);
|
||||
--band-line: var(--vcs-conflict);
|
||||
}
|
||||
.divider :global(.cm-mergeBand-change) {
|
||||
--band: color-mix(in srgb, var(--vcs-modified) 14%, transparent);
|
||||
--band-line: var(--vcs-modified);
|
||||
}
|
||||
.divider :global(.cm-mergeBand) {
|
||||
fill: var(--band);
|
||||
}
|
||||
.divider :global(.cm-mergeBandLine) {
|
||||
fill: none;
|
||||
stroke: var(--band-line);
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.pane > :global(.cm-editor) {
|
||||
flex: 1;
|
||||
|
||||
@@ -18,6 +18,7 @@ import { firstLineOf, languageFor, viewerBase } from "./cm";
|
||||
import { ideaDiffConfig } from "./diffOptions";
|
||||
import { confirmDialog } from "./dialogs";
|
||||
import { focusedDiffNavigator, setFocusedDiffNavigator, type DiffNavigator } from "./diffNavigator";
|
||||
import { mergeDividers } from "./mergeDividers";
|
||||
import { syncMergeScroll } from "./mergeScroll";
|
||||
import { mergeTitles } from "./conflicts";
|
||||
import {
|
||||
@@ -123,6 +124,8 @@ export function MergeEditor({ input }: { input: EditorInput }) {
|
||||
const oursRef = useRef<HTMLDivElement>(null);
|
||||
const resultRef = useRef<HTMLDivElement>(null);
|
||||
const theirsRef = useRef<HTMLDivElement>(null);
|
||||
const leftDividerRef = useRef<HTMLDivElement>(null);
|
||||
const rightDividerRef = useRef<HTMLDivElement>(null);
|
||||
const resultView = useRef<EditorView | null>(null);
|
||||
const oursView = useRef<EditorView | null>(null);
|
||||
const theirsView = useRef<EditorView | null>(null);
|
||||
@@ -233,8 +236,12 @@ export function MergeEditor({ input }: { input: EditorInput }) {
|
||||
}
|
||||
// Scroll the three panes together, lined up through their changes.
|
||||
const stopSync = syncMergeScroll({ ours, result, theirs });
|
||||
const left = leftDividerRef.current;
|
||||
const right = rightDividerRef.current;
|
||||
const stopDividers = left && right ? mergeDividers({ ours, result, theirs }, { left, right }) : () => {};
|
||||
return () => {
|
||||
stopSync();
|
||||
stopDividers();
|
||||
ours.destroy();
|
||||
theirs.destroy();
|
||||
result.destroy();
|
||||
@@ -623,6 +630,7 @@ export function MergeEditor({ input }: { input: EditorInput }) {
|
||||
role="region"
|
||||
onContextMenu={(e) => oursView.current && showSideMenu(e, oursView.current, "left")}
|
||||
/>
|
||||
<div ref={leftDividerRef} className={styles.divider} aria-hidden />
|
||||
<div
|
||||
ref={resultRef}
|
||||
className={styles.pane}
|
||||
@@ -630,6 +638,7 @@ export function MergeEditor({ input }: { input: EditorInput }) {
|
||||
role="region"
|
||||
onContextMenu={(e) => resultView.current && showResultMenu(e, resultView.current)}
|
||||
/>
|
||||
<div ref={rightDividerRef} className={styles.divider} aria-hidden />
|
||||
<div
|
||||
ref={theirsRef}
|
||||
className={styles.pane}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { drawMergeDivider } from "../mergeDividers";
|
||||
import { applyTo, mergeField, startMerge } from "../mergeModel";
|
||||
|
||||
const lines = (...l: string[]) => l.map((x) => `${x}\n`).join("");
|
||||
const views: EditorView[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const v of views.splice(0)) v.destroy();
|
||||
});
|
||||
|
||||
function view(doc: string, extensions: Extension = []) {
|
||||
const v = new EditorView({ state: EditorState.create({ doc, extensions }), parent: document.body });
|
||||
views.push(v);
|
||||
return v;
|
||||
}
|
||||
|
||||
/** A divider the size the merge editor gives it (jsdom lays nothing out). */
|
||||
function divider() {
|
||||
const el = document.createElement("div");
|
||||
el.getBoundingClientRect = () => ({
|
||||
x: 0,
|
||||
y: 0,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 30,
|
||||
bottom: 600,
|
||||
width: 30,
|
||||
height: 600,
|
||||
toJSON: () => ({}),
|
||||
});
|
||||
return { el, svg: document.createElementNS("http://www.w3.org/2000/svg", "svg") };
|
||||
}
|
||||
|
||||
const bands = (svg: SVGSVGElement) => [...svg.querySelectorAll(".cm-mergeBand")].map((p) => p.getAttribute("class"));
|
||||
|
||||
describe("merge dividers", () => {
|
||||
// #3876: a band joins each side change to where it lands in the result.
|
||||
it("draws a band per open change of each side, and drops a side's band once it is accepted", () => {
|
||||
const base = lines("a", "b", "c", "d", "e", "f", "g");
|
||||
const left = lines("a", "B", "c", "d", "e", "F1", "g");
|
||||
const right = lines("a", "b", "c", "D", "e", "F2", "g");
|
||||
const start = startMerge(left, base, right);
|
||||
const result = view(start.text, [mergeField.init(() => start.changes)]);
|
||||
const ours = view(left);
|
||||
const theirs = view(right);
|
||||
const l = divider();
|
||||
const r = divider();
|
||||
drawMergeDivider("left", ours, result, l.el, l.svg);
|
||||
drawMergeDivider("right", theirs, result, r.el, r.svg);
|
||||
expect(bands(l.svg)).toEqual(["cm-mergeBand cm-mergeBand-change", "cm-mergeBand cm-mergeBand-conflict"]);
|
||||
expect(bands(r.svg)).toEqual(["cm-mergeBand cm-mergeBand-change", "cm-mergeBand cm-mergeBand-conflict"]);
|
||||
|
||||
result.dispatch(applyTo(result.state, [0], { type: "accept", side: "left", resolve: true })!);
|
||||
drawMergeDivider("left", ours, result, l.el, l.svg);
|
||||
drawMergeDivider("right", theirs, result, r.el, r.svg);
|
||||
expect(bands(l.svg)).toEqual(["cm-mergeBand cm-mergeBand-conflict"]);
|
||||
expect(bands(r.svg)).toEqual(["cm-mergeBand cm-mergeBand-change", "cm-mergeBand cm-mergeBand-conflict"]);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,14 @@ import { EditorView, GutterMarker, ViewPlugin, type PluginValue, type ViewUpdate
|
||||
import { foldState, foldedRanges } from "@codemirror/language";
|
||||
import type { HunkKind, LineHunk } from "@/bindings";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { LaneMarker, gutterLaneMarkers, scrollbarMarks, type EditorDocContext, type ScrollbarMark } from "@/editor/api";
|
||||
import {
|
||||
LaneMarker,
|
||||
gutterLaneMarkers,
|
||||
lineChanges,
|
||||
scrollbarMarks,
|
||||
type EditorDocContext,
|
||||
type ScrollbarMark,
|
||||
} from "@/editor/api";
|
||||
import { lineStarts } from "./hunks";
|
||||
import { useVcs } from "./store";
|
||||
|
||||
@@ -85,6 +92,7 @@ export const hunkField = StateField.define<HunkState>({
|
||||
});
|
||||
return { hunks, markers: buildMarkers(hunks, tr.state.doc) };
|
||||
},
|
||||
provide: (f) => lineChanges.from(f, (v) => v.hunks),
|
||||
});
|
||||
|
||||
export function editorHunks(state: EditorState): EditorHunk[] {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* The dividers between the merge editor's panes: a curved band joins each change in a side
|
||||
* pane to where it lands in the result, as IDEA's merge viewer draws them (DiffDividerDrawUtil),
|
||||
* so neighbouring changes read apart. A side's band goes once that side is accepted or ignored,
|
||||
* like its highlighting.
|
||||
*/
|
||||
import { StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { bandPath, extent } from "./diffScroll";
|
||||
import { changesSide, isConflict, mergeField, type MergeSide } from "./mergeModel";
|
||||
|
||||
const SVG = "http://www.w3.org/2000/svg";
|
||||
|
||||
/** Draws the bands in `left` (yours ↔ result) and `right` (result ↔ theirs); returns the function that stops it. */
|
||||
export function mergeDividers(
|
||||
views: { ours: EditorView; result: EditorView; theirs: EditorView },
|
||||
dividers: { left: HTMLElement; right: HTMLElement },
|
||||
): () => void {
|
||||
const layers = {
|
||||
left: dividers.left.appendChild(document.createElementNS(SVG, "svg")),
|
||||
right: dividers.right.appendChild(document.createElementNS(SVG, "svg")),
|
||||
};
|
||||
let frame = -1;
|
||||
let stopped = false;
|
||||
const draw = () => {
|
||||
frame = -1;
|
||||
drawMergeDivider("left", views.ours, views.result, dividers.left, layers.left);
|
||||
drawMergeDivider("right", views.theirs, views.result, dividers.right, layers.right);
|
||||
};
|
||||
const schedule = () => {
|
||||
if (frame < 0 && !stopped) frame = requestAnimationFrame(draw);
|
||||
};
|
||||
const panes = [views.ours, views.result, views.theirs];
|
||||
// Edits, resolutions, folding, wrapping and measuring all come as view updates.
|
||||
const listener = EditorView.updateListener.of(schedule);
|
||||
for (const v of panes) v.dispatch({ effects: StateEffect.appendConfig.of(listener) });
|
||||
for (const v of panes) v.scrollDOM.addEventListener("scroll", schedule, { passive: true });
|
||||
const resize = new ResizeObserver(schedule);
|
||||
resize.observe(dividers.left);
|
||||
schedule();
|
||||
return () => {
|
||||
stopped = true;
|
||||
if (frame >= 0) cancelAnimationFrame(frame);
|
||||
for (const v of panes) v.scrollDOM.removeEventListener("scroll", schedule);
|
||||
resize.disconnect();
|
||||
layers.left.remove();
|
||||
layers.right.remove();
|
||||
};
|
||||
}
|
||||
|
||||
/** One divider's bands, for the changes `side` makes; exported for tests. */
|
||||
export function drawMergeDivider(
|
||||
side: MergeSide,
|
||||
sideView: EditorView,
|
||||
result: EditorView,
|
||||
divider: HTMLElement,
|
||||
svg: SVGSVGElement,
|
||||
) {
|
||||
const rect = divider.getBoundingClientRect();
|
||||
const w = rect.width;
|
||||
const h = rect.height;
|
||||
if (!w || !h) return;
|
||||
svg.setAttribute("width", String(w));
|
||||
svg.setAttribute("height", String(h));
|
||||
svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
|
||||
// The left divider has the side pane on its left, the right one has the result there.
|
||||
const offSide = sideView.documentTop - rect.top;
|
||||
const offResult = result.documentTop - rect.top;
|
||||
let paths = "";
|
||||
for (const c of result.state.field(mergeField, false) ?? []) {
|
||||
if (!changesSide(c, side) || c.done[side]) continue;
|
||||
const [from, to] = side === "left" ? c.leftRange : c.rightRange;
|
||||
const [s0, s1] = extent(sideView, from, to).map((y) => y + offSide) as [number, number];
|
||||
const [r0, r1] = extent(result, c.from, c.to).map((y) => y + offResult) as [number, number];
|
||||
if ((s1 < -1 && r1 < -1) || (s0 > h + 1 && r0 > h + 1)) continue;
|
||||
const [a0, a1, b0, b1] = side === "left" ? [s0, s1, r0, r1] : [r0, r1, s0, s1];
|
||||
const kind = isConflict(c) ? "conflict" : "change";
|
||||
const midA = (a0 + a1) / 2;
|
||||
const midB = (b0 + b1) / 2;
|
||||
paths +=
|
||||
`<path class="cm-mergeBand cm-mergeBand-${kind}" d="${bandPath(w, a0, a1, b0, b1)}"/>` +
|
||||
`<path class="cm-mergeBandLine cm-mergeBand-${kind}" d="M0 ${midA}C${w * 0.3} ${midA} ${w * 0.7} ${midB} ${w} ${midB}"/>`;
|
||||
}
|
||||
svg.innerHTML = paths;
|
||||
}
|
||||
@@ -1,12 +1,33 @@
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
|
||||
/** File / folder chooser (Tauri dialog); null when cancelled or outside Tauri. */
|
||||
export async function choosePath(opts: {
|
||||
export interface ChoosePathOptions {
|
||||
directory: boolean;
|
||||
title: string;
|
||||
defaultPath?: string;
|
||||
}): Promise<string | null> {
|
||||
}
|
||||
|
||||
type HostChooser = (opts: ChoosePathOptions) => Promise<string | null>;
|
||||
let hostChooser: HostChooser | null = null;
|
||||
|
||||
/**
|
||||
* Registers the in-app chooser that browses the remote host (the workbench's, in `inputDialogs`):
|
||||
* the desktop's own dialog would show this machine's files.
|
||||
*/
|
||||
export function registerHostPathChooser(chooser: HostChooser): () => void {
|
||||
hostChooser = chooser;
|
||||
return () => {
|
||||
if (hostChooser === chooser) hostChooser = null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* File / folder chooser for a path on the host this window's commands run on: the desktop's dialog
|
||||
* locally, the in-app chooser in a remote window. Null when cancelled or outside Tauri.
|
||||
*/
|
||||
export async function choosePath(opts: ChoosePathOptions): Promise<string | null> {
|
||||
if (!isTauri()) return null;
|
||||
if (isRemoteWindow() && hostChooser) return hostChooser(opts);
|
||||
// Lazy on purpose: loading platform/dialog starts its GTK capability probe at module load.
|
||||
const { open } = await import("@/platform/dialog");
|
||||
const picked = await open({
|
||||
|
||||
@@ -218,6 +218,37 @@ describe("color schemes", () => {
|
||||
);
|
||||
});
|
||||
|
||||
// #3851: the editor showed the red-green colours while Color Scheme showed the plain ones.
|
||||
it("resolves the red-green variant of the bundled schemes only", () => {
|
||||
const rg = (id: Parameters<typeof schemeTokens>[0], name: string) => schemeTokens(id, undefined, true).get(name);
|
||||
// The reporter's screenshot: keyword, string, function, number, constant.
|
||||
expect(
|
||||
["--syn-keyword", "--syn-string", "--syn-function", "--syn-number", "--syn-constant"].map((n) => rg("dark", n)),
|
||||
).toEqual(["#597cc2", "#94907f", "#d9af6c", "#66a6ff", "#828eba"]);
|
||||
expect(rg("light", "--syn-keyword")).toBe("#00428c");
|
||||
for (const id of ["dark-hc", "solarized-dark"] as const)
|
||||
expect(rg(id, "--syn-keyword")).toBe(schemeTokens(id).get("--syn-keyword"));
|
||||
// VCS colours follow the setting in every scheme.
|
||||
expect(rg("dark-hc", "--gutter-added")).not.toBe(schemeTokens("dark-hc").get("--gutter-added"));
|
||||
expect(schemeTokens("dark").get("--syn-keyword")).toBe("#cf8e6d");
|
||||
expect(resolvedAttribute("dark", "keyword", {}, true).foreground).toBe("#597cc2");
|
||||
const customs = { "custom-rg": { name: "Mine", parent: "dark" as const, attributes: {} } };
|
||||
expect(resolvedAttribute("custom-rg", "keyword", customs, true).foreground).toBe("#cf8e6d");
|
||||
});
|
||||
|
||||
it("gives an explicit bundled scheme its red-green variant", () => {
|
||||
const root = document.documentElement;
|
||||
root.dataset.theme = "light";
|
||||
root.dataset.redGreen = "";
|
||||
try {
|
||||
expect(schemeCss("dark", undefined, root)).toContain("--syn-keyword: #597cc2 !important");
|
||||
delete root.dataset.redGreen;
|
||||
expect(schemeCss("dark", undefined, root)).toContain("--syn-keyword: #cf8e6d !important");
|
||||
} finally {
|
||||
delete root.dataset.redGreen;
|
||||
}
|
||||
});
|
||||
|
||||
it("applies an explicit scheme over a plugin theme of the same base", () => {
|
||||
const root = document.documentElement;
|
||||
root.dataset.theme = "dark";
|
||||
|
||||
@@ -441,7 +441,7 @@ function blocks(css: string): Array<{ selectors: string[]; decls: Vars }> {
|
||||
if (!selector.startsWith("@")) {
|
||||
const decls: Vars = new Map();
|
||||
for (const m of text.slice(start, i).matchAll(/(--[\w-]+)\s*:\s*([^;]+);/g)) decls.set(m[1]!, m[2]!.trim());
|
||||
out.push({ selectors: selector.split(",").map((s) => s.trim()), decls });
|
||||
out.push({ selectors: splitSelectors(selector), decls });
|
||||
}
|
||||
start = i + 1;
|
||||
}
|
||||
@@ -450,6 +450,39 @@ function blocks(css: string): Array<{ selectors: string[]; decls: Vars }> {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A selector list split at its top-level commas, not those inside `:not(…)`. */
|
||||
function splitSelectors(list: string): string[] {
|
||||
const out: string[] = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const ch = list[i];
|
||||
if (ch === "(") depth++;
|
||||
else if (ch === ")") depth--;
|
||||
else if (ch === "," && depth === 0) {
|
||||
out.push(list.slice(start, i).trim());
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
out.push(list.slice(start).trim());
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether a `[data-red-green]` rule of tokens.css applies to a window showing built-in scheme `id`. */
|
||||
function redGreenApplies(id: SchemeId, selector: string): boolean {
|
||||
if (!selector.includes("[data-red-green]") || typeof document === "undefined") return false;
|
||||
const root = document.implementation.createHTMLDocument("").documentElement;
|
||||
root.dataset.theme = themeKind(id);
|
||||
root.dataset.redGreen = "";
|
||||
if (id === "dark-hc") root.dataset.contrast = "high";
|
||||
else if (id !== "light" && id !== "dark") root.dataset.colorTheme = id;
|
||||
try {
|
||||
return root.matches(selector);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function themeSelectors(id: SchemeId): string[] {
|
||||
if (id === "light") return [':root[data-theme="light"]'];
|
||||
if (id === "dark-hc") return [':root[data-theme="dark-hc"]', ':root[data-theme="dark"][data-contrast="high"]'];
|
||||
@@ -459,7 +492,7 @@ function themeSelectors(id: SchemeId): string[] {
|
||||
|
||||
let source: string = tokensCss;
|
||||
let parsed: ReturnType<typeof blocks> | null = null;
|
||||
const resolvedCache = new Map<SchemeId, Vars>();
|
||||
const resolvedCache = new Map<string, Vars>();
|
||||
|
||||
/** Replaces the token source (tests: CSS `?raw` imports are empty under vitest). */
|
||||
export function _setSchemeSource(css: string) {
|
||||
@@ -468,15 +501,22 @@ export function _setSchemeSource(css: string) {
|
||||
resolvedCache.clear();
|
||||
}
|
||||
|
||||
/** All tokens of a theme with `var()` references resolved (so they survive under another theme). */
|
||||
export function schemeTokens(id: SchemeId, css: string = source): Vars {
|
||||
const cached = css === source ? resolvedCache.get(id) : undefined;
|
||||
/**
|
||||
* All tokens of a theme with `var()` references resolved (so they survive under another theme);
|
||||
* with `redGreen`, as Adjust colors for red-green vision deficiency recolours it.
|
||||
*/
|
||||
export function schemeTokens(id: SchemeId, css: string = source, redGreen = false): Vars {
|
||||
const key = redGreen ? `${id}+red-green` : id;
|
||||
const cached = css === source ? resolvedCache.get(key) : undefined;
|
||||
if (cached) return cached;
|
||||
const all = css === source ? (parsed ??= blocks(css)) : blocks(css);
|
||||
const own = themeSelectors(id);
|
||||
const merged: Vars = new Map();
|
||||
for (const b of all) if (b.selectors.includes(":root")) for (const [k, v] of b.decls) merged.set(k, v);
|
||||
for (const b of all) if (b.selectors.some((s) => own.includes(s))) for (const [k, v] of b.decls) merged.set(k, v);
|
||||
if (redGreen)
|
||||
for (const b of all)
|
||||
if (b.selectors.some((s) => redGreenApplies(id, s))) for (const [k, v] of b.decls) merged.set(k, v);
|
||||
const resolve = (value: string, depth = 0): string =>
|
||||
depth > 8
|
||||
? value
|
||||
@@ -493,7 +533,7 @@ export function schemeTokens(id: SchemeId, css: string = source): Vars {
|
||||
);
|
||||
const out: Vars = new Map();
|
||||
for (const [k, v] of merged) out.set(k, resolve(v));
|
||||
if (css === source) resolvedCache.set(id, out);
|
||||
if (css === source) resolvedCache.set(key, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -644,10 +684,12 @@ export function listSchemes(customs: CustomColorSchemes = {}) {
|
||||
return [...SCHEMES, ...Object.entries(customSchemes(customs)).map(([id, s]) => ({ id, name: s.name }))];
|
||||
}
|
||||
|
||||
export function resolvedSchemeTokens(id: string, customs: CustomColorSchemes = {}): Vars {
|
||||
/** With `redGreen`, a built-in scheme's red-green variant; a custom scheme keeps its parent's own colours. */
|
||||
export function resolvedSchemeTokens(id: string, customs: CustomColorSchemes = {}, redGreen = false): Vars {
|
||||
const custom = customSchemes(customs)[id];
|
||||
const base = isBuiltinTheme(id) ? id : (custom?.parent ?? "light");
|
||||
const tokens = new Map(schemeTokens(base));
|
||||
const builtin = isBuiltinTheme(id);
|
||||
const base = builtin ? id : (custom?.parent ?? "light");
|
||||
const tokens = new Map(schemeTokens(base, source, redGreen && builtin));
|
||||
for (const [key, value] of overrideDeclarations(custom?.attributes)) tokens.set(key, value);
|
||||
return tokens;
|
||||
}
|
||||
@@ -687,12 +729,13 @@ export function resolvedAttribute(
|
||||
id: string,
|
||||
attrId: string,
|
||||
customs: CustomColorSchemes = {},
|
||||
redGreen = false,
|
||||
): TextAttributesOverride {
|
||||
const attr = ATTRIBUTES.find((a) => a.id === attrId);
|
||||
if (!attr) return {};
|
||||
const custom = customSchemes(customs)[id];
|
||||
const own = custom?.attributes[attr.id];
|
||||
const vars = resolvedSchemeTokens(id, customs);
|
||||
const vars = resolvedSchemeTokens(id, customs, redGreen);
|
||||
if (attr.language)
|
||||
for (const [key, value] of overrideDeclarations(custom?.attributes, attr.language)) vars.set(key, value);
|
||||
|
||||
@@ -748,7 +791,7 @@ export function schemeCss(
|
||||
const el = root === undefined ? (typeof document !== "undefined" ? document.documentElement : null) : root;
|
||||
const pluginTheme = !!el?.dataset.pluginTheme && id === setting;
|
||||
if (id !== themeScheme(root) || pluginTheme) {
|
||||
const tokens = resolvedSchemeTokens(id, valid);
|
||||
const tokens = resolvedSchemeTokens(id, valid, !!el?.hasAttribute("data-red-green"));
|
||||
for (const [k, v] of tokens)
|
||||
if (SCHEME_VARS.has(k) || k.startsWith("--syn-")) {
|
||||
decls.push([k, v]);
|
||||
|
||||
@@ -2042,6 +2042,7 @@
|
||||
"Enable openidea for this session": "Enable openidea for this session",
|
||||
"Agent Config": "Agent Config",
|
||||
"Active via {source}": "Active via {source}",
|
||||
"Disabled for this session ({source})": "Disabled for this session ({source})",
|
||||
"Import into Global settings to toggle per session and share across agents": "Import into Global settings to toggle per session and share across agents",
|
||||
"No matching MCP servers.": "No matching MCP servers.",
|
||||
"Changes apply on the next message.": "Changes apply on the next message.",
|
||||
@@ -2330,5 +2331,9 @@
|
||||
"Java agent": "Java agent",
|
||||
"Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.": "Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.",
|
||||
"Java Agents": "Java Agents",
|
||||
"File at a Git revision (read-only).": "File at a Git revision (read-only)."
|
||||
"File at a Git revision (read-only).": "File at a Git revision (read-only).",
|
||||
"Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.": "Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.",
|
||||
"Appearance settings": "Appearance settings",
|
||||
"No such file or folder": "No such file or folder",
|
||||
"Choose a folder": "Choose a folder"
|
||||
}
|
||||
@@ -8426,6 +8426,7 @@
|
||||
"Enable openidea for this session": "在当前会话启用 openidea",
|
||||
"Agent Config": "智能体配置",
|
||||
"Active via {source}": "通过 {source} 生效",
|
||||
"Disabled for this session ({source})": "当前会话已禁用({source})",
|
||||
"Import into Global settings to toggle per session and share across agents": "导入到全局设置以支持按会话开关并在所有智能体间共享",
|
||||
"No matching MCP servers.": "没有匹配的 MCP 服务器。",
|
||||
"Changes apply on the next message.": "更改将在下一条消息生效。",
|
||||
@@ -8713,5 +8714,9 @@
|
||||
"Java agents of {list} were not added: they load only in local projects.": "未添加 {list} 的 Java 代理:Java 代理只加载到本地项目中。",
|
||||
"Java agent": "Java 代理",
|
||||
"Java Agents": "Java 代理",
|
||||
"File at a Git revision (read-only).": "Git 修订版中的文件(只读)。"
|
||||
"File at a Git revision (read-only).": "Git 修订版中的文件(只读)。",
|
||||
"Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.": "已开启「针对红绿色觉缺陷调整颜色」,此方案显示的是红绿色觉变体的颜色。",
|
||||
"Appearance settings": "外观设置",
|
||||
"No such file or folder": "文件或文件夹不存在",
|
||||
"Choose a folder": "请选择文件夹"
|
||||
}
|
||||
@@ -60,3 +60,26 @@
|
||||
.area::placeholder {
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
.pathRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
.pathInput {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.pathList {
|
||||
height: 280px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control, 4px);
|
||||
}
|
||||
.entryName {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.entry {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
@@ -9,8 +9,11 @@
|
||||
*/
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { create } from "zustand";
|
||||
import { registerHostPathChooser, type ChoosePathOptions } from "@/platform/choosePath";
|
||||
import { t, tx, VerbatimTextContext } from "@/platform/i18n";
|
||||
import { Checkbox, Dialog, Given, Input, List, T } from "@/ui";
|
||||
import { call, commands, type FileEntry } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { Checkbox, Dialog, Given, Icon, IconButton, Input, List, T } from "@/ui";
|
||||
import styles from "./inputDialogs.module.css";
|
||||
|
||||
export interface PromptInputOptions {
|
||||
@@ -59,7 +62,8 @@ export interface PickItemsOptions {
|
||||
type Request =
|
||||
| { kind: "prompt"; id: number; options: PromptInputOptions; resolve: (v: string | null) => void }
|
||||
| { kind: "choose"; id: number; options: ChooseItemOptions; resolve: (v: string | null) => void }
|
||||
| { kind: "pick"; id: number; options: PickItemsOptions; resolve: (v: string[] | null) => void };
|
||||
| { kind: "pick"; id: number; options: PickItemsOptions; resolve: (v: string[] | null) => void }
|
||||
| { kind: "path"; id: number; options: ChoosePathOptions; resolve: (v: string | null) => void };
|
||||
|
||||
const useInputDialogs = create<{ stack: Request[] }>(() => ({ stack: [] }));
|
||||
let seq = 0;
|
||||
@@ -97,6 +101,13 @@ export function pickItems(options: PickItemsOptions): Promise<string[] | null> {
|
||||
return open<string[]>((id, resolve) => ({ kind: "pick", id, options, resolve }), options.signal);
|
||||
}
|
||||
|
||||
/** A file or folder on the host this window's commands run on, browsed in the IDE (a remote window's chooser). */
|
||||
export function choosePathOnHost(options: ChoosePathOptions): Promise<string | null> {
|
||||
return open<string>((id, resolve) => ({ kind: "path", id, options, resolve }));
|
||||
}
|
||||
|
||||
registerHostPathChooser(choosePathOnHost);
|
||||
|
||||
export function InputDialogsHost() {
|
||||
const stack = useInputDialogs((s) => s.stack);
|
||||
return (
|
||||
@@ -108,6 +119,8 @@ export function InputDialogsHost() {
|
||||
</VerbatimTextContext.Provider>
|
||||
) : r.kind === "choose" ? (
|
||||
<ChooseDialog key={r.id} options={r.options} done={r.resolve} />
|
||||
) : r.kind === "path" ? (
|
||||
<PathDialog key={r.id} options={r.options} done={r.resolve} />
|
||||
) : (
|
||||
<VerbatimTextContext.Provider key={r.id} value={!!r.options.verbatim}>
|
||||
<PickDialog options={r.options} done={r.resolve} />
|
||||
@@ -335,3 +348,153 @@ function PickDialog({ options, done }: { options: PickItemsOptions; done: (v: st
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** The folder that holds `path` (either separator), or null at a root. */
|
||||
export function parentPath(path: string): string | null {
|
||||
if (/^(?:[\\/]+|[A-Za-z]:[\\/]*)$/.test(path)) return null;
|
||||
const trimmed = path.length > 1 ? path.replace(/[\\/]+$/, "") : path;
|
||||
const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
|
||||
if (cut < 0) return null;
|
||||
const parent = trimmed.slice(0, cut);
|
||||
// `/a` → `/`; `C:\a` → `C:\`.
|
||||
if (!parent || /^[A-Za-z]:$/.test(parent)) return parent + trimmed[cut];
|
||||
return parent === trimmed ? null : parent;
|
||||
}
|
||||
|
||||
function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: string | null) => void }) {
|
||||
const root = useProject((s) => s.project?.root ?? null);
|
||||
const [dir, setDir] = useState<string | null>(null);
|
||||
const [entries, setEntries] = useState<FileEntry[]>([]);
|
||||
const [active, setActive] = useState(-1);
|
||||
const [value, setValue] = useState(options.defaultPath || root || "");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const request = useRef(0);
|
||||
|
||||
const isDir = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.targetKind === "dir");
|
||||
const visit = async (path: string) => {
|
||||
const id = ++request.current;
|
||||
setLoading(true);
|
||||
try {
|
||||
const listed = await call(commands.fsReadDir(path));
|
||||
if (id !== request.current) return true;
|
||||
const shown = listed
|
||||
.filter((e) => !options.directory || isDir(e))
|
||||
.sort((a, b) => Number(isDir(b)) - Number(isDir(a)) || a.name.localeCompare(b.name));
|
||||
setDir(path);
|
||||
setEntries(shown);
|
||||
setActive(-1);
|
||||
setValue(path);
|
||||
setError(null);
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (id === request.current) setError(e instanceof Error ? e.message : String(e));
|
||||
return false;
|
||||
} finally {
|
||||
if (id === request.current) setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const start = options.defaultPath || root || "/";
|
||||
// A file path starts in its folder, with the file in the field.
|
||||
void visit(start).then((ok) => {
|
||||
const parent = parentPath(start);
|
||||
if (!ok && parent) void visit(parent).then((found) => found && !options.directory && setValue(start));
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const choose = (entry: FileEntry) => {
|
||||
if (isDir(entry)) void visit(entry.path);
|
||||
else done(entry.path);
|
||||
};
|
||||
const submit = async () => {
|
||||
const path = value.trim();
|
||||
if (!path) return;
|
||||
let kind: string;
|
||||
try {
|
||||
kind = await call(commands.fsEntryKind(path));
|
||||
} catch {
|
||||
return setError(tx("No such file or folder"));
|
||||
}
|
||||
const folder = kind === "dir";
|
||||
if (options.directory) return folder ? done(path) : setError(tx("Choose a folder"));
|
||||
if (folder) return void visit(path);
|
||||
done(path);
|
||||
};
|
||||
const up = dir === null ? null : parentPath(dir);
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
blockWorkbenchShortcuts
|
||||
title={options.title}
|
||||
onClose={() => done(null)}
|
||||
width={520}
|
||||
buttons={[
|
||||
{ label: tx("OK"), role: "default", disabled: !value.trim(), onClick: () => void submit() },
|
||||
{ label: t("common.cancel"), role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<form
|
||||
className={styles.form}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
<div className={styles.pathRow}>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
title={tx("Parent Folder")}
|
||||
disabled={!up || loading}
|
||||
onClick={() => up && void visit(up)}
|
||||
/>
|
||||
<Input
|
||||
data-autofocus
|
||||
className={styles.pathInput}
|
||||
aria-label={options.title}
|
||||
value={value}
|
||||
invalid={!!error}
|
||||
onChange={(e) => {
|
||||
setValue(e.target.value);
|
||||
setError(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<List
|
||||
items={entries}
|
||||
getKey={(e) => e.path}
|
||||
activeIndex={active}
|
||||
onActiveChange={(i) => {
|
||||
setActive(i);
|
||||
const entry = entries[i];
|
||||
if (entry) setValue(entry.path);
|
||||
}}
|
||||
// A click selects; a double click or Enter opens the folder or chooses the file.
|
||||
onActivate={(entry, _i, e) => (e.type !== "click" || e.detail > 1) && choose(entry)}
|
||||
rowHeight={24}
|
||||
className={styles.pathList}
|
||||
aria-label={dir ?? options.title}
|
||||
empty={
|
||||
<div className={styles.hint}>
|
||||
<T>{loading ? "Loading…" : "Empty folder"}</T>
|
||||
</div>
|
||||
}
|
||||
renderItem={(entry, state) => (
|
||||
<div className={`${state.active ? styles.activeRow : styles.row} ${styles.entry}`}>
|
||||
<Icon name={isDir(entry) ? "folder" : "file"} />
|
||||
<span className={styles.entryName}>{entry.name}</span>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{error && (
|
||||
<div className={styles.error}>
|
||||
<T>{error}</T>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import type { FileEntry } from "@/platform/ipc";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
readDir: vi.fn(),
|
||||
entryKind: vi.fn(),
|
||||
nativeOpen: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => true,
|
||||
commands: { ...real.commands, fsReadDir: mocks.readDir, fsEntryKind: mocks.entryKind },
|
||||
};
|
||||
});
|
||||
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: vi.fn() }));
|
||||
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { InputDialogsHost, parentPath } from "./inputDialogs";
|
||||
|
||||
const tree: Record<string, [string, "dir" | "file"][]> = {
|
||||
"/srv/app": [
|
||||
["runner", "dir"],
|
||||
["pom.xml", "file"],
|
||||
],
|
||||
"/srv/app/runner": [
|
||||
["plugins", "dir"],
|
||||
["server.jar", "file"],
|
||||
],
|
||||
"/srv": [["app", "dir"]],
|
||||
};
|
||||
|
||||
function entry(dir: string, name: string, kind: "dir" | "file"): FileEntry {
|
||||
return {
|
||||
name,
|
||||
path: `${dir}/${name}`,
|
||||
kind,
|
||||
size: 0,
|
||||
mtimeMs: null,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.readDir.mockImplementation(async (path: string) =>
|
||||
tree[path]
|
||||
? { status: "ok", data: tree[path].map(([n, k]) => entry(path, n, k)) }
|
||||
: { status: "error", error: { kind: "notFound", message: `${path} not found`, detail: null } },
|
||||
);
|
||||
mocks.entryKind.mockImplementation(async (path: string) => {
|
||||
if (tree[path]) return { status: "ok", data: "dir" };
|
||||
if (Object.entries(tree).some(([d, es]) => es.some(([n, k]) => k === "file" && `${d}/${n}` === path)))
|
||||
return { status: "ok", data: "file" };
|
||||
return { status: "error", error: { kind: "notFound", message: "not found", detail: null } };
|
||||
});
|
||||
useRemote.setState({ session: { root: "/srv/app", os: "linux", commands: [] } as never });
|
||||
render(<InputDialogsHost />);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const d of screen.queryAllByRole("dialog")) fireEvent.click(within(d).getByRole("button", { name: "Cancel" }));
|
||||
cleanup();
|
||||
useRemote.setState({ session: null });
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const dialog = () => within(screen.getByRole("dialog"));
|
||||
|
||||
describe("choosePath in a remote window", () => {
|
||||
it("browses the remote host instead of opening the desktop's dialog", async () => {
|
||||
let result!: Promise<string | null>;
|
||||
act(() => {
|
||||
result = choosePath({ directory: false, title: "Select Library JAR", defaultPath: "/srv/app" });
|
||||
});
|
||||
await waitFor(() => expect(dialog().getByText("runner")).toBeTruthy());
|
||||
expect(dialog().getByText("pom.xml")).toBeTruthy();
|
||||
expect(mocks.nativeOpen).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(dialog().getByText("runner"), { detail: 2 });
|
||||
await waitFor(() => expect(dialog().getByText("server.jar")).toBeTruthy());
|
||||
fireEvent.mouseDown(dialog().getByText("server.jar"));
|
||||
fireEvent.click(dialog().getByText("server.jar"));
|
||||
expect((dialog().getByRole("textbox") as HTMLInputElement).value).toBe("/srv/app/runner/server.jar");
|
||||
fireEvent.click(dialog().getByText("server.jar"), { detail: 2 });
|
||||
await expect(result).resolves.toBe("/srv/app/runner/server.jar");
|
||||
});
|
||||
|
||||
it("lists only folders when choosing one, goes up, and returns the folder shown", async () => {
|
||||
let result!: Promise<string | null>;
|
||||
act(() => {
|
||||
result = choosePath({ directory: true, title: "Select Folder", defaultPath: "/srv/app" });
|
||||
});
|
||||
await waitFor(() => expect(dialog().getByText("runner")).toBeTruthy());
|
||||
expect(dialog().queryByText("pom.xml")).toBeNull();
|
||||
|
||||
fireEvent.click(dialog().getByRole("button", { name: "Parent Folder" }));
|
||||
await waitFor(() => expect(dialog().getByText("app")).toBeTruthy());
|
||||
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
|
||||
await expect(result).resolves.toBe("/srv");
|
||||
});
|
||||
|
||||
it("starts in a file's folder and rejects a missing path", async () => {
|
||||
let result!: Promise<string | null>;
|
||||
act(() => {
|
||||
result = choosePath({ directory: false, title: "Select File", defaultPath: "/srv/app/pom.xml" });
|
||||
});
|
||||
await waitFor(() => expect(dialog().getByText("runner")).toBeTruthy());
|
||||
const field = dialog().getByRole("textbox");
|
||||
expect((field as HTMLInputElement).value).toBe("/srv/app/pom.xml");
|
||||
fireEvent.change(field, { target: { value: "/srv/app/missing.jar" } });
|
||||
fireEvent.click(dialog().getByRole("button", { name: "OK" }));
|
||||
await waitFor(() => expect(dialog().getByText("No such file or folder")).toBeTruthy());
|
||||
fireEvent.click(dialog().getByRole("button", { name: "Cancel" }));
|
||||
await expect(result).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parentPath", () => {
|
||||
it("handles Unix and Windows paths and roots", () => {
|
||||
expect(parentPath("/srv/app")).toBe("/srv");
|
||||
expect(parentPath("/srv")).toBe("/");
|
||||
expect(parentPath("/")).toBeNull();
|
||||
expect(parentPath("C:\\Users\\me")).toBe("C:\\Users");
|
||||
expect(parentPath("C:\\Users")).toBe("C:\\");
|
||||
expect(parentPath("C:\\")).toBeNull();
|
||||
expect(parentPath("/srv/app/")).toBe("/srv");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Заблокувати користувача