Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 7f5403ba8a fix(database): table tabs keep their filter, sort and page when switching tabs
Table editor tabs unmounted when another tab was shown, so their WHERE / ORDER BY
text, paging and unsubmitted edits were lost and the rows were queried again.
Table tabs are now kept alive like other editors, and the view state (filter,
sort, page) is remembered per table so a tab that is closed and reopened, or
dropped from the kept set, starts from the same view.

Fixes #4158
2026-11-18 17:47:09 +08:00
130 змінених файлів з 1334 додано та 3975 видалено

No files matched your search

+51 -438
Переглянути файл
@@ -399,429 +399,163 @@ pub fn apply_save_json(
Ok(saved_names)
}
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
".github/plugin/plugin.json",
".plugin/plugin.json",
".claude-plugin/plugin.json",
".cursor-plugin/plugin.json",
"plugin.json",
];
#[derive(Clone, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum SourceFormat {
Jsonc,
CodexToml,
CopilotPlugin { root: PathBuf },
}
#[derive(Clone)]
struct SourceSpec {
id: String,
label: String,
id: &'static str,
label: &'static str,
path: PathBuf,
format: SourceFormat,
suggested_scope: McpScope,
native_provider: Option<&'static str>,
claude_project_lookup: bool,
disabled_servers: std::sync::Arc<BTreeSet<String>>,
}
#[derive(Default)]
struct CopilotSettings {
disabled_mcp_servers: std::sync::Arc<BTreeSet<String>>,
disabled_plugins: BTreeSet<String>,
}
fn external_source_specs(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<SourceSpec> {
let mut specs = Vec::new();
let no_disabled: std::sync::Arc<BTreeSet<String>> = std::sync::Arc::new(BTreeSet::new());
if let Some(root) = workspace_root {
specs.push(SourceSpec {
id: "workspace-mcp".into(),
label: "Project (.mcp.json)".into(),
id: "workspace-mcp",
label: "Project (.mcp.json)",
path: root.join(".mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("claude"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "vscode-mcp".into(),
label: "VS Code (.vscode/mcp.json)".into(),
id: "vscode-mcp",
label: "VS Code (.vscode/mcp.json)",
path: root.join(".vscode").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "cursor-project".into(),
label: "Cursor Project (.cursor/mcp.json)".into(),
id: "cursor-project",
label: "Cursor Project (.cursor/mcp.json)",
path: root.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("cursor"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "codex-project".into(),
label: "Codex Project (.codex/config.toml)".into(),
id: "codex-project",
label: "Codex Project (.codex/config.toml)",
path: root.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::Workspace,
native_provider: Some("codex"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "gemini-project".into(),
label: "Gemini Project (.gemini/settings.json)".into(),
id: "gemini-project",
label: "Gemini Project (.gemini/settings.json)",
path: root.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("gemini"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
}
if let Some(home) = home_dir {
let copilot_dir = home.join(".copilot");
let copilot_settings = read_copilot_settings(&copilot_dir);
specs.push(SourceSpec {
id: "copilot-cli".into(),
label: "GitHub Copilot CLI".into(),
path: copilot_dir.join("mcp-config.json"),
id: "copilot-cli",
label: "GitHub Copilot CLI",
path: home.join(".copilot").join("mcp-config.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("copilot"),
claude_project_lookup: false,
disabled_servers: copilot_settings.disabled_mcp_servers.clone(),
});
specs.extend(copilot_plugin_source_specs(&copilot_dir, &copilot_settings));
specs.push(SourceSpec {
id: "claude-code".into(),
label: "Claude Code".into(),
id: "claude-code",
label: "Claude Code",
path: home.join(".claude.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("claude"),
claude_project_lookup: true,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "codex".into(),
label: "Codex".into(),
id: "codex",
label: "Codex",
path: home.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::User,
native_provider: Some("codex"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "cursor".into(),
label: "Cursor".into(),
id: "cursor",
label: "Cursor",
path: home.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("cursor"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "gemini".into(),
label: "Gemini CLI".into(),
id: "gemini",
label: "Gemini CLI",
path: home.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("gemini"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "jetbrains-air".into(),
label: "JetBrains Air".into(),
id: "jetbrains-air",
label: "JetBrains Air",
path: home.join(".jetbrains").join("mcp").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "copilot-intellij".into(),
label: "GitHub Copilot (JetBrains)".into(),
id: "copilot-intellij",
label: "GitHub Copilot (JetBrains)",
path: home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled,
});
}
specs
}
fn read_copilot_settings(copilot_dir: &Path) -> CopilotSettings {
let Ok(text) = std::fs::read_to_string(copilot_dir.join("settings.json")) else {
return CopilotSettings::default();
};
let Ok(root) = parse_jsonc_value(&text) else {
return CopilotSettings::default();
};
let disabled_mcp_servers = root
.get("disabledMcpServers")
.and_then(Value::as_array)
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned))
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
let disabled_plugins = root
.get("enabledPlugins")
.and_then(Value::as_object)
.map(|obj| {
obj.iter()
.filter(|(_, v)| v.as_bool() == Some(false))
.map(|(k, _)| k.trim().to_owned())
.filter(|k| !k.is_empty())
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
CopilotSettings { disabled_mcp_servers: std::sync::Arc::new(disabled_mcp_servers), disabled_plugins }
}
fn copilot_plugin_source_specs(copilot_dir: &Path, settings: &CopilotSettings) -> Vec<SourceSpec> {
let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json")) else {
return Vec::new();
};
let Ok(root) = parse_jsonc_value(&text) else {
return Vec::new();
};
let Some(installed) = root.get("installedPlugins").and_then(Value::as_array) else {
return Vec::new();
};
let mut seen_ids = HashSet::new();
let mut specs = Vec::new();
for entry in installed {
let Some(obj) = entry.as_object() else { continue };
if obj.get("enabled").and_then(Value::as_bool) == Some(false) {
continue;
}
let Some(name) = obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) else {
continue;
};
let marketplace = obj.get("marketplace").and_then(Value::as_str).map(str::trim).unwrap_or_default();
if settings.disabled_plugins.contains(name)
|| (!marketplace.is_empty()
&& (settings.disabled_plugins.contains(&format!("{name}@{marketplace}"))
|| settings.disabled_plugins.contains(&format!("{marketplace}/{name}"))))
{
continue;
}
let Some(raw_cache) = obj.get("cache_path").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
else {
continue;
};
let plugin_root =
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
if !plugin_root.is_dir() {
continue;
}
let Some((manifest_path, _)) = read_copilot_plugin_servers(&plugin_root) else {
continue;
};
let base_id = if marketplace.is_empty() {
format!("copilot-plugin:{name}")
} else {
format!("copilot-plugin:{marketplace}/{name}")
};
let mut id = base_id.clone();
let mut suffix = 2usize;
while !seen_ids.insert(id.clone()) {
id = format!("{base_id}#{suffix}");
suffix += 1;
}
let label = if marketplace.is_empty() {
format!("GitHub Copilot Plugin ({name})")
} else {
format!("GitHub Copilot Plugin ({name} · {marketplace})")
};
specs.push(SourceSpec {
id,
label,
path: manifest_path,
format: SourceFormat::CopilotPlugin { root: plugin_root },
suggested_scope: McpScope::User,
native_provider: Some("copilot"),
claude_project_lookup: false,
disabled_servers: settings.disabled_mcp_servers.clone(),
});
}
specs
}
fn resolve_within_dir(base_dir: &Path, candidate: &Path) -> Option<PathBuf> {
if candidate.as_os_str().is_empty() {
return None;
}
let base_canon = dunce::canonicalize(base_dir).ok()?;
let clean = candidate.strip_prefix(".").unwrap_or(candidate);
let joined = if clean.is_relative() { base_dir.join(clean) } else { clean.to_path_buf() };
let meta = std::fs::metadata(&joined).ok()?;
if !meta.is_file() {
return None;
}
let target_canon = dunce::canonicalize(&joined).ok()?;
target_canon.starts_with(&base_canon).then_some(joined)
}
fn expand_plugin_root_vars(value: &str, root: &str) -> String {
value.replace("${COPILOT_PLUGIN_ROOT}", root).replace("${CLAUDE_PLUGIN_ROOT}", root).replace("${PLUGIN_ROOT}", root)
}
fn expand_plugin_servers(servers: &mut BTreeMap<String, AgentMcpServer>, plugin_root: &Path) {
let root = plugin_root.to_string_lossy();
for srv in servers.values_mut() {
if let Some(cmd) = srv.command.as_mut() {
*cmd = expand_plugin_root_vars(cmd, &root);
}
for arg in &mut srv.args {
*arg = expand_plugin_root_vars(arg, &root);
}
if let Some(url) = srv.url.as_mut() {
*url = expand_plugin_root_vars(url, &root);
}
for val in srv.env.values_mut() {
*val = expand_plugin_root_vars(val, &root);
}
for val in srv.headers.values_mut() {
*val = expand_plugin_root_vars(val, &root);
}
}
}
fn extract_plugin_manifest_servers(
plugin_root: &Path,
manifest_path: &Path,
mcp_val: &Value,
) -> (PathBuf, BTreeMap<String, AgentMcpServer>) {
match mcp_val {
Value::String(rel) => {
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
let map = read_external_file(&path);
return (path, map);
}
(manifest_path.to_path_buf(), BTreeMap::new())
}
Value::Object(_) => {
let wrapper = json!({ "mcpServers": mcp_val });
(manifest_path.to_path_buf(), extract_servers_from_root(&wrapper, None))
}
Value::Array(items) => {
let mut merged = BTreeMap::new();
let mut first_path: Option<PathBuf> = None;
for item in items {
match item {
Value::String(rel) => {
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
let map = read_external_file(&path);
if !map.is_empty() && first_path.is_none() {
first_path = Some(path);
}
merged.extend(map);
}
}
Value::Object(_) => {
let map = extract_servers_from_root(item, None);
if !map.is_empty() && first_path.is_none() {
first_path = Some(manifest_path.to_path_buf());
}
merged.extend(map);
}
_ => {}
}
}
(first_path.unwrap_or_else(|| manifest_path.to_path_buf()), merged)
}
_ => (manifest_path.to_path_buf(), BTreeMap::new()),
}
}
fn read_copilot_plugin_servers(plugin_root: &Path) -> Option<(PathBuf, BTreeMap<String, AgentMcpServer>)> {
if let Some(dot_mcp) = resolve_within_dir(plugin_root, Path::new(".mcp.json")) {
let mut servers = read_external_file(&dot_mcp);
if !servers.is_empty() {
expand_plugin_servers(&mut servers, plugin_root);
return Some((dot_mcp, servers));
}
}
for rel in COPILOT_PLUGIN_MANIFESTS {
let Some(manifest_path) = resolve_within_dir(plugin_root, Path::new(rel)) else {
continue;
};
let Ok(text) = std::fs::read_to_string(&manifest_path) else {
continue;
};
let Ok(manifest) = parse_jsonc_value(&text) else {
continue;
};
let Some(mcp_val) = manifest.get("mcpServers") else {
continue;
};
let (source_path, mut servers) = extract_plugin_manifest_servers(plugin_root, &manifest_path, mcp_val);
if !servers.is_empty() {
expand_plugin_servers(&mut servers, plugin_root);
return Some((source_path, servers));
}
}
None
}
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
let mut servers = match &spec.format {
SourceFormat::CopilotPlugin { root } => {
read_copilot_plugin_servers(root).map(|(_, map)| map).unwrap_or_default()
}
SourceFormat::CodexToml => {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
parse_codex_toml_servers(&text)
}
SourceFormat::Jsonc => {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
};
let mut map = extract_servers_from_root(&root, None);
if spec.claude_project_lookup
&& let Some(ws) = workspace_root
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
{
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
for (proj_key, proj_val) in projects {
let matches =
Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
if matches {
for (name, srv) in extract_servers_from_root(proj_val, None) {
map.insert(name, srv);
}
}
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
if spec.format == SourceFormat::CodexToml {
return parse_codex_toml_servers(&text);
}
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
};
let mut servers = extract_servers_from_root(&root, None);
if spec.claude_project_lookup
&& let Some(ws) = workspace_root
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
{
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
for (proj_key, proj_val) in projects {
let matches = Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
if matches {
for (name, srv) in extract_servers_from_root(proj_val, None) {
servers.insert(name, srv);
}
}
map
}
};
for name in spec.disabled_servers.iter() {
if let Some(srv) = servers.get_mut(name) {
srv.enabled = false;
}
}
servers
@@ -878,8 +612,8 @@ pub fn discover_external_sources(home_dir: Option<&Path>, workspace_root: Option
})
.collect();
out.push(McpExternalSource {
id: spec.id,
label: spec.label,
id: spec.id.to_owned(),
label: spec.label.to_owned(),
path: IpcPath(spec.path),
suggested_scope: spec.suggested_scope,
native_provider: spec.native_provider.map(str::to_owned),
@@ -907,7 +641,7 @@ pub fn apply_import_selected(
let mut by_source: BTreeMap<&str, BTreeMap<String, AgentMcpServer>> = BTreeMap::new();
for spec in &specs {
if selections.iter().any(|s| s.source_id == spec.id) {
by_source.insert(spec.id.as_str(), read_source_servers(spec, workspace_root));
by_source.insert(spec.id, read_source_servers(spec, workspace_root));
}
}
let target = match scope {
@@ -1636,125 +1370,4 @@ mod tests {
assert_eq!(workspace["events-sse"].transport, McpTransport::Sse);
assert_eq!(workspace["events-sse"].url.as_deref(), Some("https://sse.example.com/events"));
}
#[test]
fn discovers_and_imports_copilot_installed_plugin_mcp_servers() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let copilot = home.join(".copilot");
let azure_root = copilot.join("installed-plugins/_direct/azure-skills");
let inline_root = copilot.join("installed-plugins/awesome-copilot/inline-tools");
let disabled_root = copilot.join("installed-plugins/_direct/disabled-plug");
let outside_root = tmp.path().join("outside");
std::fs::create_dir_all(azure_root.join(".plugin")).unwrap();
std::fs::create_dir_all(inline_root.join(".claude-plugin")).unwrap();
std::fs::create_dir_all(&disabled_root).unwrap();
std::fs::create_dir_all(&outside_root).unwrap();
std::fs::write(
azure_root.join(".plugin/plugin.json"),
r#"{"name":"azure","version":"1.2.106","mcpServers":"./.mcp.json"}"#,
)
.unwrap();
std::fs::write(
azure_root.join(".mcp.json"),
r#"{"mcpServers":{"azure":{"command":"npx","args":["-y","@azure/mcp@latest","${COPILOT_PLUGIN_ROOT}/cfg"],"env":{"PLUG_DIR":"${CLAUDE_PLUGIN_ROOT}"}}}}"#,
)
.unwrap();
std::fs::write(
inline_root.join(".claude-plugin/plugin.json"),
r#"{"name":"inline-tools","version":"0.1.0","mcpServers":{"inline-srv":{"command":"${PLUGIN_ROOT}/bin/run","args":["--stdio"]},"muted-srv":{"command":"echo","args":["off"]}}}"#,
)
.unwrap();
std::fs::write(
disabled_root.join(".mcp.json"),
r#"{"mcpServers":{"never":{"command":"npx","args":["never"]}}}"#,
)
.unwrap();
std::fs::write(outside_root.join("secret.json"), r#"{"mcpServers":{"escaped":{"command":"sh"}}}"#).unwrap();
let escape_root = copilot.join("installed-plugins/_direct/escape-plug");
std::fs::create_dir_all(escape_root.join(".plugin")).unwrap();
std::fs::write(
escape_root.join(".plugin/plugin.json"),
r#"{"name":"escape-plug","mcpServers":"../../../../outside/secret.json"}"#,
)
.unwrap();
// `~/.copilot/config.json` includes leading `//` comments in Copilot CLI.
let config_json = format!(
"// Managed automatically.\n{}",
serde_json::json!({
"installedPlugins": [
{
"name": "azure",
"marketplace": "",
"enabled": true,
"cache_path": azure_root,
},
{
"name": "inline-tools",
"marketplace": "awesome-copilot",
"enabled": true,
"cache_path": inline_root,
},
{
"name": "disabled-plug",
"marketplace": "",
"enabled": false,
"cache_path": disabled_root,
},
{
"name": "escape-plug",
"marketplace": "",
"enabled": true,
"cache_path": escape_root,
}
]
})
);
std::fs::write(copilot.join("config.json"), config_json).unwrap();
std::fs::write(copilot.join("settings.json"), r#"{"disabledMcpServers":["muted-srv"]}"#).unwrap();
let sources = discover_external_sources(Some(&home), None);
assert_eq!(sources.len(), 2);
let azure_src = sources.iter().find(|s| s.id == "copilot-plugin:azure").unwrap();
assert_eq!(azure_src.label, "GitHub Copilot Plugin (azure)");
assert_eq!(azure_src.native_provider.as_deref(), Some("copilot"));
assert_eq!(azure_src.path.0, azure_root.join(".mcp.json"));
assert_eq!(azure_src.servers.len(), 1);
assert!(azure_src.servers[0].enabled);
assert_eq!(
azure_src.servers[0].args,
vec!["-y", "@azure/mcp@latest", &format!("{}/cfg", azure_root.display())]
);
let inline_src = sources.iter().find(|s| s.id == "copilot-plugin:awesome-copilot/inline-tools").unwrap();
assert_eq!(inline_src.label, "GitHub Copilot Plugin (inline-tools · awesome-copilot)");
assert_eq!(inline_src.path.0, inline_root.join(".claude-plugin/plugin.json"));
let active = inline_src.servers.iter().find(|s| s.name == "inline-srv").unwrap();
assert!(active.enabled);
assert_eq!(active.command.as_deref(), Some(format!("{}/bin/run", inline_root.display()).as_str()));
let muted = inline_src.servers.iter().find(|s| s.name == "muted-srv").unwrap();
assert!(!muted.enabled);
let mut user = BTreeMap::new();
let mut workspace = BTreeMap::new();
let imported = apply_import_selected(
&mut user,
&mut workspace,
Some(&home),
None,
McpScope::User,
&[McpImportSelection { source_id: "copilot-plugin:azure".into(), name: "azure".into() }],
false,
)
.unwrap();
assert_eq!(imported, vec!["azure".to_string()]);
assert_eq!(user["azure"].env.get("PLUG_DIR").map(String::as_str), Some(azure_root.to_str().unwrap()));
}
}
+1 -19
Переглянути файл
@@ -536,9 +536,7 @@ impl PathMap {
let abs = if p.is_absolute() {
p.to_path_buf()
} else {
// rustc prints workspace members' files relative to the workspace root, above
// the member's manifest directory (`base`) when a member is built on its own.
let in_base = base.and_then(|b| Path::new(b).ancestors().map(|a| a.join(p)).find(|c| c.exists()));
let in_base = base.map(|b| Path::new(b).join(p)).filter(|c| c.exists());
in_base.unwrap_or_else(|| cwd.join(p))
};
let abs = normalize(&abs);
@@ -1305,22 +1303,6 @@ mod tests {
assert_eq!(identifier_len("x é_1 c", 2), 3);
}
#[test]
fn resolves_a_member_build_s_workspace_relative_paths() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
write(&root, "client/src/main.rs", "fn main() {}\n");
write(&root, "client/src/lib.rs", "\n");
write(&root, "src/lib.rs", "\n");
let map = PathMap { root: root.clone(), canonical: None };
let member = root.join("client");
let base = member.to_str();
// Build Module runs in the member; rustc names its files from the workspace root.
assert_eq!(map.resolve("client/src/main.rs", &member, base), root.join("client/src/main.rs"));
// A crate built from its own directory names them from there.
assert_eq!(map.resolve("src/lib.rs", &member, base), member.join("src/lib.rs"));
}
// Uses Unix absolute paths for the canonical root.
#[cfg(unix)]
#[test]
-31
Переглянути файл
@@ -916,37 +916,6 @@ impl DbManager {
self.tunnels.lock().remove(id);
}
/// Creates a database on the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `template`, the database
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
pub async fn create_database(&self, id: &str, template: &str, statement: &str) -> IdeResult<()> {
let id = split_target(id).0;
if self.source(id)?.read_only {
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
}
self.disconnect(&format!("{id}:{template}")).await;
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
self.remember_statement(id, statement);
Ok(())
}
/// Drops `database` of the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `database`.
/// Refuses the database the data source connects to and read-only data sources.
pub async fn drop_database(&self, id: &str, database: &str, statement: &str) -> IdeResult<()> {
let id = split_target(id).0;
if self.source(id)?.read_only {
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
}
if self.databases(id).await?.current == database {
return Err(IdeError::invalid(format!("the data source connects to {database}; it cannot drop it")));
}
self.disconnect(&format!("{id}:{database}")).await;
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
self.remember_statement(id, statement);
Ok(())
}
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
let id = split_target(id).0;
-38
Переглянути файл
@@ -230,44 +230,6 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
}
/// Runs `job` with the newest installed copy of its tool, the way the dialogs do.
#[tokio::test]
async fn drops_a_database_the_ide_holds_connections_to() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
db.execute("p", "DROP DATABASE IF EXISTS oi_drop_me", 0, &c).await?;
db.execute("p", "CREATE DATABASE oi_drop_me TEMPLATE template0", 0, &c).await?;
// What the tree and a manual-commit console leave open on the database.
db.schemas("p:oi_drop_me").await?;
db.set_manual_commit("p:oi_drop_me", true).await?;
db.execute("p:oi_drop_me", "SELECT 1", 1, &c).await?;
db.drop_database("p", "oi_drop_me", "drop database oi_drop_me").await?;
assert!(!db.is_connected("p:oi_drop_me"));
assert!(!db.databases("p").await?.names.iter().any(|n| n == "oi_drop_me"));
let current = db.databases("p").await?.current;
let refused = db.drop_database("p", &current, &format!("drop database \"{current}\"")).await;
assert!(refused.is_err());
Ok(())
}
#[tokio::test]
async fn creates_a_database_from_a_template_the_ide_holds_connections_to() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
db.execute("p", "DROP DATABASE IF EXISTS oi_from_template", 0, &c).await?;
db.schemas("p:template1").await?;
db.create_database("p", "template1", "create database oi_from_template").await?;
assert!(!db.is_connected("p:template1"));
assert!(db.databases("p").await?.names.iter().any(|n| n == "oi_from_template"));
db.execute("p", "DROP DATABASE oi_from_template", 0, &c).await?;
Ok(())
}
async fn run_tool(db: &DbManager, target: &str, job: ide_db::tools::DbToolJob) -> IdeResult<()> {
let install = ide_db::tools::find_installs(job.tool()).into_iter().next().expect("installed");
let mut lines = Vec::new();
-41
Переглянути файл
@@ -95,44 +95,3 @@ async fn sqlserver_values_paging_transactions_and_cancellation() {
task.await.unwrap();
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
}
#[tokio::test]
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
let mut parts = server.splitn(4, ':');
let (host, port, user, password) = (
parts.next().unwrap(),
parts.next().unwrap().parse().unwrap(),
parts.next().unwrap(),
parts.next().unwrap_or(""),
);
let source = |database: &str| DataSource {
id: "s".into(),
name: "sqlserver".into(),
driver: DbDriver::SqlServer,
host: host.into(),
port: Some(port),
user: user.into(),
database: database.into(),
ssl: DbSslMode::Disable,
..Default::default()
};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = ide_db::DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![source("master")]).await.unwrap();
db.set_password("s", Some(password.into()), false).await.unwrap();
let name = format!("oi_force_drop_{}", std::process::id());
// The tree's connection to `model` would keep SQL Server from copying it.
db.schemas("s:model").await.unwrap();
db.create_database("s", "model", &format!("create database {name};")).await.unwrap();
assert!(!db.is_connected("s:model"));
let other = Pool::connect(&source(&name), Some(password), None).await.unwrap();
let held = Held::acquire(&other).await.unwrap();
let force = format!("alter database {name} set single_user with rollback immediate;\ndrop database {name};");
db.drop_database("s", &name, &force).await.unwrap();
assert!(!db.databases("s").await.unwrap().names.contains(&name));
drop(held);
}
-28
Переглянути файл
@@ -139,32 +139,6 @@ pub async fn db_disconnect(host: &Host, window: &str, id: String) -> IdeResult<(
Ok(())
}
#[command(trust = trusted)]
pub async fn db_create_database(
host: &Host,
window: &str,
id: String,
template: String,
statement: String,
) -> IdeResult<()> {
// Creates a database on the server of data source `id` with `statement`, copied from `template` (New › Database).
let db = host.project(window)?.db.clone();
db.create_database(&id, &template, &statement).await
}
#[command(trust = trusted)]
pub async fn db_drop_database(
host: &Host,
window: &str,
id: String,
database: String,
statement: String,
) -> IdeResult<()> {
// Drops `database` of the server of data source `id` with `statement` (Drop… on a database node).
let db = host.project(window)?.db.clone();
db.drop_database(&id, &database, &statement).await
}
#[command(trust = trusted)]
pub async fn db_databases(host: &Host, window: &str, id: String) -> IdeResult<Databases> {
// Databases of the server of data source `id` (PostgreSQL); connect to one as `<id>:<database>`.
@@ -504,12 +478,10 @@ ide_command::domain!(
db_connected,
db_console_path,
db_consoles,
db_create_database,
db_database_catalog,
db_databases,
db_ddl,
db_disconnect,
db_drop_database,
db_execute,
db_explain,
db_finish_transaction,
-2
Переглянути файл
@@ -286,8 +286,6 @@ impl Host {
effective.languages.java.gradle.linked_projects.as_deref(),
build_files.as_deref(),
);
// After the import settings: they extend the workspace folder's name.
ide_sdk::jdtls_workspaces::use_own_temp(cfg, &data_dir);
}
}));
}
+5 -11
Переглянути файл
@@ -879,15 +879,16 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
// Room for activation (about 3_100 on macOS, more on Windows). A background task gets ten
// times it (5 s / 500 ms): enough for each step of `patient` with its CPU work (32_000 to
// 80_000), not for the whole run without the refill on each report.
let limits = Limits {
let f = fixture(Limits {
fuel: 40_000,
timeout: Duration::from_millis(500),
background: Duration::from_millis(5_000),
..Limits::default()
};
let f = fixture(limits);
});
f.install(&misbehave_pkg());
f.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
if f.host.set_capability("misbehave", "process:git", true).is_err() {
return;
}
// Warm up activation in its own call so `patient` starts with a fresh budget.
assert_eq!(f.run("misbehave", "echo", Some("warm")).unwrap().as_deref(), Some("warm"));
@@ -896,13 +897,6 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
let err = f.run("misbehave", "spin", None).unwrap_err();
assert!(err.contains("exceeded its CPU budget (40000 fuel per call)"), "{err}");
// Beginning a task alone must not renew its scaled budget.
let quiet = fixture(limits);
quiet.install(&misbehave_pkg());
quiet.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
let err = quiet.run("misbehave", "patient", Some("quiet:4000")).unwrap_err();
assert!(err.contains("exceeded its CPU budget (400000 fuel per call)"), "{err}");
}
#[test]
-45
Переглянути файл
@@ -65,28 +65,6 @@ pub(crate) fn lenient_diagnostics(server: &str, items: Value) -> Vec<lsp::Diagno
parsed
}
/// rust-analyzer publishes its own analysis next to `cargo check`'s (flycheck): one type
/// mismatch then arrives as `rust-analyzer(E0308)` and `rustc(E0308)`. Its own entry is
/// dropped when the compiler reports the same code and severity over an overlapping range.
fn drop_compiler_duplicates(diagnostics: &mut Vec<lsp::Diagnostic>) {
let overlaps = |a: &lsp::Range, b: &lsp::Range| a.start <= b.end && b.start <= a.end;
let compiler: Vec<(lsp::Range, Option<lsp::NumberOrString>, Option<lsp::DiagnosticSeverity>)> = diagnostics
.iter()
.filter(|d| d.source.as_deref() == Some("rustc") && d.code.is_some())
.map(|d| (d.range, d.code.clone(), d.severity))
.collect();
if compiler.is_empty() {
return;
}
diagnostics.retain(|d| {
d.source.as_deref() != Some("rust-analyzer")
|| d.code.is_none()
|| !compiler
.iter()
.any(|(range, code, severity)| code == &d.code && severity == &d.severity && overlaps(range, &d.range))
});
}
impl ClientHandler {
pub fn new(mgr: Weak<LspManager>, server: Arc<Server>, generation: u64) -> Self {
Self { mgr, server, generation }
@@ -315,7 +293,6 @@ impl ClientHandler {
}
};
params.diagnostics = lenient_diagnostics(&self.server.name, raw.unwrap_or(Value::Null));
drop_compiler_duplicates(&mut params.diagnostics);
let Some(path) = uri_to_path(params.uri.as_str())
.or_else(|| crate::notebook::is_cell_uri(params.uri.as_str()).then(|| PathBuf::from(params.uri.as_str())))
else {
@@ -724,28 +701,6 @@ mod tests {
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
#[test]
fn rust_analyzer_s_own_entry_yields_to_the_compiler_s_for_the_same_error() {
let diagnostic = |source: &str, code: &str, line: u32, severity| lsp::Diagnostic {
range: lsp::Range::new(lsp::Position::new(line, 21), lsp::Position::new(line, 27)),
severity: Some(severity),
code: Some(lsp::NumberOrString::String(code.into())),
source: Some(source.into()),
message: format!("{source} {code}"),
..Default::default()
};
let error = lsp::DiagnosticSeverity::ERROR;
let mut items = vec![
diagnostic("rust-analyzer", "E0308", 1, error),
diagnostic("rustc", "E0308", 1, error),
diagnostic("rust-analyzer", "E0308", 5, error),
diagnostic("rust-analyzer", "unused_variables", 1, lsp::DiagnosticSeverity::WARNING),
];
drop_compiler_duplicates(&mut items);
let left: Vec<_> = items.iter().map(|d| (d.message.as_str(), d.range.start.line)).collect();
assert_eq!(left, [("rustc E0308", 1), ("rust-analyzer E0308", 5), ("rust-analyzer unused_variables", 1)]);
}
#[test]
fn tsserver_aborts_are_out_of_memory() {
assert!(tsserver_ran_out_of_memory("TSServer exited. Code: 134. Signal: null"));
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b24fb8d5161006104698fb07a43432601b4f16fdc4a34cc70058cbef7e973066
1056d650117bc2216ac518aa26b27cf898f58db62369ae285b9d8925ada74dff
+3 -9
Переглянути файл
@@ -181,13 +181,9 @@ impl commands::Guest for Misbehave {
};
let child = process::start(&cmd, None)?;
// CPU work per step (loop iterations), for fuel budget tests.
let arg = arg.as_deref().unwrap_or("");
let report = !arg.starts_with("quiet:");
let work: u64 = arg.strip_prefix("quiet:").unwrap_or(arg).parse().unwrap_or(0);
let work: u64 = arg.as_deref().and_then(|a| a.parse().ok()).unwrap_or(0);
for step in 0..25 {
if report {
task.report(step, Some(25), Some("waiting"));
}
task.report(step, Some(25), Some("waiting"));
let mut x: u64 = 0;
for _ in 0..work {
x = std::hint::black_box(x.wrapping_add(1));
@@ -199,9 +195,7 @@ impl commands::Guest for Misbehave {
// Let it finish on its own: no kill, no slow teardown.
child.close_stdin()?;
let _ = child.wait(5_000);
if report {
task.report(25, Some(25), Some("done"));
}
task.report(25, Some(25), Some("done"));
Ok(Some("still here".into()))
}
// `editor.write` is not granted: an error, not a trap.
+3 -93
Переглянути файл
@@ -21,63 +21,10 @@ fn root(data_dir: &Path) -> PathBuf {
data_dir.join("lsp").join("jdtls")
}
/// jdtls' temporary folder, inside its workspace.
const TEMP_DIR: &str = ".tmp";
fn workspace(cfg: &LanguageServerConfig) -> Option<&Path> {
cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)).map(Path::new)
}
fn temp_arg(workspace: &Path) -> String {
format!("-Djava.io.tmpdir={}", workspace.join(TEMP_DIR).to_string_lossy())
}
/// Gives jdtls a temporary folder inside a workspace of ours (`<workspace>/.tmp`) unless the
/// user's JVM arguments choose one. JDT APT copies a project's annotation processor jars into a
/// new `jdt-apt-*` folder for each processor class loader and deletes it only when the JVM exits
/// normally — never on Windows, where the jars are still open then — so in the system temp
/// folder they pile up with every start; [`mark_used`] empties this one before each start.
pub fn use_own_temp(cfg: &mut LanguageServerConfig, data_dir: &Path) {
if cfg.name != "jdtls" || cfg.args.iter().any(|a| a.contains("-Djava.io.tmpdir=")) {
return;
}
let Some(arg) = workspace(cfg).filter(|w| w.starts_with(root(data_dir))).map(temp_arg) else { return };
// Launched directly, JVM options go before `-jar`; through the script, as `--jvm-arg=`.
match cfg.args.iter().position(|a| a == "-jar") {
Some(jar) => cfg.args.insert(jar, arg),
None => cfg.args.push(format!("--jvm-arg={arg}")),
}
}
/// Empties the temporary folder [`use_own_temp`] gave the workspace. Best effort: files a server
/// still has open on Windows stay until a later start.
fn clear_temp(cfg: &LanguageServerConfig, workspace: &Path) {
let arg = temp_arg(workspace);
if !cfg.args.iter().any(|a| a.strip_prefix("--jvm-arg=").unwrap_or(a) == arg) {
return;
}
let temp = workspace.join(TEMP_DIR);
for entry in std::fs::read_dir(&temp).into_iter().flatten().flatten() {
let path = entry.path();
let removed = if entry.file_type().is_ok_and(|t| t.is_dir()) {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
if let Err(e) = removed {
tracing::debug!("jdtls: cannot remove temporary {}: {e}", path.display());
}
}
if let Err(e) = std::fs::create_dir_all(&temp) {
tracing::warn!("jdtls: cannot create its temporary folder {}: {e}", temp.display());
}
}
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder), and empties
/// the workspace's temporary folder.
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
pub fn mark_used(cfg: &LanguageServerConfig) {
let Some(dir) = workspace(cfg) else { return };
clear_temp(cfg, dir);
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(|()| {
let marker = std::fs::File::create(dir.join(USED_MARKER))?;
marker.set_modified(SystemTime::now())
@@ -195,43 +142,6 @@ mod tests {
assert!(ws.exists());
}
#[test]
fn jdtls_keeps_its_temporary_files_in_its_workspace_and_starts_with_none() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("p");
let temp = format!("-Djava.io.tmpdir={}", ws.join(TEMP_DIR).to_string_lossy());
// Through the launcher script.
let mut script = cfg(&ws);
use_own_temp(&mut script, tmp.path());
assert_eq!(script.args.last(), Some(&format!("--jvm-arg={temp}")));
// Launched directly: a JVM option, before `-jar`.
let mut direct = cfg(&ws);
direct.args.splice(0..0, ["-Xmx2G".to_owned(), "-jar".to_owned(), "launcher.jar".to_owned()]);
use_own_temp(&mut direct, tmp.path());
assert_eq!(direct.args[..3], ["-Xmx2G".to_owned(), temp.clone(), "-jar".to_owned()]);
let stale = ws.join(TEMP_DIR).join("jdt-apt-1");
std::fs::create_dir_all(&stale).unwrap();
std::fs::write(stale.join("0_processor.jar"), "").unwrap();
std::fs::write(ws.join(TEMP_DIR).join("file.tmp"), "").unwrap();
mark_used(&direct);
assert!(ws.join(TEMP_DIR).is_dir());
assert_eq!(std::fs::read_dir(ws.join(TEMP_DIR)).unwrap().count(), 0);
// The user's own choice, and a workspace that is not ours, are left alone.
let mut own = cfg(&ws);
own.args.push("--jvm-arg=-Djava.io.tmpdir=/elsewhere".into());
use_own_temp(&mut own, tmp.path());
assert_eq!(own.args.iter().filter(|a| a.contains("java.io.tmpdir")).count(), 1);
let mut theirs = cfg(&tmp.path().join("their-workspace"));
use_own_temp(&mut theirs, tmp.path());
assert!(!theirs.args.iter().any(|a| a.contains("java.io.tmpdir")));
std::fs::create_dir_all(ws.join(TEMP_DIR).join("kept")).unwrap();
mark_used(&cfg(&ws));
assert!(ws.join(TEMP_DIR).join("kept").exists());
}
#[cfg(unix)]
#[test]
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
+2 -31
Переглянути файл
@@ -121,14 +121,7 @@ fn read_snapshot_text(path: &Path) -> Option<String> {
if bytes.iter().take(8192).any(|b| *b == 0) {
return None;
}
String::from_utf8(bytes).ok().map(|text| document_text(&text).into_owned())
}
/// `text` as a document holds it: without the UTF-8 BOM and with `\n` line endings. Saves
/// record the document's text, so a file read from disk must match it to dedupe, and
/// Revert writes it back through the document, which adds the file's BOM and line endings.
fn document_text(text: &str) -> std::borrow::Cow<'_, str> {
ide_text::normalize_line_endings(text.strip_prefix('\u{feff}').unwrap_or(text))
String::from_utf8(bytes).ok()
}
impl LocalHistory {
@@ -345,10 +338,7 @@ impl LocalHistory {
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
}
match fs::read(self.blob_path(id)) {
Ok(bytes) => {
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
Ok(document_text(&text).into_owned())
}
Ok(bytes) => Ok(String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Err(IdeError::not_found(format!("history snapshot {id} not found")))
}
@@ -542,25 +532,6 @@ mod tests {
}
}
#[test]
fn a_file_read_from_disk_matches_the_saved_document_text() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
fs::create_dir_all(&root).unwrap();
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
let a = root.join("a.txt");
// A save records the document's text; the file on disk has a BOM and CRLF.
fs::write(&a, b"\xEF\xBB\xBFheader\r\nbody\r\n").unwrap();
h.record(&a, "header\nbody\n", "Saved").unwrap();
assert!(h.record_file(&a, "External change", false).unwrap());
let list = h.list(&a).unwrap();
assert_eq!(list.iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["Saved"], "no second revision");
// A snapshot stored with its BOM before reads back as document text.
h.record(&a, "\u{feff}old\r\n", "External change").unwrap();
let old = &h.list(&a).unwrap()[0];
assert_eq!(h.content(&old.id).unwrap(), "old\n");
}
#[test]
fn events_labels_and_deletions() {
let tmp = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -131,7 +131,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
+1 -1
Переглянути файл
@@ -131,7 +131,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
-1
Переглянути файл
@@ -416,7 +416,6 @@ test("dragging the Changes pane's edge resizes it for the next session too", asy
// The next session starts with the dragged width.
await page.reload();
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
await seedTasks(page, "editor");
await seedChanges(page);
await expect.poll(async () => Math.round((await changes.boundingBox())!.width)).toBe(Math.round(widened));
-34
Переглянути файл
@@ -1024,37 +1024,3 @@ test("aligns Mermaid diagrams in replies to their container align attribute", as
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
test("renders LaTeX math formulas with KaTeX and keeps wide equations scrollable", async ({ page }) => {
const reply = await openReply(
page,
[
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\), prices $5 and $10 stay plain.",
"",
"$$",
"\\int_{-\\infty}^{\\infty} e^{-x^2} \\, dx = \\sqrt{\\pi}",
"$$",
"",
"```math",
"\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2} + a_1 + a_2 + a_3 + a_4 + a_5 + a_6 + a_7 + a_8 + a_9 + a_{10}",
"```",
].join("\n"),
);
await expect(reply.locator(".katex")).toHaveCount(4);
await expect(reply.locator(".katex-display")).toHaveCount(2);
await expect(reply).toContainText("prices $5 and $10 stay plain.");
const layout = await reply.evaluate((el) => {
const firstKatex = el.querySelector<HTMLElement>(".katex")!;
const display = el.querySelectorAll<HTMLElement>(".katex-display");
const font = getComputedStyle(firstKatex).fontFamily;
return {
font,
height: firstKatex.getBoundingClientRect().height,
overflowX: getComputedStyle(display[1]!).overflowX,
};
});
expect(layout.font).toContain("KaTeX_Main");
expect(layout.height).toBeGreaterThan(10);
expect(layout.overflowX).toBe("auto");
});
+1 -1
Переглянути файл
@@ -102,7 +102,7 @@ test("stripe themes inherit base tooltip tokens and keep shortcut text readable"
delete root.dataset.colorTheme;
root.dataset.theme = kind;
root.dataset.pluginTheme = "test/base-tooltip";
const path = "/src/features/plugins/themeRuntime.ts";
const path = "/src/features/plugins/bridge.ts";
const { pluginThemeCss } = await import(/* @vite-ignore */ path);
const style = document.createElement("style");
style.id = "test-plugin-theme";
-1
Переглянути файл
@@ -80,7 +80,6 @@
"dompurify": "^3.4.17",
"emmet": "2.4.11",
"immer": "^11.1.21",
"katex": "^0.19.1",
"marked": "^18.1.1",
"mermaid": "12.1.0",
"react": "^19.1.0",
Створено
-11
Переглянути файл
@@ -119,9 +119,6 @@ importers:
immer:
specifier: ^11.1.21
version: 11.1.21
katex:
specifier: ^0.19.1
version: 0.19.1
marked:
specifier: ^18.1.1
version: 18.1.1
@@ -1802,10 +1799,6 @@ packages:
resolution: {integrity: sha512-/B6p9eY9DX7aHBfpkHdpirDTZ5QH9xTwL9y837PWuzuv41O5jFdqNQwVQEQsimY0/iVNkwBY4+4hMfhQ7d4Dbw==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
@@ -3799,10 +3792,6 @@ snapshots:
dependencies:
commander: 15.1.0
[email protected]:
dependencies:
commander: 15.1.0
[email protected]: {}
[email protected]:
-2
Переглянути файл
@@ -93,12 +93,10 @@ db_connect trusted project_host bin
db_connected trusted project_host bindings sync
db_console_path always project_host bindings sync
db_consoles always project_host bindings sync
db_create_database trusted project_host bindings async
db_database_catalog trusted project_host bindings async
db_databases trusted project_host bindings async
db_ddl trusted project_host bindings async
db_disconnect trusted project_host bindings async
db_drop_database trusted project_host bindings async
db_dump_info trusted desktop bindings async
db_execute trusted project_host bindings async
db_explain trusted project_host bindings async
-29
Переглянути файл
@@ -1,29 +0,0 @@
import type { AuxKind } from "./platform/auxWindow";
import { mountWindowRoot } from "./windowBoot";
import { activateSecondaryWindow } from "./workbench/activateSecondary";
export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string }): Promise<void> {
activateSecondaryWindow();
switch (aux.kind) {
case "settings": {
const { bootSettingsWindow } = await import("./settingsWindowBoot");
mountWindowRoot(bootSettingsWindow(aux.parent));
return;
}
case "comparison": {
const { bootComparisonWindow } = await import("./comparisonWindowBoot");
mountWindowRoot(bootComparisonWindow(aux.parent));
return;
}
case "diff": {
const { bootDiffWindow } = await import("./diffWindowBoot");
mountWindowRoot(bootDiffWindow(aux.parent));
return;
}
case "deployment": {
const { bootDeploymentWindow } = await import("./deploymentWindowBoot");
mountWindowRoot(bootDeploymentWindow(aux.parent));
return;
}
}
}
-2
Переглянути файл
@@ -272,12 +272,10 @@ export const commands = {
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_console_path", { id })),
/** The query consoles of data source `id`; `create` adds the next one first. */
dbConsoles: (id: string, create: boolean) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
dbCreateDatabase: (id: string, template: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_create_database", { id, template, statement })),
dbDatabaseCatalog: (id: string, database: string) => typedError<DbCatalogSchema[], IdeError>(__TAURI_INVOKE("db_database_catalog", { id, database })),
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
dbDdl: (id: string, schema: string, table: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_ddl", { id, schema, table })),
dbDisconnect: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_disconnect", { id })),
dbDropDatabase: (id: string, database: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_drop_database", { id, database, statement })),
/** What made the dump at `path` and whether it creates its own database (from its first bytes). */
dbDumpInfo: (path: string) => typedError<DbDumpInfo, IdeError>(__TAURI_INVOKE("db_dump_info", { path })),
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })),
-27
Переглянути файл
@@ -1,27 +0,0 @@
import type { ComponentType } from "react";
import { activate as editor } from "./editor/core";
import { confirmLeave } from "./features/app/closeGuard";
import { installLocaleSync } from "./features/app/locale";
import { installMenuBridge } from "./features/app/menuBridge";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activate as vcs } from "./features/vcs";
import { activateComparisonWindow, ComparisonWindow } from "./features/vcs/ComparisonWindow";
import { installKeyboardDispatcher } from "./platform/keymap";
import { activateList } from "./windowBoot";
/**
* Comparison window of project window `parent`: changed files between two
* revisions and their diffs, with the editor and Git but no workbench.
*/
export function bootComparisonWindow(parent: string): ComponentType {
activateList("comparison window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["menu", installMenuBridge],
["editor", editor],
["vcs", vcs],
["comparison", () => activateComparisonWindow(parent, (project) => confirmLeave(undefined, project))],
]);
installKeyboardDispatcher();
return ComparisonWindow;
}
-20
Переглянути файл
@@ -1,20 +0,0 @@
import type { ComponentType } from "react";
import { installLocaleSync } from "./features/app/locale";
import { activateDeploymentWindow, DeploymentWindow } from "./features/deployment/window";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activateDiffViewer } from "./features/vcs/diffViewer";
import { activateList } from "./windowBoot";
/**
* Sync with Deployed window of project window `parent`: local files next to
* their copies on a deployment server, with the diff viewer but no workbench.
*/
export function bootDeploymentWindow(parent: string): ComponentType {
activateList("deployment window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["diff", activateDiffViewer],
["deployment", () => activateDeploymentWindow(parent)],
]);
return DeploymentWindow;
}
-24
Переглянути файл
@@ -1,24 +0,0 @@
import type { ComponentType } from "react";
import { installLocaleSync } from "./features/app/locale";
import { installMenuBridge } from "./features/app/menuBridge";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activate as vcs } from "./features/vcs";
import { activateDiffWindow, DiffWindow } from "./features/vcs/DiffWindow";
import { installKeyboardDispatcher } from "./platform/keymap";
import { activateList } from "./windowBoot";
/**
* Diff window of project window `parent`: one file's diff, with Git and its own
* documents but no workbench.
*/
export function bootDiffWindow(parent: string): ComponentType {
activateList("diff window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["menu", installMenuBridge],
["vcs", vcs],
["diff", () => activateDiffWindow(parent)],
]);
installKeyboardDispatcher();
return DiffWindow;
}
+1 -16
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerEditorKind, setFileDecorations, type EditorKindContribution } from "@/workbench/contributions";
import { registerEditorKind, type EditorKindContribution } from "@/workbench/contributions";
import { t } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { confirm } from "@/workbench/messages";
@@ -166,18 +166,3 @@ describe("editor kinds' isBusy on tab-limit eviction", () => {
}
});
});
describe("Close non-modified files first", () => {
it("keeps a tab with a VCS change, as Close Unmodified Tabs does", async () => {
controller = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b", "/p/c.ts": "c" }));
controller.start();
useProject.setState({ settings: { editor: { tabs: { tabLimit: 2, closingPolicy: "unchanged" } } } as never });
setFileDecorations("vcs", new Map([["/p/a.ts", { color: "modified" }]]));
try {
for (const path of ["/p/a.ts", "/p/b.ts", "/p/c.ts"]) await controller.openFile(path);
expect(pane().tabs.map((tab) => tab.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
} finally {
setFileDecorations("vcs", new Map());
}
});
});
+9 -14
Переглянути файл
@@ -272,14 +272,6 @@ export function tabTrailing(input: EditorInput, kinds: EditorKinds): ReactNode {
}
}
/** Unsaved changes or a VCS status: what Close Unmodified Tabs and the tab limit's policy keep. */
function tabModified(tab: Tab): boolean {
return (
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color))
);
}
export class EditorController implements SlotHost {
manager: DocumentManager;
readonly slots = new Map<string, EditorSlot>();
@@ -395,11 +387,10 @@ export class EditorController implements SlotHost {
// Untitled buffers belong to the window, not a project: their tabs
// survive the switch (the backend carries them into the new
// registry) and their slots rebuild against the carried documents.
// Closing to Welcome drops them; the leave guard already asked about them.
const carriedUntitled: Tab[] = [];
let carriedActive: string | null = null;
const cs = useTabs.getState();
for (const pane of root || s.lightEdit ? Object.values(cs.panes) : []) {
for (const pane of Object.values(cs.panes)) {
for (const tab of pane.tabs) {
if (isUntitledUri(tab.input.path ?? "")) {
carriedUntitled.push(tab);
@@ -1449,7 +1440,8 @@ export class EditorController implements SlotHost {
paneId,
prefs.tabLimit,
prefs.closingPolicy,
tabModified,
(tab) =>
inputDirty(tab.input, kinds) ?? !!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
keep ?? current.panes[paneId]?.active ?? undefined,
protect,
)
@@ -1733,10 +1725,13 @@ export class EditorController implements SlotHost {
protect: (tab) => tab.pinned,
});
}
/** Keeps tabs with unsaved changes or a VCS status (tabs shown as modified). */
/** Keeps tabs with unsaved changes or a VCS status (IDEA: tabs shown as modified). */
closeUnmodified(paneId: string): Promise<boolean> {
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, tabModified) : s), {
protect: (tab) => tab.pinned || tabModified(tab),
const modified = (tab: Tab) =>
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color));
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, modified) : s), {
protect: (tab) => tab.pinned || modified(tab),
});
}
closeReadOnly(paneId: string): Promise<boolean> {
-14
Переглянути файл
@@ -15,7 +15,6 @@ const { serializeSession } = await import("./model/session");
const { useDocMeta } = await import("./model/document");
const { save } = await import("@/platform/dialog");
const editorKinds = await import("@/workbench/contributions");
const { useProject } = await import("@/platform/project");
let ctrl: InstanceType<typeof EditorController> | null = null;
let backend: MemoryBackend;
@@ -159,19 +158,6 @@ describe("untitled editor input", () => {
expect([...backend.files.keys()]).toEqual(["/p/main.rs"]);
});
it("follows the window into another project but not to the Welcome screen", async () => {
const project = (root: string) => ({ root, name: root, trusted: true, isGit: false, settings: {} }) as never;
try {
await ctrl!.openUntitled({ focus: false });
useProject.setState({ project: project("/a") });
expect(activeTab().input.kind).toBe("untitled");
useProject.setState({ project: null });
expect(Object.values(useTabs.getState().panes).flatMap((p) => p.tabs)).toEqual([]);
} finally {
useProject.setState({ project: null });
}
});
it("reuses the buffer for a re-opened untitled name and shares it across tabs", async () => {
const info = await backend.openUntitled(null);
const twice = await backend.openUntitled("untitled:Untitled-1");
-8
Переглянути файл
@@ -69,14 +69,6 @@ describe("markdown rendering", () => {
expect(md.markupToHtml({ kind: "markdown", value: "`x`" })).toBe("<p><code>x</code></p>\n");
expect(md.markupToHtml({ kind: "plaintext", value: "<b>" })).toBe('<p class="cm-lsp-plain">&#60;b&#62;</p>');
});
it("renders LaTeX math in LSP / documentation markdown", async () => {
const md = await freshMarkdown();
await md.loadMarkdown();
const root = document.createElement("div");
root.innerHTML = md.markupToHtml({ kind: "markdown", value: "Complexity $O(n \\log n)$" });
expect(root.querySelector(".katex")).not.toBeNull();
});
});
// On Windows, opening `//server/share` signs in to that server with the user's credentials.
-13
Переглянути файл
@@ -1,13 +0,0 @@
.katex {
overflow-wrap: normal;
}
.katex-display {
overflow-x: auto;
overflow-y: hidden;
padding: 2px 0;
}
.katex-error {
color: var(--danger) !important;
}
-85
Переглянути файл
@@ -1,85 +0,0 @@
import { describe, expect, it } from "vitest";
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { mathExtension, renderMath } from "./markdownMath";
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
function parseSafe(md: string): HTMLElement {
const html = marked.parse(md, { async: false }) as string;
const root = DOMPurify.sanitize(html, {
USE_PROFILES: { html: true },
ADD_ATTR: ["data-math"],
FORBID_TAGS: ["style", "form"],
FORBID_ATTR: ["style"],
RETURN_DOM: true,
}) as HTMLElement;
renderMath(root);
return root;
}
describe("markdown LaTeX math", () => {
it("renders inline $...$ and avoids currency false positives", () => {
const root = parseSafe(
"Energy $E = mc^2$ and CJK 设$x=1$时.\n\nPrices: $5 and $10, or $5-$10, or $ 5 $, or \\$x\\$.",
);
expect(root.querySelectorAll(".katex")).toHaveLength(2);
expect(root.querySelectorAll(".katex-display")).toHaveLength(0);
const paras = [...root.querySelectorAll("p")];
expect(paras[1]!.textContent).toBe("Prices: $5 and $10, or $5-$10, or $ 5 $, or $x$.");
});
it("prevents * and _ inside math from triggering emphasis while allowing emphasis around math", () => {
const root = parseSafe("Formula $(a)_1 + (b)_2$ and $a * b$ and $c * d$, plus **$x^2$**.");
expect(root.querySelector("em")).toBeNull();
expect(root.querySelectorAll(".katex")).toHaveLength(4);
expect(root.querySelector("strong .katex")).not.toBeNull();
});
it("renders multi-line, single-line, inline, and adjacent $$...$$ blocks", () => {
const root = parseSafe(
"Para\n$$\n\\begin{aligned}\na &= b \\\\\nc &= d\n\\end{aligned}\n$$\n\n$$E = mc^2$$\n\n$$a$$ and $$b$$",
);
expect(root.querySelectorAll(".katex-display")).toHaveLength(4);
expect(root.querySelector("p")?.textContent).toBe("Para");
const lastP = [...root.querySelectorAll("p")].at(-1)!;
expect(lastP.querySelectorAll(".katex-display")).toHaveLength(2);
expect(lastP.textContent).toContain("and");
});
it("renders \\(...\\) and \\[...\\] without breaking escaped links", () => {
const root = parseSafe("Inline \\(x + y\\).\n\n\\[\nx^2 + y^2 = z^2\n\\]\n\n\\[text\\](https://example.com)");
expect(root.querySelectorAll(".katex")).toHaveLength(2);
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
const lastP = [...root.querySelectorAll("p")].at(-1)!;
expect(lastP.textContent).toBe("[text](https://example.com)");
});
it("renders ```math code blocks while keeping ```latex and inline code literal", () => {
const root = parseSafe("```math\n\\int_0^1 x^2 dx\n```\n\n```latex\n$x$\n```\n\nInline `$y$`.");
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
expect(root.querySelector("pre > code.language-latex")?.textContent).toBe("$x$\n");
expect(root.querySelector("p > code")?.textContent).toBe("$y$");
});
it("renders invalid LaTeX as an error node instead of throwing", () => {
const root = parseSafe("Bad $\\unknowncommand{x}$ and $$\\frac{1$$");
expect(root.querySelectorAll(".katex")).toHaveLength(1);
expect(root.querySelector(".katex-error")).not.toBeNull();
expect(root.textContent).toContain("\\unknowncommand");
});
it("blocks unsafe LaTeX trust commands and raw HTML style/script injection", () => {
const root = parseSafe(
[
"$\\href{javascript:alert(1)}{click}$",
'<div style="position:fixed">x</div>',
'<span data-math="inline"><img src=x onerror=alert(1)>a</span>',
].join("\n\n"),
);
expect(root.querySelector("a")).toBeNull();
expect(root.querySelector("img")).toBeNull();
expect(root.querySelector("div[style]")).toBeNull();
expect(root.querySelectorAll(".katex")).toHaveLength(2);
});
});
-215
Переглянути файл
@@ -1,215 +0,0 @@
/**
* LaTeX math support for Markdown (`marked` + `DOMPurify` + KaTeX).
*
* `mathExtension()` tokenizes `$$...$$`, `$...$`, `\[...\]`, `\(...\)`, and
* ```` ```math ```` blocks into sanitized-safe `<div|span data-math="display|inline">`
* placeholders, which survive `DOMPurify` (with `data-math` allowed) and are
* rendered synchronously into KaTeX DOM by `renderMath()` right after sanitization.
*/
import katex from "katex";
import "katex/dist/katex.min.css";
import "./markdownMath.css";
import type { MarkedExtension, Tokens } from "marked";
interface MathToken extends Tokens.Generic {
type: "blockMath" | "inlineMath";
raw: string;
text: string;
display: boolean;
}
const escapeHtml = (s: string) =>
s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
export function mathPlaceholder(tex: string, display: boolean, block = display): string {
const tag = block ? "div" : "span";
const mode = display ? "display" : "inline";
return `<${tag} data-math="${mode}">${escapeHtml(tex)}</${tag}>`;
}
/** Finds the closing `delim` (`$$`, `\)`, or `\]`) skipping `\` escapes. Returns content end index or -1. */
function findClosingDelimiter(src: string, from: number, delim: string): number {
for (let i = from; i < src.length; i++) {
if (src.startsWith(delim, i)) return i;
if (src[i] === "\\") {
i++;
continue;
}
}
return -1;
}
/**
* Matches inline `$...$` from index 0 using Pandoc-style guards so currency
* like `$5 and $10` or `$5-$10` stays plain text while `$x$`, `设$x=1$`, etc. match.
*/
function matchInlineDollar(src: string): { end: number; text: string } | null {
if (src[0] !== "$" || src[1] === "$" || !src[1] || /\s/.test(src[1])) return null;
for (let i = 1; i < src.length; i++) {
const ch = src[i]!;
if (ch === "\\") {
i++;
continue;
}
if (ch === "\n" && (src[i + 1] === "\n" || (src[i + 1] === "\r" && src[i + 2] === "\n"))) {
return null;
}
if (ch === "$") {
if (i <= 1 || /\s/.test(src[i - 1]!)) continue;
const next = src[i + 1] ?? "";
if (next === "$" || /\d/.test(next)) return null;
const text = src.slice(1, i);
if (!text.trim()) return null;
return { end: i + 1, text };
}
}
return null;
}
/** Matches inline `$$...$$`, `$...$`, `\(...\)`, or `\[...\]` starting at index 0 of `src`. */
function matchInlineMath(src: string): { raw: string; text: string; display: boolean } | null {
if (src.startsWith("$$")) {
const close = findClosingDelimiter(src, 2, "$$");
if (close > 2) {
const text = src.slice(2, close);
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
}
return null;
}
if (src[0] === "$") {
const m = matchInlineDollar(src);
return m ? { raw: src.slice(0, m.end), text: m.text, display: false } : null;
}
if (src.startsWith("\\(")) {
const close = findClosingDelimiter(src, 2, "\\)");
if (close > 2) {
const text = src.slice(2, close);
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: false };
}
return null;
}
if (src.startsWith("\\[")) {
const close = findClosingDelimiter(src, 2, "\\]");
if (close > 2 && src[close + 2] !== "(") {
const text = src.slice(2, close);
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
}
return null;
}
return null;
}
const BLOCK_DOLLAR_MULTI = /^ {0,3}\$\$[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\$\$[ \t]*(?:\r?\n+|$)/;
const BLOCK_DOLLAR_SINGLE = /^ {0,3}\$\$((?:\\[\s\S]|[^$\n]|\$(?!\$))+?)\$\$[ \t]*(?:\r?\n+|$)/;
const BLOCK_BRACKET_MULTI = /^ {0,3}\\\[[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\\\][ \t]*(?:\r?\n+|$)/;
const BLOCK_BRACKET_SINGLE = /^ {0,3}\\\[((?:\\[\s\S]|[^\\\n]|\\(?!\]))+?)\\\][ \t]*(?:\r?\n+|$)/;
function matchBlockMath(src: string): { raw: string; text: string } | null {
for (const re of [BLOCK_DOLLAR_MULTI, BLOCK_DOLLAR_SINGLE, BLOCK_BRACKET_MULTI, BLOCK_BRACKET_SINGLE]) {
const m = re.exec(src);
if (m && m[1]!.trim()) return { raw: m[0], text: m[1]! };
}
return null;
}
/** Masks math spans with `a`s (preserving newlines) so `*` and `_` inside math never trigger emphasis. */
function maskInlineMath(src: string): string {
let out = "";
let i = 0;
while (i < src.length) {
if (src[i] === "\\" && src[i + 1] !== "(" && src[i + 1] !== "[") {
out += src.slice(i, i + 2);
i += 2;
continue;
}
if (src[i] === "$" || (src[i] === "\\" && (src[i + 1] === "(" || src[i + 1] === "["))) {
const m = matchInlineMath(src.slice(i));
if (m) {
out += m.raw.replace(/[^\r\n]/g, "a");
i += m.raw.length;
continue;
}
}
out += src[i]!;
i++;
}
return out;
}
export function mathExtension(): MarkedExtension {
return {
hooks: {
emStrongMask(src) {
return maskInlineMath(src);
},
},
renderer: {
code({ text, lang }) {
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() !== "math") return false;
return `${mathPlaceholder(text, true, true)}\n`;
},
},
extensions: [
{
name: "blockMath",
level: "block",
start(src) {
const m = /\n {0,3}(?:\$\$|\\\[)/.exec(src);
return m ? m.index : undefined;
},
tokenizer(src): MathToken | undefined {
const m = matchBlockMath(src);
if (!m) return undefined;
return { type: "blockMath", raw: m.raw, text: m.text, display: true };
},
renderer(token) {
const t = token as MathToken;
return `${mathPlaceholder(t.text, true, true)}\n`;
},
},
{
name: "inlineMath",
level: "inline",
start(src) {
for (let i = 0; i < src.length; i++) {
const ch = src[i]!;
if (ch === "\\") {
const next = src[i + 1];
if (next === "(" || next === "[") return i;
i++;
continue;
}
if (ch === "$") return i;
}
return undefined;
},
tokenizer(src): MathToken | undefined {
const m = matchInlineMath(src);
if (!m) return undefined;
return { type: "inlineMath", raw: m.raw, text: m.text, display: m.display };
},
renderer(token) {
const t = token as MathToken;
return mathPlaceholder(t.text, t.display, false);
},
},
],
};
}
/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */
export function renderMath(root: ParentNode): void {
root.querySelectorAll<HTMLElement>("[data-math]").forEach((el) => {
const mode = el.getAttribute("data-math");
el.removeAttribute("data-math");
if (mode !== "inline" && mode !== "display") return;
const tex = (el.textContent ?? "").trim();
if (!tex) return;
katex.render(tex, el, {
displayMode: mode === "display",
throwOnError: false,
strict: false,
trust: false,
});
});
}
+3 -8
Переглянути файл
@@ -1,24 +1,19 @@
/** Markdown → sanitized HTML (marked + DOMPurify); loaded on demand by `markdown.ts`. */
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { mathExtension, renderMath } from "./markdownMath";
/** DOMPurify's default link schemes plus `file:` and jdtls' `jdt:` (library classes). */
const ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel|file|jdt):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i;
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
const marked = new Marked({ gfm: true, breaks: false });
export function markdownToSafeHtml(markdown: string): string {
const html = marked.parse(markdown, { async: false }) as string;
// Comments and docs come from anyone; a `<style>` here would restyle the whole IDE.
const root = DOMPurify.sanitize(html, {
return DOMPurify.sanitize(html, {
USE_PROFILES: { html: true },
ALLOWED_URI_REGEXP: ALLOWED_URI,
ADD_ATTR: ["data-math"],
FORBID_TAGS: ["style", "form"],
FORBID_ATTR: ["style"],
RETURN_DOM: true,
}) as HTMLElement;
renderMath(root);
return root.innerHTML;
});
}
-14
Переглянути файл
@@ -36,20 +36,6 @@ describe("Go to Test / Test Subject", () => {
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/FooTest.java");
});
it("uses the top-level class at the caret when a file declares several", async () => {
const files = [
"/p/src/main/java/a/Widget.java",
"/p/src/test/java/a/WidgetTest.java",
"/p/src/test/java/a/HelperTest.java",
];
const d = { ...deps(files), classAtCaret: async () => "Helper" };
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", d);
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/HelperTest.java");
const other = { ...deps(files), classAtCaret: async () => null };
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", other);
expect(other.open).toHaveBeenCalledWith("/p/src/test/java/a/WidgetTest.java");
});
it("goes back from a test to its subject", async () => {
const d = deps(["/p/src/main/java/a/Foo.java", "/p/src/test/java/a/FooTest.java"]);
await gotoTestOrSubject("/p/src/test/java/a/FooTest.java", "", d);
+1 -14
Переглянути файл
@@ -36,19 +36,6 @@ export interface TestNavDeps {
/** Create New Test… in `directory` (file templates), or a Rust test module in the file itself. */
createTest: (req: { directory: string; name: string; extension: string; subject: string }) => void;
createRustTestModule: () => void;
/** Name of the top-level class, interface, enum or object around the caret, if any. */
classAtCaret?: () => Promise<string | null>;
}
/** Languages whose files are named after a class but may declare several top-level ones. */
const CLASS_FILE = /\.(java|kt|scala|groovy|cs)$/;
/** The file name as the class at the caret would have it (`Helper.java` inside `Widget.java`), else the file's own. */
async function subjectFileName(path: string, deps: TestNavDeps): Promise<string> {
const name = basename(path);
if (!CLASS_FILE.test(name) || !deps.classAtCaret) return name;
const cls = await deps.classAtCaret().catch(() => null);
return cls ? cls + splitName(name).ext : name;
}
const isRustIntegrationTest = (path: string) => path.endsWith(".rs") && /\/tests\/[^/]+\.rs$/.test(path);
@@ -101,7 +88,7 @@ function relLabel(root: string | null, path: string) {
export async function gotoTestOrSubject(path: string, text: string, deps: TestNavDeps): Promise<void> {
const roots = deps.roots();
const root = deps.projectRoot();
const name = await subjectFileName(path, deps);
const name = basename(path);
const rank = (paths: string[]) => rankCandidates(path, paths, belowRoot(root, roots));
if (isTestSide(path, roots)) {
+1 -5
Переглянути файл
@@ -22,7 +22,7 @@ import { registerRelatedProvider, relatedItems } from "@/editor/relatedProviders
import { gotoTestOrSubject, type TestNavDeps } from "./gotoTest";
import { headerSourceItems } from "./headerSource";
import { projectPythonHierarchy, pythonSuperDeps } from "./pythonHierarchy";
import { baseName, memberAt, methodStop, superMethods, topLevelTypeAt, type SuperDeps } from "./structureNav";
import { baseName, memberAt, methodStop, superMethods, type SuperDeps } from "./structureNav";
import { tx } from "@/platform/i18n";
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
@@ -150,10 +150,6 @@ function testDeps(view: EditorView, ctx: EditorDocContext): TestNavDeps {
})),
}),
hint: (text) => showHint(view, text),
classAtCaret: async () => {
const outline = await call(commands.docOutline(ctx.doc));
return topLevelTypeAt(outline, offsetToPos(view.state.doc, view.state.selection.main.head))?.name ?? null;
},
createTest: ({ directory, name, extension }) =>
void executeAction("templates.newFromTemplate", { directory, name, extension, kindId: "test" }),
createRustTestModule: () => {
+1 -10
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { HierarchyItem, OutlineItem, SymbolKind } from "@/platform/ipc";
import { memberAt, methodStop, methodStops, superMethods, topLevelTypeAt } from "./structureNav";
import { memberAt, methodStop, methodStops, superMethods } from "./structureNav";
const r = (l1: number, l2: number) => ({ start: { line: l1, col: 0 }, end: { line: l2, col: 1 } });
function item(name: string, kind: SymbolKind, from: number, to: number, children: OutlineItem[] = []): OutlineItem {
@@ -100,12 +100,3 @@ describe("Super Method", () => {
expect(await lines("eat")).toEqual([2, 4]);
});
});
describe("topLevelTypeAt", () => {
it("answers the outermost type, through namespaces, and nothing outside a type", () => {
expect(topLevelTypeAt(OUTLINE, { line: 13, col: 2 })?.name).toBe("Foo");
expect(topLevelTypeAt(OUTLINE, { line: 23, col: 0 })).toBeNull();
const ns = [item("App", "namespace", 0, 30, [item("Widget", "class", 1, 10), item("Helper", "class", 12, 20)])];
expect(topLevelTypeAt(ns, { line: 15, col: 0 })?.name).toBe("Helper");
});
});
-11
Переглянути файл
@@ -36,17 +36,6 @@ export function methodStop(outline: readonly OutlineItem[], caret: Pos, dir: 1 |
return null;
}
/** The outermost type around `caret`, looking through namespaces and packages (C#, Kotlin scripts). */
export function topLevelTypeAt(outline: readonly OutlineItem[], caret: Pos): OutlineItem | null {
let level: readonly OutlineItem[] = outline;
for (;;) {
const hit = level.find((i) => inside(i, caret));
if (!hit) return null;
if (hit.kind !== "namespace" && hit.kind !== "package") return TYPES.has(hit.kind) ? hit : null;
level = hit.children;
}
}
export interface CaretMember {
/** Innermost method at the caret. */
method: OutlineItem | null;
-11
Переглянути файл
@@ -369,17 +369,6 @@ describe("streamed replies", () => {
expect(container.querySelector("details p")?.textContent).toBe("text");
});
it("renders LaTeX math across streamed blocks", () => {
const text = "Inline $a + b$.\n\n$$\n\\frac{1}{2}\n$$\n\nTail";
const blocks = markdownBlocks(text);
expect(blocks).toHaveLength(3);
expect(blocks.join("")).toBe(text);
const { container } = render(<Markdown text={text} cwd="/repo" />);
expect(container.querySelectorAll(".katex")).toHaveLength(2);
expect(container.querySelector(".katex-display")).not.toBeNull();
expect(screen.queryByRole("button", { name: "Copy Code" })).toBeNull();
});
it("cuts only what streamed on after the blocks that ended", () => {
const before = markdownBlocks("One.\n\nTwo.\n\nThr");
const after = markdownBlocks("One.\n\nTwo.\n\nThree.\n\n- a", before);
+3 -5
Переглянути файл
@@ -11,7 +11,6 @@ import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react"
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { highlightInto } from "@/editor/lsp/markdown";
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
import { iconNode } from "@/ui/iconNode";
import { tx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
@@ -38,7 +37,7 @@ const marked = new Marked({
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
},
},
}).use(mathExtension());
});
/** Rendered messages by text, least recently used first: reopening a conversation renders it again. */
const rendered = new Map<string, string>();
@@ -134,11 +133,10 @@ function renderHtml(text: string): string {
FORBID_TAGS: ["style", "form", "source"],
FORBID_ATTR: ["style", "srcset"],
ALLOW_DATA_ATTR: false,
// Only the mermaid and math placeholders written by the renderer above; data attributes
// Only the mermaid placeholder written by the renderer above; data attributes
// quoted in a reply stay out.
ADD_ATTR: ["data-mermaid", "data-math"],
ADD_ATTR: ["data-mermaid"],
}) as HTMLElement;
renderMath(root);
root.querySelectorAll("li").forEach(wrapLooseText);
// WebKit cuts controls inside <pre> out of a text selection, even when transparent.
root.querySelectorAll("pre").forEach((pre) => {
+52 -3
Переглянути файл
@@ -17,13 +17,24 @@ import {
registerMenuGroup,
registerMenuSlotItem,
registerOverlay,
registerSettingsPages,
registerStatusItem,
registerToolWindow,
toolWindowService,
} from "@/workbench/contributions";
import { AgentsStatus } from "./AgentsStatus";
import { activateSettingsPages } from "./settingsPages";
import { HOME_KIND, MCP_PAGE, REGISTRY_PAGE, SESSION_KIND, TASK_DRAG, TOOL_WINDOW, providerIcon } from "./model";
import {
AGENTS_GROUP,
HOME_KIND,
MCP_PAGE,
POLICY_PAGE,
REGISTRY_PAGE,
SESSION_KIND,
TASK_DRAG,
TOOL_WINDOW,
WORKING_STATUS_PAGE,
providerIcon,
} from "./model";
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
import { focusedSession, inputSession } from "./sessionFocus";
import { cycleFocusedEffort } from "./effortFocus";
@@ -43,7 +54,45 @@ import { TaskStatusMark } from "./TaskStatusMark";
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
import { replyActions } from "./replyActions";
export { activateSettingsPages } from "./settingsPages";
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Coding Agents",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: WORKING_STATUS_PAGE,
title: "Working Status",
group: AGENTS_GROUP,
// After Chat.
order: 465,
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
},
{
id: MCP_PAGE,
title: "External MCP Servers",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
id: POLICY_PAGE,
title: "Command Permissions",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
}
export function activate(): () => void {
const sync = (root: string | null | undefined) => {
-43
Переглянути файл
@@ -1,43 +0,0 @@
import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, WORKING_STATUS_PAGE } from "./model";
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Coding Agents",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: WORKING_STATUS_PAGE,
title: "Working Status",
group: AGENTS_GROUP,
// After Chat.
order: 465,
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
},
{
id: MCP_PAGE,
title: "External MCP Servers",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
id: POLICY_PAGE,
title: "Command Permissions",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
}
+2 -19
Переглянути файл
@@ -192,20 +192,6 @@ describe("replacing a project in this window", () => {
expect(useProject.getState().project?.root).toBe("/local");
});
it("asks about trust before leaving, so Don't Open keeps the current project running", async () => {
useProject.setState({
...projectState("/a"),
settings: { general: { openProjectIn: "same" } },
} as never);
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
vi.mocked(confirmProjectTrust).mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Cancelled" }));
await openProjectWithPolicy("/b");
expect(confirmProjectTrust).toHaveBeenCalledWith("/b", "local");
expect(confirmLeaveProject).not.toHaveBeenCalled();
expect(openProject).not.toHaveBeenCalled();
expect(notify).not.toHaveBeenCalled();
});
it("opens the local project when its path matches the remote root", async () => {
useProject.setState({
...projectState("/same"),
@@ -806,14 +792,11 @@ describe("trust is asked before a new project window opens", () => {
expect(windowOpenProject).toHaveBeenCalled();
});
it("asks once this window takes the project, before leaving its current one", async () => {
it("asks only once, from openProject, when the project opens in this window", async () => {
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
await openProjectInWindow("/p/b", false);
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", false, []);
expect(confirmProjectTrust).toHaveBeenCalledOnce();
expect(vi.mocked(confirmProjectTrust).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(confirmLeaveProject).mock.invocationCallOrder[0]!,
);
expect(confirmProjectTrust).not.toHaveBeenCalled();
expect(openProject).toHaveBeenCalledWith("/p/b");
});
});
+6
Переглянути файл
@@ -22,6 +22,12 @@ import { installLaunchHandling, installLightEditAutoClose, windowActions } from
import { WorkspaceDialogHost } from "./WorkspaceDialog";
import { installWindowGroups } from "@/platform/windowGroups";
/** The UI locale of a secondary (Settings, comparison) window. */
export const activateLocale = installLocaleSync;
/** Native menu items of a secondary window that runs actions itself (comparison). */
export const activateMenuBridge = installMenuBridge;
export { confirmLeave } from "./closeGuard";
export function activate(): () => void {
const disposers = [
installLocaleSync(),
-7
Переглянути файл
@@ -57,13 +57,6 @@ async function openHere(path: string): Promise<boolean> {
if (!isRemoteWindow() && useProject.getState().project?.root === path) return true;
// A folder of a WSL distro runs there, not as a network folder; the window then drops untitled buffers.
const wsl = await commands.wslResolve(path).catch(() => null);
try {
// Asked before leaving, so Don't Open keeps the current project and its processes running.
if (!wsl) await confirmProjectTrust(path, "local");
} catch (e) {
openFailed(path, e);
return false;
}
if (!(await confirmLeaveProject(!wsl))) return false;
try {
if (wsl) await connectRemote(wsl.target, wsl.path);
-3
Переглянути файл
@@ -370,9 +370,6 @@
font-size: var(--fs-small);
color: var(--fg-muted);
}
.formFull {
grid-column: 1 / -1;
}
.paramInput {
font-family: var(--openidea-editor-font, var(--font-mono));
font-weight: var(--fw-code);
+1 -1
Переглянути файл
@@ -454,7 +454,7 @@ export function DatabaseView() {
case "source":
return sourceIcon(n.source);
case "database":
return "db-database";
return "database";
case "schema":
return "db-schema";
case "folder":
+6 -184
Переглянути файл
@@ -1,42 +1,34 @@
/**
* Dialogs of the Database tree's object actions, after IDEA's: Rename, Confirm
* Drop, Truncate, Modify Table / New Table, New Database / New Schema (with a
* Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
* Drop, Truncate, Modify Table / New Table (with a Preview of the SQL they
* run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { call, commands, type DbColumnInfo, type DbDriver } from "@/platform/ipc";
import { highlightInto } from "@/editor/lsp/markdown";
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, Select, T, type SelectOption } from "@/ui";
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, T } from "@/ui";
import { parseSourceUrl, sourceLabel, splitTarget } from "./model";
import { nodeTarget, schemaObjectOf, tableOf, type DbNode } from "./nodes";
import {
alterTableSql,
canAlterColumn,
createDatabaseSql,
createSchemaSql,
createTableSql,
draftOf,
dropDatabaseSql,
dropSql,
ident,
reference,
renameSql,
truncateSql,
type ColumnDraft,
templateOf,
type CreateOptions,
type DbObjectRef,
} from "./objects";
import {
closeDialog,
detailsKey,
connectedTargets,
createDatabase,
dropDatabase,
loadDetails,
openSourceDialog,
readableDdl,
refresh,
renameSource,
runSql,
sourceById,
@@ -88,15 +80,14 @@ function objectName(o: DbObjectRef): string {
function useRunner() {
const [busy, setBusy] = useState(false);
const running = useRef(false);
const runAndClose = async (id: string, statements: string[]): Promise<boolean> => {
if (running.current) return false;
const runAndClose = async (id: string, statements: string[]) => {
if (running.current) return;
running.current = true;
setBusy(true);
const ok = await runSql(id, statements);
running.current = false;
setBusy(false);
if (ok) closeDialog();
return ok;
};
return { busy, runAndClose };
}
@@ -125,7 +116,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
width={480}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: () => void submit() },
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: submit },
]}
>
<div className={styles.dialogBody}>
@@ -222,169 +213,6 @@ function TruncateDialog({ id, schema, table }: { id: string; schema: string; tab
);
}
// ---- New Database / New Schema / Drop database ---------------------------------
const TEMPLATES: SelectOption[] = [
{ value: "", label: "Server default" },
...["template0", "template1"].map((name) => ({ value: name, label: name, verbatim: true })),
];
/** An optional text field of the create dialogs: empty leaves it to the server. */
function OptionField({
id,
label,
value,
onChange,
}: {
id: string;
label: string;
value: string;
onChange: (value: string) => void;
}) {
return (
<>
<label className={styles.formLabel} htmlFor={id}>
{tx(label)}
</label>
<Input id={id} placeholder="Server default" value={value} onChange={(e) => onChange(e.target.value)} />
</>
);
}
/** New › Database (`database`) or New › Schema (`schema`) in target `id`. */
function CreateDialog({ id, what }: { id: string; what: "database" | "schema" }) {
const driver = driverOf(id);
const [name, setName] = useState("");
const [opts, setOpts] = useState<CreateOptions>({});
const { busy: running, runAndClose } = useRunner();
const [creating, setCreating] = useState(false);
const busy = running || creating;
const sql = (what === "database" ? createDatabaseSql : createSchemaSql)(driver, name.trim() || "<name>", opts);
const submit = async () => {
if (what === "schema") {
if (await runAndClose(id, [sql])) void refresh(id);
return;
}
setCreating(true);
if (await createDatabase(id, templateOf(driver, opts), sql)) closeDialog();
else setCreating(false);
};
const field = (key: keyof CreateOptions, label: string) => (
<OptionField
id={`db-new-${key}`}
label={label}
value={opts[key] ?? ""}
onChange={(value) => setOpts((o) => ({ ...o, [key]: value }))}
/>
);
return (
<Dialog
open
onClose={closeDialog}
title={what === "database" ? "New Database" : "New Schema"}
width={560}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "OK", role: "default", disabled: busy || !name.trim(), onClick: submit },
]}
>
<div className={styles.form}>
<label className={styles.formLabel} htmlFor="db-new-name">
<T>Name:</T>
</label>
<Input id="db-new-name" autoFocus value={name} onChange={(e) => setName(e.target.value)} />
{what === "database" && driver === "postgres" && (
<>
{field("owner", "Owner:")}
<label className={styles.formLabel} htmlFor="db-new-template">
<T>Template:</T>
</label>
<Select
id="db-new-template"
value={opts.template ?? ""}
options={TEMPLATES}
onChange={(template) => setOpts((o) => ({ ...o, template }))}
/>
<span />
<span className={styles.formHint}>
<T>Restoring a dump needs template0: template1 can already hold extensions and schemas.</T>
</span>
{field("encoding", "Encoding:")}
{field("tablespace", "Tablespace:")}
</>
)}
{what === "database" && driver === "sqlServer" && field("collation", "Collation:")}
{what === "schema" && driver === "mysql" && (
<>
{field("charset", "Character set:")}
{field("collation", "Collation:")}
</>
)}
{what === "schema" && driver !== "mysql" && field("owner", "Owner:")}
<div className={styles.formFull}>
<SqlPreview sql={sql} />
</div>
</div>
</Dialog>
);
}
/** PostgreSQL 13 added `drop database … with (force)`. */
const PG_FORCE_DROP = 130000;
function DropDatabaseDialog({ id, database }: { id: string; database: string }) {
const driver = driverOf(id);
const [force, setForce] = useState(false);
const [version, setVersion] = useState<number | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
if (driver !== "postgres") return;
let live = true;
void withConnection(id, () => call(commands.dbServerVersion(id)))
.then((v) => live && setVersion(v))
.catch(() => {});
return () => {
live = false;
};
}, [id, driver]);
const canForce = driver === "sqlServer" || (version ?? 0) >= PG_FORCE_DROP;
const sql = dropDatabaseSql(driver, database, force && canForce);
const submit = async () => {
setBusy(true);
if (await dropDatabase(id, database, sql)) closeDialog();
else setBusy(false);
};
return (
<Dialog
open
onClose={closeDialog}
title="Confirm Drop"
width={520}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "OK", role: "default", disabled: busy, onClick: () => void submit() },
]}
>
<div className={styles.dialogBody}>
<div className={styles.dialogLead}>
{tx`Drop database`} <strong>{database}</strong>
{tx`? This cannot be undone.`}
</div>
<span className={styles.formHint}>
<T>The IDE closes its own connections to the database first.</T>
</span>
<Checkbox
checked={force && canForce}
onChange={setForce}
disabled={!canForce}
label="Close the sessions of other clients"
/>
<SqlPreview sql={sql} />
</div>
</Dialog>
);
}
// ---- Modify Table / New Table -----------------------------------------------
const TYPES: Record<DbDriver, string[]> = {
@@ -898,12 +726,6 @@ export function ObjectDialogs() {
return <DropDialog id={dialog.id} object={dialog.object} />;
case "truncate":
return <TruncateDialog id={dialog.id} schema={dialog.schema} table={dialog.table} />;
case "createDatabase":
return <CreateDialog id={dialog.id} what="database" />;
case "createSchema":
return <CreateDialog id={dialog.id} what="schema" />;
case "dropDatabase":
return <DropDatabaseDialog id={dialog.id} database={dialog.database} />;
case "modifyTable":
return (
<ModifyTableDialog
+2
Переглянути файл
@@ -81,6 +81,8 @@ function tableTarget(arg: unknown): TableCommandTarget {
return { rows: activeCellGrid()?.selectedRows() ?? [], editor: null };
}
export { activateSettingsPages } from "./settingsPages";
export function activate(): () => void {
const disposers = [
onIdeEvent("dbSourcesChanged", () => {
-50
Переглянути файл
@@ -4,12 +4,8 @@ import {
alterTableSql,
canDrop,
canModifyTable,
createDatabaseSql,
createSchemaSql,
createTableSql,
draftOf,
dropDatabaseSql,
templateOf,
dropSql,
ident,
reference,
@@ -345,49 +341,3 @@ describe("snowflake object SQL", () => {
expect(alterTableSql("snowflake", "HR", "EMP", "EMP", dropped)).toEqual(["alter table HR.EMP drop column NAME;"]);
});
});
describe("database and schema SQL", () => {
it("creates a PostgreSQL database with only the options given", () => {
expect(createDatabaseSql("postgres", "shop", {})).toBe("create database shop;");
expect(
createDatabaseSql("postgres", "Shop Copy", {
owner: "app",
template: "template0",
encoding: "UTF8",
tablespace: " ",
}),
).toBe(`create database "Shop Copy" owner app template template0 encoding 'UTF8';`);
expect(createDatabaseSql("postgres", "shop", { encoding: "it's" })).toBe("create database shop encoding 'it''s';");
});
it("names the database the server copies for a new one", () => {
expect(templateOf("postgres", {})).toBe("template1");
expect(templateOf("postgres", { template: "template0" })).toBe("template0");
expect(templateOf("sqlServer", { template: "ignored" })).toBe("model");
});
it("creates a SQL Server database with a collation", () => {
expect(createDatabaseSql("sqlServer", "shop", { collation: "Latin1_General_CI_AS", owner: "ignored" })).toBe(
"create database shop collate Latin1_General_CI_AS;",
);
});
it("creates a schema with an owner, and a MySQL schema as a database", () => {
expect(createSchemaSql("postgres", "sales", {})).toBe("create schema sales;");
expect(createSchemaSql("postgres", "sales", { owner: "app" })).toBe("create schema sales authorization app;");
expect(createSchemaSql("sqlServer", "sales", { owner: "dbo" })).toBe("create schema sales authorization dbo;");
expect(createSchemaSql("mysql", "shop", { charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci" })).toBe(
"create database shop character set utf8mb4 collate utf8mb4_0900_ai_ci;",
);
expect(createSchemaSql("mysql", "shop", {})).toBe("create database shop;");
});
it("drops a database, forcing out other sessions when asked", () => {
expect(dropDatabaseSql("postgres", "shop", false)).toBe("drop database shop;");
expect(dropDatabaseSql("postgres", "shop", true)).toBe("drop database shop with (force);");
expect(dropDatabaseSql("sqlServer", "shop", false)).toBe("drop database shop;");
expect(dropDatabaseSql("sqlServer", "shop", true)).toBe(
"alter database shop set single_user with rollback immediate;\ndrop database shop;",
);
});
});
-57
Переглянути файл
@@ -180,63 +180,6 @@ export function truncateSql(
return `truncate table ${q}${opts.restartIdentity ? " restart identity" : ""}${opts.cascade ? " cascade" : ""};`;
}
const literal = (value: string) => `'${value.replace(/'/g, "''")}'`;
/** Options of New › Database / New › Schema; an empty or absent one is left to the server. */
export interface CreateOptions {
owner?: string;
template?: string;
encoding?: string;
tablespace?: string;
charset?: string;
collation?: string;
}
/** New › Database (PostgreSQL, SQL Server). */
export function createDatabaseSql(driver: DbDriver, name: string, opts: CreateOptions): string {
const clauses: string[] = [];
const add = (keyword: string, value: string | undefined, quote = (v: string) => ident(driver, v)) => {
if (value?.trim()) clauses.push(`${keyword} ${quote(value.trim())}`);
};
if (driver === "postgres") {
add("owner", opts.owner);
add("template", opts.template);
add("encoding", opts.encoding, literal);
add("tablespace", opts.tablespace);
} else if (driver === "sqlServer") {
add("collate", opts.collation, (v) => v);
}
return `create database ${ident(driver, name)}${clauses.map((c) => ` ${c}`).join("")};`;
}
/** The database the server copies for New › Database: the chosen template on PostgreSQL, `model` on SQL Server. */
export function templateOf(driver: DbDriver, opts: CreateOptions): string {
return driver === "sqlServer" ? "model" : opts.template?.trim() || "template1";
}
/** New › Schema; on MySQL a schema is a database, with a character set and collation instead of an owner. */
export function createSchemaSql(driver: DbDriver, name: string, opts: CreateOptions): string {
if (driver === "mysql") {
const charset = opts.charset?.trim() ? ` character set ${opts.charset.trim()}` : "";
const collation = opts.collation?.trim() ? ` collate ${opts.collation.trim()}` : "";
return `create database ${ident(driver, name)}${charset}${collation};`;
}
const owner = opts.owner?.trim() ? ` authorization ${ident(driver, opts.owner.trim())}` : "";
return `create schema ${ident(driver, name)}${owner};`;
}
/**
* Drop on a database node. `force` ends the sessions of other clients first:
* `with (force)` on PostgreSQL 13+, single-user mode on SQL Server.
*/
export function dropDatabaseSql(driver: DbDriver, name: string, force: boolean): string {
const db = ident(driver, name);
// One batch: the session that sets single-user mode is the single user, so it must drop too.
if (driver === "sqlServer" && force)
return `alter database ${db} set single_user with rollback immediate;\ndrop database ${db};`;
return `drop database ${db}${force && driver === "postgres" ? " with (force)" : ""};`;
}
export type ScriptKind = "selectAll" | "selectFirst" | "insert" | "update" | "delete";
export const SCRIPT_LABELS: Record<ScriptKind, string> = {
-10
Переглянути файл
@@ -417,16 +417,6 @@ describe("connection and metadata continuations", () => {
});
}
it("does not list sources after the project is closed", async () => {
// Closing the project resets `loaded`; a still-mounted SQL console then asks for sources again.
useProject.setState({ project: null });
backend.sources.mockRejectedValue(new Error("no project is open in this window"));
backend.connected.mockRejectedValue(new Error("no project is open in this window"));
await loadSources();
expect(ui.notify).not.toHaveBeenCalled();
expect(backend.sources).not.toHaveBeenCalled();
});
it("can load metadata again after a disconnect fails", async () => {
backend.disconnect.mockRejectedValueOnce(new Error("disconnect failed"));
await expect(disconnect("pg")).rejects.toThrow("disconnect failed");
-53
Переглянути файл
@@ -130,11 +130,6 @@ export type DialogState =
/** Confirm Drop / Truncate, with a preview of the statement. */
| { kind: "drop"; id: string; object: DbObjectRef }
| { kind: "truncate"; id: string; schema: string; table: string }
/** New › Database of data source `id`; New › Schema in target `id`. */
| { kind: "createDatabase"; id: string }
| { kind: "createSchema"; id: string }
/** Drop on database `database` of data source `id`. */
| { kind: "dropDatabase"; id: string; database: string }
/** Modify Table (`table` null: New › Table); `focusColumn` selects a column, `addColumn` starts a new one. */
| { kind: "modifyTable"; id: string; schema: string; table: string | null; focusColumn?: string; addColumn?: boolean }
/** Quick Documentation of a tree node, shown at `anchor` (client coordinates). */
@@ -330,8 +325,6 @@ function sourceMutation(id: string): () => boolean {
}
export async function loadSources(): Promise<void> {
// Closing the project resets `loaded` while its SQL consoles are still mounted.
if (!useProject.getState().project) return;
const request = ++sourcesRequest;
const current = projectRequest();
const intents = new Map(connectionIntents);
@@ -621,20 +614,6 @@ export function listsDatabases(source: DataSource | undefined): boolean {
);
}
/** New › Database and Drop on database nodes: PostgreSQL and SQL Server data sources that show their databases. */
export function createsDatabases(source: DataSource | undefined): boolean {
return listsDatabases(source) && source?.driver !== "snowflake";
}
/** The target New › Schema creates a schema in: a database node, or a data source that shows schemas directly. */
export function newSchemaTarget(n: DbNode): string | null {
if (n.kind === "database") return createsDatabases(sourceById(n.id)) ? n.id : null;
if (n.kind !== "source" || !n.source.id) return null;
const driver = n.source.driver;
if (driver !== "postgres" && driver !== "sqlServer" && driver !== "mysql") return null;
return listsDatabases(n.source) ? null : n.source.id;
}
interface LoadedLevels {
schemas: string[];
tables: [string, string][];
@@ -1112,38 +1091,6 @@ export async function runSql(id: string, texts: string[]): Promise<boolean> {
}
}
/**
* Creates a database on data source `id` with `sql` after disconnecting `template`, then refreshes
* the data source, reloading what the tree had shown of `template` too.
*/
export async function createDatabase(id: string, template: string, sql: string): Promise<boolean> {
const levels = loadedLevels(id);
await disconnect(`${id}:${template}`);
try {
// Asks for a password the data source does not save, like any statement it runs.
await withConnection(id, () => call(commands.dbCreateDatabase(id, template, sql)));
} catch (e) {
notifications().notify({ level: "error", title: tx`Cannot create database`, body: message(e) });
void refresh(id, levels);
return false;
}
void refresh(id, levels);
return true;
}
/** Drops `database` of data source `id` with `sql` after disconnecting it, then refreshes the data source. */
export async function dropDatabase(id: string, database: string, sql: string): Promise<boolean> {
await disconnect(`${id}:${database}`);
try {
await withConnection(id, () => call(commands.dbDropDatabase(id, database, sql)));
} catch (e) {
notifications().notify({ level: "error", title: tx`Cannot drop database ${database}`, body: message(e) });
return false;
}
void refresh(id);
return true;
}
/** Opens the query console of `id` with `text` appended and selected (SQL Scripts › …). */
export async function openConsoleWith(id: string, text: string): Promise<void> {
let path: string;
-27
Переглянути файл
@@ -15,7 +15,6 @@ import {
DB_TOOL_WINDOW,
OUTPUT_TAB,
connect,
createsDatabases,
RESULTS_VIEW,
detailsKey,
disconnect,
@@ -25,7 +24,6 @@ import {
loadSources,
loadTables,
consoleFiles,
newSchemaTarget,
newConsole,
openConsole,
openConsoleFile,
@@ -360,9 +358,6 @@ export function registerDatabaseTreeActions(): () => void {
if (!n) return;
const id = nodeTarget(n);
if (n.kind === "source") return void removeSource(n.source);
const source = sourceById(id);
if (n.kind === "database" && !n.current && !source?.readOnly && createsDatabases(source))
return openDialog({ kind: "dropDatabase", id: splitTarget(n.id).id, database: n.name });
const o = objectOf(n);
if (id && o && canDrop(driverOf(id), o)) openDialog({ kind: "drop", id, object: o });
},
@@ -395,28 +390,6 @@ export function registerDatabaseTreeActions(): () => void {
});
},
}),
tree({
id: "db.newDatabase",
title: "Database…",
icon: "db-database",
keywords: ["create database", "new database"],
run: ({ arg }) => {
const source = sourceOf(nodeFrom(arg));
if (source?.id && !source.readOnly && createsDatabases(source))
openDialog({ kind: "createDatabase", id: source.id });
},
}),
tree({
id: "db.newSchema",
title: "Schema…",
icon: "db-schema",
keywords: ["create schema", "new schema"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const id = n && newSchemaTarget(n);
if (id && !sourceById(id)?.readOnly) openDialog({ kind: "createSchema", id });
},
}),
tree({
id: "db.newTable",
title: "Table",
+3 -25
Переглянути файл
@@ -5,15 +5,7 @@ import { fileSourceName, parseSourceUrl } from "./model";
import { VENDORS, vendorPreset } from "./vendors";
import { nodeTarget, objectOf, tableOf, type DbNode } from "./nodes";
import { SCRIPT_LABELS, canDrop, canModifyTable, canRename, type ScriptKind } from "./objects";
import {
connectedTargets,
createsDatabases,
newSchemaTarget,
openDialog,
openSourceDialog,
sourceById,
useDatabase,
} from "./store";
import { connectedTargets, openDialog, openSourceDialog, sourceById, useDatabase } from "./store";
import { readClipboardPlainText } from "@/platform/clipboard";
import { useRemote } from "@/platform/remote";
import { dumpScope, mysqlDumpScope } from "./dumpTools";
@@ -121,8 +113,6 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
const rename = act("db.rename", n, { disabled: !(n.kind === "source" || (o && canRename(driver, o))) });
const drop = act("db.drop", n, { disabled: !o || !canDrop(driver, o) });
const copyRef = act("db.copyReference", n);
const readOnly = !!sourceById(id)?.readOnly;
const newSchema = newSchemaTarget(n) ? [act("db.newSchema", n, { disabled: readOnly })] : [];
const navigation = (extra: MenuItem[] = []): MenuItem => ({
label: "Navigation",
submenu: [...extra, act("db.jumpToConsole", n)],
@@ -134,18 +124,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
return [
act("db.properties", n, { label: "Properties" }),
sep,
{
label: "New",
icon: "plus",
submenu: [
newConsole,
sep,
...(createsDatabases(n.source) ? [act("db.newDatabase", n, { disabled: readOnly })] : []),
...newSchema,
...(createsDatabases(n.source) || newSchema.length ? [sep] : []),
...dataSourceItems(),
],
},
{ label: "New", icon: "plus", submenu: [newConsole, sep, ...dataSourceItems()] },
{ label: "Copy/Paste", submenu: [copyRef, act("db.duplicateSource", n)] },
refresh,
...(n.source.driver === "snowflake" ? [act("db.introspect", n)] : []),
@@ -165,7 +144,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
}
case "database":
return [
{ label: "New", icon: "plus", submenu: [newConsole, ...(newSchema.length ? [sep, ...newSchema] : [])] },
{ label: "New", icon: "plus", submenu: [newConsole] },
{ label: "Copy/Paste", submenu: [copyRef] },
refresh,
act("db.disconnect", n, { disabled: !useDatabase.getState().connected.has(id) || n.current }),
@@ -173,7 +152,6 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
navigation(),
sqlScripts(n, false),
...importExport(dumpItems(n, true)),
...(createsDatabases(sourceById(id)) ? [sep, act("db.drop", n, { disabled: n.current || readOnly })] : []),
];
case "schema":
case "folder":
-57
Переглянути файл
@@ -1,57 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { provideEditorService } from "@/workbench/contributions";
import { addBreakpoint, useBreakpoints } from "../breakpoints/store";
import { DebuggerOverlays } from "../ui/Overlays";
import { useOverlays } from "../ui/popoverStore";
const openFile = vi.fn(async () => undefined);
provideEditorService({ openFile } as never);
const path = "/p/main.py";
describe("the Breakpoints dialog", () => {
beforeEach(() => {
openFile.mockClear();
useBreakpoints.setState({ byFile: {}, status: {}, muted: false });
const first = addBreakpoint(path, 2, { condition: "value == 2" });
addBreakpoint(path, 6);
useOverlays.setState({ breakpoints: { id: first.id } } as never);
});
afterEach(() => {
cleanup();
act(() => useOverlays.setState({ breakpoints: null } as never));
});
const dialog = () => screen.getByRole("dialog", { name: "Breakpoints" });
const row = (name: string) => within(within(dialog()).getByLabelText("All breakpoints")).getByText(name);
const condition = () => within(dialog()).getByLabelText("Condition") as HTMLInputElement;
/** A row's mouse click as the list sees it: mousedown selects, click (with its count) activates. */
const clickRow = (name: string, detail: number) => {
fireEvent.mouseDown(row(name), { button: 0 });
fireEvent.click(row(name), { detail });
};
const breakpointAt = (line: number) => useBreakpoints.getState().byFile[path]!.find((b) => b.line === line)!;
it("selects a breakpoint on click and goes to its source on double-click", () => {
render(<DebuggerOverlays />);
clickRow("main.py:7", 1);
expect(openFile).not.toHaveBeenCalled();
// Its details show beside the list.
expect(within(dialog()).getAllByText("main.py:7")).toHaveLength(2);
clickRow("main.py:3", 2);
expect(openFile).toHaveBeenCalledWith(path, { selection: { line: 2, col: 0 } });
});
it("saves the condition being typed when the dialog closes or another breakpoint is shown", () => {
render(<DebuggerOverlays />);
fireEvent.change(condition(), { target: { value: "value == 1" } });
fireEvent.click(within(dialog()).getByRole("button", { name: "Done" }));
expect(breakpointAt(2).condition).toBe("value == 1");
act(() => useOverlays.setState({ breakpoints: { id: breakpointAt(2).id } } as never));
fireEvent.change(condition(), { target: { value: "value == 3" } });
clickRow("main.py:7", 1);
expect(breakpointAt(2).condition).toBe("value == 3");
});
});
+10 -58
Переглянути файл
@@ -179,19 +179,12 @@ function BreakpointFields({
const commitText = () => {
const d = draft.current;
const cond = d.condition.trim() || null;
const changes = {
if (cond) pushHistory("condition", cond);
updateBreakpoint(path, bp.id, {
condition: cond,
hitCondition: d.hitCondition.trim() || null,
logMessage: d.logEval ? d.logMessage.trim() || null : null,
};
if (
changes.condition === (bp.condition ?? null) &&
changes.hitCondition === (bp.hitCondition ?? null) &&
changes.logMessage === (bp.logMessage ?? null)
)
return;
if (cond) pushHistory("condition", cond);
updateBreakpoint(path, bp.id, changes);
});
};
useEffect(() => {
if (!commitRef) return;
@@ -403,13 +396,9 @@ function BreakpointsDialog() {
}, [byFile, methods, fields]);
const items = rows.filter((r) => r.type !== "section");
const [selected, setSelected] = useState<string | null>(null);
// The shown breakpoint's typed fields, saved before it is closed or another one is shown:
// Enter on Done and a click on a row don't blur them.
const commitRef = useRef<(() => void) | null>(null);
const open = !!state;
const current = items.find((r) => r.key === (selected ?? state?.id)) ?? items[0];
const close = () => {
commitRef.current?.();
setSelected(null);
useOverlays.setState({ breakpoints: null });
};
@@ -459,14 +448,8 @@ function BreakpointsDialog() {
isSection={(r) => r.type === "section"}
renderSection={(r) => <div className={styles.exceptionAdapter}>{r.type === "section" ? r.label : ""}</div>}
activeIndex={current ? rows.indexOf(current) : -1}
onActiveChange={(i) => {
commitRef.current?.();
setSelected(rows[i]?.key ?? null);
}}
// A click selects; double-click or Enter goes to the source.
onActivate={(r, _i, e) => {
if (e.type === "keydown" || e.detail > 1) goTo(r);
}}
onActiveChange={(i) => setSelected(rows[i]?.key ?? null)}
onActivate={(r) => goTo(r)}
aria-label="All breakpoints"
className={styles.bpList}
empty={
@@ -539,9 +522,9 @@ function BreakpointsDialog() {
</div>
<div className={styles.bpDetail}>
{current?.type === "line" ? (
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} commitRef={commitRef} />
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} />
) : current?.type === "special" ? (
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} commitRef={commitRef} />
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} />
) : null}
</div>
</div>
@@ -596,15 +579,7 @@ function ExceptionBreakpoints({ open }: { open: boolean }) {
);
}
function BreakpointDetail({
row,
onGo,
commitRef,
}: {
row: BpRow;
onGo: () => void;
commitRef: MutableRefObject<(() => void) | null>;
}) {
function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
const { path, bp } = row;
const st = useBreakpoints((s) => s.status[bp.id]);
return (
@@ -622,7 +597,7 @@ function BreakpointDetail({
</Button>
</div>
{st && <div className={styles.statusLine}>{st.verified ? tx("Verified") : (st.message ?? "Not verified")}</div>}
<BreakpointFields path={path} bp={bp} commitRef={commitRef} />
<BreakpointFields path={path} bp={bp} />
<Checkbox
checked={!!bp.temporary}
onChange={(temporary) => updateBreakpoint(path, bp.id, { temporary })}
@@ -632,34 +607,11 @@ function BreakpointDetail({
);
}
function SpecialDetail({
bp,
onGo,
commitRef,
}: {
bp: SpecialBreakpoint;
onGo: () => void;
commitRef: MutableRefObject<(() => void) | null>;
}) {
function SpecialDetail({ bp, onGo }: { bp: SpecialBreakpoint; onGo: () => void }) {
const st = useSpecialBreakpoints((s) => s.status[bp.id]);
const [name, setName] = useState(bp.kind === "method" ? bp.name : bp.label);
const [condition, setCondition] = useState(bp.condition ?? "");
const [hitCondition, setHitCondition] = useState(bp.hitCondition ?? "");
const draft = useRef({ name, condition, hitCondition });
useEffect(() => {
draft.current = { name, condition, hitCondition };
commitRef.current = () => {
const d = draft.current;
updateSpecial(bp.id, {
name: d.name.trim(),
condition: d.condition.trim() || null,
hitCondition: d.hitCondition.trim() || null,
});
};
return () => {
commitRef.current = null;
};
});
return (
<div className={styles.detail}>
<div className={styles.bpTitle}>
+2
Переглянути файл
@@ -17,6 +17,8 @@ import { transferMenuEntries } from "./model";
import { REMOTE_HOST_WINDOW, useDeployment } from "./store";
import { installDeploymentEditorHost } from "./windowBridge";
export { activateDeploymentWindow, DeploymentWindow } from "./window";
/** Deployed URL of the path the last menu was prepared for. */
let webUrlFor: { path: string; url: string | null } | null = null;
+2
Переглянути файл
@@ -24,6 +24,8 @@ import { githubHandler, handlerContextKey } from "./toolwindow/handlers";
import { GithubDialogHost } from "./ui/dialogs";
import { activateSettingsPages } from "./settingsPages";
export { activateSettingsPages } from "./settingsPages";
const WINDOW = "pullRequests";
const TIMELINE_KIND = "github.timeline";
const WHEN = "projectOpen";
+86 -12
Переглянути файл
@@ -13,7 +13,13 @@ import { activate as projectTree } from "./project-tree";
import { activate as search } from "./search";
import { activate as dependencies } from "./dependencies";
import { activate as codeInsight } from "./code-insight";
import { activate as vcs } from "./vcs";
import {
activate as vcs,
activateComparisonWindow,
activateDiffViewer,
activateDiffWindow,
activateSettingsPages as vcsPages,
} from "./vcs";
import { activate as terminal } from "./terminal";
import { activate as run } from "./run";
import { activate as dotnet } from "./dotnet";
@@ -26,13 +32,13 @@ import { activate as profiler } from "./profiler";
import { activate as logcat } from "./logcat";
import { activate as buildTools } from "./build-tools";
import { activate as build } from "./build";
import { activate as templates } from "./templates";
import { activate as todo } from "./todo";
import { activate as settings } from "./settings";
import { activate as app } from "./app";
import { activate as templates, activateSettingsPages as templatesPages } from "./templates";
import { activate as todo, activateSettingsPages as todoPages } from "./todo";
import { activate as settings, activateRuntimeSettings, activateSettingsWindow } from "./settings";
import { activate as app, activateLocale as appLocale, activateMenuBridge, confirmLeave } from "./app";
import { activate as perf } from "./perf";
import { activate as plugins } from "./plugins";
import { activate as tools } from "./tools";
import { activate as plugins, activateSettingsPages as pluginsPages } from "./plugins";
import { activate as tools, activateSettingsPages as toolsPages } from "./tools";
import { activate as scratch } from "./scratch";
import { activate as libraries } from "./libraries";
import { activate as viewers } from "./viewers";
@@ -40,16 +46,16 @@ import { activate as notebook } from "./notebook";
import { activate as web } from "./web";
import { activate as analysis } from "./analysis";
import { activate as services } from "./services";
import { activate as github } from "./github";
import { activate as github, activateSettingsPages as githubPages } from "./github";
import { activate as httpClient } from "./http-client";
import { activate as cucumber } from "./cucumber";
import { activate as rails } from "./rails";
import { activate as thymeleaf } from "./thymeleaf";
import { activate as database } from "./database";
import { activate as database, activateSettingsPages as databasePages } from "./database";
import { activate as graphql } from "./graphql";
import { activate as deployment } from "./deployment";
import { activate as agents } from "./agents";
import { activate as vim } from "./vim";
import { activate as deployment, activateDeploymentWindow } from "./deployment";
import { activate as agents, activateSettingsPages as agentsPages } from "./agents";
import { activate as vim, activateSettingsPages as vimPages } from "./vim";
import { activate as ssh } from "./ssh";
import { activate as lspMessages } from "./lsp-messages";
import { activate as remoteDev } from "./remote-dev";
@@ -126,3 +132,71 @@ function activateAll(what: string, list: Array<[string, Activate]>): () => void
export function activateFeatures(): () => void {
return activateAll("feature", features);
}
export { SettingsWindow } from "./settings";
export { ComparisonWindow, DiffWindow } from "./vcs";
export { DeploymentWindow } from "./deployment";
/**
* A comparison window of project window `parent`: the changed files between two revisions and
* their diffs, with the editor and Git but no workbench.
*/
export function activateComparisonWindowFeatures(parent: string): () => void {
return activateAll("comparison window", [
["locale", appLocale],
["settings", activateRuntimeSettings],
["menu", activateMenuBridge],
["editor", editor],
["vcs", vcs],
["comparison", () => activateComparisonWindow(parent, (project) => confirmLeave(undefined, project))],
]);
}
/**
* The diff window of project window `parent`: one file's diff, with Git and its own documents but
* no workbench.
*/
export function activateDiffWindowFeatures(parent: string): () => void {
return activateAll("diff window", [
["locale", appLocale],
["settings", activateRuntimeSettings],
["menu", activateMenuBridge],
["vcs", vcs],
["diff", () => activateDiffWindow(parent)],
]);
}
/**
* The Sync with Deployed window of project window `parent`: local files next to their copies on a
* deployment server, with the diff viewer but no workbench.
*/
export function activateDeploymentWindowFeatures(parent: string): () => void {
return activateAll("deployment window", [
["locale", appLocale],
["settings", activateRuntimeSettings],
["diff", activateDiffViewer],
["deployment", () => activateDeploymentWindow(parent)],
]);
}
/**
* The native Settings window of project window `parent`: only the settings
* pages (no workbench, project, editors or background services).
*/
export function activateSettingsWindowFeatures(parent: string): () => void {
const pages: Array<[string, Activate]> = [
["project-trust", projectTrust],
["locale", appLocale],
["settings", () => activateSettingsWindow(parent)],
["templates", templatesPages],
["todo", todoPages],
["plugins", pluginsPages],
["tools", toolsPages],
["agents", agentsPages],
["vim", vimPages],
["vcs", vcsPages],
["github", githubPages],
["database", databasePages],
];
return activateAll("settings pages", pages);
}
-13
Переглянути файл
@@ -104,19 +104,6 @@ describe("notebook Markdown preview", () => {
rerender(<MarkdownCell source="plain" attachments={{}} path="/p/a.ipynb" />);
expect(container.querySelector("p")).toBe(paragraph);
});
it("renders LaTeX math in Markdown cells while blocking unsafe styles", () => {
const { container } = render(
<MarkdownCell
source={'Inline $x^2$ and <div style="position:fixed">hi</div>\n\n$$\n\\sum_{i=1}^n i\n$$'}
attachments={{}}
path="/p/a.ipynb"
/>,
);
expect(container.querySelectorAll(".katex")).toHaveLength(2);
expect(container.querySelector(".katex-display")).not.toBeNull();
expect(container.querySelector("div[style]")).toBeNull();
});
});
describe("notebook image outputs", () => {
+2 -4
Переглянути файл
@@ -1,6 +1,5 @@
import DOMPurify from "dompurify";
import { Marked } from "marked";
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
import { mimeText, object, own } from "./outputs";
export const OUTPUT_CSP =
@@ -195,7 +194,7 @@ function htmlRoot(html: string, markdown = false): HTMLElement {
"rowspan",
"scope",
"align",
...(markdown ? ["href", "data-math"] : ["style"]),
...(markdown ? ["href"] : ["style"]),
],
// Attachment references are resolved by us after sanitization. No arbitrary
// URI survives the explicit src allowlist below.
@@ -222,14 +221,13 @@ export function staticOutputDocument(html: string): string {
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OUTPUT_CSP}"><style>body{margin:8px;font:13px system-ui,sans-serif;color:#222;background:white;overflow-wrap:anywhere}table{border-collapse:collapse;max-width:100%}th,td{padding:4px 8px;border:1px solid #ddd;text-align:left}pre{white-space:pre-wrap}img{max-width:100%;height:auto}</style></head><body>${root.innerHTML}</body></html>`;
}
const markdown = new Marked({ gfm: true }).use(mathExtension());
const markdown = new Marked({ gfm: true });
/**
* Sanitized Markdown with inert links; link clicks are handled by the editor and
* `attachment:` images are left for `resolveMarkdownAttachments`.
*/
export function markdownRoot(source: string): HTMLElement {
const root = htmlRoot(markdown.parse(source, { async: false }) as string, true);
renderMath(root);
for (const link of root.querySelectorAll("a[href]")) {
const href = link.getAttribute("href")!;
link.removeAttribute("href");
+253 -13
Переглянути файл
@@ -6,35 +6,262 @@
* variables, notifications become balloons, consent requests open the
* permission dialog, and opened files fire `on-language` / `on-file`.
*/
import type { PluginEvent, PluginUpdate } from "@/bindings";
import type { ActiveTheme, PluginEvent, PluginUpdate } from "@/bindings";
import { useEditorRegistry } from "@/editor/api";
import { refreshLanguageInfos } from "@/editor/core/cm/languages";
import { clearBackoffs } from "@/editor/lsp/availability";
import { endpointsChanged, notifications } from "@/workbench/contributions";
import { useI18n } from "@/platform/i18n";
import { useProducerNames } from "@/platform/inspections";
import { languageListChanged } from "@/platform/languageList";
import {
isThemeAvailable,
parsePluginThemeRef,
providePluginThemePreview,
useContributedThemes,
} from "@/platform/themes";
import {
applyThemeAttributes,
currentThemeChoice,
currentThemeId,
subscribeScheme,
syncWindowBackground,
useThemeOverride,
windowBackgroundHex,
} from "@/workbench/theme";
import { executeAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { pluginsBackend } from "./backend";
import { trackIconTheme } from "./iconThemes";
import { defineBuiltinUiPoints } from "./points";
import { localizeContributions, loadPluginCatalogs, usePluginCatalogs } from "./pluginText";
import { clearUiContributions, syncUiContributions } from "./projection";
import { handleRuntimeEvent, refreshEventKinds, startRuntimeUi } from "./runtimeUi";
import { grantPlugin, runPluginCommand, refreshPlugins, updateAllPlugins, usePlugins } from "./store";
import { followThemeSetting, syncPluginProjection, trackPluginTheme } from "./themeRuntime";
import { refreshRunTargets } from "./runTargets";
import {
grantPlugin,
runPluginCommand,
refreshPlugins,
selectPluginTheme,
updateAllPlugins,
usePlugins,
} from "./store";
export { pluginActionId } from "./points";
export {
applyPluginTheme,
followThemeSetting,
PLUGIN_THEME_CACHE_KEY,
PLUGIN_THEME_STYLE_ID,
providePluginThemePreviews,
trackPluginTheme,
type CachedPluginTheme,
} from "./themeRuntime";
/** Keeps the projected UI contributions in line with the plugin list. */
export function syncProjection(): () => void {
return syncPluginProjection(clearBackoffs);
const apply = () => {
const s = usePlugins.getState();
syncUiContributions(localizeContributions(s.ui, usePluginCatalogs.getState().catalogs), s.plugins);
// Their problems are listed by name in Settings › Inspections.
useProducerNames.setState({
names: new Map(
s.plugins.flatMap((p): [string, string][] => [
[`plugin:${p.id}`, p.name],
[`plugin-provider:${p.id}`, p.name],
]),
),
});
};
const loadCatalogs = () => void loadPluginCatalogs(usePlugins.getState().ui, useI18n.getState().locale);
apply();
loadCatalogs();
const unsubscribe = [
usePlugins.subscribe((s, prev) => {
if (s.ui !== prev.ui) loadCatalogs();
if (s.ui !== prev.ui || s.plugins !== prev.plugins) {
clearBackoffs();
apply();
}
}),
usePluginCatalogs.subscribe((s, prev) => s.catalogs !== prev.catalogs && apply()),
useI18n.subscribe((s, prev) => s.locale !== prev.locale && loadCatalogs()),
];
return () => {
unsubscribe.forEach((u) => u());
clearUiContributions();
};
}
// --- theme ------------------------------------------------------------------
export const PLUGIN_THEME_STYLE_ID = "openidea-plugin-theme";
/** Stylesheet for a plugin theme. Its selector outranks every built-in theme block. */
export function pluginThemeCss(theme: ActiveTheme["theme"]): string {
const kind = theme.kind === "light" ? "light" : "dark";
const decls = [` color-scheme: ${kind};`];
for (const [name, value] of Object.entries(theme.tokens)) {
// Backend validates; keep the guard so a malformed payload can't inject declarations.
if (!/^--[a-z0-9-]+$/.test(name) || value == null || /[;{}<>\\]/.test(value)) continue;
decls.push(` ${name}: ${value};`);
}
return `:root[data-plugin-theme]:not([data-plugin-theme=""]) {\n${decls.join("\n")}\n}\n`;
}
/**
* Applies a plugin theme (null restores the built-in one): its tokens as a
* stylesheet over the built-in light or dark base named by its `kind`. A
* stylesheet rather than inline styles, so the accent picked in Settings ›
* Appearance and the editor colour scheme still layer on top.
*/
export function applyPluginTheme(theme: ActiveTheme | null, root: HTMLElement = document.documentElement) {
const doc = root.ownerDocument;
const current = doc.getElementById(PLUGIN_THEME_STYLE_ID);
const id = theme && `${theme.pluginId}/${theme.theme.id}`;
const css = theme && pluginThemeCss(theme.theme);
// The same theme again (each window hears every selection): replacing its stylesheet restyles the page.
if (theme && current?.textContent === css && root.dataset.pluginTheme === id) return;
current?.remove();
const had = root.dataset.pluginTheme !== undefined;
if (!theme) {
delete root.dataset.pluginTheme;
delete root.dataset.pluginThemeKind;
if (had) applyThemeAttributes(currentThemeId(), root);
} else {
const style = doc.createElement("style");
style.id = PLUGIN_THEME_STYLE_ID;
style.textContent = css;
doc.head.appendChild(style);
root.dataset.pluginTheme = id!;
root.dataset.pluginThemeKind = theme.theme.kind === "light" ? "light" : "dark";
applyThemeAttributes(currentThemeId(), root);
}
if (had || theme) syncWindowBackground();
}
/**
* Quick Switch's theme preview of plugin themes: a live plugin's theme as it
* contributes it, shown in this window only; nothing is selected or saved.
*/
export function providePluginThemePreviews(): () => void {
return providePluginThemePreview((ref) => {
const state = usePlugins.getState();
if (ref === "selected") return applyPluginTheme(state.activeTheme);
const want = ref ? parsePluginThemeRef(ref) : null;
const item = want
? state.ui.find((c) => c.point === "themes" && c.pluginId === want.pluginId && c.key === want.themeId)
: undefined;
applyPluginTheme(item ? { pluginId: item.pluginId, theme: item.decl as ActiveTheme["theme"] } : null);
});
}
/** localStorage key read by public/boot.js: the selected theme's stylesheet, applied before the app loads. */
export const PLUGIN_THEME_CACHE_KEY = "openidea.pluginTheme";
export interface CachedPluginTheme {
/** `data-plugin-theme`: `<pluginId>/<themeId>`. */
id: string;
kind: "light" | "dark";
css: string;
}
function cachePluginTheme(theme: ActiveTheme | null) {
try {
if (!theme) {
localStorage.removeItem(PLUGIN_THEME_CACHE_KEY);
return;
}
const cached: CachedPluginTheme = {
id: `${theme.pluginId}/${theme.theme.id}`,
kind: theme.theme.kind === "light" ? "light" : "dark",
css: pluginThemeCss(theme.theme),
};
localStorage.setItem(PLUGIN_THEME_CACHE_KEY, JSON.stringify(cached));
} catch {
/* storage unavailable */
}
}
let reportedFrame: string | undefined;
/**
* Tells the backend the theme's resolved frame colour, which new windows open
* in. Selecting a theme clears it there, so it is sent once per selection.
*/
function reportThemeFrame(theme: ActiveTheme | null) {
const frame = theme ? windowBackgroundHex() : null;
if (!theme || !frame) {
reportedFrame = undefined;
return;
}
const key = `${theme.pluginId}/${theme.theme.id}|${frame}`;
if (key === reportedFrame) return;
reportedFrame = key;
void pluginsBackend()
.setThemeFrame(frame)
.catch(() => (reportedFrame = undefined));
}
/**
* Applies the selected plugin theme and keeps it for the next start-up. Until
* the first plugin list arrives, the theme public/boot.js restored stays.
*/
export function trackPluginTheme(): () => void {
const sync = (s: ReturnType<typeof usePlugins.getState>) => {
if (!s.activeTheme && (!s.loaded || s.error)) return;
applyPluginTheme(s.activeTheme);
cachePluginTheme(s.activeTheme);
reportThemeFrame(s.activeTheme);
};
sync(usePlugins.getState());
const unsubscribe = usePlugins.subscribe((s, prev) => {
if (s.activeTheme !== prev.activeTheme || s.loaded !== prev.loaded) sync(s);
});
return () => {
unsubscribe();
applyPluginTheme(null);
};
}
/**
* Makes the plugin host's theme the one the Appearance settings select: a
* plugin theme (`plugin:<id>/<theme>`, from any theme picker, the OS mode with
* "Sync with OS", or the plugin's details page) is selected there once its
* plugin is live; a built-in one clears it. While the selected plugin is off,
* its built-in base shows and the selection is kept for when it is back.
*/
export function followThemeSetting(): () => void {
let requested: string | undefined;
const reconcile = () => {
const plugins = usePlugins.getState();
if (!plugins.loaded || plugins.error || !useProject.getState().settings?.appearance) return;
const choice = currentThemeChoice();
const want = parsePluginThemeRef(choice);
const target = want && isThemeAvailable(choice) ? choice : null;
const active = plugins.activeTheme;
const current = active ? `plugin:${active.pluginId}/${active.theme.id}` : null;
if (target === current || (want && !target && !current)) {
requested = undefined;
return;
}
// A selected plugin that is off: leave the host's selection for when it is back.
if (want && !target) {
if (requested === "") return;
requested = "";
void selectPluginTheme(null, null);
return;
}
if (requested === (target ?? "")) return;
requested = target ?? "";
void selectPluginTheme(want && target ? want.pluginId : null, want && target ? want.themeId : null);
};
reconcile();
const disposers = [
// Not on the host's theme changing: another window selects it before this one's settings
// say so, and selecting this window's choice back would flip it until they agree.
usePlugins.subscribe((s, prev) => {
if (s.loaded !== prev.loaded) reconcile();
}),
useProject.subscribe((s, prev) => {
if (s.settings?.appearance !== prev.settings?.appearance) reconcile();
}),
useThemeOverride.subscribe(reconcile),
useContributedThemes.subscribe(reconcile),
subscribeScheme(reconcile),
];
return () => disposers.forEach((d) => d());
}
/** Reports the focused editor's file to the backend (`editor-focused` events). */
@@ -108,6 +335,19 @@ export function handlePluginEvent(e: PluginEvent) {
}
}
/**
* For windows that only show plugins (Settings): stays in line with what
* changes elsewhere — installs, enable / disable, the theme, languages —
* while notifications and permission prompts stay with the project windows.
*/
export function followPluginChanges(): () => void {
return pluginsBackend().onEvent((e) => {
if (e.type === "runTargetsChanged") void refreshRunTargets(false).catch(() => {});
if (e.type === "commandsChanged" || e.type === "themeChanged" || e.type === "languagesChanged")
handlePluginEvent(e);
});
}
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
function scheduleRefresh() {
-267
Переглянути файл
@@ -1,267 +0,0 @@
/**
* Editor-free first-party plugin UI points (commands, themes, icon themes,
* secrets, endpoints), shared by the workbench and the Settings window without
* pulling in CodeMirror-backed plugin editors.
*/
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
import type { PluginInfo, ThemeDef } from "@/bindings";
import { pluginIconName } from "./pluginIcon";
import { registerAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { addContributedTheme, pluginThemeRef } from "@/platform/themes";
import { currentThemeChoice, setTheme, useThemeOverride } from "@/workbench/theme";
import { useProject } from "@/platform/project";
import { Button, Kbd, T } from "@/ui";
import { addIconTheme, iconThemeKey, selectIconTheme, useSelectedIconTheme } from "./iconThemes";
import { defineUiPoint, type UiItem } from "./projection";
import { SecretsDetails, type SecretDecl } from "./secrets";
import { pluginSettingsPageId } from "./settings";
import { pluginsBackend } from "./backend";
import { isLive, runPluginCommand } from "./store";
import styles from "./PluginsPage.module.css";
/** Unpacks an action argument: a bare path, or a menu's `{ path, paths }`. */
export function commandArgs(arg: unknown): [string | null, string[]] {
if (typeof arg === "string") return [arg, []];
const { path, paths, line, column } = (arg ?? {}) as {
path?: unknown;
paths?: unknown;
line?: unknown;
column?: unknown;
};
if (typeof path !== "string" || !Array.isArray(paths)) return [null, []];
if (typeof line === "number" && typeof column === "number")
return [JSON.stringify({ path, line, column }), paths.filter((p): p is string => typeof p === "string")];
return [path, paths.filter((p): p is string => typeof p === "string")];
}
export const pluginActionId = (pluginId: string, commandId: string) => `plugin.${pluginId}.${commandId}`;
interface CommandDecl {
id: string;
title: string;
icon?: string | null;
category?: string | null;
when?: string | null;
}
function CommandsDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<CommandDecl>[] }) {
const runnable = plugin.status === "active" || plugin.status === "inactive";
return (
<ul className={styles.items}>
{items.map(({ decl: c }) => {
const actionId = pluginActionId(plugin.id, c.id);
return (
<li key={c.id} className={styles.item}>
<span className={styles.itemMain}>{c.title}</span>
<Kbd action={actionId} />
<span className={styles.mono} title={tx("Action id (bind it in Keymap)")}>
{actionId}
</span>
<Button
size="small"
variant="ghost"
icon="run"
disabled={!runnable}
onClick={() => void runPluginCommand(plugin.id, c.id)}
aria-label={tx`Run ${c.title}`}
>
<T>Run</T>
</Button>
</li>
);
})}
</ul>
);
}
function ThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<ThemeDef>[] }) {
// The selection is the Appearance setting; these buttons write it as the theme pickers do.
useProject((s) => s.settings?.appearance);
useThemeOverride((s) => s.theme);
const selected = currentThemeChoice();
const live = isLive(plugin.status);
return (
<ul className={styles.items}>
{items.map(({ decl: t }) => {
const isActive = selected === pluginThemeRef(plugin.id, t.id);
return (
<li key={t.id} className={styles.item}>
<span className={styles.itemMain}>{t.name}</span>
<span className={styles.muted}>{t.kind === "dark" ? tx("Dark") : tx("Light")}</span>
{isActive ? (
<Button
size="small"
variant="secondary"
onClick={() => void setTheme(t.kind === "light" ? "light" : "dark")}
>
<T>Use Default Theme</T>
</Button>
) : (
<Button
size="small"
variant="ghost"
disabled={!live}
onClick={() => void setTheme(pluginThemeRef(plugin.id, t.id))}
aria-label={tx`Apply theme ${t.name}`}
>
<T>Apply</T>
</Button>
)}
</li>
);
})}
</ul>
);
}
interface IconThemeDecl {
id: string;
label: string;
icons: number;
}
function IconThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<IconThemeDecl>[] }) {
const selected = useSelectedIconTheme();
return (
<ul className={styles.items}>
{items.map(({ decl: t }) => {
const key = iconThemeKey(plugin.id, t.id);
return (
<li key={t.id} className={styles.item}>
<span className={styles.itemMain}>{t.label}</span>
<span className={styles.muted}>{tx`${t.icons} icons`}</span>
{selected === key ? (
<Button size="small" variant="secondary" onClick={() => void selectIconTheme(null)}>
<T>Use Default Icons</T>
</Button>
) : (
<Button
size="small"
variant="ghost"
onClick={() => void selectIconTheme(key)}
aria-label={tx`Apply icon theme ${t.label}`}
>
<T>Apply</T>
</Button>
)}
</li>
);
})}
</ul>
);
}
const endpointPlugins = new Map<string, { declarations: number; dispose: () => void }>();
/** One endpoint provider per plugin, however many `[[contributes.endpoints]]` it declares. */
function providePluginEndpoints(pluginId: string): () => void {
let entry = endpointPlugins.get(pluginId);
if (!entry) {
const dispose = registerEndpointProvider({
id: `plugin:${pluginId}`,
endpoints: async (root): Promise<EndpointEntry[]> =>
(await pluginsBackend().endpoints(pluginId)).map((e) => ({
method: e.method ?? "*",
url: e.path,
framework: e.framework,
handler: e.handler ?? undefined,
controller: e.framework,
methodName: e.handler ?? "",
pluginId,
path: e.location.path,
rel: e.location.path.startsWith(`${root}/`) ? e.location.path.slice(root.length + 1) : e.location.path,
line: e.location.range.start.line,
col: e.location.range.start.col,
})),
});
entry = { declarations: 0, dispose };
endpointPlugins.set(pluginId, entry);
}
const held = entry;
held.declarations++;
return () => {
if (--held.declarations > 0) return;
held.dispose();
endpointPlugins.delete(pluginId);
};
}
/** Registers the editor-free UI points (commands, themes, icon themes, secrets, endpoints). */
export function defineCoreUiPoints(): () => void {
const disposers = [
defineUiPoint("mcpTools", {}),
defineUiPoint("serverCommands", {}),
defineUiPoint("endpoints", { project: ({ pluginId }) => providePluginEndpoints(pluginId) }),
defineUiPoint<CommandDecl>("commands", {
title: "Commands",
project: ({ pluginId, decl }, { plugin }) => {
let disposed = false;
const action = {
id: pluginActionId(pluginId, decl.id),
title: decl.title,
category: decl.category ?? plugin.name,
icon:
decl.icon && !decl.icon.endsWith(".svg")
? decl.icon
: plugin.icon
? pluginIconName(pluginId, plugin.icon)
: "package",
when: decl.when ?? undefined,
verbatim: true,
// A command can call a model or a server; its toolbar button must show the click was taken.
indicatesRunning: true,
keywords: ["plugin", plugin.name, pluginId],
description: tx`From plugin ${plugin.name}`,
run: async ({ arg }: { arg?: unknown }) => {
const [path, paths] = commandArgs(arg);
await runPluginCommand(pluginId, decl.id, path, paths);
},
};
let off = registerAction(action);
if (decl.icon?.endsWith(".svg"))
void pluginsBackend()
.assets(pluginId, `commandIcon/${decl.id}`)
.then((assets) => {
const svg = assets.find(([id]) => id === `commandIcon/${decl.id}`)?.[1];
if (!svg || disposed) return;
off();
off = registerAction({ ...action, icon: pluginIconName(pluginId, { light: svg, dark: null }) });
})
.catch(console.warn);
return () => {
disposed = true;
off();
};
},
Details: CommandsDetails,
}),
// Offered by every theme picker while the plugin is live; `followThemeSetting` applies the selected one.
defineUiPoint<ThemeDef>("themes", {
title: "Themes",
project: ({ pluginId, decl }, { plugin }) =>
addContributedTheme({
id: pluginThemeRef(pluginId, decl.id),
label: decl.name,
kind: decl.kind === "light" ? "light" : "dark",
origin: plugin.name,
}),
Details: ThemesDetails,
}),
defineUiPoint<IconThemeDecl>("iconThemes", {
title: "File Icon Themes",
project: ({ pluginId, decl }, { plugin }) =>
addIconTheme({
pluginId,
id: decl.id,
label: decl.label,
origin: plugin.name,
settingsPage: `${pluginSettingsPageId(pluginId)}.${decl.id.replace(/\./g, "-")}`,
}),
Details: IconThemesDetails,
}),
// Stored by the backend; listed here with a field per secret.
defineUiPoint<SecretDecl>("secrets", { title: "Secrets", Details: SecretsDetails }),
];
return () => disposers.reverse().forEach((d) => d());
}
+13 -13
Переглянути файл
@@ -3,21 +3,21 @@
* commands get it (path, language, selections in line / UTF-16 column). Tool
* windows' renders and events carry it too, so their buttons act on what the
* user is editing; a custom editor's calls carry its own document instead.
*
* Provided by the workbench (`points.tsx`) so editor-free windows (Settings)
* do not pull in `@/editor/api` and CodeMirror.
*/
import type { PluginEditor } from "@/bindings";
let provider: (() => PluginEditor | null) | null = null;
export function providePluginEditorContext(fn: () => PluginEditor | null): () => void {
provider = fn;
return () => {
if (provider === fn) provider = null;
};
}
import { activeEditor } from "@/editor/api";
export function editorContext(): PluginEditor | null {
return provider?.() ?? null;
const editor = activeEditor();
if (!editor?.ctx.path) return null;
const { doc, selection } = editor.view.state;
const pos = (offset: number) => {
const line = doc.lineAt(offset);
return { line: line.number - 1, col: offset - line.from };
};
return {
path: editor.ctx.path,
language: editor.ctx.language,
selections: selection.ranges.map((r) => ({ start: pos(r.from), end: pos(r.to) })),
};
}
+48 -4
Переглянути файл
@@ -16,22 +16,66 @@ import { pluginLanguageVisuals } from "./languageVisuals";
* `line-markers` providers (`lineMarkerGutter.ts`).
*/
import { registerEditorContribution } from "@/editor/api";
import { lazyComponent, lazyWhen } from "@/ui";
import { executeAction, registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { editorService, registerOverlay } from "@/workbench/contributions";
import { providePluginThemePreviews, startPluginBridge } from "./bridge";
import { editorService, registerOverlay, registerSettingsPage } from "@/workbench/contributions";
import {
followPluginChanges,
providePluginThemePreviews,
startPluginBridge,
syncProjection,
trackPluginTheme,
} from "./bridge";
import { ConsentDialogHost, provideConsentDialog } from "./consent";
import { trackIconTheme } from "./iconThemes";
import { pluginLineMarkerGutter } from "./lineMarkerGutter";
import { defineBuiltinUiPoints } from "./points";
import { startViewUi } from "./uiPoints";
import { showInstalledIntellijThemes } from "./intellijThemesDialogStore";
import { showInstalledIntellijThemes, useIntellijThemesDialog } from "./intellijThemesDialogStore";
import { startWorkspaceContains } from "./workspaceContains";
import { startPluginDecorations } from "./decorations";
import { startOneDarkNotice } from "./oneDarkNotice";
import { startIndexedMarkers } from "./indexedMarkers";
import { startRunTargets } from "./runTargets";
import { startPluginNavigation } from "./navigation";
import { IntellijThemesDialogHost, registerPluginsPage } from "./settingsPages";
import { installFromDisk, refreshPlugins, reloadPlugin, SETTINGS_PAGE_ID, updateAllPlugins, usePlugins } from "./store";
function registerPluginsPage(): () => void {
return registerSettingsPage({
id: SETTINGS_PAGE_ID,
title: "Plugins",
// After Editor, as in IntelliJ IDEA.
order: 250,
bleed: true,
keywords: ["plugin", "extension", "wasm", "install", "theme", "marketplace"],
component: lazyComponent(() => import("./PluginsPage").then((m) => m.PluginsPage)),
});
}
/** Settings › Plugins for the Settings window: the page plus the plugin theme. */
const useIntellijThemesOpen = () => useIntellijThemesDialog((s) => s.open);
const IntellijThemesDialogHost = lazyWhen(useIntellijThemesOpen, () =>
import("./IntellijThemesDialog").then((m) => m.IntellijThemesDialogHost),
);
export function activateSettingsPages(): () => void {
const disposers = [
registerPluginsPage(),
registerOverlay({ id: "plugins.consent", component: ConsentDialogHost }),
registerOverlay({ id: "plugins.intellijThemes", component: IntellijThemesDialogHost }),
provideConsentDialog(),
defineBuiltinUiPoints(),
followPluginChanges(),
startRunTargets(false),
syncProjection(),
trackPluginTheme(),
trackIconTheme(),
];
void refreshPlugins();
return () => disposers.reverse().forEach((d) => d());
}
export function activate(): () => void {
const disposers = [
registerPluginsPage(),
+254 -19
Переглянути файл
@@ -3,31 +3,266 @@
* declaration is projected onto the workbench, and how its items appear on
* the plugin details page. One `defineUiPoint` per contribution type.
*/
import type { PluginEditor } from "@/bindings";
import { activeEditor } from "@/editor/api";
import { defineCoreUiPoints } from "./corePoints";
import { providePluginEditorContext } from "./editorContext";
import { defineViewUiPoints } from "./uiPoints";
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
import type { PluginInfo, ThemeDef } from "@/bindings";
import { pluginIconName } from "./pluginIcon";
import { registerAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { addContributedTheme, pluginThemeRef } from "@/platform/themes";
import { currentThemeChoice, setTheme, useThemeOverride } from "@/workbench/theme";
import { useProject } from "@/platform/project";
import { Button, Kbd, T } from "@/ui";
import { addIconTheme, iconThemeKey, selectIconTheme, useSelectedIconTheme } from "./iconThemes";
import { defineUiPoint, type UiItem } from "./projection";
import { SecretsDetails, type SecretDecl } from "./secrets";
import { defineViewUiPoints, pluginSettingsPageId } from "./uiPoints";
import { pluginsBackend } from "./backend";
import { isLive, runPluginCommand } from "./store";
import styles from "./PluginsPage.module.css";
export { commandArgs, pluginActionId } from "./corePoints";
function activePluginEditor(): PluginEditor | null {
const editor = activeEditor();
if (!editor?.ctx.path) return null;
const { doc, selection } = editor.view.state;
const pos = (offset: number) => {
const line = doc.lineAt(offset);
return { line: line.number - 1, col: offset - line.from };
/** Unpacks an action argument: a bare path, or a menu's `{ path, paths }`. */
export function commandArgs(arg: unknown): [string | null, string[]] {
if (typeof arg === "string") return [arg, []];
const { path, paths, line, column } = (arg ?? {}) as {
path?: unknown;
paths?: unknown;
line?: unknown;
column?: unknown;
};
return {
path: editor.ctx.path,
language: editor.ctx.language,
selections: selection.ranges.map((r) => ({ start: pos(r.from), end: pos(r.to) })),
if (typeof path !== "string" || !Array.isArray(paths)) return [null, []];
if (typeof line === "number" && typeof column === "number")
return [JSON.stringify({ path, line, column }), paths.filter((p): p is string => typeof p === "string")];
return [path, paths.filter((p): p is string => typeof p === "string")];
}
export const pluginActionId = (pluginId: string, commandId: string) => `plugin.${pluginId}.${commandId}`;
interface CommandDecl {
id: string;
title: string;
icon?: string | null;
category?: string | null;
when?: string | null;
}
function CommandsDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<CommandDecl>[] }) {
const runnable = plugin.status === "active" || plugin.status === "inactive";
return (
<ul className={styles.items}>
{items.map(({ decl: c }) => {
const actionId = pluginActionId(plugin.id, c.id);
return (
<li key={c.id} className={styles.item}>
<span className={styles.itemMain}>{c.title}</span>
<Kbd action={actionId} />
<span className={styles.mono} title={tx("Action id (bind it in Keymap)")}>
{actionId}
</span>
<Button
size="small"
variant="ghost"
icon="run"
disabled={!runnable}
onClick={() => void runPluginCommand(plugin.id, c.id)}
aria-label={tx`Run ${c.title}`}
>
<T>Run</T>
</Button>
</li>
);
})}
</ul>
);
}
function ThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<ThemeDef>[] }) {
// The selection is the Appearance setting; these buttons write it as the theme pickers do.
useProject((s) => s.settings?.appearance);
useThemeOverride((s) => s.theme);
const selected = currentThemeChoice();
const live = isLive(plugin.status);
return (
<ul className={styles.items}>
{items.map(({ decl: t }) => {
const isActive = selected === pluginThemeRef(plugin.id, t.id);
return (
<li key={t.id} className={styles.item}>
<span className={styles.itemMain}>{t.name}</span>
<span className={styles.muted}>{t.kind === "dark" ? tx("Dark") : tx("Light")}</span>
{isActive ? (
<Button
size="small"
variant="secondary"
onClick={() => void setTheme(t.kind === "light" ? "light" : "dark")}
>
<T>Use Default Theme</T>
</Button>
) : (
<Button
size="small"
variant="ghost"
disabled={!live}
onClick={() => void setTheme(pluginThemeRef(plugin.id, t.id))}
aria-label={tx`Apply theme ${t.name}`}
>
<T>Apply</T>
</Button>
)}
</li>
);
})}
</ul>
);
}
interface IconThemeDecl {
id: string;
label: string;
icons: number;
}
function IconThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<IconThemeDecl>[] }) {
const selected = useSelectedIconTheme();
return (
<ul className={styles.items}>
{items.map(({ decl: t }) => {
const key = iconThemeKey(plugin.id, t.id);
return (
<li key={t.id} className={styles.item}>
<span className={styles.itemMain}>{t.label}</span>
<span className={styles.muted}>{tx`${t.icons} icons`}</span>
{selected === key ? (
<Button size="small" variant="secondary" onClick={() => void selectIconTheme(null)}>
<T>Use Default Icons</T>
</Button>
) : (
<Button
size="small"
variant="ghost"
onClick={() => void selectIconTheme(key)}
aria-label={tx`Apply icon theme ${t.label}`}
>
<T>Apply</T>
</Button>
)}
</li>
);
})}
</ul>
);
}
const endpointPlugins = new Map<string, { declarations: number; dispose: () => void }>();
/** One endpoint provider per plugin, however many `[[contributes.endpoints]]` it declares. */
function providePluginEndpoints(pluginId: string): () => void {
let entry = endpointPlugins.get(pluginId);
if (!entry) {
const dispose = registerEndpointProvider({
id: `plugin:${pluginId}`,
endpoints: async (root): Promise<EndpointEntry[]> =>
(await pluginsBackend().endpoints(pluginId)).map((e) => ({
method: e.method ?? "*",
url: e.path,
framework: e.framework,
handler: e.handler ?? undefined,
controller: e.framework,
methodName: e.handler ?? "",
pluginId,
path: e.location.path,
rel: e.location.path.startsWith(`${root}/`) ? e.location.path.slice(root.length + 1) : e.location.path,
line: e.location.range.start.line,
col: e.location.range.start.col,
})),
});
entry = { declarations: 0, dispose };
endpointPlugins.set(pluginId, entry);
}
const held = entry;
held.declarations++;
return () => {
if (--held.declarations > 0) return;
held.dispose();
endpointPlugins.delete(pluginId);
};
}
/** Registers the client side of every first-party UI point. */
export function defineBuiltinUiPoints(): () => void {
const disposers = [providePluginEditorContext(activePluginEditor), defineCoreUiPoints(), defineViewUiPoints()];
const disposers = [
defineUiPoint("mcpTools", {}),
defineUiPoint("serverCommands", {}),
defineUiPoint("endpoints", { project: ({ pluginId }) => providePluginEndpoints(pluginId) }),
defineUiPoint<CommandDecl>("commands", {
title: "Commands",
project: ({ pluginId, decl }, { plugin }) => {
let disposed = false;
const action = {
id: pluginActionId(pluginId, decl.id),
title: decl.title,
category: decl.category ?? plugin.name,
icon:
decl.icon && !decl.icon.endsWith(".svg")
? decl.icon
: plugin.icon
? pluginIconName(pluginId, plugin.icon)
: "package",
when: decl.when ?? undefined,
verbatim: true,
// A command can call a model or a server; its toolbar button must show the click was taken.
indicatesRunning: true,
keywords: ["plugin", plugin.name, pluginId],
description: tx`From plugin ${plugin.name}`,
run: async ({ arg }: { arg?: unknown }) => {
const [path, paths] = commandArgs(arg);
await runPluginCommand(pluginId, decl.id, path, paths);
},
};
let off = registerAction(action);
if (decl.icon?.endsWith(".svg"))
void pluginsBackend()
.assets(pluginId, `commandIcon/${decl.id}`)
.then((assets) => {
const svg = assets.find(([id]) => id === `commandIcon/${decl.id}`)?.[1];
if (!svg || disposed) return;
off();
off = registerAction({ ...action, icon: pluginIconName(pluginId, { light: svg, dark: null }) });
})
.catch(console.warn);
return () => {
disposed = true;
off();
};
},
Details: CommandsDetails,
}),
// Offered by every theme picker while the plugin is live; `followThemeSetting` applies the selected one.
defineUiPoint<ThemeDef>("themes", {
title: "Themes",
project: ({ pluginId, decl }, { plugin }) =>
addContributedTheme({
id: pluginThemeRef(pluginId, decl.id),
label: decl.name,
kind: decl.kind === "light" ? "light" : "dark",
origin: plugin.name,
}),
Details: ThemesDetails,
}),
defineUiPoint<IconThemeDecl>("iconThemes", {
title: "File Icon Themes",
project: ({ pluginId, decl }, { plugin }) =>
addIconTheme({
pluginId,
id: decl.id,
label: decl.label,
origin: plugin.name,
settingsPage: `${pluginSettingsPageId(pluginId)}.${decl.id.replace(/\./g, "-")}`,
}),
Details: IconThemesDetails,
}),
// Stored by the backend; listed here with a field per secret.
defineUiPoint<SecretDecl>("secrets", { title: "Secrets", Details: SecretsDetails }),
defineViewUiPoints(),
];
return () => disposers.reverse().forEach((d) => d());
}
-125
Переглянути файл
@@ -1,125 +0,0 @@
/**
* Settings › Plugins for the standalone Settings window: registers the Plugins
* page, projects plugin commands/keymaps/settings/themes, and follows plugin
* updates without pulling in CodeMirror editor extensions.
*/
import { isMacHost, registerExtensionBindings } from "@/platform/keymap";
import { languageListChanged } from "@/platform/languageList";
import { lazyComponent, lazyWhen } from "@/ui";
import { registerOverlay, registerSettingsPage } from "@/workbench/contributions";
import { pluginsBackend } from "./backend";
import { ConsentDialogHost, provideConsentDialog } from "./consent";
import { defineCoreUiPoints, pluginActionId } from "./corePoints";
import { trackIconTheme } from "./iconThemes";
import { useIntellijThemesDialog } from "./intellijThemesDialogStore";
import { defineUiPoint } from "./projection";
import { refreshRunTargets, startRunTargets } from "./runTargets";
import { projectSettings, type SettingsDecl } from "./settings";
import { refreshPlugins, SETTINGS_PAGE_ID, usePlugins } from "./store";
import { syncPluginProjection, trackPluginTheme } from "./themeRuntime";
export function registerPluginsPage(): () => void {
return registerSettingsPage({
id: SETTINGS_PAGE_ID,
title: "Plugins",
// After Editor, as in IntelliJ IDEA.
order: 250,
bleed: true,
keywords: ["plugin", "extension", "wasm", "install", "theme", "marketplace"],
component: lazyComponent(() => import("./PluginsPage").then((m) => m.PluginsPage)),
});
}
const useIntellijThemesOpen = () => useIntellijThemesDialog((s) => s.open);
export const IntellijThemesDialogHost = lazyWhen(useIntellijThemesOpen, () =>
import("./IntellijThemesDialog").then((m) => m.IntellijThemesDialogHost),
);
interface KeymapDecl {
command: string;
key: string;
mac?: string | null;
when?: string | null;
}
const VIEW_ONLY_POINTS: ReadonlyArray<[string, string]> = [
["menus", "Menus"],
["statusBar", "Status Bar Items"],
["views", "Tool Windows"],
["customEditors", "Editors"],
["editorPanels", "Editor Panels"],
["markerIcons", "Marker Icons"],
["fileIcons", "File Icons"],
["commitChecks", "Commit Checks"],
["snippets", "Snippets"],
["fileTemplates", "File Templates"],
];
function defineSettingsUiPoints(): () => void {
const disposers = [
defineCoreUiPoints(),
defineUiPoint<KeymapDecl>("keymaps", {
title: "Shortcuts",
project: ({ pluginId, decl }) =>
decl.key === "Escape" && decl.when
? undefined
: registerExtensionBindings(pluginActionId(pluginId, decl.command), [
isMacHost() ? (decl.mac ?? decl.key) : decl.key,
]),
}),
defineUiPoint<SettingsDecl>("settings", {
title: "Settings",
project: ({ pluginId, decl }) => projectSettings(pluginId, decl),
}),
...VIEW_ONLY_POINTS.map(([point, title]) => defineUiPoint(point, { title })),
];
return () => disposers.reverse().forEach((d) => d());
}
function followSettingsPluginChanges(): () => void {
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
const off = pluginsBackend().onEvent((e) => {
switch (e.type) {
case "runTargetsChanged":
void refreshRunTargets(false).catch(() => {});
break;
case "commandsChanged":
if (!refreshTimer) {
refreshTimer = setTimeout(() => {
refreshTimer = null;
void refreshPlugins();
}, 30);
}
break;
case "themeChanged":
usePlugins.setState({ activeTheme: e.theme });
break;
case "languagesChanged":
languageListChanged();
break;
default:
break;
}
});
return () => {
if (refreshTimer) clearTimeout(refreshTimer);
off();
};
}
export function activateSettingsPages(): () => void {
const disposers = [
registerPluginsPage(),
registerOverlay({ id: "plugins.consent", component: ConsentDialogHost }),
registerOverlay({ id: "plugins.intellijThemes", component: IntellijThemesDialogHost }),
provideConsentDialog(),
defineSettingsUiPoints(),
followSettingsPluginChanges(),
startRunTargets(false),
syncPluginProjection(),
trackPluginTheme(),
trackIconTheme(),
];
void refreshPlugins();
return () => disposers.reverse().forEach((d) => d());
}
-240
Переглянути файл
@@ -1,240 +0,0 @@
/**
* Editor-free plugin theme application and UI contribution projection, shared
* between the workbench bridge and the Settings window.
*/
import type { ActiveTheme } from "@/bindings";
import { useI18n } from "@/platform/i18n";
import { useProducerNames } from "@/platform/inspections";
import { useProject } from "@/platform/project";
import {
isThemeAvailable,
parsePluginThemeRef,
providePluginThemePreview,
useContributedThemes,
} from "@/platform/themes";
import {
applyThemeAttributes,
currentThemeChoice,
currentThemeId,
subscribeScheme,
syncWindowBackground,
useThemeOverride,
windowBackgroundHex,
} from "@/workbench/theme";
import { pluginsBackend } from "./backend";
import { loadPluginCatalogs, localizeContributions, usePluginCatalogs } from "./pluginText";
import { clearUiContributions, syncUiContributions } from "./projection";
import { selectPluginTheme, usePlugins } from "./store";
/** Keeps the projected UI contributions in line with the plugin list. */
export function syncPluginProjection(onPluginsChanged?: () => void): () => void {
const apply = () => {
const s = usePlugins.getState();
syncUiContributions(localizeContributions(s.ui, usePluginCatalogs.getState().catalogs), s.plugins);
// Their problems are listed by name in Settings › Inspections.
useProducerNames.setState({
names: new Map(
s.plugins.flatMap((p): [string, string][] => [
[`plugin:${p.id}`, p.name],
[`plugin-provider:${p.id}`, p.name],
]),
),
});
};
const loadCatalogs = () => void loadPluginCatalogs(usePlugins.getState().ui, useI18n.getState().locale);
apply();
loadCatalogs();
const unsubscribe = [
usePlugins.subscribe((s, prev) => {
if (s.ui !== prev.ui) loadCatalogs();
if (s.ui !== prev.ui || s.plugins !== prev.plugins) {
onPluginsChanged?.();
apply();
}
}),
usePluginCatalogs.subscribe((s, prev) => s.catalogs !== prev.catalogs && apply()),
useI18n.subscribe((s, prev) => s.locale !== prev.locale && loadCatalogs()),
];
return () => {
unsubscribe.forEach((u) => u());
clearUiContributions();
};
}
export const PLUGIN_THEME_STYLE_ID = "openidea-plugin-theme";
/** Stylesheet for a plugin theme. Its selector outranks every built-in theme block. */
export function pluginThemeCss(theme: ActiveTheme["theme"]): string {
const kind = theme.kind === "light" ? "light" : "dark";
const decls = [` color-scheme: ${kind};`];
for (const [name, value] of Object.entries(theme.tokens)) {
// Backend validates; keep the guard so a malformed payload can't inject declarations.
if (!/^--[a-z0-9-]+$/.test(name) || value == null || /[;{}<>\\]/.test(value)) continue;
decls.push(` ${name}: ${value};`);
}
return `:root[data-plugin-theme]:not([data-plugin-theme=""]) {\n${decls.join("\n")}\n}\n`;
}
/**
* Applies a plugin theme (null restores the built-in one): its tokens as a
* stylesheet over the built-in light or dark base named by its `kind`. A
* stylesheet rather than inline styles, so the accent picked in Settings ›
* Appearance and the editor colour scheme still layer on top.
*/
export function applyPluginTheme(theme: ActiveTheme | null, root: HTMLElement = document.documentElement) {
const doc = root.ownerDocument;
const current = doc.getElementById(PLUGIN_THEME_STYLE_ID);
const id = theme && `${theme.pluginId}/${theme.theme.id}`;
const css = theme && pluginThemeCss(theme.theme);
// The same theme again (each window hears every selection): replacing its stylesheet restyles the page.
if (theme && current?.textContent === css && root.dataset.pluginTheme === id) return;
current?.remove();
const had = root.dataset.pluginTheme !== undefined;
if (!theme) {
delete root.dataset.pluginTheme;
delete root.dataset.pluginThemeKind;
if (had) applyThemeAttributes(currentThemeId(), root);
} else {
const style = doc.createElement("style");
style.id = PLUGIN_THEME_STYLE_ID;
style.textContent = css;
doc.head.appendChild(style);
root.dataset.pluginTheme = id!;
root.dataset.pluginThemeKind = theme.theme.kind === "light" ? "light" : "dark";
applyThemeAttributes(currentThemeId(), root);
}
if (had || theme) syncWindowBackground();
}
/**
* Quick Switch's theme preview of plugin themes: a live plugin's theme as it
* contributes it, shown in this window only; nothing is selected or saved.
*/
export function providePluginThemePreviews(): () => void {
return providePluginThemePreview((ref) => {
const state = usePlugins.getState();
if (ref === "selected") return applyPluginTheme(state.activeTheme);
const want = ref ? parsePluginThemeRef(ref) : null;
const item = want
? state.ui.find((c) => c.point === "themes" && c.pluginId === want.pluginId && c.key === want.themeId)
: undefined;
applyPluginTheme(item ? { pluginId: item.pluginId, theme: item.decl as ActiveTheme["theme"] } : null);
});
}
/** localStorage key read by public/boot.js: the selected theme's stylesheet, applied before the app loads. */
export const PLUGIN_THEME_CACHE_KEY = "openidea.pluginTheme";
export interface CachedPluginTheme {
/** `data-plugin-theme`: `<pluginId>/<themeId>`. */
id: string;
kind: "light" | "dark";
css: string;
}
function cachePluginTheme(theme: ActiveTheme | null) {
try {
if (!theme) {
localStorage.removeItem(PLUGIN_THEME_CACHE_KEY);
return;
}
const cached: CachedPluginTheme = {
id: `${theme.pluginId}/${theme.theme.id}`,
kind: theme.theme.kind === "light" ? "light" : "dark",
css: pluginThemeCss(theme.theme),
};
localStorage.setItem(PLUGIN_THEME_CACHE_KEY, JSON.stringify(cached));
} catch {
/* storage unavailable */
}
}
let reportedFrame: string | undefined;
/**
* Tells the backend the theme's resolved frame colour, which new windows open
* in. Selecting a theme clears it there, so it is sent once per selection.
*/
function reportThemeFrame(theme: ActiveTheme | null) {
const frame = theme ? windowBackgroundHex() : null;
if (!theme || !frame) {
reportedFrame = undefined;
return;
}
const key = `${theme.pluginId}/${theme.theme.id}|${frame}`;
if (key === reportedFrame) return;
reportedFrame = key;
void pluginsBackend()
.setThemeFrame(frame)
.catch(() => (reportedFrame = undefined));
}
/**
* Applies the selected plugin theme and keeps it for the next start-up. Until
* the first plugin list arrives, the theme public/boot.js restored stays.
*/
export function trackPluginTheme(): () => void {
const sync = (s: ReturnType<typeof usePlugins.getState>) => {
if (!s.activeTheme && (!s.loaded || s.error)) return;
applyPluginTheme(s.activeTheme);
cachePluginTheme(s.activeTheme);
reportThemeFrame(s.activeTheme);
};
sync(usePlugins.getState());
const unsubscribe = usePlugins.subscribe((s, prev) => {
if (s.activeTheme !== prev.activeTheme || s.loaded !== prev.loaded) sync(s);
});
return () => {
unsubscribe();
applyPluginTheme(null);
};
}
/**
* Makes the plugin host's theme the one the Appearance settings select: a
* plugin theme (`plugin:<id>/<theme>`, from any theme picker, the OS mode with
* "Sync with OS", or the plugin's details page) is selected there once its
* plugin is live; a built-in one clears it. While the selected plugin is off,
* its built-in base shows and the selection is kept for when it is back.
*/
export function followThemeSetting(): () => void {
let requested: string | undefined;
const reconcile = () => {
const plugins = usePlugins.getState();
if (!plugins.loaded || plugins.error || !useProject.getState().settings?.appearance) return;
const choice = currentThemeChoice();
const want = parsePluginThemeRef(choice);
const target = want && isThemeAvailable(choice) ? choice : null;
const active = plugins.activeTheme;
const current = active ? `plugin:${active.pluginId}/${active.theme.id}` : null;
if (target === current || (want && !target && !current)) {
requested = undefined;
return;
}
// A selected plugin that is off: leave the host's selection for when it is back.
if (want && !target) {
if (requested === "") return;
requested = "";
void selectPluginTheme(null, null);
return;
}
if (requested === (target ?? "")) return;
requested = target ?? "";
void selectPluginTheme(want && target ? want.pluginId : null, want && target ? want.themeId : null);
};
reconcile();
const disposers = [
// Not on the host's theme changing: another window selects it before this one's settings
// say so, and selecting this window's choice back would flip it until they agree.
usePlugins.subscribe((s, prev) => {
if (s.loaded !== prev.loaded) reconcile();
}),
useProject.subscribe((s, prev) => {
if (s.settings?.appearance !== prev.settings?.appearance) reconcile();
}),
useThemeOverride.subscribe(reconcile),
useContributedThemes.subscribe(reconcile),
subscribeScheme(reconcile),
];
return () => disposers.forEach((d) => d());
}
+1 -1
Переглянути файл
@@ -279,7 +279,7 @@ interface StatusDecl {
// --- settings ---------------------------------------------------------------------
export { withPluginSetting } from "./settings";
export { withPluginSetting, pluginSettingsPageId } from "./settings";
// --- views and custom editors -----------------------------------------------------
+1 -4
Переглянути файл
@@ -86,7 +86,6 @@ import {
VIEW_MODES,
autoExpand,
clearRevealRequest,
explainHiddenPath,
loadDir,
loadOutline,
revealPath,
@@ -518,7 +517,7 @@ export function ProjectView() {
// Select a revealed path once its row exists.
useEffect(() => {
if (!revealRequest) return;
const { path, focus, seq, explain } = revealRequest;
const { path, focus, seq } = revealRequest;
const exact = model.keyOfPath.get(path);
const loadingAncestors = info.pending.some((p) => p === path || isInside(path, p));
if (!exact && loadingAncestors) return;
@@ -529,8 +528,6 @@ export function ProjectView() {
handle.current?.reveal(key);
revealing.current = false;
if (focus) handle.current?.focus();
const shown = model.byKey.get(key)?.path;
if (explain && !exact && shown) explainHiddenPath(path, shown);
}, [revealRequest, model, info]);
// Autoscroll from source: follow the active editor.
+1 -1
Переглянути файл
@@ -108,7 +108,7 @@ export function selectInProjectView(path?: string | null, focus = true) {
if (!target) return false;
if (!modeShows(target)) setViewMode("project");
showProjectView(focus);
return revealPath(target, focus, true);
return revealPath(target, focus);
}
/**
-28
Переглянути файл
@@ -7,8 +7,6 @@ import {
reloadLoadedDirs,
currentModel,
expandAll,
explainHiddenPath,
hidingOption,
initProjectTree,
loadDir,
revealPath,
@@ -20,7 +18,6 @@ import {
} from "./store";
import { beginNew, commitEditing, copySelection, paste, transfer } from "./operations";
import { closeFileRefactorDialog, pendingFileRefactorDialog } from "./FileRefactorDialogs";
import { provideNotificationService } from "@/workbench/contributions";
const ROOT = "/p";
let fs: MemoryFs;
@@ -322,28 +319,3 @@ it("keeps the primary first and sorts attachments by name", () => {
initProjectTree("/ws", "Workspace", ["/z", "/c", "/a"]);
expect(currentModel().roots.map((n) => n.path)).toEqual(["/a", "/c", "/z"]);
});
describe("a file the view options hide", () => {
const entry = (name: string, ignored = false) => ({ name, path: `/p/${name}`, isDir: true, ignored }) as never;
it("names the option that hides it below the shown ancestor, and offers to turn it on", () => {
useProjectTree.setState({ listings: new Map([["/p", [entry("build", true), entry("src")]]]) });
setViewOption("showExcluded", false);
expect(hidingOption("/p/build/out.txt", "/p")).toBe("showExcluded");
expect(hidingOption("/p/.git/config", "/p")).toBe(
useProjectTree.getState().options.showHidden ? null : "showHidden",
);
expect(hidingOption("/p/src/a.ts", "/p")).toBeNull();
const notify = vi.fn();
provideNotificationService({ notify } as never);
explainHiddenPath("/p/build/out.txt", "/p");
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "out.txt is hidden because Show Excluded Files is off" }),
);
notify.mock.calls[0]![0].actions[0].run();
expect(useProjectTree.getState().options.showExcluded).toBe(true);
expect(useProjectTree.getState().revealRequest?.path).toBe("/p/build/out.txt");
expect(hidingOption("/p/build/out.txt", "/p")).toBeNull();
});
});
+3 -46
Переглянути файл
@@ -10,9 +10,6 @@ import { commands, type FileEntry, type OutlineItem } from "@/bindings";
import { withDocument } from "@/editor/lsp/files";
import { IpcError } from "@/platform/ipc";
import { libraryEntryPaths } from "@/platform/virtualDocs";
import { isIgnoredName } from "@/platform/ignoredNames";
import { tx } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
import { ipcPath } from "@/platform/paths";
import {
DEFAULT_TREE_OPTIONS,
@@ -125,8 +122,7 @@ interface ProjectTreeState {
editing: Editing | null;
clipboard: Clipboard | null;
/** A path to select (and scroll to) once its row is visible. */
/** `explain`: say which view option hides the path when only an ancestor can be selected. */
revealRequest: { path: string; focus: boolean; seq: number; explain?: boolean } | null;
revealRequest: { path: string; focus: boolean; seq: number } | null;
/** Folder key highlighted as drop target. */
dropTarget: string | null;
mode: ViewMode;
@@ -639,7 +635,7 @@ export function dropOutlines(paths: readonly string[]) {
let revealSeq = 0;
/** Expands the ancestors of `path` and selects it once visible. */
export function revealPath(requested: string, focus = false, explain = false) {
export function revealPath(requested: string, focus = false) {
const { expanded } = get();
const project = get().root;
if (!project) return false;
@@ -672,7 +668,7 @@ export function revealPath(requested: string, focus = false, explain = false) {
changed = true;
}
if (changed) setExpanded(next);
set({ revealRequest: { path, focus, seq: ++revealSeq, ...(explain ? { explain } : {}) } });
set({ revealRequest: { path, focus, seq: ++revealSeq } });
for (const a of folders) void loadDir(a);
return true;
}
@@ -738,45 +734,6 @@ function groupAncestors(model: TreeModel, key: string): string[] {
}
}
/**
* The view option that hides `path` below its shown ancestor `shown`: a hidden name
* (Show Hidden Files) or an ignored entry (Show Excluded Files). Null when no option does.
*/
export function hidingOption(path: string, shown: string): "showHidden" | "showExcluded" | null {
const { listings, options } = get();
if (!isSameOrInside(path, shown) || path === shown) return null;
let dir = shown;
for (const name of path.slice(shown.length + 1).split("/")) {
if (isIgnoredName(name)) return options.showHidden ? null : "showHidden";
if (listings.get(dir)?.find((e) => e.name === name)?.ignored) return options.showExcluded ? null : "showExcluded";
dir = `${dir}/${name}`;
}
return null;
}
const OPTION_TITLES = { showHidden: "Show Hidden Files", showExcluded: "Show Excluded Files" } as const;
/** Select Opened File reached only `shown`: say which option hides `path`, offering to turn it on. */
export function explainHiddenPath(path: string, shown: string) {
const option = hidingOption(path, shown);
if (!option) return;
const title = OPTION_TITLES[option];
notifications().notify({
level: "info",
key: "project.hiddenPath",
title: tx`${nameOf(path)} is hidden because ${title} is off`,
actions: [
{
label: tx(title),
run: () => {
setViewOption(option, true);
revealPath(path, true);
},
},
],
});
}
export function clearRevealRequest(seq: number) {
if (get().revealRequest?.seq === seq) set({ revealRequest: null });
}
+1 -27
Переглянути файл
@@ -140,14 +140,6 @@ function TrustSettings() {
setError(String(e));
}
};
const trust = async (path: string) => {
try {
await call(commands.projectTrustSet(path, true, false));
await refresh();
} catch (e) {
setError(String(e));
}
};
const addLocation = async () => {
try {
const { open } = await import("@/platform/dialog");
@@ -177,24 +169,6 @@ function TrustSettings() {
</Button>
</div>
))}
{decisions?.restricted.length ? (
<>
<h3>
<T>Restricted projects</T>
</h3>
<p className={styles.hint}>
<T>These projects open in Restricted Mode, even inside a trusted location.</T>
</p>
{decisions.restricted.map((path) => (
<div className={styles.row} key={path}>
<span className={styles.path}>{path}</span>
<Button onClick={() => void trust(path)}>
<T>Trust</T>
</Button>
</div>
))}
</>
) : null}
<div className={styles.sectionHead}>
<h3>
<T>Trusted locations</T>
@@ -204,7 +178,7 @@ function TrustSettings() {
</Button>
</div>
<p className={styles.hint}>
<T>Every project inside a trusted location is trusted without asking, unless it is a restricted project.</T>
<T>Every project inside a trusted location is trusted without asking.</T>
</p>
{decisions?.locations.map((path) => (
<div className={styles.row} key={path}>
+1 -5
Переглянути файл
@@ -58,13 +58,9 @@
justify-content: space-between;
gap: var(--space-3);
}
.content h3 {
.sectionHead h3 {
margin: 0;
}
.content > h3,
.sectionHead {
margin-top: var(--space-3);
}
.hint {
color: var(--fg-secondary);
}
+1 -19
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { confirmProjectTrust } from "@/platform/projectTrust";
import { executeAction } from "@/platform/actions";
import { emitLocalIdeEvent } from "@/platform/ipc";
@@ -165,24 +165,6 @@ it("adds a picked folder as a trusted location from settings", async () => {
expect(addLocation).toHaveBeenCalledTimes(1);
});
it("lists restricted projects, which a trusted location doesn't cover, and trusts one from settings", async () => {
const Page = useSettingsPages.getState().pages.get("projectTrust")!.component!;
listDecisions.mockResolvedValue({
status: "ok",
data: { projects: [], locations: ["/projects"], restricted: ["/projects/app"] },
});
render(<Page />);
expect(await screen.findByRole("heading", { name: "Restricted projects" })).toBeTruthy();
listDecisions.mockResolvedValue({
status: "ok",
data: { projects: ["/projects/app"], locations: ["/projects"], restricted: [] },
});
fireEvent.click(screen.getByRole("button", { name: "Trust" }));
await waitFor(() => expect(screen.queryByRole("heading", { name: "Restricted projects" })).toBeNull());
expect(decide).toHaveBeenCalledWith("/projects/app", true, false);
expect(screen.getByText("/projects/app")).toBeTruthy();
});
it.each(["Trust Project", "Preview in Restricted Mode"])(
"keeps a local opening's trust decision on the client: %s",
async (button) => {
+3 -15
Переглянути файл
@@ -36,7 +36,6 @@ import {
import { selectedTarget } from "./sessionTargets";
import styles from "./Run.module.css";
import { tx } from "@/platform/i18n";
import { confirm } from "@/workbench/messages";
type Row =
/** A labelled group, or a thin separator when `label` is empty. */
@@ -112,16 +111,6 @@ function anchorElement(): Element | { x: number; y: number } {
}
/** Run/Debug configuration chooser popup (⌃⌥R), anchored to the title bar widget. */
/** Deletes a configuration from the chooser once the user confirms, as IDEA's popup asks first. */
async function askDeleteConfig(config: RunConfig) {
const ok = await confirm({
title: "Confirmation",
message: tx`Are you sure you want to delete ${config.name}?`,
ok: "Delete",
});
if (ok) await deleteConfig(config.id);
}
export function ConfigChooserOverlay() {
const open = useRun((s) => s.chooserOpen);
if (!open) return null;
@@ -261,11 +250,10 @@ function ConfigChooser() {
e.key === "Delete" &&
row?.type === "config" &&
canDeleteConfig(row.config.id) &&
input().selectionStart === query.length &&
input().selectionEnd === query.length
input().selectionStart === query.length
) {
e.preventDefault();
void askDeleteConfig(row.config);
void deleteConfig(row.config.id);
return;
}
if (numbers.size && !e.altKey && !e.ctrlKey && !e.metaKey && /^Digit[1-9]$|^Numpad[1-9]$/.test(e.code)) {
@@ -298,7 +286,7 @@ function ConfigChooser() {
{ kind: "header", label: "Configuration" },
{ label: "Edit…", icon: "edit", run: () => activate(row, "edit") },
{ label: pinned.includes(c.id) ? "Unpin" : "Pin", icon: "pin", run: () => togglePinned(c.id) },
...(canDeleteConfig(c.id) ? [{ label: "Delete", danger: true, run: () => void askDeleteConfig(c) }] : []),
...(canDeleteConfig(c.id) ? [{ label: "Delete", danger: true, run: () => void deleteConfig(c.id) }] : []),
];
};
const openMenu = (c: RunConfig, at: Element) => setMenu({ name: c.name, anchor: at, items: menuItems(c) });
+3 -29
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
const ipc = vi.hoisted(() => ({
runSaveConfigs: vi.fn(),
@@ -17,7 +17,6 @@ vi.mock("@/platform/ipc", async (importOriginal) => ({
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { MessagesHost } from "@/workbench/messages";
import { EditConfigsOverlay } from "./EditConfigsDialog";
import { ConfigChooserOverlay } from "./ConfigChooser";
import {
@@ -142,39 +141,14 @@ it("keeps other temporary and non-temporary configurations on removal", async ()
expect(useRun.getState().configs.map((c) => c.id)).toEqual(expect.arrayContaining(["npm:app", other.id]));
});
it("chooser popup Delete removes the selected detection once confirmed", async () => {
it("chooser popup Delete removes the selected detection", async () => {
useRun.setState({ chooserOpen: true, editorOpen: false });
render(
<>
<ConfigChooserOverlay />
<MessagesHost />
</>,
);
render(<ConfigChooserOverlay />);
fireEvent.keyDown(document.querySelector("input[data-autofocus]")!, { key: "Delete" });
const ask = await screen.findByRole("dialog", { name: "Confirmation" });
expect(ipc.runSaveConfigs).not.toHaveBeenCalled();
fireEvent.click(within(ask).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(ipc.runSaveConfigs).toHaveBeenCalledWith([], ["npm:app"]));
await waitFor(() => expect(useRun.getState().configs).toEqual([]));
});
it("chooser popup Delete edits the search text when the caret is not at its end", async () => {
useRun.setState({ chooserOpen: true, editorOpen: false });
render(
<>
<ConfigChooserOverlay />
<MessagesHost />
</>,
);
const input = document.querySelector<HTMLInputElement>("input[data-autofocus]")!;
fireEvent.change(input, { target: { value: "app" } });
input.setSelectionRange(1, 1);
fireEvent.keyDown(input, { key: "Delete" });
await act(async () => {});
expect(screen.queryByRole("dialog", { name: "Confirmation" })).toBeNull();
expect(ipc.runSaveConfigs).not.toHaveBeenCalled();
});
it("Cancel discards a pending detected removal", () => {
render(<EditConfigsOverlay />);
fireEvent.click(screen.getByRole("button", { name: "Remove Configuration" }));
-43
Переглянути файл
@@ -1,43 +0,0 @@
import type { Action } from "@/platform/actions";
import { nativeToAsciiAction } from "./nativeToAscii";
/** Java's page first: JDK, Maven and the language server are what new projects most often need. */
export const NEW_PROJECTS_PAGE = "languages.java";
export function settingsActions(open: (page?: string, newProjects?: boolean) => void): Action[] {
return [
nativeToAsciiAction(),
{
id: "file.settings",
title: "Settings…",
category: "File",
icon: "settings",
keywords: ["preferences", "options", "configure"],
run: ({ arg }) => open(typeof arg === "string" ? arg : undefined),
},
{
id: "file.newProjectsSettings",
title: "Settings for New Projects…",
category: "File",
icon: "settings",
keywords: ["new projects setup", "default settings", "default project", "default jdk", "global settings"],
run: ({ arg }) => open(typeof arg === "string" ? arg : NEW_PROJECTS_PAGE, true),
},
{
id: "settings.keymap",
title: "Keymap…",
category: "File",
icon: "keyboard",
keywords: ["shortcuts", "keyboard", "bindings"],
run: () => open("keymap"),
},
{
id: "settings.appearance",
title: "Appearance…",
category: "View",
icon: "sun",
keywords: ["theme", "accent", "font size"],
run: () => open("appearance"),
},
];
}
+169 -9
Переглянути файл
@@ -12,20 +12,32 @@
* `file.newProjectsSettings` (IDEA's Settings for New Projects) edits the
* global layer only, which new projects inherit.
*/
import { registerActions } from "@/platform/actions";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { registerActions, type Action } from "@/platform/actions";
import { call, commands, isTauri } from "@/platform/ipc";
import { lazyWhen } from "@/ui";
import { useProject } from "@/platform/project";
import { isPopupOpen, lazyComponent, lazyWhen } from "@/ui";
import { loadSettings, useProject } from "@/platform/project";
import { logError } from "@/platform/errorLog";
import { restoreRemote } from "@/platform/remote";
import { provideSettingsSearchIndex, registerOverlay } from "@/workbench/contributions";
import { windowBackgroundHex } from "@/workbench/theme";
import { settingsActions } from "./actions";
import {
LazyProjectStructureDialog,
LazySettingsDialog,
loadBuiltinPages,
unloadBuiltinPages,
} from "./dialog/LazySettingsDialog";
import { openProjectStructure, openSettings, useSettingsDialog } from "./model/staging";
import {
closeSettings,
openProjectStructure,
openSettings,
rebaseSettings,
selectPage,
setNewProjects,
setQuery,
settingsTitle,
useSettingsDialog,
} from "./model/staging";
import {
appearanceToggleActions,
navigationBarActions,
@@ -35,15 +47,62 @@ import {
import { PresentationAssistant } from "./presentation/PresentationAssistant";
import { activateFileTypes } from "./fileTypesRuntime";
import { trackRuntimeSettings } from "./runtime";
import { activateSettingsWindow, relaunchSettings } from "./settingsWindow";
import { installSettingsHost } from "./window/bridge";
import { installActionProxies, installSettingsHost } from "./window/bridge";
import { showAssignShortcut, useAssignShortcut } from "./keymap/assignShortcutStore";
import { settingsSearchEntries } from "./searchIndex";
import { activatePythonStatus } from "./languages/PythonStatus";
import { activatePhpStatus } from "./languages/PhpStatus";
import { nativeToAsciiAction } from "./nativeToAscii";
import { isImeKey } from "@/platform/ime";
import { trackIconThemePages } from "./iconThemePages";
export { activateSettingsWindow };
/** Settings-driven runtime state (zoom, fonts, theme) of a secondary window. */
export const activateRuntimeSettings = trackRuntimeSettings;
export const SettingsWindow = lazyComponent(() => import("./window/SettingsWindow").then((m) => m.SettingsWindow));
/** Same event as `windows::LAUNCH_EVENT`: a pending launch (page) is waiting. */
const LAUNCH_EVENT = "openidea://launch";
/** Java's page first: JDK, Maven and the language server are what new projects most often need. */
const NEW_PROJECTS_PAGE = "languages.java";
function settingsActions(open: (page?: string, newProjects?: boolean) => void): Action[] {
return [
nativeToAsciiAction(),
{
id: "file.settings",
title: "Settings…",
category: "File",
icon: "settings",
keywords: ["preferences", "options", "configure"],
run: ({ arg }) => open(typeof arg === "string" ? arg : undefined),
},
{
id: "file.newProjectsSettings",
title: "Settings for New Projects…",
category: "File",
icon: "settings",
keywords: ["new projects setup", "default settings", "default project", "default jdk", "global settings"],
run: ({ arg }) => open(typeof arg === "string" ? arg : NEW_PROJECTS_PAGE, true),
},
{
id: "settings.keymap",
title: "Keymap…",
category: "File",
icon: "keyboard",
keywords: ["shortcuts", "keyboard", "bindings"],
run: () => open("keymap"),
},
{
id: "settings.appearance",
title: "Appearance…",
category: "View",
icon: "sun",
keywords: ["theme", "accent", "font size"],
run: () => open("appearance"),
},
];
}
const separateWindow = () => useProject.getState().settings?.appearance?.settingsInSeparateWindow !== false;
@@ -59,7 +118,7 @@ async function showSettings(page?: string, newProjects = false) {
}
await loadBuiltinPages();
// Like a launch into the open window: go to the page, keep the edits not applied yet.
if (useSettingsDialog.getState().open) relaunchSettings({ page, newProjects });
if (useSettingsDialog.getState().open) relaunch({ page, newProjects });
else openSettings(page, { newProjects });
}
@@ -112,3 +171,104 @@ export function activate(): () => void {
];
return () => disposers.reverse().forEach((d) => d());
}
function navigate(page: string | undefined) {
if (!page) return;
setQuery("");
selectPage(page);
}
interface SettingsLaunch {
page?: string;
newProjects: boolean;
}
async function takeLaunch(): Promise<SettingsLaunch | null> {
const launch = await commands.windowTakeLaunch().catch(() => null);
return launch && { page: launch.settingsPage ?? undefined, newProjects: launch.newProjects };
}
/** A launch for the open window: its page, and the mode when it asks for new projects. */
function relaunch(launch: SettingsLaunch | null) {
if (!launch) return;
if (launch.newProjects) setNewProjects(true);
navigate(launch.page);
}
function listenLaunch(): () => void {
let disposed = false;
let off: (() => void) | undefined;
void getCurrentWebviewWindow()
.listen(LAUNCH_EVENT, () => void takeLaunch().then(relaunch))
.then((u) => {
if (disposed) return u();
off = u;
// A page requested before we listened: its event is gone, the launch is not.
void takeLaunch().then(relaunch);
});
return () => {
disposed = true;
off?.();
};
}
/** Esc and ⌘W cancel, like closing the window; ⌘, stays here. */
function installWindowKeys(): () => void {
const onKey = (e: KeyboardEvent) => {
if (e.defaultPrevented || isImeKey(e)) return;
const mod = e.metaKey || e.ctrlKey;
if ((e.key === "Escape" && !isPopupOpen()) || (mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "w")) {
e.preventDefault();
closeSettings();
} else if (mod && e.key === ",") {
e.preventDefault();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}
/**
* The settings window (`settings-<parent>`): settings pages only, working on
* the parent's project; Cancel / OK / Esc close the window.
*/
export function activateSettingsWindow(parent: string): () => void {
const disposers = [
trackRuntimeSettings(),
trackIconThemePages(),
unloadBuiltinPages,
registerActions(settingsActions((page, newProjects) => relaunch({ page, newProjects: !!newProjects }))),
installActionProxies(parent),
listenLaunch(),
installWindowKeys(),
useSettingsDialog.subscribe((s, prev) => {
if (prev.open && !s.open) void getCurrentWebviewWindow().close();
if (s.newProjects !== prev.newProjects) {
void getCurrentWebviewWindow()
.setTitle(settingsTitle(s.newProjects))
.catch(() => {});
}
}),
];
void (async () => {
useSettingsDialog.setState({ pagesLoading: true });
openSettings();
try {
const launch = await takeLaunch();
relaunch(launch);
await Promise.all([
loadBuiltinPages().catch((e) => logError("cannot register settings pages", e)),
(async () => {
await restoreRemote();
const project = await commands.projectCurrent().catch(() => null);
if (project) useProject.setState({ project, settings: project.settings });
else await loadSettings().catch((e) => console.warn("cannot load settings", e));
rebaseSettings();
})(),
]);
} finally {
useSettingsDialog.setState({ pagesLoading: false });
}
})().catch((e) => logError("settings window startup failed", e));
return () => disposers.reverse().forEach((d) => d());
}
-132
Переглянути файл
@@ -1,132 +0,0 @@
/**
* Standalone native Settings window (`settings-<parent>`): settings pages only,
* working on the parent's project without importing workbench status bar widgets
* or CodeMirror.
*/
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { registerActions } from "@/platform/actions";
import { logError } from "@/platform/errorLog";
import { isImeKey } from "@/platform/ime";
import { commands } from "@/platform/ipc";
import { loadSettings, useProject } from "@/platform/project";
import { restoreRemote } from "@/platform/remote";
import { isPopupOpen } from "@/ui";
import { settingsActions } from "./actions";
import { loadBuiltinPages, unloadBuiltinPages } from "./dialog/LazySettingsDialog";
import { trackIconThemePages } from "./iconThemePages";
import {
closeSettings,
openSettings,
rebaseSettings,
selectPage,
setNewProjects,
setQuery,
settingsTitle,
useSettingsDialog,
} from "./model/staging";
import { trackRuntimeSettings } from "./runtime";
import { installActionProxies } from "./window/bridge";
/** Same event as `windows::LAUNCH_EVENT`: a pending launch (page) is waiting. */
const LAUNCH_EVENT = "openidea://launch";
export interface SettingsLaunch {
page?: string;
newProjects: boolean;
}
function navigate(page: string | undefined) {
if (!page) return;
setQuery("");
selectPage(page);
}
async function takeLaunch(): Promise<SettingsLaunch | null> {
const launch = await commands.windowTakeLaunch().catch(() => null);
return launch && { page: launch.settingsPage ?? undefined, newProjects: launch.newProjects };
}
/** A launch for the open window: its page, and the mode when it asks for new projects. */
export function relaunchSettings(launch: SettingsLaunch | null) {
if (!launch) return;
if (launch.newProjects) setNewProjects(true);
navigate(launch.page);
}
function listenLaunch(): () => void {
let disposed = false;
let off: (() => void) | undefined;
void getCurrentWebviewWindow()
.listen(LAUNCH_EVENT, () => void takeLaunch().then(relaunchSettings))
.then((u) => {
if (disposed) return u();
off = u;
// A page requested before we listened: its event is gone, the launch is not.
void takeLaunch().then(relaunchSettings);
});
return () => {
disposed = true;
off?.();
};
}
/** Esc and ⌘W cancel, like closing the window; ⌘, stays here. */
function installWindowKeys(): () => void {
const onKey = (e: KeyboardEvent) => {
if (e.defaultPrevented || isImeKey(e)) return;
const mod = e.metaKey || e.ctrlKey;
if ((e.key === "Escape" && !isPopupOpen()) || (mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "w")) {
e.preventDefault();
closeSettings();
} else if (mod && e.key === ",") {
e.preventDefault();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}
/**
* The settings window (`settings-<parent>`): settings pages only, working on
* the parent's project; Cancel / OK / Esc close the window.
*/
export function activateSettingsWindow(parent: string): () => void {
const disposers = [
trackRuntimeSettings(),
trackIconThemePages(),
unloadBuiltinPages,
registerActions(settingsActions((page, newProjects) => relaunchSettings({ page, newProjects: !!newProjects }))),
installActionProxies(parent),
listenLaunch(),
installWindowKeys(),
useSettingsDialog.subscribe((s, prev) => {
if (prev.open && !s.open) void getCurrentWebviewWindow().close();
if (s.newProjects !== prev.newProjects) {
void getCurrentWebviewWindow()
.setTitle(settingsTitle(s.newProjects))
.catch(() => {});
}
}),
];
void (async () => {
useSettingsDialog.setState({ pagesLoading: true });
openSettings();
try {
const launch = await takeLaunch();
relaunchSettings(launch);
await Promise.all([
loadBuiltinPages().catch((e) => logError("cannot register settings pages", e)),
(async () => {
await restoreRemote();
const project = await commands.projectCurrent().catch(() => null);
if (project) useProject.setState({ project, settings: project.settings });
else await loadSettings().catch((e) => console.warn("cannot load settings", e));
rebaseSettings();
})(),
]);
} finally {
useSettingsDialog.setState({ pagesLoading: false });
}
})().catch((e) => logError("settings window startup failed", e));
return () => disposers.reverse().forEach((d) => d());
}
+33 -1
Переглянути файл
@@ -3,16 +3,17 @@
* (`expr.if` …), Emmet (Tab expansion, Update Tag with Emmet) and file
* templates ("New ▸ …").
*/
import { lazyComponent } from "@/ui";
import { registerActions, type Action } from "@/platform/actions";
import { activeEditor, registerEditorContribution } from "@/editor/api";
import {
notifications,
registerMenuGroup,
registerOverlay,
registerSettingsPages,
hasRunConfiguration,
type MenuGroupContext,
} from "@/workbench/contributions";
import { activateSettingsPages } from "./settingsPages";
import { insertLiveTemplate, surroundTarget, surroundWith, templateEditorExtension } from "./editor";
import { ChooserHost } from "./popup/Chooser";
import { NewFileDialogHost, openNewFileDialog } from "./files/NewFileDialog";
@@ -163,6 +164,37 @@ function registerFileTemplateActions(): () => void {
};
}
/** Live / postfix / file template pages (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: "editor.liveTemplates",
title: "Live Templates",
group: "Editor",
order: 28,
keywords: ["snippet", "abbreviation", "surround", "template"],
component: lazyComponent(() => import("./settings/LiveTemplatesPage").then((m) => m.LiveTemplatesPage)),
},
{
// IDEA: Editor › General › Postfix Completion.
id: "editor.general.postfixCompletion",
title: "Postfix Completion",
group: "Editor",
order: 7,
keywords: ["postfix", "template", ".if", ".var", ".for"],
component: lazyComponent(() => import("./settings/PostfixPage").then((m) => m.PostfixPage)),
},
{
id: "editor.fileTemplates",
title: "File and Code Templates",
group: "Editor",
order: 26,
keywords: ["new file", "class", "template", "package", "includes", "file header", "code", "scheme", "reformat"],
component: lazyComponent(() => import("./settings/FileTemplatesPage").then((m) => m.FileTemplatesPage)),
},
]);
}
export function activate(): () => void {
const disposers = [
registerEditorContribution({ id: "templates", order: 90, extensions: templateEditorExtension }),
-33
Переглянути файл
@@ -1,33 +0,0 @@
import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
/** Live / postfix / file template pages (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: "editor.liveTemplates",
title: "Live Templates",
group: "Editor",
order: 28,
keywords: ["snippet", "abbreviation", "surround", "template"],
component: lazyComponent(() => import("./settings/LiveTemplatesPage").then((m) => m.LiveTemplatesPage)),
},
{
// IDEA: Editor › General › Postfix Completion.
id: "editor.general.postfixCompletion",
title: "Postfix Completion",
group: "Editor",
order: 7,
keywords: ["postfix", "template", ".if", ".var", ".for"],
component: lazyComponent(() => import("./settings/PostfixPage").then((m) => m.PostfixPage)),
},
{
id: "editor.fileTemplates",
title: "File and Code Templates",
group: "Editor",
order: 26,
keywords: ["new file", "class", "template", "package", "includes", "file header", "code", "scheme", "reformat"],
component: lazyComponent(() => import("./settings/FileTemplatesPage").then((m) => m.FileTemplatesPage)),
},
]);
}
+14 -3
Переглянути файл
@@ -1,13 +1,24 @@
/** TODO tool window, project TODO index and in-editor TODO highlighting. */
import { registerActions } from "@/platform/actions";
import { registerEditorContribution } from "@/editor/api";
import { registerToolWindow, toolWindowService } from "@/workbench/contributions";
import { hasIcon } from "@/ui";
import { activateSettingsPages } from "./settingsPages";
import { registerSettingsPage, registerToolWindow, toolWindowService } from "@/workbench/contributions";
import { hasIcon, lazyComponent } from "@/ui";
import { TodoHeaderActions, TodoTabs, TodoView, useTodoBadge, useTodoHeaderMenu, useTodoView } from "./TodoView";
import { todoEditorExtension } from "./highlight";
import { installTodoIndex, scanProject, syncTodoSettingsFromStorage } from "./store";
/** Settings › Editor › TODO (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPage({
id: "editor.todo",
title: "TODO",
group: "Editor",
order: 40,
keywords: ["todo", "fixme", "hack", "pattern"],
component: lazyComponent(() => import("./TodoSettingsPage").then((m) => m.TodoSettingsPage)),
});
}
export function activate(): () => void {
const disposers = [
installTodoIndex(),
-14
Переглянути файл
@@ -1,14 +0,0 @@
import { lazyComponent } from "@/ui";
import { registerSettingsPage } from "@/workbench/contributions";
/** Settings › Editor › TODO (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPage({
id: "editor.todo",
title: "TODO",
group: "Editor",
order: 40,
keywords: ["todo", "fixme", "hack", "pattern"],
component: lazyComponent(() => import("./TodoSettingsPage").then((m) => m.TodoSettingsPage)),
});
}
+26 -1
Переглянути файл
@@ -5,7 +5,9 @@
* Actions: `tools.languageServers` (open the page), `tools.install` (arg: tool name),
* `java.downloadJdk` (arg: `DownloadJdkArgs`).
*/
import { lazyComponent } from "@/ui";
import { executeAction, registerActions } from "@/platform/actions";
import { registerSettingsPage } from "@/workbench/contributions";
import { installExpiredServerPrompts } from "./expired";
import { installJdkPrompts, registerJdkActions } from "./jdk";
import {
@@ -14,9 +16,32 @@ import {
installServerWarningPrompts,
promptInstall,
} from "./missing";
import { activateSettingsPages } from "./settingsPages";
import { installTool, refreshTools, SETTINGS_PAGE_ID, toolByName, useTools } from "./store";
/** The Language Servers page (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPage({
id: SETTINGS_PAGE_ID,
title: "Language Servers",
group: "Languages & Frameworks",
order: 400,
keywords: [
"lsp",
"language server",
"debugger",
"adapter",
"dap",
"install",
"initialization options",
"rust-analyzer",
"gopls",
"pyright",
],
projectScope: true,
component: lazyComponent(() => import("./LanguageServersPage").then((m) => m.LanguageServersPage)),
});
}
export function activate(): () => void {
const disposers = [
activateSettingsPages(),
-27
Переглянути файл
@@ -1,27 +0,0 @@
import { lazyComponent } from "@/ui";
import { registerSettingsPage } from "@/workbench/contributions";
import { SETTINGS_PAGE_ID } from "./store";
/** The Language Servers page (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPage({
id: SETTINGS_PAGE_ID,
title: "Language Servers",
group: "Languages & Frameworks",
order: 400,
keywords: [
"lsp",
"language server",
"debugger",
"adapter",
"dap",
"install",
"initialization options",
"rust-analyzer",
"gopls",
"pyright",
],
projectScope: true,
component: lazyComponent(() => import("./LanguageServersPage").then((m) => m.LanguageServersPage)),
});
}
+10 -15
Переглянути файл
@@ -67,7 +67,7 @@ import {
import { applyStash, commitChanges, deleteFiles, dropStash, showUnstashDialog, stashChanges } from "./changeOps";
import { CommitOptionsPopup } from "./CommitOptions";
import { DEFAULT_LIST_NAME, useChangelists, withListDefaults } from "./changelists";
import { inclusionChecks, isCommitAll, stagingAreaOn, useStagingArea } from "./staging";
import { inclusionChecks, isCommitAll, useStagingArea } from "./staging";
import { addToChangelist, commitFiles } from "./changelistsUi";
import { acceptSide } from "./conflictsUi";
import { copyChangesAsPatch } from "./patches";
@@ -345,20 +345,15 @@ export function nodeMenu(
{ kind: "separator" as const },
]
: []),
// With the staging area a commit takes the whole index: there is no committing one file.
...(stagingAreaOn()
? []
: [
{
label: "Commit File…",
icon: "commit" as const,
disabled: !files.some((f) => groupOf(f) === "changes"),
run: () => commitFiles(paths),
},
{ kind: "separator" as const },
]),
// The node itself, like double-click: under Staged or Unstaged its side of the index.
opts?.roots && first
{
label: "Commit File…",
icon: "commit",
disabled: !files.some((f) => groupOf(f) === "changes"),
run: () => commitFiles(paths),
},
{ kind: "separator" },
// Under the modal interface the node itself, like double-click, in the front window.
vcsDiffInFront() && opts?.roots && first
? {
label: "Show Diff",
icon: "diff",
+1 -14
Переглянути файл
@@ -23,9 +23,6 @@ const isLabel = (e: HistoryEntry) => e.kind === "label";
const time = (e: HistoryEntry) => e.timestampMs ?? 0;
/** Per file, the newest snapshot recorded before `at` (the state at a label). */
/** The backend's label of the snapshot taken when a file is deleted (`ide-workspace::history::DELETED`). */
const DELETED = "Deleted";
export function snapshotsBefore(entries: readonly HistoryEntry[], at: number): Map<string, HistoryEntry> {
const out = new Map<string, HistoryEntry>();
for (const e of entries) {
@@ -116,17 +113,7 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
);
return;
}
// A file whose last revision before the label is its deletion was absent then: nothing to restore.
const recorded = view.folder ? [...(atLabel?.values() ?? [])] : fileAtLabel ? [fileAtLabel] : [];
const targets = recorded.filter((e) => e.label !== DELETED);
if (!view.folder && fileAtLabel?.label === DELETED) {
notifications().notify({
level: "info",
title: tx`${baseName(path)} did not exist at label '${current.label}'`,
key: "localHistory.revert",
});
return;
}
const targets = view.folder ? [...(atLabel?.values() ?? [])] : fileAtLabel ? [fileAtLabel] : [];
if (!targets.length) {
notifications().notify({
level: "info",
-14
Переглянути файл
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import type { Branch } from "@/bindings";
import {
branchFolderKeys,
branchNamePrefixes,
buildBranchRows,
buildBranchTree,
filterBranchTree,
@@ -184,19 +183,6 @@ describe("buildBranchRows", () => {
});
});
describe("branchNamePrefixes", () => {
it("lists local branch folders shallowest first, once each, without remote ones", () => {
const prefixes = branchNamePrefixes([
b("feat/2610/08/login"),
b("feat/2610/signup"),
b("fix/crash"),
b("main"),
b("origin/release/1.0"),
]);
expect(prefixes).toEqual(["feat/", "fix/", "feat/2610/", "feat/2610/08/"]);
});
});
describe("pushRecent", () => {
it("moves a branch to the front without duplicates", () => {
expect(pushRecent(["a", "b", "c"], "b")).toEqual(["b", "a", "c"]);
+2 -6
Переглянути файл
@@ -294,14 +294,10 @@ describe("Changes tree diffs follow the commit interface setting (#1863)", () =>
expect(openFile).not.toHaveBeenCalled();
});
// The row's own diff (under Staged or Unstaged, its side of the index), in an editor tab.
it("opens the node's diff in an editor tab with the non-modal interface", async () => {
it("keeps the Show Diff action item with the non-modal interface", () => {
modal(false);
const menu = nodeMenu([node], ["/p"], { roots: [node] });
const show = menu.find((m) => m.kind !== "separator" && "label" in m && m.label === "Show Diff");
(show as { run: () => void }).run();
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(1));
expect(openDiffDialog).not.toHaveBeenCalled();
expect(menu).toContainEqual({ kind: "action", action: "vcs.showDiff", arg: "/p/src/a.ts" });
});
});
+6 -5
Переглянути файл
@@ -95,14 +95,15 @@ describe("Local History", () => {
expect(list).toHaveTextContent("src/gone.ts");
expect(screen.getByText(/Label 'Before Git checkout' · 2 files recorded before it/)).toBeInTheDocument();
// Revert at the label restores every file's last revision before it; a file
// deleted before the label was absent then and stays absent.
// Revert at the label restores every file's last revision before it.
fireEvent.click(screen.getByRole("button", { name: "Revert" }));
const confirm = await screen.findByRole("dialog", { name: "Revert" });
expect(confirm).toHaveTextContent("Revert 1 files under src to label 'Before Git checkout'?");
fireEvent.click(within(confirm).getByRole("button", { name: "Revert" }));
await waitFor(() => expect(historyRestore).toHaveBeenCalledTimes(1));
expect(historyRestore).toHaveBeenCalledWith("/p/src/a.ts", id("e"));
await waitFor(() => expect(historyRestore).toHaveBeenCalledTimes(2));
expect(historyRestore.mock.calls.map((c) => c.join(" ")).sort()).toEqual([
`/p/src/a.ts ${id("e")}`,
`/p/src/gone.ts ${id("d")}`,
]);
// A deleted file's row offers Restore.
fireEvent.click(within(list).getAllByRole("option")[1]!);
-32
Переглянути файл
@@ -1,32 +0,0 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { BranchInfo } from "@/bindings";
import { installOperationNoticeExpiry } from "../operations";
import { useVcs } from "../store";
const { expire } = vi.hoisted(() => ({ expire: vi.fn() }));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify: vi.fn(), expire }),
}));
const branch = (operation: string | null) => ({ head: "main", operation }) as unknown as BranchInfo;
let dispose: () => void;
beforeEach(() => {
expire.mockClear();
useVcs.setState({ branch: branch("merge") });
dispose = installOperationNoticeExpiry();
});
afterEach(() => dispose());
it("expires the conflict notice once the merge it offers to commit or abort is over", () => {
useVcs.setState({ branch: branch("merge") });
expect(expire).not.toHaveBeenCalled();
useVcs.setState({ branch: branch(null) });
expect(expire).toHaveBeenCalledWith("vcs.conflicts");
});
it("keeps it while an operation is still in progress", () => {
useVcs.setState({ branch: branch("rebase") });
expect(expire).not.toHaveBeenCalled();
});
-33
Переглянути файл
@@ -18,7 +18,6 @@ import { useChangelists } from "../changelists";
import { useCommit } from "../commitStore";
import { inclusionChecks, isCommitAll, stagingChecks } from "../staging";
import { useVcs } from "../store";
import { provideEditorService } from "@/workbench/contributions";
const file = (rel: string, staged: FileStatus["staged"], unstaged: FileStatus["unstaged"]): FileStatus => ({
path: `/p/${rel}`,
@@ -130,38 +129,6 @@ describe("staging operations of the tree's nodes", () => {
enabled(nodeMenu([underUnstaged], []), "Unstage"),
]).toEqual([true, false]);
});
it("shows a row's side of the index from Show Diff: HEAD ↔ Index under Staged, Index ↔ working copy under Unstaged", async () => {
useSettings(true);
const openInput = vi.fn(async () => undefined);
provideEditorService({ openInput } as never);
const show = (node: (typeof roots)[number]) => {
const menu = nodeMenu([node], [], { roots });
(menu.find((m) => "label" in m && m.label === "Show Diff") as { run: () => void }).run();
};
const sides = () => {
const data = (openInput.mock.calls.at(-1) as unknown as [{ data: { left: unknown; right: unknown } }])[0].data;
return [data.left, data.right];
};
show(group("staged").children!.find((n) => n.label === "Partial.kt")!);
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(1));
expect(sides()).toEqual([
{ type: "rev", rev: "HEAD" },
{ type: "rev", rev: ":0", label: "Index" },
]);
show(group("unstaged").children!.find((n) => n.label === "Partial.kt")!);
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(2));
expect(sides()).toEqual([{ type: "rev", rev: ":0", label: "Index" }, { type: "worktree" }]);
});
it("has no Commit File…: a commit takes the whole index", () => {
useSettings(true);
const labels = (items: MenuItem[]) => items.map((i) => ("label" in i ? i.label : null));
for (const node of [group("staged").children![0]!, group("unstaged").children![0]!])
expect(labels(nodeMenu([node], []))).not.toContain("Commit File…");
useSettings(false);
expect(labels(nodeMenu([group("unstaged").children![0]!], []))).toContain("Commit File…");
});
});
describe("the Commit tool window with the staging area", () => {
+5 -10
Переглянути файл
@@ -60,7 +60,6 @@ import {
showWorktrees,
} from "./gitMenuDialogs";
import { currentRepo, refreshNow, repoName, repoOf, statusOf, useVcs } from "./store";
import { stagingAreaOn } from "./staging";
import { showSyncCommitsForCurrent } from "./SyncCommitsPopup";
import { tx } from "@/platform/i18n";
@@ -434,24 +433,21 @@ export function registerVcsActions(): () => void {
}
if (await showDirectoryWorkingDiff(paths)) return;
const state = useVcs.getState();
// The tree the Commit tool window shows: with the staging area, Staged / Unstaged and no lists.
const staging = stagingAreaOn();
const tree = buildChangeTree(
state.status,
state.root ?? "",
useCommit.getState().groupByDir,
staging ? undefined : useChangelists.getState().state,
useChangelists.getState().state,
state.roots,
useCommit.getState().groupByStaging || staging,
useCommit.getState().groupByStaging,
undefined,
useCommit.getState().groupByRepo,
useCommit.getState().showUnversionedSeparately,
);
// The selected rows while the tree has focus: a file under Staged or Unstaged diffs that side.
const targets = showDiffTargets(tree, paths, !argPaths(arg)?.length && commitWindowFocused());
// The modal interface has one front diff window (#1863): a file with its group
// as the F7 chain, or several selected files as the chain.
if (isModalCommit()) {
const targets = showDiffTargets(tree, paths, !argPaths(arg)?.length && commitWindowFocused());
const [first] = targets;
const data =
targets.length > 1
@@ -465,9 +461,8 @@ export function registerVcsActions(): () => void {
await openVcsDiff({ ...data, line });
return;
}
for (const target of targets.slice(0, 5)) {
const data = typeof target === "string" ? groupDiffData(tree, target) : changeNodeDiffData(tree, target);
await openDiff({ ...data, line }, { preview: targets.length === 1 });
for (const path of paths.slice(0, 5)) {
await openDiff({ ...groupDiffData(tree, path), line }, { preview: paths.length === 1 });
}
},
},
+1 -2
Переглянути файл
@@ -5,7 +5,7 @@ import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { ask } from "@/workbench/messages";
import { branchNamePrefixes, isFavoriteBranch, pushRecent, shortRemoteName } from "./branches";
import { isFavoriteBranch, pushRecent, shortRemoteName } from "./branches";
import { showCommitRange } from "./CompareBranches";
import { confirmDialog, promptText } from "./dialogs";
import { cleanUpBranchNameOnTyping } from "@/platform/gitRefName";
@@ -199,7 +199,6 @@ export async function newBranch(from?: string, repo = currentRepo()) {
label: "New branch name:",
// Kept even when that branch exists (the current one always does): the user edits it.
initial: suggestion,
prefixes: branchNamePrefixes(branches),
mono: true,
okLabel: "Create",
sanitize: cleanUpBranchNameOnTyping,
-17
Переглянути файл
@@ -176,23 +176,6 @@ export function shortRemoteName(name: string): string {
return i < 0 ? name : name.slice(i + 1);
}
/**
* The folders of local branch names, shallowest first (`feat/ui/login` contributes `feat/` and
* `feat/ui/`): what the New Branch dialog suggests while typing. Remote branches are left out.
*/
export function branchNamePrefixes(branches: readonly Branch[]): string[] {
const prefixes = new Map<string, number>();
for (const branch of branches) {
if (branch.remote) continue;
const name = branch.name;
let depth = 1;
for (let slash = name.indexOf("/"); slash !== -1; slash = name.indexOf("/", slash + 1)) {
prefixes.set(name.slice(0, slash + 1), depth++);
}
}
return [...prefixes.keys()].sort((a, b) => prefixes.get(a)! - prefixes.get(b)! || a.localeCompare(b));
}
export const MAX_RECENT = 5;
/** Recently checked-out local branches other than the current one, newest first. */
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more