дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-19 08:05:40 +02:00
Порівняти коміти
14
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
4189dc9b83 | ||
|
|
27fdbe71e5 | ||
|
|
d5cd5e7a55 | ||
|
|
c32a68c0b8 | ||
|
|
59cc84521f | ||
|
|
4faa37aaea | ||
|
|
aaf25d9f0d | ||
|
|
913ad6616c | ||
|
|
b80f0f9e39 | ||
|
|
460027fd4b | ||
|
|
33c5627bdb | ||
|
|
3a22a2d0f0 | ||
|
|
c169b8ab3c | ||
|
|
0dbce5d09e |
No files matched your search
@@ -159,6 +159,15 @@ pub async fn doc_highlights(host: &Host, window: &str, doc: DocId) -> IdeResult<
|
||||
.await
|
||||
}
|
||||
|
||||
/// Python class facts the inheritance inspections read: base names as written, a method's
|
||||
/// parameters, decorator semantics and its body shape. Tree-sitter answers; no LSP.
|
||||
pub async fn doc_python_facts(host: &Host, window: &str, doc: DocId) -> IdeResult<ide_language::PythonFacts> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
let snap = project.documents.text_snapshot(doc)?;
|
||||
blocking(move || Ok(syntax.python_facts(&snap.language, &snap.text))).await
|
||||
}
|
||||
|
||||
/// Extend Selection (⌥↑): syntax ranges around `offset`, innermost first.
|
||||
/// Large documents fall back to word / line / document ranges.
|
||||
pub async fn doc_selection_ranges(host: &Host, window: &str, doc: DocId, offset: u32) -> IdeResult<Vec<Range>> {
|
||||
@@ -208,6 +217,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("doc_outline", |c| async move { doc_outline(&c.host, &c.window, c.arg("doc")?).await });
|
||||
d.add("doc_folding", |c| async move { doc_folding(&c.host, &c.window, c.arg("doc")?).await });
|
||||
d.add("doc_highlights", |c| async move { doc_highlights(&c.host, &c.window, c.arg("doc")?).await });
|
||||
d.add("doc_python_facts", |c| async move { doc_python_facts(&c.host, &c.window, c.arg("doc")?).await });
|
||||
d.add("doc_selection_ranges", |c| async move {
|
||||
doc_selection_ranges(&c.host, &c.window, c.arg("doc")?, c.arg("offset")?).await
|
||||
});
|
||||
|
||||
@@ -1472,6 +1472,15 @@ pub async fn lsp_type_hierarchy(
|
||||
host.project(window)?.lsp.type_hierarchy(doc, pos, direction).await
|
||||
}
|
||||
|
||||
pub async fn lsp_prepare_type_hierarchy(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<Option<HierarchyItem>> {
|
||||
host.project(window)?.lsp.prepare_type_hierarchy(doc, pos).await
|
||||
}
|
||||
|
||||
pub fn lsp_servers(host: &Host, window: &str) -> IdeResult<Vec<ServerInfo>> {
|
||||
Ok(host.project(window)?.lsp.servers())
|
||||
}
|
||||
@@ -1856,6 +1865,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("lsp_type_hierarchy", |c| async move {
|
||||
lsp_type_hierarchy(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?, c.arg("direction")?).await
|
||||
});
|
||||
d.add("lsp_prepare_type_hierarchy", |c| async move {
|
||||
lsp_prepare_type_hierarchy(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?).await
|
||||
});
|
||||
d.add("lsp_servers", |c| async move { lsp_servers(&c.host, &c.window) });
|
||||
d.add("lsp_resend_diagnostics", |c| async move { lsp_resend_diagnostics(&c.host, &c.window) });
|
||||
d.add("lsp_restart", |c| async move { lsp_restart(&c.host, &c.window, c.arg("server")?).await });
|
||||
|
||||
@@ -1458,7 +1458,7 @@ fn content_root_watcher(
|
||||
) -> Option<Watcher> {
|
||||
let (kotlin_bridge, phpstan) = (kotlin_bridge.cloned(), phpstan.cloned());
|
||||
let (index, documents, history, lsp) = (index.clone(), documents.clone(), history.clone(), lsp.clone());
|
||||
let root = dir.to_path_buf();
|
||||
let (root, events) = (dir.to_path_buf(), sink.clone());
|
||||
Watcher::start(
|
||||
dir,
|
||||
excludes.to_vec(),
|
||||
@@ -1480,6 +1480,11 @@ fn content_root_watcher(
|
||||
}
|
||||
documents.on_disk_changed(&[&changed[..], &ignored].concat());
|
||||
record_external_changes(&history, &changed, &batch.removed);
|
||||
// A member outside the project folder: its repository changes (commit, checkout,
|
||||
// fetch, pull) reach the UI only through this watcher.
|
||||
if batch.vcs.iter().any(|p| vcs_path_changed(p)) {
|
||||
events.emit(IdeEvent::VcsChanged { root: root.clone().into() });
|
||||
}
|
||||
}),
|
||||
)
|
||||
.map_err(|e| tracing::warn!("content root watcher {}: {e}", dir.display()))
|
||||
|
||||
@@ -28,6 +28,7 @@ pub use syntax::{
|
||||
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
pub use syntax::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
|
||||
@@ -43,7 +43,7 @@ fn extract(tree: &Tree, text: &str) -> Vec<ClassBases> {
|
||||
// Selection-range start of the class: its name identifier (`class Foo`
|
||||
// -> `Foo`), matching `outline.rs` and the gutter marker candidates.
|
||||
let range = idx.range(name_node.start_byte(), name_node.end_byte());
|
||||
let bases = node.child_by_field_name("superclasses").map(|args| base_names(args, text)).unwrap_or_default();
|
||||
let bases = class_base_names(node, text);
|
||||
out.push(ClassBases { name, line: range.start.line, col: range.start.col, bases });
|
||||
});
|
||||
out
|
||||
@@ -67,6 +67,11 @@ fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bare base names a `class_definition` node writes (keyword arguments left out).
|
||||
pub(super) fn class_base_names(node: Node, text: &str) -> Vec<String> {
|
||||
node.child_by_field_name("superclasses").map(|args| base_names(args, text)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn base_names(args: Node, text: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = args.walk();
|
||||
|
||||
@@ -10,6 +10,7 @@ mod inheritance;
|
||||
pub(crate) mod lines;
|
||||
mod literals;
|
||||
mod outline;
|
||||
mod python_facts;
|
||||
mod rst;
|
||||
mod selection;
|
||||
mod sfc;
|
||||
@@ -27,6 +28,7 @@ pub use inheritance::ClassBases;
|
||||
pub use lines::{shift_pos, shift_range};
|
||||
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
|
||||
pub use outline::merge_visibility;
|
||||
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -0,0 +1,438 @@
|
||||
//! Python class facts the inheritance inspections need: base names as written, parameter
|
||||
//! lists, decorator semantics and what a method body does. They come from the syntax tree in
|
||||
//! one pass, so the frontend reasons about the inheritance graph without parsing source text.
|
||||
//!
|
||||
//! Deliberately small: a fact exists here only when a check can decide it without guessing.
|
||||
|
||||
use super::lines::LineIndex;
|
||||
use crate::{LanguageId, Syntax};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use tree_sitter::{Node, Tree};
|
||||
|
||||
/// One Python module's classes, in source order.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PythonFacts {
|
||||
pub classes: Vec<PythonClassFacts>,
|
||||
}
|
||||
|
||||
/// A class definition and the methods it declares.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PythonClassFacts {
|
||||
pub name: String,
|
||||
/// The class name identifier (selection range).
|
||||
pub selection: crate::Range,
|
||||
/// Base names as written, a qualified name reduced to its last segment.
|
||||
pub bases: Vec<String>,
|
||||
pub methods: Vec<PythonMethodFacts>,
|
||||
}
|
||||
|
||||
/// A method definition the inspections can reason about.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PythonMethodFacts {
|
||||
pub name: String,
|
||||
/// The method name identifier (selection range).
|
||||
pub selection: crate::Range,
|
||||
/// Parameter names in order; `None` for a form whose forwarding cannot be compared
|
||||
/// (`*args`, `**kwargs`, keyword-only, positional-only).
|
||||
pub params: Option<Vec<String>>,
|
||||
/// Decorated with `abstractmethod` (`abc.abstractmethod` included).
|
||||
pub abstract_method: bool,
|
||||
/// Decorated with `override` from `typing` / `typing_extensions`.
|
||||
pub override_decorated: bool,
|
||||
pub body: MethodBody,
|
||||
}
|
||||
|
||||
/// What a method body does, for the shapes a check can decide without guessing.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", tag = "kind")]
|
||||
pub enum MethodBody {
|
||||
/// `pass`, `...`, a docstring, or nothing at all.
|
||||
Empty,
|
||||
/// Exactly one `super().name(args)` call, optionally `return`ed.
|
||||
SuperCall { returns: bool, target: String, args: Vec<String> },
|
||||
/// Anything else.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Syntax {
|
||||
/// The classes of a Python `text` with the facts the inheritance checks need.
|
||||
/// Every other language returns an empty result.
|
||||
pub fn python_facts(&self, lang: &LanguageId, text: &str) -> PythonFacts {
|
||||
self.analyze(lang, text, |g, tree, text| (g.spec.name == "python").then(|| extract(tree, text)))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
fn extract(tree: &Tree, text: &str) -> PythonFacts {
|
||||
let idx = LineIndex::new(text);
|
||||
let imports = ImportBindings::collect(tree, text);
|
||||
let mut classes = Vec::new();
|
||||
let mut cursor = tree.walk();
|
||||
visit(&mut cursor, &mut |node| {
|
||||
if node.kind() != "class_definition" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else { return };
|
||||
let name = text_of(name_node, text);
|
||||
if name.is_empty() {
|
||||
return;
|
||||
}
|
||||
classes.push(PythonClassFacts {
|
||||
name,
|
||||
selection: idx.range(name_node.start_byte(), name_node.end_byte()),
|
||||
bases: super::inheritance::class_base_names(node, text),
|
||||
methods: methods_of(node, text, &idx, &imports),
|
||||
});
|
||||
});
|
||||
PythonFacts { classes }
|
||||
}
|
||||
|
||||
/// The methods declared directly in `class`.
|
||||
fn methods_of(class: Node, text: &str, idx: &LineIndex, imports: &ImportBindings) -> Vec<PythonMethodFacts> {
|
||||
let Some(body) = class.child_by_field_name("body") else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = body.walk();
|
||||
for member in body.named_children(&mut cursor) {
|
||||
// A decorated method is a `decorated_definition` wrapping the `function_definition`.
|
||||
let method = match member.kind() {
|
||||
"function_definition" => member,
|
||||
"decorated_definition" => match member.child_by_field_name("definition") {
|
||||
Some(inner) if inner.kind() == "function_definition" => inner,
|
||||
_ => continue,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
let Some(name_node) = method.child_by_field_name("name") else { continue };
|
||||
let name = text_of(name_node, text);
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let decorators = decorators_of(method, text);
|
||||
out.push(PythonMethodFacts {
|
||||
name,
|
||||
selection: idx.range(name_node.start_byte(), name_node.end_byte()),
|
||||
params: parameters_of(method, text),
|
||||
abstract_method: decorators.iter().any(|d| last_segment(d) == "abstractmethod"),
|
||||
override_decorated: decorators.iter().any(|d| imports.is_typing_override(d)),
|
||||
body: body_of(method, text),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The parameter names of a `function_definition`, or `None` when the signature contains a
|
||||
/// form whose forwarding cannot be compared without guessing.
|
||||
fn parameters_of(function: Node, text: &str) -> Option<Vec<String>> {
|
||||
let params = function.child_by_field_name("parameters")?;
|
||||
let mut names = Vec::new();
|
||||
let mut cursor = params.walk();
|
||||
for param in params.named_children(&mut cursor) {
|
||||
let name = match param.kind() {
|
||||
"identifier" => text_of(param, text),
|
||||
"typed_parameter" | "default_parameter" | "typed_default_parameter" => {
|
||||
let named = param
|
||||
.child_by_field_name("name")
|
||||
.or_else(|| param.child_by_field_name("pattern"))
|
||||
.or_else(|| param.named_child(0))?;
|
||||
if named.kind() != "identifier" {
|
||||
return None;
|
||||
}
|
||||
text_of(named, text)
|
||||
}
|
||||
// `*args`, `**kwargs`, `/`, `*`: the call form cannot be compared textually.
|
||||
_ => return None,
|
||||
};
|
||||
if !name.is_empty() {
|
||||
names.push(name);
|
||||
}
|
||||
}
|
||||
Some(names)
|
||||
}
|
||||
|
||||
/// A `function_definition`'s body, classified into the shapes a check can decide.
|
||||
fn body_of(function: Node, text: &str) -> MethodBody {
|
||||
let Some(body) = function.child_by_field_name("body") else { return MethodBody::Empty };
|
||||
// A docstring is not a statement the checks care about.
|
||||
let statements: Vec<Node> = statements_of(body).into_iter().filter(|s| !is_string(*s)).collect();
|
||||
if statements.is_empty() || statements.iter().all(|s| is_noop(*s)) {
|
||||
return MethodBody::Empty;
|
||||
}
|
||||
let [only] = statements.as_slice() else { return MethodBody::Other };
|
||||
let call = match only.kind() {
|
||||
"expression_statement" => (only.named_child(0), false),
|
||||
"return_statement" => (only.named_child(0), true),
|
||||
_ => (None, false),
|
||||
};
|
||||
match call {
|
||||
(Some(call), returns) if is_super_call(call, text) => {
|
||||
let target = call
|
||||
.child_by_field_name("function")
|
||||
.and_then(|f| f.child_by_field_name("attribute"))
|
||||
.map(|a| text_of(a, text))
|
||||
.unwrap_or_default();
|
||||
let args = call
|
||||
.child_by_field_name("arguments")
|
||||
.map(|args| {
|
||||
let mut cursor = args.walk();
|
||||
args.named_children(&mut cursor).map(|a| text_of(a, text)).collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
MethodBody::SuperCall { returns, target, args }
|
||||
}
|
||||
_ => MethodBody::Other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `node` is a `super().name(...)` call.
|
||||
fn is_super_call(node: Node, text: &str) -> bool {
|
||||
if node.kind() != "call" {
|
||||
return false;
|
||||
}
|
||||
let Some(function) = node.child_by_field_name("function") else { return false };
|
||||
if function.kind() != "attribute" {
|
||||
return false;
|
||||
}
|
||||
function.child_by_field_name("object").is_some_and(|object| {
|
||||
object.kind() == "call"
|
||||
&& object
|
||||
.child_by_field_name("function")
|
||||
.is_some_and(|f| f.kind() == "identifier" && text_of(f, text) == "super")
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `statement` is `pass` or a bare `...`.
|
||||
fn is_noop(statement: Node) -> bool {
|
||||
match statement.kind() {
|
||||
"pass_statement" => true,
|
||||
"expression_statement" => statement.named_child(0).is_some_and(|child| child.kind() == "ellipsis"),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A string expression statement: a docstring.
|
||||
fn is_string(statement: Node) -> bool {
|
||||
statement.kind() == "expression_statement" && statement.named_child(0).is_some_and(|child| child.kind() == "string")
|
||||
}
|
||||
|
||||
/// The statements of a `block`, comments excluded.
|
||||
fn statements_of(block: Node) -> Vec<Node> {
|
||||
let mut cursor = block.walk();
|
||||
block.named_children(&mut cursor).filter(|child| child.kind() != "comment").collect()
|
||||
}
|
||||
|
||||
/// The decorators written on a definition, without the `@` or the call arguments.
|
||||
fn decorators_of(definition: Node, text: &str) -> Vec<String> {
|
||||
let Some(parent) = definition.parent() else { return Vec::new() };
|
||||
if parent.kind() != "decorated_definition" {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = parent.walk();
|
||||
for decorator in parent.named_children(&mut cursor) {
|
||||
if decorator.kind() != "decorator" {
|
||||
continue;
|
||||
}
|
||||
let Some(inner) = decorator.named_child(0) else { continue };
|
||||
let target =
|
||||
if inner.kind() == "call" { inner.child_by_field_name("function").unwrap_or(inner) } else { inner };
|
||||
let name = text_of(target, text).trim().to_owned();
|
||||
if !name.is_empty() {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The last segment of a dotted name (`typing.override` -> `override`).
|
||||
fn last_segment(name: &str) -> &str {
|
||||
name.rsplit('.').next().unwrap_or(name)
|
||||
}
|
||||
|
||||
fn text_of(node: Node, text: &str) -> String {
|
||||
text.get(node.byte_range()).unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
/// The module-level `from ... import ...` bindings, so `override` can be told apart from a
|
||||
/// same-named decorator of another library.
|
||||
struct ImportBindings {
|
||||
/// (local name, module, exported name)
|
||||
bindings: Vec<(String, String, String)>,
|
||||
}
|
||||
|
||||
impl ImportBindings {
|
||||
fn collect(tree: &Tree, text: &str) -> Self {
|
||||
let mut bindings = Vec::new();
|
||||
let mut cursor = tree.walk();
|
||||
visit(&mut cursor, &mut |node| {
|
||||
if node.kind() != "import_from_statement" {
|
||||
return;
|
||||
}
|
||||
let Some(module) = node.child_by_field_name("module_name") else { return };
|
||||
let module = text_of(module, text);
|
||||
let mut names = node.walk();
|
||||
for name in node.children_by_field_name("name", &mut names) {
|
||||
let (local, exported) = match name.kind() {
|
||||
"aliased_import" => (
|
||||
name.child_by_field_name("alias").map(|n| text_of(n, text)),
|
||||
name.child_by_field_name("name").map(|n| text_of(n, text)),
|
||||
),
|
||||
_ => {
|
||||
let written = text_of(name, text);
|
||||
(Some(written.clone()), Some(written))
|
||||
}
|
||||
};
|
||||
if let (Some(local), Some(exported)) = (local, exported) {
|
||||
bindings.push((local, module.clone(), exported));
|
||||
}
|
||||
}
|
||||
});
|
||||
Self { bindings }
|
||||
}
|
||||
|
||||
/// Whether `decorator` names `override` from `typing` / `typing_extensions`.
|
||||
fn is_typing_override(&self, decorator: &str) -> bool {
|
||||
const MODULES: [&str; 2] = ["typing", "typing_extensions"];
|
||||
let segments: Vec<&str> = decorator.split('.').filter(|s| !s.is_empty()).collect();
|
||||
match segments.as_slice() {
|
||||
// `@typing.override`, or `@t.override` after `import typing as t`.
|
||||
[prefix, "override"] => {
|
||||
MODULES.contains(prefix)
|
||||
|| self
|
||||
.bindings
|
||||
.iter()
|
||||
.find(|(local, _, _)| local == prefix)
|
||||
.is_some_and(|(_, module, _)| MODULES.contains(&module.as_str()))
|
||||
}
|
||||
// `@override`, or `@ov` after `from typing import override as ov`.
|
||||
[local] => match self.bindings.iter().find(|(bound, _, _)| bound == local) {
|
||||
Some((_, module, exported)) => exported == "override" && MODULES.contains(&module.as_str()),
|
||||
// Nothing contradicts a bare `@override`: the usual `from typing import *`.
|
||||
None => *local == "override",
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Depth-first pre-order traversal of all descendants of `cursor`'s node.
|
||||
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
|
||||
loop {
|
||||
f(cursor.node());
|
||||
if cursor.goto_first_child() {
|
||||
continue;
|
||||
}
|
||||
loop {
|
||||
if cursor.goto_next_sibling() {
|
||||
break;
|
||||
}
|
||||
if !cursor.goto_parent() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
static SYNTAX: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
|
||||
|
||||
fn facts(src: &str) -> PythonFacts {
|
||||
SYNTAX.get_or_init(Syntax::new).python_facts(&LanguageId::new("python"), src)
|
||||
}
|
||||
|
||||
fn method<'a>(facts: &'a PythonFacts, class: &str, method: &str) -> &'a PythonMethodFacts {
|
||||
facts
|
||||
.classes
|
||||
.iter()
|
||||
.find(|c| c.name == class)
|
||||
.and_then(|c| c.methods.iter().find(|m| m.name == method))
|
||||
.expect("method not found")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classes_carry_bases_and_methods() {
|
||||
let f = facts(
|
||||
"class Base(ABC):\n pass\n\nclass Child(Base, pkg.Mixin):\n def run(self, x=1):\n pass\n",
|
||||
);
|
||||
assert_eq!(f.classes.len(), 2);
|
||||
assert_eq!(f.classes[0].name, "Base");
|
||||
assert_eq!(f.classes[0].bases, ["ABC"]);
|
||||
assert_eq!(f.classes[1].bases, ["Base", "Mixin"]);
|
||||
assert_eq!(f.classes[1].methods.len(), 1);
|
||||
assert_eq!(f.classes[1].selection.start.line, 3);
|
||||
assert_eq!(f.classes[1].selection.start.col, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameters_are_names_in_order_and_none_for_splats() {
|
||||
let f = facts(
|
||||
"class C:\n def a(self, x: int, y=2):\n pass\n\n def b(self, *args):\n pass\n\n def c(self, *, x):\n pass\n",
|
||||
);
|
||||
assert_eq!(
|
||||
method(&f, "C", "a").params.as_deref(),
|
||||
Some(["self".to_string(), "x".to_string(), "y".to_string()].as_slice())
|
||||
);
|
||||
assert_eq!(method(&f, "C", "b").params, None);
|
||||
assert_eq!(method(&f, "C", "c").params, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_shapes_are_classified() {
|
||||
let f = facts(
|
||||
"class C:\n def noop(self):\n pass\n\n def dots(self):\n ...\n\n def doc(self):\n \"\"\"text\"\"\"\n\n def forward(self, x):\n return super().run(x)\n\n def call(self):\n super().run()\n\n def other(self):\n return 1\n",
|
||||
);
|
||||
assert_eq!(method(&f, "C", "noop").body, MethodBody::Empty);
|
||||
assert_eq!(method(&f, "C", "dots").body, MethodBody::Empty);
|
||||
assert_eq!(method(&f, "C", "doc").body, MethodBody::Empty);
|
||||
assert_eq!(
|
||||
method(&f, "C", "forward").body,
|
||||
MethodBody::SuperCall { returns: true, target: "run".into(), args: vec!["x".into()] }
|
||||
);
|
||||
assert_eq!(
|
||||
method(&f, "C", "call").body,
|
||||
MethodBody::SuperCall { returns: false, target: "run".into(), args: vec![] }
|
||||
);
|
||||
assert_eq!(method(&f, "C", "other").body, MethodBody::Other);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decorators_are_their_names_and_semantics() {
|
||||
let f = facts(
|
||||
"from abc import abstractmethod\nfrom typing import override\n\nclass C:\n @abstractmethod\n def a(self):\n pass\n\n @override\n def b(self):\n pass\n\n @functools.cache\n def c(self):\n pass\n",
|
||||
);
|
||||
assert!(method(&f, "C", "a").abstract_method);
|
||||
assert!(!method(&f, "C", "a").override_decorated);
|
||||
assert!(method(&f, "C", "b").override_decorated);
|
||||
assert!(!method(&f, "C", "c").override_decorated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn override_of_another_library_is_not_typing_override() {
|
||||
let f = facts("from mylib import override\n\nclass C:\n @override\n def a(self):\n pass\n");
|
||||
assert!(!method(&f, "C", "a").override_decorated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliased_override_and_qualified_forms_are_recognised() {
|
||||
let f = facts(
|
||||
"from typing import override as ov\n\nclass C:\n @ov\n def a(self):\n pass\n\nclass D:\n @typing_extensions.override\n def b(self):\n pass\n",
|
||||
);
|
||||
assert!(method(&f, "C", "a").override_decorated);
|
||||
assert!(method(&f, "D", "b").override_decorated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_classes_and_other_languages() {
|
||||
let f = facts("class Outer:\n class Inner:\n def m(self):\n pass\n");
|
||||
let names: Vec<&str> = f.classes.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(names, ["Outer", "Inner"]);
|
||||
let other = SYNTAX.get_or_init(Syntax::new).python_facts(&LanguageId::new("rust"), "class C {}");
|
||||
assert_eq!(other.classes.len(), 0);
|
||||
}
|
||||
}
|
||||
@@ -3097,6 +3097,21 @@ impl LspManager {
|
||||
Ok(CallHierarchy { items: out, incomplete })
|
||||
}
|
||||
|
||||
/// The type at `pos` as the server's type hierarchy names it (with its `detail`, the
|
||||
/// package for Java); `None` when there is no type there.
|
||||
pub async fn prepare_type_hierarchy(&self, doc: DocId, pos: Pos) -> IdeResult<Option<HierarchyItem>> {
|
||||
let (snap, targets) = self.doc_targets(doc, "type hierarchy", |c| c.has("typeHierarchyProvider")).await?;
|
||||
let t = &targets[0];
|
||||
let items: Option<Vec<serde_json::Value>> =
|
||||
self.call(t, "textDocument/prepareTypeHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
|
||||
let conv = self.conv(t.enc());
|
||||
Ok(items
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(convert::type_item_from_json)
|
||||
.find_map(|i| convert::type_item(&conv, &i)))
|
||||
}
|
||||
|
||||
pub async fn type_hierarchy(
|
||||
&self,
|
||||
doc: DocId,
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// One row of a process listing.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -104,16 +105,21 @@ pub struct MemoryRoot {
|
||||
}
|
||||
|
||||
/// Memory of one row of the breakdown.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProcessMemory {
|
||||
pub category: MemoryCategory,
|
||||
pub label: String,
|
||||
/// Project, run kind or similar.
|
||||
pub detail: Option<String>,
|
||||
/// The row's top process (the language server, run or terminal shell).
|
||||
pub pid: u32,
|
||||
/// Number of processes counted in this row.
|
||||
pub processes: u32,
|
||||
pub bytes: Option<u64>,
|
||||
/// CPU use since the previous measurement, in percent of one core (Activity
|
||||
/// Monitor's "% CPU"); `None` on the first measurement of every process.
|
||||
pub cpu_percent: Option<f32>,
|
||||
}
|
||||
|
||||
/// Recognises WebView helpers that are our children (WebKitGTK, WebView2).
|
||||
@@ -137,17 +143,21 @@ pub fn attribute(
|
||||
self_pid: u32,
|
||||
roots: &[MemoryRoot],
|
||||
footprint: impl Fn(u32) -> Option<u64>,
|
||||
mut cpu: impl FnMut(u32) -> Option<f32>,
|
||||
) -> Vec<ProcessMemory> {
|
||||
let mut claimed = HashSet::from([self_pid]);
|
||||
let mut out = Vec::new();
|
||||
let mut push = |category, label: String, detail, pids: Vec<u32>| {
|
||||
let sizes: Vec<u64> = pids.iter().filter_map(|&p| footprint(p)).collect();
|
||||
let loads: Vec<f32> = pids.iter().filter_map(|&p| cpu(p)).collect();
|
||||
out.push(ProcessMemory {
|
||||
category,
|
||||
label,
|
||||
detail,
|
||||
pid: pids[0],
|
||||
processes: pids.len() as u32,
|
||||
bytes: (!sizes.is_empty()).then(|| sizes.iter().sum()),
|
||||
cpu_percent: (!loads.is_empty()).then(|| loads.iter().sum()),
|
||||
});
|
||||
};
|
||||
push(MemoryCategory::App, "Backend".into(), None, vec![self_pid]);
|
||||
@@ -180,6 +190,84 @@ pub fn attribute(
|
||||
out
|
||||
}
|
||||
|
||||
/// CPU load per process from the change of its CPU time between measurements.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CpuSampler {
|
||||
last: HashMap<u32, CpuSample>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct CpuSample {
|
||||
time: Duration,
|
||||
at: Instant,
|
||||
percent: Option<f32>,
|
||||
}
|
||||
|
||||
/// Shorter gaps (several windows polling at once) keep the previous value
|
||||
/// instead of measuring over a few milliseconds.
|
||||
const MIN_CPU_INTERVAL: Duration = Duration::from_millis(500);
|
||||
|
||||
impl CpuSampler {
|
||||
/// Percent of one core used by `pid` since its previous sample.
|
||||
pub fn percent(&mut self, pid: u32) -> Option<f32> {
|
||||
self.record(pid, cpu_time(pid)?, Instant::now())
|
||||
}
|
||||
|
||||
fn record(&mut self, pid: u32, time: Duration, at: Instant) -> Option<f32> {
|
||||
let percent = match self.last.get(&pid) {
|
||||
Some(prev) if at.duration_since(prev.at) < MIN_CPU_INTERVAL => return prev.percent,
|
||||
// A reused pid restarts its CPU time.
|
||||
Some(prev) if time >= prev.time => {
|
||||
Some((time - prev.time).as_secs_f32() / at.duration_since(prev.at).as_secs_f32() * 100.0)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
self.last.insert(pid, CpuSample { time, at, percent });
|
||||
percent
|
||||
}
|
||||
|
||||
/// Forgets processes that are no longer listed.
|
||||
pub fn retain(&mut self, table: &ProcessTable) {
|
||||
if !table.entries.is_empty() {
|
||||
self.last.retain(|pid, _| table.get(*pid).is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// CPU time (user + system) `pid` has used so far.
|
||||
pub fn cpu_time(pid: u32) -> Option<Duration> {
|
||||
imp::cpu_time(pid)
|
||||
}
|
||||
|
||||
/// Ends `pid` and every process it started, children first: a polite request
|
||||
/// (`SIGTERM`), then a forced kill after `grace` for whatever is still running.
|
||||
/// Refuses (returns false) unless `pid` descends from `self_pid`.
|
||||
pub fn end_process_tree(self_pid: u32, pid: u32, grace: Duration) -> bool {
|
||||
let table = ProcessTable::snapshot();
|
||||
if pid == self_pid || !table.tree(self_pid).contains(&pid) {
|
||||
return false;
|
||||
}
|
||||
let pids: Vec<u32> = table.tree(pid).into_iter().rev().collect();
|
||||
for &p in &pids {
|
||||
imp::terminate(p, false);
|
||||
}
|
||||
let deadline = Instant::now() + grace;
|
||||
loop {
|
||||
let now = ProcessTable::snapshot();
|
||||
let left: Vec<u32> = pids.iter().copied().filter(|p| now.get(*p).is_some()).collect();
|
||||
if left.is_empty() {
|
||||
return true;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
for p in left {
|
||||
imp::terminate(p, true);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes the OS attributes to `pid` (see the module docs); `None` when the
|
||||
/// process is gone or not readable.
|
||||
pub fn footprint_bytes(pid: u32) -> Option<u64> {
|
||||
@@ -262,6 +350,15 @@ mod imp {
|
||||
fn proc_pidinfo(pid: i32, flavor: i32, arg: u64, buffer: *mut c_void, size: i32) -> i32;
|
||||
fn proc_pid_rusage(pid: i32, flavor: i32, buffer: *mut c_void) -> i32;
|
||||
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
|
||||
fn mach_timebase_info(info: *mut MachTimebaseInfo) -> i32;
|
||||
fn kill(pid: i32, signal: i32) -> i32;
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct MachTimebaseInfo {
|
||||
numer: u32,
|
||||
denom: u32,
|
||||
}
|
||||
|
||||
#[link(name = "objc")]
|
||||
@@ -317,6 +414,27 @@ mod imp {
|
||||
(rc == 0).then_some(info[PHYS_FOOTPRINT_WORD])
|
||||
}
|
||||
|
||||
/// `ri_user_time + ri_system_time` (words 2 and 3), in Mach absolute time units.
|
||||
pub fn cpu_time(pid: u32) -> Option<std::time::Duration> {
|
||||
static TIMEBASE: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new();
|
||||
let &(numer, denom) = TIMEBASE.get_or_init(|| {
|
||||
let mut tb = MachTimebaseInfo::default();
|
||||
// SAFETY: `tb` is a writable mach_timebase_info_data_t.
|
||||
let ok = unsafe { mach_timebase_info(&mut tb) } == 0 && tb.denom != 0;
|
||||
if ok { (tb.numer as u64, tb.denom as u64) } else { (1, 1) }
|
||||
});
|
||||
let mut info = [0u64; 64];
|
||||
// SAFETY: `info` (512 bytes) is larger than `rusage_info_v4`.
|
||||
let rc = unsafe { proc_pid_rusage(pid as i32, RUSAGE_INFO_V4, info.as_mut_ptr().cast()) };
|
||||
let ticks = (rc == 0).then(|| info[2].saturating_add(info[3]))?;
|
||||
Some(std::time::Duration::from_nanos((ticks as u128 * numer as u128 / denom as u128) as u64))
|
||||
}
|
||||
|
||||
pub fn terminate(pid: u32, force: bool) {
|
||||
// SAFETY: plain syscall.
|
||||
unsafe { kill(pid as i32, if force { 9 } else { 15 }) };
|
||||
}
|
||||
|
||||
/// `responsibility_get_pid_responsible_for_pid` (libsystem SPI used by
|
||||
/// Activity Monitor), looked up at run time so a missing symbol only
|
||||
/// disables the fallback.
|
||||
@@ -406,6 +524,39 @@ mod imp {
|
||||
None
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
fn sysconf(name: i32) -> i64;
|
||||
fn kill(pid: i32, signal: i32) -> i32;
|
||||
}
|
||||
const SC_CLK_TCK: i32 = 2;
|
||||
|
||||
/// `utime + stime` of `/proc/<pid>/stat` (fields 14 and 15, in clock ticks).
|
||||
fn stat_ticks(text: &str) -> Option<u64> {
|
||||
let mut rest = text.get(text.rfind(')')? + 1..)?.split_whitespace().skip(11);
|
||||
Some(rest.next()?.parse::<u64>().ok()? + rest.next()?.parse::<u64>().ok()?)
|
||||
}
|
||||
|
||||
pub fn cpu_time(pid: u32) -> Option<std::time::Duration> {
|
||||
static HZ: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
// SAFETY: plain libc call.
|
||||
let hz =
|
||||
*HZ.get_or_init(|| u64::try_from(unsafe { sysconf(SC_CLK_TCK) }).ok().filter(|&h| h > 0).unwrap_or(100));
|
||||
let ticks = stat_ticks(&std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?)?;
|
||||
Some(std::time::Duration::from_nanos(ticks * 1_000_000_000 / hz))
|
||||
}
|
||||
|
||||
pub fn terminate(pid: u32, force: bool) {
|
||||
// SAFETY: plain syscall.
|
||||
unsafe { kill(pid as i32, if force { 9 } else { 15 }) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn reads_cpu_ticks_from_stat() {
|
||||
let text = "7 (a (b) c) S 3 7 7 0 -1 4194560 100 0 0 0 250 50 0 0 20 0 1 0";
|
||||
assert_eq!(stat_ticks(text), Some(300));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn parses_stat_with_parens_in_name() {
|
||||
@@ -463,8 +614,18 @@ mod imp {
|
||||
fn CloseHandle(handle: *mut c_void) -> i32;
|
||||
fn OpenProcess(access: u32, inherit: i32, pid: u32) -> *mut c_void;
|
||||
fn K32GetProcessMemoryInfo(process: *mut c_void, counters: *mut c_void, cb: u32) -> i32;
|
||||
fn GetProcessTimes(
|
||||
process: *mut c_void,
|
||||
creation: *mut u64,
|
||||
exit: *mut u64,
|
||||
kernel: *mut u64,
|
||||
user: *mut u64,
|
||||
) -> i32;
|
||||
fn TerminateProcess(process: *mut c_void, code: u32) -> i32;
|
||||
}
|
||||
|
||||
const PROCESS_TERMINATE: u32 = 0x1;
|
||||
|
||||
pub fn list_processes() -> Vec<ProcEntry> {
|
||||
// SAFETY: plain Win32 call; the handle is closed below.
|
||||
let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
|
||||
@@ -507,6 +668,34 @@ mod imp {
|
||||
(ok != 0).then_some(c.PrivateUsage as u64)
|
||||
}
|
||||
|
||||
/// Kernel + user time from `GetProcessTimes` (100 ns units).
|
||||
pub fn cpu_time(pid: u32) -> Option<std::time::Duration> {
|
||||
// SAFETY: plain Win32 call; the handle is closed below.
|
||||
let h = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
|
||||
if h.is_null() {
|
||||
return None;
|
||||
}
|
||||
let (mut creation, mut exit, mut kernel, mut user) = (0u64, 0u64, 0u64, 0u64);
|
||||
// SAFETY: `h` is a process handle; the FILETIMEs are written as u64s.
|
||||
let ok = unsafe { GetProcessTimes(h, &mut creation, &mut exit, &mut kernel, &mut user) };
|
||||
// SAFETY: `h` came from OpenProcess.
|
||||
unsafe { CloseHandle(h) };
|
||||
(ok != 0).then(|| std::time::Duration::from_nanos(kernel.saturating_add(user).saturating_mul(100)))
|
||||
}
|
||||
|
||||
/// Windows has no polite request for a console process; both steps terminate it.
|
||||
pub fn terminate(pid: u32, _force: bool) {
|
||||
// SAFETY: plain Win32 call; the handle is closed below.
|
||||
let h = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) };
|
||||
if h.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: `h` is a process handle opened with PROCESS_TERMINATE.
|
||||
unsafe { TerminateProcess(h, 1) };
|
||||
// SAFETY: `h` came from OpenProcess.
|
||||
unsafe { CloseHandle(h) };
|
||||
}
|
||||
|
||||
pub fn responsible_pid(_pid: u32) -> Option<u32> {
|
||||
None
|
||||
}
|
||||
@@ -522,6 +711,10 @@ mod imp {
|
||||
pub fn footprint_bytes(_pid: u32) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
pub fn cpu_time(_pid: u32) -> Option<std::time::Duration> {
|
||||
None
|
||||
}
|
||||
pub fn terminate(_pid: u32, _force: bool) {}
|
||||
pub fn responsible_pid(_pid: u32) -> Option<u32> {
|
||||
None
|
||||
}
|
||||
@@ -589,7 +782,7 @@ mod tests {
|
||||
// Already counted under rust-analyzer: no row.
|
||||
root(301, MemoryCategory::Process, "dup", true),
|
||||
];
|
||||
let rows = attribute(&t, 100, &roots, mb);
|
||||
let rows = attribute(&t, 100, &roots, mb, |pid| (pid == 300 || pid == 301).then_some(25.0));
|
||||
let summary: Vec<(MemoryCategory, &str, u32, Option<u64>)> =
|
||||
rows.iter().map(|r| (r.category, r.label.as_str(), r.processes, r.bytes)).collect();
|
||||
assert_eq!(
|
||||
@@ -606,17 +799,56 @@ mod tests {
|
||||
]
|
||||
);
|
||||
assert_eq!(rows[2].detail.as_deref(), Some("idea"));
|
||||
let pids: Vec<u32> = rows.iter().map(|r| r.pid).collect();
|
||||
assert_eq!(pids, vec![100, 700, 200, 300, 400, 500, 600]);
|
||||
assert_eq!(rows[3].cpu_percent, Some(50.0));
|
||||
assert_eq!(rows[2].cpu_percent, None);
|
||||
assert!(!rows.iter().any(|r| r.label == "Safari"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_rows_have_no_bytes() {
|
||||
let t = table();
|
||||
let rows = attribute(&t, 100, &[root(401, MemoryCategory::Process, "cargo", false)], mb);
|
||||
let rows = attribute(&t, 100, &[root(401, MemoryCategory::Process, "cargo", false)], mb, |_| None);
|
||||
let cargo = rows.iter().find(|r| r.label == "cargo").unwrap();
|
||||
assert_eq!((cargo.processes, cargo.bytes), (1, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_percent_comes_from_the_change_in_cpu_time() {
|
||||
let mut s = CpuSampler::default();
|
||||
let t0 = Instant::now();
|
||||
let ms = Duration::from_millis;
|
||||
assert_eq!(s.record(7, ms(1000), t0), None, "first sample has nothing to compare with");
|
||||
assert_eq!(s.record(7, ms(1500), t0 + ms(1000)), Some(50.0));
|
||||
assert_eq!(s.record(7, ms(1900), t0 + ms(1100)), Some(50.0), "too soon: previous value");
|
||||
assert_eq!(s.record(7, ms(3500), t0 + ms(2000)), Some(200.0), "two busy cores");
|
||||
assert_eq!(s.record(7, ms(10), t0 + ms(3000)), None, "pid reused by a new process");
|
||||
s.retain(&ProcessTable::from_entries([e(8, 1, "other")]));
|
||||
assert_eq!(s.record(7, ms(500), t0 + ms(4000)), None, "forgotten once unlisted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ends_only_descendants() {
|
||||
let me = std::process::id();
|
||||
assert!(!end_process_tree(me, me, Duration::ZERO));
|
||||
assert!(!end_process_tree(me, 1, Duration::ZERO));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn ends_a_child_and_its_children() {
|
||||
let mut child = std::process::Command::new("sh").args(["-c", "sleep 30 & wait"]).spawn().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while ProcessTable::snapshot().children(child.id()).is_empty() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let sleeper = ProcessTable::snapshot().children(child.id())[0];
|
||||
assert!(end_process_tree(std::process::id(), child.id(), Duration::from_secs(2)));
|
||||
assert!(child.wait().is_ok());
|
||||
assert!(ProcessTable::snapshot().get(sleeper).is_none(), "grandchild ended too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measures_this_process() {
|
||||
if cfg!(any(target_os = "macos", target_os = "linux", windows)) {
|
||||
@@ -625,6 +857,13 @@ mod tests {
|
||||
assert!(t.get(me).is_some(), "own pid listed");
|
||||
let bytes = footprint_bytes(me).expect("own footprint");
|
||||
assert!(bytes > 1 << 16 && bytes < 1 << 40, "{bytes}");
|
||||
let before = cpu_time(me).expect("own CPU time");
|
||||
let spin = Instant::now();
|
||||
while spin.elapsed() < Duration::from_millis(50) {
|
||||
std::hint::black_box(spin.elapsed());
|
||||
}
|
||||
let used = cpu_time(me).unwrap() - before;
|
||||
assert!(used > Duration::from_millis(10) && used < Duration::from_secs(5), "{used:?}");
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(imp::responsible_pid(std::process::id()).is_some(), "responsibility SPI resolved");
|
||||
|
||||
@@ -136,6 +136,11 @@ buttons can act on what the user is editing.
|
||||
Toolbar buttons: `View::new(body).button(Button::new("refresh", "Refresh").icon("refresh"))`
|
||||
and `.status("12 items")`.
|
||||
|
||||
An item or button `icon` is an IDE icon name, a registered plugin icon, or a small raster image as a `data:` URI
|
||||
(`data:image/png;base64,…`; PNG, JPEG, GIF or WebP, at most 64 KiB), drawn at the icon's size: an avatar or a pipeline
|
||||
status badge. Fetch the image yourself (a `net` grant) and pass it inline; the IDE never loads URLs for an icon. Older
|
||||
hosts show the generic file icon in its place.
|
||||
|
||||
### Events
|
||||
|
||||
`ViewEvent` carries `Button(id)`, `Activate(key)` (double click or Enter), `Select(key)`,
|
||||
|
||||
@@ -126,6 +126,8 @@ register_plugin!(TodoFinder, views);
|
||||
|
||||
工具栏按钮:`View::new(body).button(Button::new("refresh", "Refresh").icon("refresh"))`,状态行:`.status("12 items")`。
|
||||
|
||||
条目和按钮的 `icon` 可以是 IDE 图标名、已注册的插件图标,或者以 `data:` URI 给出的小尺寸位图(`data:image/png;base64,…`,支持 PNG、JPEG、GIF、WebP,最大 64 KiB),按图标尺寸绘制,适合头像或流水线状态徽章。图片由插件自己获取(需要 `net` 授权)后内联传入,IDE 不会为图标加载 URL。较旧的宿主会在该位置显示通用文件图标。
|
||||
|
||||
### 事件
|
||||
|
||||
`ViewEvent` 包括 `Button(id)`、`Activate(key)`(双击或回车)、`Select(key)`、`Expand(key)`、`Collapse(key)`、
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Per-user IDE state
|
||||
/shelf/
|
||||
/changelists.json
|
||||
@@ -134,6 +134,17 @@ pub async fn doc_outline(window: Window, state: State<'_, AppState>, doc: DocId)
|
||||
ide_host::ops::doc::doc_outline(&state.host, window.label(), doc).await
|
||||
}
|
||||
|
||||
/// Python class facts for the inheritance inspections: tree-sitter, no language server.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_python_facts(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
doc: DocId,
|
||||
) -> IdeResult<ide_language::PythonFacts> {
|
||||
ide_host::ops::doc::doc_python_facts(&state.host, window.label(), doc).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_folding(window: Window, state: State<'_, AppState>, doc: DocId) -> IdeResult<Vec<FoldRange>> {
|
||||
|
||||
@@ -380,6 +380,17 @@ pub async fn lsp_call_hierarchy(
|
||||
ide_host::ops::lsp::lsp_call_hierarchy(&state.host, window.label(), request, doc, pos, direction).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn lsp_prepare_type_hierarchy(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<Option<HierarchyItem>> {
|
||||
ide_host::ops::lsp::lsp_prepare_type_hierarchy(&state.host, window.label(), doc, pos).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn lsp_type_hierarchy(
|
||||
|
||||
@@ -209,6 +209,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
doc::doc_set_bom,
|
||||
doc::doc_set_line_ending,
|
||||
doc::doc_outline,
|
||||
doc::doc_python_facts,
|
||||
doc::doc_folding,
|
||||
doc::doc_highlights,
|
||||
doc::doc_selection_ranges,
|
||||
@@ -292,6 +293,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
lsp::lsp_code_lens,
|
||||
lsp::lsp_document_links,
|
||||
lsp::lsp_call_hierarchy,
|
||||
lsp::lsp_prepare_type_hierarchy,
|
||||
lsp::lsp_type_hierarchy,
|
||||
lsp::lsp_servers,
|
||||
lsp::lsp_resend_diagnostics,
|
||||
@@ -635,6 +637,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
plugin::plugin_set_theme_frame,
|
||||
perf::app_metrics,
|
||||
perf::clear_caches,
|
||||
perf::end_process,
|
||||
analysis::inspect_code,
|
||||
analysis::analysis_locate_duplicates,
|
||||
analysis::structural_languages,
|
||||
|
||||
@@ -5,9 +5,10 @@ use crate::state::AppState;
|
||||
use ide_core::IdeResult;
|
||||
use ide_core::event::ServerStatus;
|
||||
use ide_language::SyntaxCacheStats;
|
||||
use ide_workspace::memory::{self, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
|
||||
use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use tauri::{AppHandle, State, Window};
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
@@ -55,6 +56,9 @@ fn ms(d: std::time::Duration) -> f64 {
|
||||
d.as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// CPU time of every measured process at the previous `app_metrics` call, shared by all windows.
|
||||
static CPU: LazyLock<Mutex<CpuSampler>> = LazyLock::new(Default::default);
|
||||
|
||||
/// Snapshot of process memory and subsystem sizes, summed over all projects.
|
||||
/// Async: the process walk runs on the blocking pool, not the main thread.
|
||||
#[tauri::command]
|
||||
@@ -129,7 +133,9 @@ pub async fn app_metrics(app: AppHandle, state: State<'_, AppState>) -> IdeResul
|
||||
.map(|(pid, label)| openidea_root(pid, label.into(), None)),
|
||||
);
|
||||
}
|
||||
Ok(memory::attribute(&table, me, &roots, memory::footprint_bytes))
|
||||
let mut cpu = CPU.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cpu.retain(&table);
|
||||
Ok(memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| cpu.percent(pid)))
|
||||
})
|
||||
.await?;
|
||||
Ok(m)
|
||||
@@ -219,6 +225,15 @@ pub struct ClearCachesResult {
|
||||
|
||||
/// "Clear caches": drops syntax trees and EditorConfig files of the window's
|
||||
/// project, shrinks the in-memory index and compacts its on-disk cache.
|
||||
/// Ends a process OpenIDEA started (a row of the memory breakdown) and its
|
||||
/// children; its owner (language server, run, terminal) sees it exit. Returns
|
||||
/// false for a process that isn't ours.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn end_process(pid: u32) -> IdeResult<bool> {
|
||||
blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, std::time::Duration::from_secs(3)))).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clear_caches(window: Window, state: State<'_, AppState>) -> IdeResult<ClearCachesResult> {
|
||||
|
||||
@@ -799,6 +799,9 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"toolWindowLayouts",
|
||||
"Tool Window Layouts",
|
||||
vec![
|
||||
act("layout.saveCurrent", "Save Changes in Current Layout"),
|
||||
act("layout.restoreCurrent", "Restore Current Layout"),
|
||||
SEP,
|
||||
act("layout.save", "Save Current Layout as…"),
|
||||
act("layout.restoreDefault", "Restore Default Layout"),
|
||||
SEP,
|
||||
@@ -2318,6 +2321,8 @@ mod tests {
|
||||
"view.quickSwitchScheme",
|
||||
"code.cleanup",
|
||||
"runAnything.show",
|
||||
"layout.saveCurrent",
|
||||
"layout.restoreCurrent",
|
||||
"layout.save",
|
||||
"layout.restoreDefault",
|
||||
"layout.rename",
|
||||
|
||||
+68
-1
@@ -351,6 +351,8 @@ export const commands = {
|
||||
* re-parse); large documents get no syntax structure.
|
||||
*/
|
||||
docOutline: (doc: DocId) => typedError<OutlineItem[], IdeError>(__TAURI_INVOKE("doc_outline", { doc })),
|
||||
/** Python class facts for the inheritance inspections: tree-sitter, no language server. */
|
||||
docPythonFacts: (doc: DocId) => typedError<PythonFacts, IdeError>(__TAURI_INVOKE("doc_python_facts", { doc })),
|
||||
docFolding: (doc: DocId) => typedError<FoldRange[], IdeError>(__TAURI_INVOKE("doc_folding", { doc })),
|
||||
/**
|
||||
* Tree-sitter highlighting for languages the UI has no CodeMirror mode for;
|
||||
@@ -605,6 +607,19 @@ export const commands = {
|
||||
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
|
||||
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
|
||||
lspCallHierarchy: (request: RequestId, doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<CallHierarchy, IdeError>(__TAURI_INVOKE("lsp_call_hierarchy", { request, doc, pos, direction })),
|
||||
lspPrepareTypeHierarchy: (doc: DocId, pos: Pos) => typedError<{
|
||||
name: string,
|
||||
kind: SymbolKind,
|
||||
detail: string | null,
|
||||
/** File path, or the URI of a virtual document (see `uri`). */
|
||||
path: IpcPath,
|
||||
/** Set for non-`file:` items (library classes). */
|
||||
uri?: string | null,
|
||||
range: Range,
|
||||
selectionRange: Range,
|
||||
/** Call sites, for call hierarchy. */
|
||||
fromRanges: Range[],
|
||||
} | null, IdeError>(__TAURI_INVOKE("lsp_prepare_type_hierarchy", { doc, pos })),
|
||||
lspTypeHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<HierarchyItem[], IdeError>(__TAURI_INVOKE("lsp_type_hierarchy", { doc, pos, direction })),
|
||||
lspServers: () => typedError<ServerInfo[], IdeError>(__TAURI_INVOKE("lsp_servers")),
|
||||
/** Re-emits the language servers' current diagnostics (the UI loaded after they arrived). */
|
||||
@@ -1530,11 +1545,15 @@ export const commands = {
|
||||
* Async: the process walk runs on the blocking pool, not the main thread.
|
||||
*/
|
||||
appMetrics: () => typedError<AppMetrics, IdeError>(__TAURI_INVOKE("app_metrics")),
|
||||
clearCaches: () => typedError<ClearCachesResult, IdeError>(__TAURI_INVOKE("clear_caches")),
|
||||
/**
|
||||
* "Clear caches": drops syntax trees and EditorConfig files of the window's
|
||||
* project, shrinks the in-memory index and compacts its on-disk cache.
|
||||
* Ends a process OpenIDEA started (a row of the memory breakdown) and its
|
||||
* children; its owner (language server, run, terminal) sees it exit. Returns
|
||||
* false for a process that isn't ours.
|
||||
*/
|
||||
clearCaches: () => typedError<ClearCachesResult, IdeError>(__TAURI_INVOKE("clear_caches")),
|
||||
endProcess: (pid: number) => typedError<boolean, IdeError>(__TAURI_INVOKE("end_process", { pid })),
|
||||
/**
|
||||
* Inspect Code: diagnostics of every file in `scope` that a language server
|
||||
* serves. Files stream through `on_event` as they finish; ends with `Done`.
|
||||
@@ -7567,6 +7586,15 @@ export type MergeVersions = {
|
||||
merged: string | null,
|
||||
};
|
||||
|
||||
/** What a method body does, for the shapes a check can decide without guessing. */
|
||||
export type MethodBody =
|
||||
/** `pass`, `...`, a docstring, or nothing at all. */
|
||||
{ kind: "empty" } |
|
||||
/** Exactly one `super().name(args)` call, optionally `return`ed. */
|
||||
{ kind: "superCall"; returns: boolean; target: string; args: string[] } |
|
||||
/** Anything else. */
|
||||
{ kind: "other" };
|
||||
|
||||
/** Per-function totals (a recursive function's samples count once in `total`). */
|
||||
export type MethodStat = {
|
||||
frame: number,
|
||||
@@ -8510,9 +8538,16 @@ export type ProcessMemory = {
|
||||
label: string,
|
||||
/** Project, run kind or similar. */
|
||||
detail: string | null,
|
||||
/** The row's top process (the language server, run or terminal shell). */
|
||||
pid: number,
|
||||
/** Number of processes counted in this row. */
|
||||
processes: number,
|
||||
bytes: number | null,
|
||||
/**
|
||||
* CPU use since the previous measurement, in percent of one core (Activity
|
||||
* Monitor's "% CPU"); `None` on the first measurement of every process.
|
||||
*/
|
||||
cpuPercent: number | null,
|
||||
};
|
||||
|
||||
export type Profile = {
|
||||
@@ -8776,12 +8811,44 @@ export type PullRequestSummary = {
|
||||
/** Push dialog › Push tags: every tag, or only annotated tags on the pushed commits. */
|
||||
export type PushTags = "all" | "currentBranch";
|
||||
|
||||
/** A class definition and the methods it declares. */
|
||||
export type PythonClassFacts = {
|
||||
name: string,
|
||||
/** The class name identifier (selection range). */
|
||||
selection: Range,
|
||||
/** Base names as written, a qualified name reduced to its last segment. */
|
||||
bases: string[],
|
||||
methods: PythonMethodFacts[],
|
||||
};
|
||||
|
||||
/** Python Debugger (debugpy launch options). */
|
||||
export type PythonDebuggerSettings = {
|
||||
attachSubprocess?: boolean,
|
||||
gevent?: boolean,
|
||||
};
|
||||
|
||||
/** One Python module's classes, in source order. */
|
||||
export type PythonFacts = {
|
||||
classes: PythonClassFacts[],
|
||||
};
|
||||
|
||||
/** A method definition the inspections can reason about. */
|
||||
export type PythonMethodFacts = {
|
||||
name: string,
|
||||
/** The method name identifier (selection range). */
|
||||
selection: Range,
|
||||
/**
|
||||
* Parameter names in order; `None` for a form whose forwarding cannot be compared
|
||||
* (`*args`, `**kwargs`, keyword-only, positional-only).
|
||||
*/
|
||||
params: string[] | null,
|
||||
/** Decorated with `abstractmethod` (`abc.abstractmethod` included). */
|
||||
abstractMethod: boolean,
|
||||
/** Decorated with `override` from `typing` / `typing_extensions`. */
|
||||
overrideDecorated: boolean,
|
||||
body: MethodBody,
|
||||
};
|
||||
|
||||
export type PythonPackage = {
|
||||
name: string,
|
||||
version: string,
|
||||
|
||||
@@ -619,7 +619,7 @@ export function _saveParticipants(): SaveParticipant[] {
|
||||
export async function revealRange(
|
||||
path: string,
|
||||
range: { start: { line: number; col: number }; end?: { line: number; col: number } },
|
||||
options: { preview?: boolean; focus?: boolean } = {},
|
||||
options: { preview?: boolean; focus?: boolean; external?: boolean } = {},
|
||||
): Promise<void> {
|
||||
const service = maybeEditorService();
|
||||
if (!service) return;
|
||||
|
||||
@@ -387,7 +387,7 @@ describe("EditorController", () => {
|
||||
"vcs.showHistoryForSelection",
|
||||
"vcs.rollback",
|
||||
],
|
||||
["vcs.push", "vcs.update", "vcs.fetch"],
|
||||
["vcs.push", "vcs.pull", "vcs.fetch"],
|
||||
["vcs.merge", "vcs.rebase"],
|
||||
["vcs.branches", "vcs.newBranch", "vcs.newTag", "vcs.resetHead"],
|
||||
["vcs.stash", "vcs.unstash"],
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
menuGroupItems,
|
||||
notifications,
|
||||
openFileExternally,
|
||||
opensExternally,
|
||||
resolveFileEditor,
|
||||
textEditorWrapperFor,
|
||||
uriOpenerFor,
|
||||
@@ -1085,7 +1086,7 @@ export class EditorController implements SlotHost {
|
||||
// Files opened with another application, then images/binary/huge files in a
|
||||
// contributed viewer, unless already open as text.
|
||||
if (!o.asText && !findTab(useTabs.getState(), fileKey(path))) {
|
||||
if (await openFileExternally(path)) return;
|
||||
if (o.external === false ? opensExternally(path) : await openFileExternally(path)) return;
|
||||
const viewer = await resolveFileEditor(path);
|
||||
if (viewer) {
|
||||
try {
|
||||
@@ -2067,11 +2068,11 @@ function gitMenu(path: string): MenuItem {
|
||||
{ kind: "action", action: "vcs.rollback", arg: [path], label: "Rollback…" },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.push", label: "Push…" },
|
||||
{ kind: "action", action: "vcs.update", label: "Pull…" },
|
||||
{ kind: "action", action: "vcs.pull", arg: [path], label: "Pull…" },
|
||||
{ kind: "action", action: "vcs.fetch", label: "Fetch" },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.merge" },
|
||||
{ kind: "action", action: "vcs.rebase" },
|
||||
{ kind: "action", action: "vcs.merge", arg: [path] },
|
||||
{ kind: "action", action: "vcs.rebase", arg: [path] },
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.branches", label: "Branches…" },
|
||||
{ kind: "action", action: "vcs.newBranch" },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerFileEditorProvider } from "@/workbench/contributions";
|
||||
import { registerExternalFileOpenHandler, registerFileEditorProvider } from "@/workbench/contributions";
|
||||
import { EditorController, openFilePaths, useTabs } from "./controller";
|
||||
import { createMemoryBackend } from "./backend";
|
||||
import { storeSession } from "./model/session";
|
||||
@@ -64,6 +64,17 @@ function tabFor(path: string) {
|
||||
}
|
||||
|
||||
describe("file open order", () => {
|
||||
it("leaves a file for another application unopened when external opens are off", async () => {
|
||||
const open = vi.fn(() => true);
|
||||
dispose = registerExternalFileOpenHandler({ id: "ext", matches: (p) => p === "/p/a.ts", open });
|
||||
const controller = setup();
|
||||
await controller.openFile("/p/a.ts", { focus: false, external: false });
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
expect(openFilePaths(useTabs.getState())).toEqual([]);
|
||||
await controller.openFile("/p/a.ts", { focus: false });
|
||||
expect(open).toHaveBeenCalledWith("/p/a.ts");
|
||||
});
|
||||
|
||||
it("keeps the caret and activation of a file opened while the project's session restores", async () => {
|
||||
const before = setup();
|
||||
before.restoreSession("/p");
|
||||
|
||||
@@ -269,25 +269,69 @@ export async function baseDeclarations(index: InheritanceIndex, cls: ClassInheri
|
||||
}
|
||||
|
||||
/**
|
||||
* Every ancestor of `cls`, nearest first (breadth-first, each declaration once), up to
|
||||
* `depth` levels. The order within a level follows the source's base order.
|
||||
* Standard bases that declare no method a project class could override or implement (only
|
||||
* dunders), so a chain ending in them is still fully known: `class Shape(ABC)`.
|
||||
*/
|
||||
const EMPTY_BASES: ReadonlySet<string> = new Set(["object", "ABC", "Generic", "Protocol"]);
|
||||
|
||||
/** One class `cls` inherits from, and how far up it sits (its direct bases are depth 1). */
|
||||
export interface AncestorNode {
|
||||
decl: ClassInheritance;
|
||||
depth: number;
|
||||
}
|
||||
|
||||
/** Ancestors of `cls`, and how deep the first base the project does not declare sits. */
|
||||
export interface AncestryResolution {
|
||||
/** The declarations `cls` inherits from, nearest first. */
|
||||
ancestors: AncestorNode[];
|
||||
/**
|
||||
* Depth of the shallowest base name that names no class of the project (`dict`, a library
|
||||
* class), or `Infinity` when the chain resolved completely. A rule may trust the chain up
|
||||
* to that depth only: a foreign base can declare or implement anything.
|
||||
*/
|
||||
firstUnresolvedDepth: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks `cls`'s ancestry nearest first (breadth-first, each declaration once) and reports
|
||||
* at which depth the chain leaves the project. A rule that reasons about an ancestor at
|
||||
* depth `d` is sound exactly while `firstUnresolvedDepth > d`.
|
||||
*/
|
||||
export async function ancestryResolution(
|
||||
index: InheritanceIndex,
|
||||
cls: ClassInheritance,
|
||||
depth = 8,
|
||||
): Promise<AncestryResolution> {
|
||||
const seen = new Set<string>([declarationKey(cls)]);
|
||||
const out: AncestorNode[] = [];
|
||||
let firstUnresolvedDepth = Infinity;
|
||||
let level: ClassInheritance[] = [cls];
|
||||
for (let d = 1; d <= depth && level.length; d++) {
|
||||
const next: ClassInheritance[] = [];
|
||||
for (const current of level) {
|
||||
for (const base of current.bases) {
|
||||
const found = await index.resolve(base, current.path);
|
||||
if (!found.length) {
|
||||
if (!EMPTY_BASES.has(base)) firstUnresolvedDepth = Math.min(firstUnresolvedDepth, d);
|
||||
continue;
|
||||
}
|
||||
for (const parent of found) {
|
||||
if (!seen.add(declarationKey(parent))) continue;
|
||||
out.push({ decl: parent, depth: d });
|
||||
next.push(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
level = next;
|
||||
}
|
||||
return { ancestors: out, firstUnresolvedDepth };
|
||||
}
|
||||
|
||||
/** Every ancestor of `cls`, nearest first, up to `depth` levels. */
|
||||
export async function ancestors(
|
||||
index: InheritanceIndex,
|
||||
cls: ClassInheritance,
|
||||
depth = 8,
|
||||
): Promise<ClassInheritance[]> {
|
||||
const seen = new Set<string>([declarationKey(cls)]);
|
||||
const out: ClassInheritance[] = [];
|
||||
let level = await baseDeclarations(index, cls);
|
||||
for (let d = 0; d < depth && level.length; d++) {
|
||||
const next: ClassInheritance[] = [];
|
||||
for (const parent of level) {
|
||||
if (!seen.add(declarationKey(parent))) continue;
|
||||
out.push(parent);
|
||||
next.push(...(await baseDeclarations(index, parent)));
|
||||
}
|
||||
level = next;
|
||||
}
|
||||
return out;
|
||||
return (await ancestryResolution(index, cls, depth)).ancestors.map((node) => node.decl);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
/**
|
||||
* Code analysis: Inspect Code (batch language-server diagnostics), Locate
|
||||
* Duplicates and Search / Replace Structurally.
|
||||
* Duplicates and Search / Replace Structurally, and the Python inheritance
|
||||
* inspections the IDE computes from its own graph.
|
||||
*/
|
||||
import { registerEditorContribution } from "@/editor/api";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerOverlay, registerToolWindow } from "@/workbench/contributions";
|
||||
@@ -14,12 +16,14 @@ import {
|
||||
import { AnalysisDialogHost } from "./dialogs";
|
||||
import { resetDuplicates } from "./duplicates";
|
||||
import { DuplicatesHeaderActions, DuplicatesView } from "./DuplicatesView";
|
||||
import { pythonInheritanceExtension } from "./inheritanceInspections";
|
||||
import { installInspectionProfileSync, resetInspection, runInspection } from "./inspect";
|
||||
import { defaultScope } from "./scope";
|
||||
import { InspectionHeaderActions, InspectionView, useInspectionHeaderMenu } from "./InspectionView";
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
registerEditorContribution({ id: "analysis.python-inheritance", extensions: pythonInheritanceExtension }),
|
||||
installInspectionProfileSync(),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root === prev.project?.root) return;
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
import { expect, it } from "vitest";
|
||||
import type {
|
||||
ClassInheritance,
|
||||
Diagnostic,
|
||||
MethodBody,
|
||||
OutlineItem,
|
||||
PythonClassFacts,
|
||||
PythonFacts,
|
||||
PythonMethodFacts,
|
||||
Range,
|
||||
} from "@/platform/ipc";
|
||||
import { inheritanceIndex } from "@/editor/navigation/inheritanceGraph";
|
||||
import { inheritanceDiagnostics, pythonInheritanceExtension } from "./inheritanceInspections";
|
||||
|
||||
interface MethodSpec {
|
||||
name: string;
|
||||
line: number;
|
||||
col?: number;
|
||||
params?: string[] | null;
|
||||
abstract?: boolean;
|
||||
override?: boolean;
|
||||
body?: MethodBody;
|
||||
}
|
||||
|
||||
interface ClassSpec {
|
||||
name: string;
|
||||
line: number;
|
||||
col?: number;
|
||||
/** The bases the *index* saw (defaults to `bases`). */
|
||||
indexedBases?: string[];
|
||||
bases: string[];
|
||||
methods?: MethodSpec[];
|
||||
/** Extra members (fields, properties, nested classes) the class declares. */
|
||||
members?: string[];
|
||||
}
|
||||
|
||||
const range = (line: number, col: number): Range => ({ start: { line, col }, end: { line, col: col + 1 } });
|
||||
const EMPTY: MethodBody = { kind: "empty" };
|
||||
const OTHER: MethodBody = { kind: "other" };
|
||||
const forward = (target: string, args: string[], returns = false): MethodBody => ({
|
||||
kind: "superCall",
|
||||
returns,
|
||||
target,
|
||||
args,
|
||||
});
|
||||
|
||||
const methodFacts = (spec: MethodSpec): PythonMethodFacts => ({
|
||||
name: spec.name,
|
||||
selection: range(spec.line, spec.col ?? 8),
|
||||
params: spec.params === undefined ? ["self"] : spec.params,
|
||||
abstractMethod: spec.abstract ?? false,
|
||||
overrideDecorated: spec.override ?? false,
|
||||
body: spec.body ?? EMPTY,
|
||||
});
|
||||
|
||||
const classItem = (spec: ClassSpec, col: number, methods: PythonMethodFacts[]): OutlineItem => ({
|
||||
name: spec.name,
|
||||
detail: null,
|
||||
kind: "class",
|
||||
range: range(spec.line, 0),
|
||||
selection_range: range(spec.line, col),
|
||||
children: [
|
||||
...methods.map((m): OutlineItem => ({
|
||||
name: m.name,
|
||||
detail: null,
|
||||
kind: "method",
|
||||
range: m.selection,
|
||||
selection_range: m.selection,
|
||||
children: [],
|
||||
visibility: null,
|
||||
})),
|
||||
...(spec.members ?? []).map((name): OutlineItem => ({
|
||||
name,
|
||||
detail: null,
|
||||
kind: "field",
|
||||
range: range(spec.line, 0),
|
||||
selection_range: range(spec.line, 0),
|
||||
children: [],
|
||||
visibility: null,
|
||||
})),
|
||||
],
|
||||
visibility: null,
|
||||
});
|
||||
|
||||
/** A project held as the facts, outlines and graph the inspections read. */
|
||||
class Fixture {
|
||||
private facts = new Map<string, PythonFacts>();
|
||||
private outlines = new Map<string, OutlineItem[]>();
|
||||
private graph: ClassInheritance[] = [];
|
||||
|
||||
constructor(private readonly current: string) {}
|
||||
|
||||
add(path: string, classes: readonly ClassSpec[]): this {
|
||||
const classFacts: PythonClassFacts[] = [];
|
||||
for (const spec of classes) {
|
||||
const col = spec.col ?? 6;
|
||||
const methods = (spec.methods ?? []).map(methodFacts);
|
||||
classFacts.push({ name: spec.name, selection: range(spec.line, col), bases: spec.bases, methods });
|
||||
this.graph.push({ path, line: spec.line, col, name: spec.name, bases: spec.indexedBases ?? spec.bases });
|
||||
this.outlines.set(path, [...(this.outlines.get(path) ?? []), classItem(spec, col, methods)]);
|
||||
}
|
||||
this.facts.set(path, { classes: [...(this.facts.get(path)?.classes ?? []), ...classFacts] });
|
||||
return this;
|
||||
}
|
||||
|
||||
async run(enabled?: ReadonlySet<string>): Promise<Diagnostic[]> {
|
||||
const facts = this.facts.get(this.current);
|
||||
if (!facts) throw new Error(`no fixture for ${this.current}`);
|
||||
return inheritanceDiagnostics({
|
||||
path: this.current,
|
||||
outline: this.outlines.get(this.current) ?? [],
|
||||
facts,
|
||||
index: inheritanceIndex(this.graph, { readFiles: async () => new Map() }),
|
||||
factsOf: async (path) => this.facts.get(path) ?? null,
|
||||
outlineOf: async (path) => this.outlines.get(path) ?? [],
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const codes = (diagnostics: readonly Diagnostic[]) => diagnostics.map((d) => [d.code, d.severity, d.range.start.line]);
|
||||
|
||||
/** `/p/base.py` declares the bases; `/p/a.py` holds the class under test. */
|
||||
const withBase = (child: ClassSpec, base: ClassSpec[], basePath = "/p/base.py") =>
|
||||
new Fixture("/p/a.py").add(basePath, base).add("/p/a.py", [child]);
|
||||
|
||||
it("reports circular inheritance", async () => {
|
||||
const project = new Fixture("/p/a.py").add("/p/a.py", [
|
||||
{ name: "First", line: 0, bases: ["Second"] },
|
||||
{ name: "Second", line: 4, bases: ["First"] },
|
||||
]);
|
||||
expect(codes(await project.run())).toEqual([
|
||||
["builtin:python-circular-bases", "error", 0],
|
||||
["builtin:python-circular-bases", "error", 4],
|
||||
]);
|
||||
});
|
||||
|
||||
it("accepts a legal diamond", async () => {
|
||||
const project = new Fixture("/p/a.py")
|
||||
.add("/p/base.py", [
|
||||
{ name: "Root", line: 0, bases: [] },
|
||||
{ name: "Left", line: 3, bases: ["Root"] },
|
||||
{ name: "Right", line: 6, bases: ["Root"] },
|
||||
])
|
||||
.add("/p/a.py", [{ name: "Leaf", line: 0, bases: ["Left", "Right"] }]);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports an @override no ancestor declares", async () => {
|
||||
const project = withBase(
|
||||
{ name: "C", line: 0, bases: ["Base"], methods: [{ name: "run", line: 1, override: true }] },
|
||||
[{ name: "Base", line: 0, bases: [], methods: [{ name: "other", line: 1 }] }],
|
||||
);
|
||||
expect(codes(await project.run())).toEqual([["builtin:python-override", "warning", 1]]);
|
||||
});
|
||||
|
||||
it("accepts an @override of a method, a field or a property", async () => {
|
||||
const project = withBase(
|
||||
{
|
||||
name: "C",
|
||||
line: 0,
|
||||
bases: ["Base"],
|
||||
methods: [
|
||||
{ name: "run", line: 1, override: true, body: OTHER },
|
||||
{ name: "limit", line: 3, override: true },
|
||||
{ name: "label", line: 5, override: true },
|
||||
],
|
||||
},
|
||||
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1 }], members: ["limit", "label"] }],
|
||||
);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("never reports @override on a dunder", async () => {
|
||||
const project = withBase(
|
||||
{ name: "C", line: 0, bases: ["Base"], methods: [{ name: "__eq__", line: 1, override: true }] },
|
||||
[{ name: "Base", line: 0, bases: [] }],
|
||||
);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("stays silent when a base is outside the project", async () => {
|
||||
// `dict` is not in the graph: it may declare or implement anything.
|
||||
const project = withBase(
|
||||
{
|
||||
name: "C",
|
||||
line: 0,
|
||||
bases: ["dict"],
|
||||
methods: [
|
||||
{ name: "run", line: 1, override: true },
|
||||
{ name: "go", line: 3, abstract: true },
|
||||
],
|
||||
},
|
||||
[],
|
||||
);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("knows a chain that ends in ABC or object", async () => {
|
||||
// `ABC` declares nothing a method could override, so `@override` on a method no class of
|
||||
// the chain declares is still a mistake.
|
||||
const project = withBase(
|
||||
{ name: "Circle", line: 0, bases: ["Shape"], methods: [{ name: "describ", line: 1, override: true }] },
|
||||
[{ name: "Shape", line: 0, bases: ["ABC", "object"], methods: [{ name: "describe", line: 1 }] }],
|
||||
);
|
||||
expect(codes(await project.run())).toEqual([["builtin:python-override", "warning", 1]]);
|
||||
});
|
||||
|
||||
it("reports an unimplemented abstract method", async () => {
|
||||
const project = withBase({ name: "Half", line: 0, bases: ["Base"] }, [
|
||||
{ name: "Base", line: 0, bases: [], methods: [{ name: "dispatch", line: 1, abstract: true }] },
|
||||
]);
|
||||
expect(codes(await project.run())).toEqual([["builtin:python-abstract-method", "warning", 0]]);
|
||||
});
|
||||
|
||||
it("still reports an abstract method whose declarer has a foreign base", async () => {
|
||||
// `class TokenDispatcher(ABC)` in an attached project: `ABC` is outside the graph, but
|
||||
// that cannot hide the abstract method the declarer does define.
|
||||
const project = withBase({ name: "Half", line: 0, bases: ["Base"] }, [
|
||||
{ name: "Base", line: 0, bases: ["ABC"], methods: [{ name: "dispatch", line: 1, abstract: true }] },
|
||||
]);
|
||||
expect(codes(await project.run())).toEqual([["builtin:python-abstract-method", "warning", 0]]);
|
||||
});
|
||||
|
||||
it("accepts a class that is itself abstract", async () => {
|
||||
const base = { name: "Base", line: 0, bases: [], methods: [{ name: "dispatch", line: 1, abstract: true }] };
|
||||
const declaresOwn = withBase(
|
||||
{ name: "Middle", line: 0, bases: ["Base"], methods: [{ name: "sides", line: 1, abstract: true }] },
|
||||
[base],
|
||||
);
|
||||
expect(await declaresOwn.run()).toEqual([]);
|
||||
expect(await withBase({ name: "Middle", line: 0, bases: ["Base", "ABC"] }, [base]).run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts a class that implements the abstract method", async () => {
|
||||
const project = withBase({ name: "Done", line: 0, bases: ["Base"], methods: [{ name: "dispatch", line: 1 }] }, [
|
||||
{ name: "Base", line: 0, bases: [], methods: [{ name: "dispatch", line: 1, abstract: true }] },
|
||||
]);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts a property that implements the abstract method", async () => {
|
||||
const project = withBase({ name: "Done", line: 0, bases: ["Base"], members: ["dispatch"] }, [
|
||||
{ name: "Base", line: 0, bases: [], methods: [{ name: "dispatch", line: 1, abstract: true }] },
|
||||
]);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts an abstract method an intermediate ancestor implements", async () => {
|
||||
const project = new Fixture("/p/a.py")
|
||||
.add("/p/base.py", [{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, abstract: true }] }])
|
||||
.add("/p/mid.py", [{ name: "Mid", line: 0, bases: ["Base"], methods: [{ name: "run", line: 1 }] }])
|
||||
.add("/p/a.py", [{ name: "Leaf", line: 0, bases: ["Mid"] }]);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports a redundant pass over a pass", async () => {
|
||||
const project = withBase({ name: "C", line: 0, bases: ["Base"], methods: [{ name: "run", line: 1 }] }, [
|
||||
{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1 }] },
|
||||
]);
|
||||
expect(codes(await project.run())).toEqual([["builtin:python-redundant-override", "info", 1]]);
|
||||
});
|
||||
|
||||
it("reports a redundant returned super() forward with the same arguments", async () => {
|
||||
const project = withBase(
|
||||
{
|
||||
name: "C",
|
||||
line: 0,
|
||||
bases: ["Base"],
|
||||
methods: [{ name: "run", line: 1, params: ["self", "speed"], body: forward("run", ["speed"], true) }],
|
||||
},
|
||||
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, params: ["self", "speed"], body: OTHER }] }],
|
||||
);
|
||||
expect(codes(await project.run())).toEqual([["builtin:python-redundant-override", "info", 1]]);
|
||||
});
|
||||
|
||||
it("still reports a redundant forward whose declarer has a foreign base", async () => {
|
||||
// The declarer inherits from `ABC` outside the graph; it still decides what runs.
|
||||
const project = withBase(
|
||||
{
|
||||
name: "C",
|
||||
line: 0,
|
||||
bases: ["Base"],
|
||||
methods: [{ name: "run", line: 1, params: ["self", "x"], body: forward("run", ["x"], true) }],
|
||||
},
|
||||
[
|
||||
{
|
||||
name: "Base",
|
||||
line: 0,
|
||||
bases: ["ABC"],
|
||||
methods: [{ name: "run", line: 1, params: ["self", "x"] }],
|
||||
},
|
||||
],
|
||||
);
|
||||
expect(codes(await project.run())).toEqual([["builtin:python-redundant-override", "info", 1]]);
|
||||
});
|
||||
|
||||
it("keeps a bare super() forward over a base that returns a value", async () => {
|
||||
// Dropping the override would return the base's value instead of None.
|
||||
const project = withBase(
|
||||
{
|
||||
name: "C",
|
||||
line: 0,
|
||||
bases: ["Base"],
|
||||
methods: [{ name: "run", line: 1, params: ["self", "speed"], body: forward("run", ["speed"]) }],
|
||||
},
|
||||
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, params: ["self", "speed"], body: OTHER }] }],
|
||||
);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts a bare super() forward over a base that returns nothing", async () => {
|
||||
const project = withBase(
|
||||
{
|
||||
name: "C",
|
||||
line: 0,
|
||||
bases: ["Base"],
|
||||
methods: [{ name: "run", line: 1, params: ["self", "speed"], body: forward("run", ["speed"]) }],
|
||||
},
|
||||
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, params: ["self", "speed"] }] }],
|
||||
);
|
||||
expect(codes(await project.run())).toEqual([["builtin:python-redundant-override", "info", 1]]);
|
||||
});
|
||||
|
||||
it("keeps an override whose base method does other work", async () => {
|
||||
const project = withBase({ name: "C", line: 0, bases: ["Base"], methods: [{ name: "run", line: 1, body: OTHER }] }, [
|
||||
{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, body: OTHER }] },
|
||||
]);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps an override that changes the arguments it forwards", async () => {
|
||||
const project = withBase(
|
||||
{
|
||||
name: "C",
|
||||
line: 0,
|
||||
bases: ["Base"],
|
||||
methods: [{ name: "run", line: 1, params: ["self", "speed"], body: forward("run", ["speed", "1"], true) }],
|
||||
},
|
||||
[{ name: "Base", line: 0, bases: [], methods: [{ name: "run", line: 1, params: ["self", "speed"], body: OTHER }] }],
|
||||
);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("skips a class whose header no longer matches the indexed graph", async () => {
|
||||
// The graph was indexed when the class read `Base`; the document now reads `Other`.
|
||||
const project = withBase({ name: "C", line: 0, bases: ["Other"], indexedBases: ["Base"] }, [
|
||||
{ name: "Base", line: 0, bases: [] },
|
||||
]);
|
||||
expect(await project.run()).toEqual([]);
|
||||
});
|
||||
|
||||
it("runs only the producers that are enabled", async () => {
|
||||
const project = new Fixture("/p/a.py").add("/p/a.py", [
|
||||
{ name: "First", line: 0, bases: ["Second"] },
|
||||
{ name: "Second", line: 4, bases: ["First"] },
|
||||
]);
|
||||
expect(await project.run(new Set())).toEqual([]);
|
||||
expect((await project.run()).length).toBe(2);
|
||||
});
|
||||
|
||||
it("installs the inspections for Python documents only", () => {
|
||||
const ctx = (language: string) => ({ doc: 1, path: "/p/a.py", language, uiMode: null, readOnly: false });
|
||||
expect(pythonInheritanceExtension(ctx("typescript"))).toEqual([]);
|
||||
expect(pythonInheritanceExtension(ctx("python"))).not.toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,490 @@
|
||||
/**
|
||||
* Python inheritance inspections: circular inheritance, `@override` consistency, abstract
|
||||
* methods a class leaves unimplemented, and overrides that only forward to the base.
|
||||
*
|
||||
* The rules read the IDE's inheritance graph (`inheritanceGraph.ts`) plus the facts the
|
||||
* Python parser reports for a document (`docPythonFacts`). Nothing here parses source text,
|
||||
* and a rule stays silent whenever the graph cannot decide: a base the project does not
|
||||
* contain (`dict`, a library class) may declare or implement anything, and a missing
|
||||
* warning is cheaper than a wrong one.
|
||||
*/
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { ViewPlugin, type EditorView } from "@codemirror/view";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { onServerSettled } from "@/editor/lsp/availability";
|
||||
import { setFileDiagnostics } from "@/editor/lsp/diagnostics";
|
||||
import { withDocument } from "@/editor/lsp/files";
|
||||
import { lspRequest } from "@/editor/lsp/lsp";
|
||||
import {
|
||||
ancestryResolution,
|
||||
declarationKey,
|
||||
forgetInheritanceGraph,
|
||||
projectPythonIndex,
|
||||
type AncestryResolution,
|
||||
type InheritanceIndex,
|
||||
} from "@/editor/navigation/inheritanceGraph";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import {
|
||||
PYTHON_ABSTRACT_METHOD_INSPECTION,
|
||||
PYTHON_ABSTRACT_METHOD_PRODUCER,
|
||||
PYTHON_CIRCULAR_BASES_INSPECTION,
|
||||
PYTHON_CIRCULAR_BASES_PRODUCER,
|
||||
PYTHON_OVERRIDE_INSPECTION,
|
||||
PYTHON_OVERRIDE_PRODUCER,
|
||||
PYTHON_REDUNDANT_OVERRIDE_INSPECTION,
|
||||
PYTHON_REDUNDANT_OVERRIDE_PRODUCER,
|
||||
applyProfile,
|
||||
enabledByDefault,
|
||||
inspectionProfile,
|
||||
producerInspectionId,
|
||||
} from "@/platform/inspections";
|
||||
import {
|
||||
commands,
|
||||
isCancelled,
|
||||
isTauri,
|
||||
onIdeEvent,
|
||||
type ClassInheritance,
|
||||
type Diagnostic,
|
||||
type OutlineItem,
|
||||
type PythonClassFacts,
|
||||
type PythonFacts,
|
||||
type PythonMethodFacts,
|
||||
type Range,
|
||||
} from "@/platform/ipc";
|
||||
|
||||
/** The inspection producers, one per rule. */
|
||||
const PRODUCERS = [
|
||||
PYTHON_CIRCULAR_BASES_PRODUCER,
|
||||
PYTHON_OVERRIDE_PRODUCER,
|
||||
PYTHON_ABSTRACT_METHOD_PRODUCER,
|
||||
PYTHON_REDUNDANT_OVERRIDE_PRODUCER,
|
||||
];
|
||||
|
||||
/** What the rules read for one document: its own facts and a way to read another file's. */
|
||||
export interface InheritanceInspectionDeps {
|
||||
path: string;
|
||||
outline: readonly OutlineItem[];
|
||||
facts: PythonFacts;
|
||||
index: InheritanceIndex;
|
||||
factsOf: (path: string) => Promise<PythonFacts | null>;
|
||||
outlineOf: (path: string) => Promise<readonly OutlineItem[]>;
|
||||
/** Producers whose inspection is on; missing means every rule runs. */
|
||||
enabled?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
const isDunder = (name: string) => name.startsWith("__") && name.endsWith("__");
|
||||
const baseName = (name: string) => name.replace(/\s*[(<].*$/, "");
|
||||
const sameNames = (a: readonly string[], b: readonly string[]) =>
|
||||
a.length === b.length && a.every((name, i) => name === b[i]);
|
||||
|
||||
/** One class of the document: its graph declaration, its facts and its members. */
|
||||
interface ClassView {
|
||||
decl: ClassInheritance;
|
||||
facts: PythonClassFacts;
|
||||
/** Names the class itself declares: methods, fields, properties, nested types. */
|
||||
members: ReadonlySet<string>;
|
||||
/** How deep the ancestry stays inside the project (`Infinity`: all of it). */
|
||||
firstUnresolvedDepth: number;
|
||||
}
|
||||
|
||||
/** Everything the rules need for one document, with every project read memoised. */
|
||||
class ProjectView {
|
||||
private facts = new Map<string, Promise<PythonFacts | null>>();
|
||||
private outlines = new Map<string, Promise<readonly OutlineItem[]>>();
|
||||
private ancestry = new Map<string, Promise<AncestryResolution>>();
|
||||
|
||||
constructor(private readonly deps: InheritanceInspectionDeps) {}
|
||||
|
||||
/** The document's classes, in declaration order, skipping ones the graph does not match. */
|
||||
async classes(): Promise<ClassView[]> {
|
||||
const out: ClassView[] = [];
|
||||
for (const facts of this.deps.facts.classes) {
|
||||
const decl = this.declarationOf(facts);
|
||||
if (!decl) continue;
|
||||
const item = classItem(this.deps.outline, facts);
|
||||
const { firstUnresolvedDepth } = await this.ancestryOf(decl);
|
||||
out.push({ decl, facts, members: memberNames(item), firstUnresolvedDepth });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The ancestors of `cls`, with the depth each sits at. */
|
||||
ancestors(cls: ClassView): Promise<AncestryResolution["ancestors"]> {
|
||||
return this.ancestryOf(cls.decl).then((r) => r.ancestors);
|
||||
}
|
||||
|
||||
/** Whether the whole chain resolved inside the project. */
|
||||
complete(cls: ClassView): boolean {
|
||||
return cls.firstUnresolvedDepth === Infinity;
|
||||
}
|
||||
|
||||
/** Whether the chain is trustworthy at `depth`: no foreign base sits above it. */
|
||||
knownTo(cls: ClassView, depth: number): boolean {
|
||||
return cls.firstUnresolvedDepth > depth;
|
||||
}
|
||||
|
||||
async methodsOf(decl: ClassInheritance): Promise<PythonMethodFacts[]> {
|
||||
const facts = await this.factsOf(decl.path);
|
||||
return facts?.classes.find((c) => sameDeclaration(c, decl))?.methods ?? [];
|
||||
}
|
||||
|
||||
async membersOf(decl: ClassInheritance): Promise<ReadonlySet<string>> {
|
||||
const outline = await this.outlineOf(decl.path);
|
||||
const item = outline.find(
|
||||
(i) =>
|
||||
i.kind === "class" && i.selection_range.start.line === decl.line && i.selection_range.start.col === decl.col,
|
||||
);
|
||||
return memberNames(item ?? null);
|
||||
}
|
||||
|
||||
private declarationOf(facts: PythonClassFacts): ClassInheritance | null {
|
||||
const found = this.deps.index.byName.get(facts.name) ?? [];
|
||||
return (
|
||||
found.find(
|
||||
(c) =>
|
||||
c.path === this.deps.path && c.line === facts.selection.start.line && c.col === facts.selection.start.col,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
private factsOf(path: string): Promise<PythonFacts | null> {
|
||||
return memo(this.facts, path, () => this.deps.factsOf(path));
|
||||
}
|
||||
|
||||
private outlineOf(path: string): Promise<readonly OutlineItem[]> {
|
||||
return memo(this.outlines, path, () => this.deps.outlineOf(path));
|
||||
}
|
||||
|
||||
private ancestryOf(decl: ClassInheritance): Promise<AncestryResolution> {
|
||||
return memo(this.ancestry, declarationKey(decl), () => ancestryResolution(this.deps.index, decl));
|
||||
}
|
||||
}
|
||||
|
||||
function memo<T>(cache: Map<string, Promise<T>>, key: string, read: () => Promise<T>): Promise<T> {
|
||||
let pending = cache.get(key);
|
||||
if (!pending) {
|
||||
pending = read();
|
||||
cache.set(key, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** The names a class declares: methods, fields, properties, nested types. */
|
||||
function memberNames(item: OutlineItem | null): ReadonlySet<string> {
|
||||
return new Set((item?.children ?? []).map((child) => baseName(child.name)));
|
||||
}
|
||||
|
||||
function classItem(outline: readonly OutlineItem[], cls: PythonClassFacts): OutlineItem | null {
|
||||
const find = (items: readonly OutlineItem[]): OutlineItem | null => {
|
||||
for (const item of items) {
|
||||
if (
|
||||
item.kind === "class" &&
|
||||
item.selection_range.start.line === cls.selection.start.line &&
|
||||
item.selection_range.start.col === cls.selection.start.col
|
||||
) {
|
||||
return item;
|
||||
}
|
||||
const deeper = find(item.children);
|
||||
if (deeper) return deeper;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
return find(outline);
|
||||
}
|
||||
|
||||
function sameDeclaration(cls: PythonClassFacts, decl: ClassInheritance): boolean {
|
||||
return cls.selection.start.line === decl.line && cls.selection.start.col === decl.col;
|
||||
}
|
||||
|
||||
/** Everything the four rules produce for one document. */
|
||||
export async function inheritanceDiagnostics(deps: InheritanceInspectionDeps): Promise<Diagnostic[]> {
|
||||
const view = new ProjectView(deps);
|
||||
const runs = (producer: string) => deps.enabled?.has(producer) ?? true;
|
||||
const out: Diagnostic[] = [];
|
||||
for (const cls of await view.classes()) {
|
||||
// A class whose header changed since the graph was indexed is skipped: every rule
|
||||
// below would reason about a parent the source no longer names.
|
||||
if (!sameNames(cls.facts.bases, cls.decl.bases)) continue;
|
||||
if (runs(PYTHON_CIRCULAR_BASES_PRODUCER)) out.push(...(await circularInheritance(view, cls)));
|
||||
// A method may live on any ancestor: only a fully known chain can say it does not.
|
||||
if (runs(PYTHON_OVERRIDE_PRODUCER) && view.complete(cls)) out.push(...(await unusedOverride(view, cls)));
|
||||
if (runs(PYTHON_REDUNDANT_OVERRIDE_PRODUCER)) out.push(...(await redundantOverride(view, cls)));
|
||||
if (runs(PYTHON_ABSTRACT_METHOD_PRODUCER)) out.push(...(await missingAbstractMethods(view, cls)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A class that (transitively) inherits from itself: Python raises at import time. */
|
||||
async function circularInheritance(view: ProjectView, cls: ClassView): Promise<Diagnostic[]> {
|
||||
const ancestors = await view.ancestors(cls);
|
||||
if (!ancestors.some((a) => declarationKey(a.decl) === declarationKey(cls.decl))) return [];
|
||||
return [
|
||||
problem(
|
||||
cls.facts.selection,
|
||||
PYTHON_CIRCULAR_BASES_INSPECTION,
|
||||
"error",
|
||||
tx`Circular inheritance: '${cls.facts.name}' inherits from itself`,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/** `@override` on a method no ancestor declares: a typo, or a base that changed name. */
|
||||
async function unusedOverride(view: ProjectView, cls: ClassView): Promise<Diagnostic[]> {
|
||||
const out: Diagnostic[] = [];
|
||||
for (const method of cls.facts.methods) {
|
||||
if (!method.overrideDecorated || isDunder(method.name)) continue;
|
||||
if (await declaredInAncestry(view, cls, method.name)) continue;
|
||||
out.push(
|
||||
problem(
|
||||
method.selection,
|
||||
PYTHON_OVERRIDE_INSPECTION,
|
||||
"warning",
|
||||
tx`Method '${method.name}' is marked @override but no base class declares it`,
|
||||
),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Abstract methods of the ancestry that no class on the way down implements. */
|
||||
async function missingAbstractMethods(view: ProjectView, cls: ClassView): Promise<Diagnostic[]> {
|
||||
// A class that is itself abstract (it declares abstract methods, or names `ABC` or
|
||||
// `Protocol` as a base) leaves the implementing to its subclasses.
|
||||
if (cls.facts.methods.some((m) => m.abstractMethod) || cls.facts.bases.some((b) => b === "ABC" || b === "Protocol"))
|
||||
return [];
|
||||
const out: Diagnostic[] = [];
|
||||
const reported = new Set<string>();
|
||||
for (const ancestor of await view.ancestors(cls)) {
|
||||
// A foreign base above the declarer cannot override it: Python's MRO puts it later.
|
||||
if (!view.knownTo(cls, ancestor.depth - 1)) continue;
|
||||
for (const method of await view.methodsOf(ancestor.decl)) {
|
||||
const name = method.name;
|
||||
if (!method.abstractMethod || reported.has(name) || cls.members.has(name)) continue;
|
||||
if (await implementedAbove(view, cls, ancestor.depth, name)) continue;
|
||||
reported.add(name);
|
||||
out.push(
|
||||
problem(
|
||||
cls.facts.selection,
|
||||
PYTHON_ABSTRACT_METHOD_INSPECTION,
|
||||
"warning",
|
||||
tx`Class '${cls.facts.name}' does not implement abstract method '${name}'`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether an ancestor nearer than `declarer` implements `name` concretely. */
|
||||
async function implementedAbove(
|
||||
view: ProjectView,
|
||||
cls: ClassView,
|
||||
declarerDepth: number,
|
||||
name: string,
|
||||
): Promise<boolean> {
|
||||
for (const ancestor of await view.ancestors(cls)) {
|
||||
if (ancestor.depth >= declarerDepth) return false;
|
||||
if (!view.knownTo(cls, ancestor.depth - 1)) return true;
|
||||
const method = (await view.methodsOf(ancestor.decl)).find((m) => m.name === name);
|
||||
if (method) return !method.abstractMethod;
|
||||
if ((await view.membersOf(ancestor.decl)).has(name)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A method whose body the inherited method already provides. */
|
||||
async function redundantOverride(view: ProjectView, cls: ClassView): Promise<Diagnostic[]> {
|
||||
const out: Diagnostic[] = [];
|
||||
for (const method of cls.facts.methods) {
|
||||
const inherited = await inheritedMethod(view, cls, method.name);
|
||||
// A foreign base below the declarer cannot change which method runs: MRO puts it later.
|
||||
if (!inherited || !view.knownTo(cls, inherited.depth)) continue;
|
||||
if (inherited.method.abstractMethod || !redundantBody(method, inherited.method)) continue;
|
||||
out.push(
|
||||
problem(
|
||||
method.selection,
|
||||
PYTHON_REDUNDANT_OVERRIDE_INSPECTION,
|
||||
"info",
|
||||
tx`Redundant override of '${method.name}'`,
|
||||
),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether deleting `override` keeps what it does: it is a no-op over a no-op, or it forwards
|
||||
* exactly its own parameters to the inherited method (a bare call only when the inherited
|
||||
* method returns nothing, so discarding its value changes nothing).
|
||||
*/
|
||||
function redundantBody(override: PythonMethodFacts, base: PythonMethodFacts): boolean {
|
||||
if (override.body.kind === "empty") return base.body.kind === "empty";
|
||||
if (override.body.kind !== "superCall") return false;
|
||||
if (override.body.target !== override.name) return false;
|
||||
if (!override.params || !base.params) return false;
|
||||
if (!sameNames(base.params, override.params)) return false;
|
||||
// `super().m()` forwards every parameter but the receiver.
|
||||
if (!sameNames(override.body.args, override.params.slice(1))) return false;
|
||||
return override.body.returns || base.body.kind === "empty";
|
||||
}
|
||||
|
||||
/** The nearest ancestor's method `name`. */
|
||||
async function inheritedMethod(
|
||||
view: ProjectView,
|
||||
cls: ClassView,
|
||||
name: string,
|
||||
): Promise<{ method: PythonMethodFacts; depth: number } | null> {
|
||||
for (const ancestor of await view.ancestors(cls)) {
|
||||
const found = (await view.methodsOf(ancestor.decl)).find((m) => m.name === name);
|
||||
if (found) return { method: found, depth: ancestor.depth };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether any ancestor declares `name`, as a member or a method. */
|
||||
async function declaredInAncestry(view: ProjectView, cls: ClassView, name: string): Promise<boolean> {
|
||||
for (const ancestor of await view.ancestors(cls)) {
|
||||
if ((await view.membersOf(ancestor.decl)).has(name)) return true;
|
||||
if ((await view.methodsOf(ancestor.decl)).some((m) => m.name === name)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const problem = (range: Range, producer: string, severity: Diagnostic["severity"], message: string): Diagnostic => ({
|
||||
range,
|
||||
severity,
|
||||
message,
|
||||
source: "Python",
|
||||
code: producer,
|
||||
});
|
||||
|
||||
// --- the editor plugin -------------------------------------------------------
|
||||
|
||||
const DEBOUNCE_MS = 500;
|
||||
const SOURCE = "Python";
|
||||
const refreshables = new Set<() => void>();
|
||||
let watching = false;
|
||||
|
||||
/** Python files are the ones that change this inheritance graph. */
|
||||
const isPythonFile = (path: string) => path.endsWith(".py") || path.endsWith(".pyi");
|
||||
|
||||
/** One subscription per window: the graph's inputs changed, so re-run every open document. */
|
||||
function watchChanges() {
|
||||
if (watching) return;
|
||||
watching = true;
|
||||
const refreshAll = () => {
|
||||
forgetInheritanceGraph();
|
||||
for (const refresh of refreshables) refresh();
|
||||
};
|
||||
onIdeEvent("fsChanged", (e) => {
|
||||
if ([...e.created, ...e.modified, ...e.removed].some(isPythonFile)) refreshAll();
|
||||
});
|
||||
onServerSettled(refreshAll);
|
||||
}
|
||||
|
||||
/** The producers whose inspection is on in the profile in effect. */
|
||||
function enabledProducers(): Set<string> {
|
||||
const profile = inspectionProfile();
|
||||
return new Set(
|
||||
PRODUCERS.filter((producer) => {
|
||||
const id = producerInspectionId(producer);
|
||||
return profile[id]?.enabled ?? enabledByDefault(id);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The inspection id -> producer, for applying the profile to what the rules produced. */
|
||||
const PRODUCER_OF = new Map(PRODUCERS.map((producer) => [producerInspectionId(producer), producer]));
|
||||
|
||||
/** Applies the profile in effect to `diagnostics` (their `code` is the inspection id). */
|
||||
function applyProfileTo(diagnostics: readonly Diagnostic[]): Diagnostic[] {
|
||||
const profile = inspectionProfile();
|
||||
const grouped = new Map<string, Diagnostic[]>();
|
||||
for (const diagnostic of diagnostics) {
|
||||
const id = diagnostic.code ?? "";
|
||||
grouped.set(id, [...(grouped.get(id) ?? []), diagnostic]);
|
||||
}
|
||||
return [...grouped].flatMap(([id, items]) => [
|
||||
...(applyProfile(profile, PRODUCER_OF.get(id) ?? id, items) as readonly Diagnostic[]),
|
||||
]);
|
||||
}
|
||||
|
||||
const viewers = new Map<string, number>();
|
||||
const hasClass = (items: readonly OutlineItem[]): boolean =>
|
||||
items.some((item) => item.kind === "class" || hasClass(item.children));
|
||||
|
||||
/** Runs the inspections on Python documents and publishes them as local diagnostics. */
|
||||
export function pythonInheritanceExtension(ctx: EditorDocContext): Extension {
|
||||
if (ctx.language !== "python" || ctx.virtual || ctx.doc < 0) return [];
|
||||
watchChanges();
|
||||
return ViewPlugin.define((view: EditorView) => {
|
||||
if (!isTauri()) return {};
|
||||
viewers.set(ctx.path, (viewers.get(ctx.path) ?? 0) + 1);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let sequence = 0;
|
||||
let disposed = false;
|
||||
|
||||
const run = async () => {
|
||||
const enabled = enabledProducers();
|
||||
if (!enabled.size) {
|
||||
setFileDiagnostics(ctx.path, SOURCE, []);
|
||||
return;
|
||||
}
|
||||
const mine = ++sequence;
|
||||
const text = view.state.doc;
|
||||
try {
|
||||
const outline = await lspRequest(() => commands.docOutline(ctx.doc));
|
||||
// Every rule is about a class: no class, nothing to fetch the graph for.
|
||||
if (!hasClass(outline)) {
|
||||
setFileDiagnostics(ctx.path, SOURCE, []);
|
||||
return;
|
||||
}
|
||||
const [facts, project] = await Promise.all([
|
||||
lspRequest(() => commands.docPythonFacts(ctx.doc)),
|
||||
projectPythonIndex(),
|
||||
]);
|
||||
const found = await inheritanceDiagnostics({
|
||||
path: ctx.path,
|
||||
outline,
|
||||
facts,
|
||||
index: project.index,
|
||||
enabled,
|
||||
factsOf: (path) =>
|
||||
withDocument(path, (doc) => lspRequest(() => commands.docPythonFacts(doc))).catch(() => null),
|
||||
outlineOf: (path) => withDocument(path, (doc) => lspRequest(() => commands.docOutline(doc))).catch(() => []),
|
||||
});
|
||||
if (disposed || mine !== sequence || view.state.doc !== text) return;
|
||||
// The profile decides what is shown and how strongly.
|
||||
setFileDiagnostics(ctx.path, SOURCE, applyProfileTo(found));
|
||||
} catch (e) {
|
||||
if (!isCancelled(e)) console.debug("[inheritanceInspections]", e);
|
||||
}
|
||||
};
|
||||
const schedule = () => {
|
||||
clearTimeout(timer);
|
||||
sequence++;
|
||||
timer = setTimeout(() => void run(), DEBOUNCE_MS);
|
||||
};
|
||||
const refresh = () => schedule();
|
||||
refreshables.add(refresh);
|
||||
schedule();
|
||||
|
||||
return {
|
||||
update: (update) => {
|
||||
if (update.docChanged) schedule();
|
||||
},
|
||||
destroy: () => {
|
||||
disposed = true;
|
||||
clearTimeout(timer);
|
||||
refreshables.delete(refresh);
|
||||
const left = (viewers.get(ctx.path) ?? 1) - 1;
|
||||
if (left > 0) {
|
||||
viewers.set(ctx.path, left);
|
||||
return;
|
||||
}
|
||||
viewers.delete(ctx.path);
|
||||
setFileDiagnostics(ctx.path, SOURCE, []);
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -160,6 +160,7 @@ export function HierarchyView() {
|
||||
<span className={styles.row}>
|
||||
<SymbolBadge kind={mode === "call" ? "function" : "class"} />
|
||||
<span className={styles.name}>{root.name}</span>
|
||||
{root.detail && <span className={styles.detail}>{root.detail}</span>}
|
||||
<span className={styles.muted}>
|
||||
{basename(root.path)}:{root.line + 1}
|
||||
</span>
|
||||
|
||||
@@ -39,6 +39,8 @@ export interface HierarchyRoot {
|
||||
path: string;
|
||||
line: number;
|
||||
col: number;
|
||||
/** The server's detail for the root type (its package for Java), shown beside the name. */
|
||||
detail?: string | null;
|
||||
}
|
||||
|
||||
interface HierarchyState {
|
||||
@@ -225,6 +227,20 @@ function setChildren(
|
||||
|
||||
type RootResult = "loaded" | "noTarget" | "failed" | "stale";
|
||||
|
||||
/** The root type's detail (Java: its package), like the nodes below it show theirs. */
|
||||
async function loadRootDetail(generation: number, root: HierarchyRoot) {
|
||||
try {
|
||||
const item = await withDocument(root.path, (doc) =>
|
||||
call(commands.lspPrepareTypeHierarchy(doc, { line: root.line, col: root.col })),
|
||||
);
|
||||
const s = useHierarchy.getState();
|
||||
if (s.generation !== generation || s.root !== root || !item?.detail) return;
|
||||
useHierarchy.setState({ root: { ...root, detail: item.detail } });
|
||||
} catch {
|
||||
// Older servers (remote) and servers without type hierarchy: the name alone.
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the root's level. `quiet`: a position without a symbol isn't reported (the caller retries). */
|
||||
async function loadRoot(quiet = false): Promise<RootResult> {
|
||||
const s = useHierarchy.getState();
|
||||
@@ -239,6 +255,7 @@ async function loadRoot(quiet = false): Promise<RootResult> {
|
||||
);
|
||||
setChildren(generation, ROOT_ID, [rootKey(root)], items, incomplete && incompleteNote(incomplete, root.name));
|
||||
prefetchLevels(useHierarchy.getState().children.get(ROOT_ID) ?? []);
|
||||
if (s.mode === "type") void loadRootDetail(generation, root);
|
||||
return "loaded";
|
||||
} catch (e) {
|
||||
if (useHierarchy.getState().generation !== generation) return "stale";
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
*/
|
||||
import { useEffect, useRef } from "react";
|
||||
import clsx from "clsx";
|
||||
import { BarButton, Button, Popup, T } from "@/ui";
|
||||
import { BarButton, Button, IconButton, Popup, T } from "@/ui";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { isTauri, type AppMetrics } from "@/platform/ipc";
|
||||
import { call, commands, isTauri, type AppMetrics } from "@/platform/ipc";
|
||||
import { formatBytes, formatCount, formatMs, formatSize, formatUptime } from "./format";
|
||||
import { indicatorLabel, indicatorTooltip, memorySections, summarizeMemory } from "./memory";
|
||||
import { indicatorLabel, indicatorTooltip, memorySections, summarizeMemory, type BreakdownRow } from "./memory";
|
||||
import { startPolling } from "./poll";
|
||||
import { METRICS_INTERVAL_MS, refreshMetrics, usePerf } from "./store";
|
||||
import styles from "./perf.module.css";
|
||||
@@ -82,6 +82,40 @@ function Row({ label, detail, value, title, indented }: RowProps) {
|
||||
);
|
||||
}
|
||||
|
||||
async function endProcess(pid: number) {
|
||||
const error = await call(commands.endProcess(pid)).then(
|
||||
() => null,
|
||||
(e: unknown) => String(e),
|
||||
);
|
||||
await refreshMetrics();
|
||||
if (error) usePerf.setState({ error });
|
||||
}
|
||||
|
||||
function ProcessRow({ row }: { row: BreakdownRow }) {
|
||||
const title = row.processes > 1 ? tx`PID ${row.pid} · ${row.processes} processes` : tx`PID ${row.pid}`;
|
||||
return (
|
||||
<div className={clsx(styles.row, styles.indented, styles.processRow)} title={title}>
|
||||
<span className={styles.label}>
|
||||
{row.label}
|
||||
{row.detail && <span className={styles.detail}>{row.detail}</span>}
|
||||
</span>
|
||||
<span className={clsx(styles.value, styles.cpu)}>{row.cpu}</span>
|
||||
<span className={clsx(styles.value, styles.memory)}>{row.value}</span>
|
||||
<span className={styles.end}>
|
||||
{row.endable && (
|
||||
<IconButton
|
||||
icon="close"
|
||||
size="small"
|
||||
iconSize={14}
|
||||
title={tx`End Process ${row.label}`}
|
||||
onClick={() => void endProcess(row.pid)}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MemoryDetails({ metrics: m }: { metrics: AppMetrics }) {
|
||||
const error = usePerf((s) => s.error);
|
||||
const s = m.syntax;
|
||||
@@ -89,22 +123,26 @@ export function MemoryDetails({ metrics: m }: { metrics: AppMetrics }) {
|
||||
const sections = memorySections(m.memory ?? []);
|
||||
return (
|
||||
<div className={styles.panel}>
|
||||
<div className={styles.header}>{tx("Memory & Diagnostics")}</div>
|
||||
<div className={clsx(styles.header, styles.columns)}>
|
||||
<span className={styles.groupTitle}>{tx("Memory & Diagnostics")}</span>
|
||||
<span className={styles.cpu}>
|
||||
<T>CPU</T>
|
||||
</span>
|
||||
<span className={styles.memory}>
|
||||
<T>Memory</T>
|
||||
</span>
|
||||
<span className={styles.end} />
|
||||
</div>
|
||||
{sections.map((sec) => (
|
||||
<div key={sec.title} className={styles.section} aria-label={sec.title} role="group">
|
||||
<div className={styles.groupRow}>
|
||||
<div className={clsx(styles.groupRow, styles.processRow)}>
|
||||
<span className={styles.groupTitle}>{sec.title}</span>
|
||||
<span className={styles.value}>{sec.total}</span>
|
||||
<span className={clsx(styles.value, styles.cpu)}>{sec.cpu}</span>
|
||||
<span className={clsx(styles.value, styles.memory)}>{sec.total}</span>
|
||||
<span className={styles.end} />
|
||||
</div>
|
||||
{sec.rows.map((r) => (
|
||||
<Row
|
||||
key={r.key}
|
||||
label={r.label}
|
||||
detail={r.detail}
|
||||
value={r.value}
|
||||
title={r.processes > 1 ? tx`${r.processes} processes` : undefined}
|
||||
indented
|
||||
/>
|
||||
<ProcessRow key={r.key} row={r} />
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -141,7 +141,15 @@ describe("polling", () => {
|
||||
});
|
||||
|
||||
const row = (category: ProcessMemory["category"], label: string, mb: number | null, detail: string | null = null) =>
|
||||
({ category, label, detail, processes: 1, bytes: mb == null ? null : mb * MB }) satisfies ProcessMemory;
|
||||
({
|
||||
category,
|
||||
label,
|
||||
detail,
|
||||
pid: 1,
|
||||
processes: 1,
|
||||
bytes: mb == null ? null : mb * MB,
|
||||
cpuPercent: null,
|
||||
}) satisfies ProcessMemory;
|
||||
|
||||
describe("memory breakdown", () => {
|
||||
const rows: ProcessMemory[] = [
|
||||
@@ -150,7 +158,7 @@ describe("memory breakdown", () => {
|
||||
row("app", "GPU", 40),
|
||||
row("app", "Networking", 20),
|
||||
row("languageServer", "jdtls", 900, "idea"),
|
||||
{ ...row("languageServer", "rust-analyzer", 226, "idea"), processes: 2 },
|
||||
{ ...row("languageServer", "rust-analyzer", 226, "idea"), pid: 300, processes: 2, cpuPercent: 12.4 },
|
||||
row("process", "zsh", null, "Terminal"),
|
||||
];
|
||||
|
||||
@@ -179,8 +187,14 @@ describe("memory breakdown", () => {
|
||||
label: "rust-analyzer",
|
||||
detail: "idea",
|
||||
value: "226 MB",
|
||||
cpu: "12%",
|
||||
pid: 300,
|
||||
processes: 2,
|
||||
endable: true,
|
||||
});
|
||||
expect(sections[1]!.cpu).toBe("12%");
|
||||
expect(sections[0]!.cpu).toBe("–");
|
||||
expect(sections[0]!.rows.every((r) => !r.endable)).toBe(true);
|
||||
expect(memorySections([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { clearMocks, mockIPC } from "@tauri-apps/api/mocks";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AppMetrics } from "@/platform/ipc";
|
||||
import { MemoryDetails } from "../MemoryStatus";
|
||||
@@ -22,10 +23,18 @@ const metrics: AppMetrics = {
|
||||
languageServers: 2,
|
||||
syntax: { documents: 4, trees: 2, treeTextBytes: 2 * MB, hits: 10, incrementalParses: 5, fullParses: 2 },
|
||||
memory: [
|
||||
{ category: "app", label: "Backend", detail: null, processes: 1, bytes: 60 * MB },
|
||||
{ category: "app", label: "Web content", detail: "idea", processes: 1, bytes: 300 * MB },
|
||||
{ category: "languageServer", label: "jdtls", detail: "idea", processes: 1, bytes: 900 * MB },
|
||||
{ category: "process", label: "codelldb", detail: null, processes: 1, bytes: 30 * MB },
|
||||
{ category: "app", label: "Backend", detail: null, pid: 10, processes: 1, bytes: 60 * MB, cpuPercent: 4.25 },
|
||||
{ category: "app", label: "Web content", detail: "idea", pid: 11, processes: 1, bytes: 300 * MB, cpuPercent: 1 },
|
||||
{
|
||||
category: "languageServer",
|
||||
label: "jdtls",
|
||||
detail: "idea",
|
||||
pid: 20,
|
||||
processes: 2,
|
||||
bytes: 900 * MB,
|
||||
cpuPercent: 0,
|
||||
},
|
||||
{ category: "process", label: "codelldb", detail: null, pid: 30, processes: 1, bytes: 30 * MB, cpuPercent: null },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -49,6 +58,26 @@ describe("perf views", () => {
|
||||
expect(screen.getByText("Backend malloc in use")).toBeTruthy();
|
||||
expect(screen.getByText("40 ms")).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /Clear caches/ })).toBeTruthy();
|
||||
expect(openidea.textContent).toContain("5.3%");
|
||||
expect(servers.textContent).toContain("0%");
|
||||
expect(screen.getByTitle("PID 20 · 2 processes")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("ends language servers and processes, never OpenIDEA's own", async () => {
|
||||
const calls: [string, unknown][] = [];
|
||||
mockIPC((cmd, args) => {
|
||||
calls.push([cmd, args]);
|
||||
if (cmd === "end_process") return true;
|
||||
if (cmd === "app_metrics") return metrics;
|
||||
});
|
||||
render(<MemoryDetails metrics={metrics} />);
|
||||
expect(screen.queryByRole("button", { name: "End Process Backend" })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "End Process Web content" })).toBeNull();
|
||||
expect(screen.getByRole("button", { name: "End Process codelldb" })).toBeTruthy();
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "End Process jdtls" })));
|
||||
expect(calls[0]).toEqual(["end_process", { pid: 20 }]);
|
||||
expect(calls.some(([cmd]) => cmd === "app_metrics")).toBe(true);
|
||||
clearMocks();
|
||||
});
|
||||
|
||||
it("overlay is off by default and degrades without PerformanceObserver", async () => {
|
||||
|
||||
@@ -29,6 +29,13 @@ export function formatSize(bytes: number | null | undefined): string {
|
||||
return `${trim(bytes / GB)} GB`;
|
||||
}
|
||||
|
||||
/** `0%`, `3.2%`, `45%`, `180%` (percent of one core, so several busy cores exceed 100). */
|
||||
export function formatPercent(p: number | null | undefined): string {
|
||||
if (p == null || !Number.isFinite(p) || p < 0) return "–";
|
||||
if (p < 0.05) return "0%";
|
||||
return p < 10 ? `${trim(p)}%` : `${Math.round(p)}%`;
|
||||
}
|
||||
|
||||
/** `0.4 ms`, `16 ms`, `2.3 s`. */
|
||||
export function formatMs(ms: number | null | undefined): string {
|
||||
if (ms == null || !Number.isFinite(ms)) return "–";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Memory breakdown from `AppMetrics.memory`: totals per group and the popup sections. */
|
||||
import type { AppMetrics, MemoryCategory, ProcessMemory } from "@/platform/ipc";
|
||||
import { formatBytes, formatSize } from "./format";
|
||||
import { formatBytes, formatPercent, formatSize } from "./format";
|
||||
|
||||
export interface MemorySummary {
|
||||
/** Backend + its WebView processes. */
|
||||
@@ -45,15 +45,25 @@ export interface BreakdownRow {
|
||||
/** Project, windows, run kind… */
|
||||
detail: string | null;
|
||||
value: string;
|
||||
cpu: string;
|
||||
pid: number;
|
||||
processes: number;
|
||||
/** A language server, run, terminal or other child the user may end (never OpenIDEA's own processes). */
|
||||
endable: boolean;
|
||||
}
|
||||
|
||||
export interface BreakdownSection {
|
||||
title: string;
|
||||
total: string;
|
||||
cpu: string;
|
||||
rows: BreakdownRow[];
|
||||
}
|
||||
|
||||
function cpuSum(rows: ProcessMemory[]): number | null {
|
||||
const known = rows.filter((r) => r.cpuPercent != null);
|
||||
return known.length ? known.reduce((n, r) => n + r.cpuPercent!, 0) : null;
|
||||
}
|
||||
|
||||
const SECTIONS: Array<{ category: MemoryCategory; title: string }> = [
|
||||
{ category: "app", title: "OpenIDEA" },
|
||||
{ category: "languageServer", title: "Language servers" },
|
||||
@@ -69,12 +79,16 @@ export function memorySections(rows: ProcessMemory[]): BreakdownSection[] {
|
||||
{
|
||||
title,
|
||||
total: formatSize(sum(items)),
|
||||
cpu: formatPercent(cpuSum(items)),
|
||||
rows: items.map((r, i) => ({
|
||||
key: `${category}:${i}:${r.label}`,
|
||||
label: r.label,
|
||||
detail: r.detail,
|
||||
value: formatSize(r.bytes),
|
||||
cpu: formatPercent(r.cpuPercent),
|
||||
pid: r.pid,
|
||||
processes: r.processes,
|
||||
endable: category !== "app",
|
||||
})),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
gap: 6px;
|
||||
}
|
||||
.panel {
|
||||
width: 340px;
|
||||
width: 380px;
|
||||
padding: 6px 0;
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--fs-ui);
|
||||
@@ -61,6 +61,47 @@
|
||||
color: var(--fg-emphasis);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.columns {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.columns .groupTitle {
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.processRow {
|
||||
padding-right: 4px;
|
||||
}
|
||||
.columns {
|
||||
padding-right: 4px;
|
||||
}
|
||||
.cpu,
|
||||
.memory {
|
||||
flex: none;
|
||||
text-align: right;
|
||||
}
|
||||
.cpu {
|
||||
width: 44px;
|
||||
}
|
||||
.memory {
|
||||
width: 60px;
|
||||
}
|
||||
.processRow .value {
|
||||
margin-left: 0;
|
||||
}
|
||||
.end {
|
||||
flex: none;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
}
|
||||
.end button {
|
||||
opacity: 0;
|
||||
}
|
||||
.processRow:hover .end button,
|
||||
.end button:focus-visible {
|
||||
opacity: 1;
|
||||
}
|
||||
.error {
|
||||
padding: 2px 12px;
|
||||
color: var(--danger);
|
||||
|
||||
@@ -613,6 +613,20 @@ describe("Show Members", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("autoscrolls to source without handing files to another application", async () => {
|
||||
const { rows, row } = setup();
|
||||
act(() => {
|
||||
setViewOption("autoscrollToSource", true);
|
||||
setViewOption("singleClickOpen", false);
|
||||
setViewOption("previewTab", false);
|
||||
});
|
||||
await waitFor(() => expect(rows()).toContain("README.md"));
|
||||
fireEvent.mouseDown(row("README.md"));
|
||||
await waitFor(() =>
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", expect.objectContaining({ external: false })),
|
||||
);
|
||||
});
|
||||
|
||||
it("honours member single-click options and double-click focus", async () => {
|
||||
ipc.docOpen.mockResolvedValue(ok({ id: 7 }));
|
||||
ipc.docClose.mockResolvedValue(ok(null));
|
||||
|
||||
@@ -566,9 +566,9 @@ export function ProjectView() {
|
||||
void revealRange(
|
||||
lead.path,
|
||||
{ start: lead.member.selection_range.start },
|
||||
{ preview: o.previewTab, focus: false },
|
||||
{ preview: o.previewTab, focus: false, external: false },
|
||||
);
|
||||
} else void openFile(lead.path, { preview: o.previewTab, focus: false });
|
||||
} else void openFile(lead.path, { preview: o.previewTab, focus: false, external: false });
|
||||
}, []);
|
||||
|
||||
const onActivate = useCallback((node: ProjectNode) => {
|
||||
|
||||
@@ -376,10 +376,10 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
|
||||
act("vcs.rollback", arg, "Rollback…"),
|
||||
{ kind: "separator" },
|
||||
act("vcs.push", undefined, "Push…"),
|
||||
act("vcs.update", undefined, "Pull…"),
|
||||
act("vcs.pull", arg, "Pull…"),
|
||||
act("vcs.fetch", undefined, "Fetch"),
|
||||
act("vcs.merge", undefined, "Merge…"),
|
||||
act("vcs.rebase", undefined, "Rebase…"),
|
||||
act("vcs.merge", arg, "Merge…"),
|
||||
act("vcs.rebase", arg, "Rebase…"),
|
||||
{ kind: "separator" },
|
||||
act("vcs.branches", undefined, "Branches…"),
|
||||
act("vcs.newBranch", undefined, "New Branch…"),
|
||||
|
||||
@@ -127,14 +127,14 @@ function expandFolder(path: string) {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Open
|
||||
|
||||
export async function openFile(path: string, opts: { preview?: boolean; focus?: boolean } = {}) {
|
||||
export async function openFile(path: string, opts: { preview?: boolean; focus?: boolean; external?: boolean } = {}) {
|
||||
const editor = maybeEditorService();
|
||||
if (!editor) {
|
||||
notifications().notify({ level: "warning", title: "No editor available", body: path, key: "project.noEditor" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await editor.openFile(path, { preview: opts.preview, focus: opts.focus ?? true });
|
||||
await editor.openFile(path, { preview: opts.preview, focus: opts.focus ?? true, external: opts.external });
|
||||
} catch (e) {
|
||||
fail(`Cannot open ${nameOf(path)}`, e);
|
||||
}
|
||||
|
||||
@@ -116,7 +116,15 @@ describe("inspections tree", () => {
|
||||
"Version control",
|
||||
]);
|
||||
const python = find(tree, "group:Python")!;
|
||||
expect(python.children.map((n) => n.id)).toEqual(["lsp:basedpyright", "lsp:ruff"]);
|
||||
expect(python.children.map((n) => n.id)).toEqual([
|
||||
"lsp:basedpyright",
|
||||
"lsp:ruff",
|
||||
// The Python built-ins the IDE decides itself (no server checks class rules).
|
||||
"builtin:python-circular-bases",
|
||||
"builtin:python-override",
|
||||
"builtin:python-abstract-method",
|
||||
"builtin:python-redundant-override",
|
||||
]);
|
||||
expect(python.children[1]!.children.map((n) => n.id)).toEqual(["lsp:ruff:E501", "lsp:ruff:F401"]);
|
||||
expect(find(tree, "Python/lsp:ruff:F401")!.description).toContain("imported but unused");
|
||||
expect(find(tree, "group:Other")!.children.map((n) => n.id)).toEqual(["lsp:custom-ls"]);
|
||||
|
||||
@@ -26,6 +26,17 @@ import { useProject } from "@/platform/project";
|
||||
import { DEFAULT_SETTINGS } from "../model/schema";
|
||||
import { openProjectStructure, useSettingsDialog } from "../model/staging";
|
||||
import { ProjectStructureDialog } from "../languages/ProjectStructurePage";
|
||||
import { useContextMenuStore } from "@/ui/Menu";
|
||||
|
||||
/** The Modules toolbar's + menu, then its `label` entry. */
|
||||
function addMenuItem(label: string) {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add" }));
|
||||
const item = useContextMenuStore.getState().menu?.items.find((i) => "label" in i && i.label === label) as
|
||||
| { run?: () => void }
|
||||
| undefined;
|
||||
expect(item?.run).toBeDefined();
|
||||
item!.run!();
|
||||
}
|
||||
|
||||
let disposeAction: () => void = () => {};
|
||||
|
||||
@@ -59,7 +70,7 @@ describe("Project Structure module overrides", () => {
|
||||
it("keeps an outside directory out of module overrides and names the import action", async () => {
|
||||
open.mockResolvedValue("/sibling/B");
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add Module Overrides" }));
|
||||
addMenuItem("Add Module Overrides…");
|
||||
});
|
||||
expect(open).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ directory: true, title: "Select Module Directory", defaultPath: "/project" }),
|
||||
@@ -73,7 +84,7 @@ describe("Project Structure module overrides", () => {
|
||||
it("still stores an in-project directory as a module override", async () => {
|
||||
open.mockResolvedValue("/project/mod");
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add Module Overrides" }));
|
||||
addMenuItem("Add Module Overrides…");
|
||||
});
|
||||
expect(screen.queryByText(/Module overrides only apply/)).not.toBeInTheDocument();
|
||||
expect(screen.getAllByText("mod").length).toBeGreaterThan(0);
|
||||
@@ -81,7 +92,7 @@ describe("Project Structure module overrides", () => {
|
||||
|
||||
it("imports an external Maven project from this page without the directory override picker", async () => {
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Import Module from Existing Sources" }));
|
||||
addMenuItem("Import Module from Existing Sources…");
|
||||
});
|
||||
expect(imported).toHaveBeenCalledOnce();
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
|
||||
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
|
||||
notify: vi.fn(),
|
||||
level: vi.fn(),
|
||||
set: vi.fn(),
|
||||
find: vi.fn(),
|
||||
fsChanged: undefined as ((e: FsChange) => void) | undefined,
|
||||
component: null as React.ComponentType | null,
|
||||
}));
|
||||
@@ -21,7 +22,7 @@ vi.mock("@/platform/ipc", () => ({
|
||||
if (name === "fsChanged") mocks.fsChanged = handler;
|
||||
return () => {};
|
||||
},
|
||||
commands: { sdkPhpLanguageLevel: mocks.level, settingsSet: mocks.set },
|
||||
commands: { sdkPhpLanguageLevel: mocks.level, settingsSet: mocks.set, findFiles: mocks.find },
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", () => ({
|
||||
notifications: () => ({ notify: mocks.notify }),
|
||||
@@ -31,6 +32,7 @@ vi.mock("@/workbench/contributions", () => ({
|
||||
},
|
||||
}));
|
||||
import { activatePhpStatus } from "../languages/PhpStatus";
|
||||
import { isStatusWidgetAvailable } from "@/workbench/statusBarWidgets";
|
||||
|
||||
const fromComposer: PhpLanguageLevels = {
|
||||
effective: { version: "7.4.0", source: "require" },
|
||||
@@ -48,6 +50,7 @@ let dispose: () => void;
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.level.mockResolvedValue(fromComposer);
|
||||
mocks.find.mockResolvedValue([{ path: "/project/index.php" }]);
|
||||
mocks.set.mockImplementation((_scope: string, _key: string, value: string) =>
|
||||
Promise.resolve({ languages: { php: { languageLevel: JSON.parse(value) } } }),
|
||||
);
|
||||
@@ -74,6 +77,18 @@ const pick = async (label: string) => {
|
||||
};
|
||||
|
||||
describe("PHP language level status", () => {
|
||||
it("is left out of the status bar menus in a project without PHP", async () => {
|
||||
await waitFor(() => expect(mocks.find).toHaveBeenCalled());
|
||||
expect(isStatusWidgetAvailable("php.languageLevel")).toBe(true);
|
||||
dispose();
|
||||
mocks.find.mockResolvedValue([{ path: "/project/src/php.ts" }]);
|
||||
dispose = activatePhpStatus();
|
||||
await waitFor(() => expect(isStatusWidgetAvailable("php.languageLevel")).toBe(false));
|
||||
dispose();
|
||||
expect(isStatusWidgetAvailable("php.languageLevel")).toBe(true);
|
||||
dispose = activatePhpStatus();
|
||||
});
|
||||
|
||||
it("stays hidden for other editors without asking the backend", async () => {
|
||||
mount();
|
||||
await focus("typescript", "/project/src/app.ts");
|
||||
|
||||
@@ -32,6 +32,7 @@ vi.mock("@/workbench/contributions", () => ({
|
||||
return () => {};
|
||||
},
|
||||
}));
|
||||
import { isStatusWidgetAvailable } from "@/workbench/statusBarWidgets";
|
||||
import { activatePythonStatus, interpreterChoices, isPythonPath, nearMember } from "../languages/PythonStatus";
|
||||
|
||||
let dispose: () => void;
|
||||
@@ -118,6 +119,7 @@ describe("Python interpreter status", () => {
|
||||
await waitFor(() => expect(mocks.files).toHaveBeenCalled());
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
expect(mocks.detect).not.toHaveBeenCalled();
|
||||
await waitFor(() => expect(isStatusWidgetAvailable("python.interpreter")).toBe(false));
|
||||
});
|
||||
it("shows a warning for Python files without an interpreter", async () => {
|
||||
mocks.files.mockResolvedValue([{ path: "/project/src/main.py" }]);
|
||||
|
||||
@@ -9,6 +9,16 @@ import { tx } from "@/platform/i18n";
|
||||
import { notifications, registerStatusItem } from "@/workbench/contributions";
|
||||
import { BarButton, Menu, type MenuItem } from "@/ui";
|
||||
import { phpLanguageLevel } from "./api";
|
||||
import { trackStatusWidgetAvailability } from "./statusAvailability";
|
||||
|
||||
const isPhpPath = (path: string) => /(^|[\\/])composer\.json$|\.(php|phtml)$/.test(path);
|
||||
|
||||
async function hasPhpFiles(): Promise<boolean> {
|
||||
const matches = await Promise.all(
|
||||
[".php", ".phtml", "composer.json"].map((query) => call(commands.findFiles(query, 200))),
|
||||
);
|
||||
return matches.some((files) => files.some((file) => isPhpPath(file.path)));
|
||||
}
|
||||
|
||||
/** What the widget last resolved for a file, so the popup action can read it without a render. */
|
||||
interface Status extends PhpLanguageLevels {
|
||||
@@ -149,6 +159,7 @@ export function activatePhpStatus(): () => void {
|
||||
priority: 89,
|
||||
component: PhpStatus,
|
||||
}),
|
||||
trackStatusWidgetAvailability("php.languageLevel", hasPhpFiles),
|
||||
registerActions([
|
||||
{
|
||||
id: "php.languageLevelPopup",
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
Select,
|
||||
Tree,
|
||||
folderIconName,
|
||||
showContextMenu,
|
||||
type DialogButton,
|
||||
type FolderKind,
|
||||
type IconName,
|
||||
@@ -871,13 +872,22 @@ function ModulesSection() {
|
||||
<div className={styles.splitLayout}>
|
||||
<div className={styles.sideList}>
|
||||
<div className={styles.tableToolbar}>
|
||||
<Button size="small" variant="ghost" icon="plus" onClick={() => void addModule()}>
|
||||
<T>Add Module Overrides</T>
|
||||
</Button>
|
||||
<Button size="small" variant="ghost" icon="plus" onClick={() => void executeAction("maven.importExternal")}>
|
||||
<T>Import Module from Existing Sources</T>
|
||||
</Button>
|
||||
<span className={styles.spacer} />
|
||||
<IconButton
|
||||
icon="plus"
|
||||
size="small"
|
||||
title="Add"
|
||||
onClick={(e) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
showContextMenu({ x: r.left, y: r.bottom + 2 }, [
|
||||
{ label: tx("Add Module Overrides…"), icon: "module", run: () => void addModule() },
|
||||
{
|
||||
label: tx("Import Module from Existing Sources…"),
|
||||
icon: "folder-open",
|
||||
run: () => void executeAction("maven.importExternal"),
|
||||
},
|
||||
]);
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="minus"
|
||||
size="small"
|
||||
@@ -1110,6 +1120,17 @@ function LibrariesSection() {
|
||||
setSelectedIdx(next.length - 1);
|
||||
};
|
||||
|
||||
/** IDEA's Copy: a duplicate named "<name> (copy)", selected for editing. */
|
||||
const copySelectedLibrary = () => {
|
||||
if (!current) return;
|
||||
const names = new Set(libs.map((l) => l.name));
|
||||
let name = tx`${current.name} (copy)`;
|
||||
for (let n = 2; names.has(name); n++) name = tx`${current.name} (copy ${n})`;
|
||||
const next = [...libs, { ...current, name }];
|
||||
setRawLibs(next);
|
||||
setSelectedIdx(next.length - 1);
|
||||
};
|
||||
|
||||
const removeSelectedLibrary = () => {
|
||||
if (activeIdx < 0) return;
|
||||
const next = libs.filter((_, idx) => idx !== activeIdx);
|
||||
@@ -1135,14 +1156,14 @@ function LibrariesSection() {
|
||||
<IconButton
|
||||
icon="plus"
|
||||
size="small"
|
||||
title="Add JAR or Directory…"
|
||||
onClick={() => void addLibraryFromJar(false)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Add Classes Folder…"
|
||||
onClick={() => void addLibraryFromJar(true)}
|
||||
title="New Project Library"
|
||||
onClick={(e) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
showContextMenu({ x: r.left, y: r.bottom + 2 }, [
|
||||
{ label: tx("JAR or Directory…"), icon: "file-archive", run: () => void addLibraryFromJar(false) },
|
||||
{ label: tx("Classes Folder…"), icon: "folder-open", run: () => void addLibraryFromJar(true) },
|
||||
]);
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="minus"
|
||||
@@ -1151,6 +1172,13 @@ function LibrariesSection() {
|
||||
disabled={activeIdx < 0}
|
||||
onClick={removeSelectedLibrary}
|
||||
/>
|
||||
<IconButton
|
||||
icon="copy"
|
||||
size="small"
|
||||
title="Copy Library"
|
||||
disabled={activeIdx < 0}
|
||||
onClick={copySelectedLibrary}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.sideItems}>
|
||||
{libs.length === 0 && (
|
||||
|
||||
@@ -12,6 +12,7 @@ import { effectivePython, interpreterTarget, targetChoices, type Sdk } from "./a
|
||||
import { tildify } from "./components";
|
||||
import { validateRunTargets } from "@/platform/remoteSettings";
|
||||
import { interpreterIcon, interpreterPathKey } from "./interpreters";
|
||||
import { trackStatusWidgetAvailability } from "./statusAvailability";
|
||||
|
||||
/** What the widget last resolved for a project, so the popup action can read it without a render. */
|
||||
interface Status {
|
||||
@@ -241,6 +242,11 @@ export function activatePythonStatus(): () => void {
|
||||
priority: 90,
|
||||
component: PythonStatus,
|
||||
}),
|
||||
// The widget's own rule (Python files or a configured interpreter), also while it is hidden.
|
||||
trackStatusWidgetAvailability(
|
||||
"python.interpreter",
|
||||
async () => !!useProject.getState().settings?.languages?.python?.interpreter || (await hasPythonFiles()),
|
||||
),
|
||||
registerActions([
|
||||
{
|
||||
id: "python.interpreterPopup",
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/** Keeps a language's status bar widget out of projects that don't use the language. */
|
||||
import { isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { setStatusWidgetAvailable } from "@/workbench/statusBarWidgets";
|
||||
|
||||
/**
|
||||
* Re-checks `applies` when the project, its files (index finished, files created or
|
||||
* removed) or the settings change. Without a project, or when the check fails, the
|
||||
* widget counts as available.
|
||||
*/
|
||||
export function trackStatusWidgetAvailability(id: string, applies: () => Promise<boolean>): () => void {
|
||||
let sequence = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const refresh = async () => {
|
||||
const request = ++sequence;
|
||||
if (!useProject.getState().project || !isTauri()) {
|
||||
setStatusWidgetAvailable(id, true);
|
||||
return;
|
||||
}
|
||||
const available = await applies().catch(() => true);
|
||||
if (request === sequence) setStatusWidgetAvailable(id, available);
|
||||
};
|
||||
const schedule = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => void refresh(), 300);
|
||||
};
|
||||
void refresh();
|
||||
const off = [
|
||||
onIdeEvent("indexState", (e) => {
|
||||
if (!e.indexing) schedule();
|
||||
}),
|
||||
onIdeEvent("fsChanged", (e) => {
|
||||
if (e.created.length || e.removed.length) schedule();
|
||||
}),
|
||||
onIdeEvent("settingsChanged", schedule),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root) void refresh();
|
||||
}),
|
||||
];
|
||||
return () => {
|
||||
sequence++;
|
||||
clearTimeout(timer);
|
||||
off.forEach((dispose) => dispose());
|
||||
setStatusWidgetAvailable(id, true);
|
||||
};
|
||||
}
|
||||
@@ -123,7 +123,9 @@ describe("current line decoration", () => {
|
||||
expect(hint()?.textContent).toContain("Bob Jones");
|
||||
v.dispatch({ selection: { anchor: 0 } });
|
||||
expect(hint()).toBeNull();
|
||||
await tick();
|
||||
// The document's blame is already loaded, so the new line shows without the
|
||||
// 300 ms debounce that protects a git call (#3396).
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(hint()?.textContent).toContain("Alice Smith");
|
||||
expect(mocks.blame).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.file).toHaveBeenCalledTimes(1);
|
||||
@@ -137,6 +139,17 @@ describe("current line decoration", () => {
|
||||
expect(mocks.action).toHaveBeenCalledWith("vcs.showCommit", alice.commit);
|
||||
});
|
||||
|
||||
it("still debounces the git call after an edit (#3396)", async () => {
|
||||
const v = editor();
|
||||
await tick();
|
||||
mocks.blame.mockClear();
|
||||
v.dispatch({ changes: { from: 0, insert: "x" } });
|
||||
await vi.advanceTimersByTimeAsync(299);
|
||||
expect(mocks.blame).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(mocks.blame).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("uses only the primary selection and hides multiline selections", async () => {
|
||||
const v = editor();
|
||||
v.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(0), EditorSelection.cursor(4)], 1) });
|
||||
|
||||
@@ -254,6 +254,19 @@ describe("commit navigation", () => {
|
||||
expect(api.log.mock.lastCall?.[1]).toMatchObject({ branches: ["main"], range: null, ranges: ["a..b", "c..d"] });
|
||||
});
|
||||
|
||||
it("opens a new Update Info tab per update, each repository limited to its own range", async () => {
|
||||
useVcs.setState({ roots: ["/a", "/b", "/c"] });
|
||||
const ranges = { "/a": "a1..a2", "/b": "b1..b2" };
|
||||
const first = openLogTab("update", "14:32", "toolWindow", Object.keys(ranges), { repoRanges: ranges });
|
||||
await vi.waitFor(() => expect(api.log).toHaveBeenCalledTimes(2));
|
||||
const byRepo = Object.fromEntries(
|
||||
api.log.mock.calls.map((call) => [call[0] as string, (call[1] as LogQuery).ranges]),
|
||||
);
|
||||
expect(byRepo).toEqual({ "/a": ["a1..a2"], "/b": ["b1..b2"] });
|
||||
expect(openLogTab("update", "14:32", "toolWindow", ["/a"], { repoRanges: { "/a": "a2..a3" } })).not.toBe(first);
|
||||
expect(useGitLog.getState().logTabs.filter((t) => t.kind === "update")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("offers both merge parents and selects the chosen repository-scoped commit", async () => {
|
||||
const commits = [c("merge", ["main", "side"]), c("main"), c("side")].map((c) => ({ ...c, repo: "/repo" }));
|
||||
useGitLog.setState({ commits, done: true });
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { operationRepo } from "../actions";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const ctx = vi.hoisted(() => ({ selection: [] as string[], active: null as string | null }));
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
projectViewSelection: () => ctx.selection,
|
||||
maybeEditorService: () => ({ activePath: () => ctx.active }),
|
||||
}));
|
||||
|
||||
const vcs = useVcs.getState();
|
||||
|
||||
beforeEach(() => {
|
||||
ctx.selection = [];
|
||||
ctx.active = null;
|
||||
setContext("activeToolWindow", "");
|
||||
useVcs.setState({ root: "/ws", roots: ["/ws/a", "/ws/b"], repo: "/ws/b" });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setContext("activeToolWindow", "");
|
||||
useVcs.setState(vcs);
|
||||
});
|
||||
|
||||
describe("operationRepo", () => {
|
||||
it("starts on the repository of the action's files (context menus)", () => {
|
||||
expect(operationRepo(["/ws/a/src/x.ts"])).toBe("/ws/a");
|
||||
expect(operationRepo("/ws/a")).toBe("/ws/a");
|
||||
expect(operationRepo({ repo: "/ws/a" })).toBe("/ws/a");
|
||||
});
|
||||
|
||||
it("from the keyboard, uses the focused Project view's selection, else the active editor's file", () => {
|
||||
ctx.selection = ["/ws/a/lib"];
|
||||
ctx.active = "/ws/b/main.ts";
|
||||
expect(operationRepo(undefined)).toBe("/ws/b");
|
||||
setContext("activeToolWindow", "project");
|
||||
expect(operationRepo(undefined)).toBe("/ws/a");
|
||||
});
|
||||
|
||||
it("falls back to the selected repository", () => {
|
||||
useVcs.setState({ repo: "/ws/a" });
|
||||
expect(operationRepo(undefined)).toBe("/ws/a");
|
||||
expect(operationRepo(["/elsewhere/file"])).toBe("/ws/a");
|
||||
});
|
||||
});
|
||||
@@ -192,6 +192,23 @@ describe("installRootSync", () => {
|
||||
expect(ipc.branchInfo).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("queries again when a HEAD moves or a fetch / pull / push finishes, without a .git event", async () => {
|
||||
enable(true);
|
||||
useVcs.setState({ heads: { "/p": { head: "main", headCommit: "a" } }, remoteBusy: null });
|
||||
dispose = installRootSync();
|
||||
await vi.waitFor(() => expect(ipc.branchInfo).toHaveBeenCalledTimes(2));
|
||||
useVcs.setState({ remoteBusy: "Fetching…" });
|
||||
await settle();
|
||||
expect(ipc.branchInfo).toHaveBeenCalledTimes(2);
|
||||
useVcs.setState({ remoteBusy: null });
|
||||
await vi.waitFor(() => expect(ipc.branchInfo).toHaveBeenCalledTimes(4));
|
||||
useVcs.setState({ heads: { "/p": { head: "main", headCommit: "a" } } });
|
||||
await settle();
|
||||
expect(ipc.branchInfo).toHaveBeenCalledTimes(4);
|
||||
useVcs.setState({ heads: { "/p": { head: "main", headCommit: "b" } } });
|
||||
await vi.waitFor(() => expect(ipc.branchInfo).toHaveBeenCalledTimes(6));
|
||||
});
|
||||
|
||||
it("queries the repositories again when the set of roots changes", async () => {
|
||||
enable(true);
|
||||
dispose = installRootSync();
|
||||
|
||||
@@ -145,6 +145,21 @@ function selectedPaths(arg: unknown): string[] {
|
||||
return project.length ? project : contextPaths(arg);
|
||||
}
|
||||
|
||||
/**
|
||||
* The repository a repository-wide dialog (Pull, Merge, Rebase) starts on: the one holding the
|
||||
* action's file, else the Project view's selection while it has focus, else the active editor's
|
||||
* file, else the selected repository.
|
||||
*/
|
||||
export function operationRepo(arg: unknown): string | null {
|
||||
const roots = useVcs.getState().roots;
|
||||
if (arg && typeof arg === "object" && "repo" in arg) return (arg as { repo: string | null }).repo;
|
||||
const inContext = (paths: readonly string[] | undefined) =>
|
||||
paths?.map((p) => repoOf(p, roots)).find((r) => r != null) ?? null;
|
||||
const fromProject = getContext().activeToolWindow === "project" ? projectViewSelection() : undefined;
|
||||
const active = maybeEditorService()?.activePath();
|
||||
return inContext(argPaths(arg)) ?? inContext(fromProject) ?? inContext(active ? [active] : []) ?? currentRepo();
|
||||
}
|
||||
|
||||
function showGitWindow() {
|
||||
toolWindowService().show("git", true);
|
||||
}
|
||||
@@ -289,7 +304,7 @@ export function registerVcsActions(): () => void {
|
||||
category: "Git",
|
||||
icon: "git-pull",
|
||||
when: VCS,
|
||||
run: showPullDialog,
|
||||
run: ({ arg }) => showPullDialog(operationRepo(arg)),
|
||||
},
|
||||
{
|
||||
id: "vcs.merge",
|
||||
@@ -297,7 +312,7 @@ export function registerVcsActions(): () => void {
|
||||
category: "Git",
|
||||
when: VCS,
|
||||
keywords: ["merge branch"],
|
||||
run: showMergeDialog,
|
||||
run: ({ arg }) => showMergeDialog(operationRepo(arg)),
|
||||
},
|
||||
{
|
||||
id: "vcs.rebase",
|
||||
@@ -305,7 +320,7 @@ export function registerVcsActions(): () => void {
|
||||
category: "Git",
|
||||
when: VCS,
|
||||
keywords: ["rebase branch"],
|
||||
run: showRebaseDialog,
|
||||
run: ({ arg }) => showRebaseDialog(operationRepo(arg)),
|
||||
},
|
||||
{
|
||||
id: "vcs.manageRemotes",
|
||||
|
||||
@@ -129,8 +129,9 @@ export function remoteBranchesOf(branches: readonly Branch[], remote: string): s
|
||||
|
||||
// --- Pull -------------------------------------------------------------------
|
||||
|
||||
export function showPullDialog() {
|
||||
openDialog((close) => <PullDialog onClose={close} />);
|
||||
/** `repo`: the repository it starts on (the context's), else the selected one. */
|
||||
export function showPullDialog(repo?: string | null) {
|
||||
openDialog((close) => <PullDialog initialRepo={repo} onClose={close} />);
|
||||
}
|
||||
|
||||
/** IDEA's Git Root choice: shown only when the project holds several repositories. */
|
||||
@@ -165,8 +166,8 @@ function useBranchInfo(repo: string | null) {
|
||||
return loaded?.repo === repo ? loaded.info : null;
|
||||
}
|
||||
|
||||
function PullDialog({ onClose }: { onClose: () => void }) {
|
||||
const [repo, setRepo] = useState(currentRepo);
|
||||
function PullDialog({ initialRepo, onClose }: { initialRepo?: string | null; onClose: () => void }) {
|
||||
const [repo, setRepo] = useState(() => (initialRepo === undefined ? currentRepo() : initialRepo));
|
||||
const info = useBranchInfo(repo);
|
||||
const branches = useBranches(repo);
|
||||
const [remotes, setRemotes] = useState<Remote[] | null>(null);
|
||||
@@ -279,12 +280,13 @@ function PullDialog({ onClose }: { onClose: () => void }) {
|
||||
|
||||
// --- Merge ------------------------------------------------------------------
|
||||
|
||||
export function showMergeDialog() {
|
||||
openDialog((close) => <MergeDialog onClose={close} />);
|
||||
/** `repo`: the repository it starts on (the context's), else the selected one. */
|
||||
export function showMergeDialog(repo?: string | null) {
|
||||
openDialog((close) => <MergeDialog initialRepo={repo} onClose={close} />);
|
||||
}
|
||||
|
||||
function MergeDialog({ onClose }: { onClose: () => void }) {
|
||||
const [repo, setRepo] = useState(currentRepo);
|
||||
function MergeDialog({ initialRepo, onClose }: { initialRepo?: string | null; onClose: () => void }) {
|
||||
const [repo, setRepo] = useState(() => (initialRepo === undefined ? currentRepo() : initialRepo));
|
||||
const head = useBranchInfo(repo)?.head ?? null;
|
||||
const branches = useBranches(repo);
|
||||
const [branch, setBranch] = useState<string | null>(null);
|
||||
@@ -358,12 +360,13 @@ function MergeDialog({ onClose }: { onClose: () => void }) {
|
||||
|
||||
// --- Rebase -----------------------------------------------------------------
|
||||
|
||||
export function showRebaseDialog() {
|
||||
openDialog((close) => <RebaseDialog onClose={close} />);
|
||||
/** `repo`: the repository it starts on (the context's), else the selected one. */
|
||||
export function showRebaseDialog(repo?: string | null) {
|
||||
openDialog((close) => <RebaseDialog initialRepo={repo} onClose={close} />);
|
||||
}
|
||||
|
||||
function RebaseDialog({ onClose }: { onClose: () => void }) {
|
||||
const [repo, setRepo] = useState(currentRepo);
|
||||
function RebaseDialog({ initialRepo, onClose }: { initialRepo?: string | null; onClose: () => void }) {
|
||||
const [repo, setRepo] = useState(() => (initialRepo === undefined ? currentRepo() : initialRepo));
|
||||
const head = useBranchInfo(repo)?.head ?? null;
|
||||
const branches = useBranches(repo);
|
||||
const [upstream, setUpstream] = useState<string | null>(null);
|
||||
|
||||
@@ -41,6 +41,7 @@ export function stashTabs({ combine, shelfCount, stashCount, tab }: StashTabsInp
|
||||
|
||||
/** Title of a log tab of its own. */
|
||||
export function logTabLabel(t: LogTab): string {
|
||||
if (t.kind === "update") return tx`Update Info: ${t.target}`;
|
||||
return t.kind === "history" ? tx`History: ${baseName(t.target)}` : tx`Log: ${t.target}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -69,19 +69,30 @@ export function inlineBlameSegments(line: BlameLine, now = Date.now()): BlameSeg
|
||||
class BlameCache {
|
||||
private doc: Text | undefined;
|
||||
private pending: Promise<BlameLine[]> | undefined;
|
||||
private lines: BlameLine[] | undefined;
|
||||
|
||||
clear() {
|
||||
this.doc = undefined;
|
||||
this.pending = undefined;
|
||||
this.lines = undefined;
|
||||
}
|
||||
|
||||
get(doc: Text, load: () => Promise<BlameLine[]>): Promise<BlameLine[]> {
|
||||
if (doc !== this.doc || !this.pending) {
|
||||
this.doc = doc;
|
||||
this.pending = load();
|
||||
this.lines = undefined;
|
||||
this.pending = load().then((lines) => {
|
||||
if (this.doc === doc) this.lines = lines;
|
||||
return lines;
|
||||
});
|
||||
}
|
||||
return this.pending;
|
||||
}
|
||||
|
||||
/** The resolved blame for `doc`, when it is already loaded. */
|
||||
peek(doc: Text): BlameLine[] | undefined {
|
||||
return doc === this.doc ? this.lines : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** An element's own custom property in px (its anchor offset), or 0. Inherited custom
|
||||
@@ -265,7 +276,15 @@ export function inlineBlame(ctx: EditorDocContext): Extension {
|
||||
if (update.docChanged) this.cache.clear();
|
||||
if (update.docChanged || update.selectionSet) {
|
||||
this.line = undefined;
|
||||
this.schedule();
|
||||
// A caret move in a document whose blame is already loaded needs no git
|
||||
// call, so show it without the debounce that protects that call (#3396).
|
||||
if (!update.docChanged && this.cache.peek(update.state.doc) !== undefined) {
|
||||
clearTimeout(this.timer);
|
||||
++this.generation;
|
||||
void this.refresh();
|
||||
} else {
|
||||
this.schedule();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,8 @@ export interface LogFilters {
|
||||
path: string | null;
|
||||
paths?: string[];
|
||||
range?: string | null;
|
||||
/** Revision ranges per repository root, instead of `range` (Update Info: what an update brought in). */
|
||||
repoRanges?: Record<string, string>;
|
||||
date: LogDateFilter | null;
|
||||
}
|
||||
|
||||
@@ -94,7 +96,7 @@ function parseFragments(value: unknown): LogFragments {
|
||||
/** A log tab of its own (IDEA's "History: file" / "Log: branch" tabs): its own filters and view. */
|
||||
export interface LogTab {
|
||||
id: string;
|
||||
kind: "history" | "branch" | "log" | "external";
|
||||
kind: "history" | "branch" | "log" | "external" | "update";
|
||||
/** What it shows (the file path or the branch); opening the same again selects the tab. */
|
||||
target: string;
|
||||
repo?: string | null;
|
||||
@@ -405,6 +407,7 @@ export function openLogTab(
|
||||
target: string,
|
||||
location: LogTab["location"] = "toolWindow",
|
||||
repositories?: string[],
|
||||
initialFilters?: Partial<LogFilters>,
|
||||
): string {
|
||||
const active = useGitLog.getState().logTabs.find((t) => t.id === useGitLog.getState().shownLog);
|
||||
repositories ??=
|
||||
@@ -421,6 +424,7 @@ export function openLogTab(
|
||||
: (active?.repo ?? (kind === "log" ? null : currentRepoRoot()));
|
||||
const existing =
|
||||
kind !== "log" &&
|
||||
kind !== "update" &&
|
||||
useGitLog
|
||||
.getState()
|
||||
.logTabs.find(
|
||||
@@ -442,6 +446,7 @@ export function openLogTab(
|
||||
: {
|
||||
...emptyFilters(),
|
||||
...(kind === "history" ? { path: target } : kind === "branch" ? { branches: [target] } : {}),
|
||||
...initialFilters,
|
||||
};
|
||||
parked.set(id, freshView(filters));
|
||||
useGitLog.setState((s) => ({
|
||||
@@ -566,6 +571,13 @@ function parseFilters(value: unknown): LogFilters {
|
||||
text: typeof raw.text === "string" ? raw.text : "",
|
||||
path: typeof raw.path === "string" ? raw.path : null,
|
||||
range: typeof raw.range === "string" ? raw.range : null,
|
||||
...(raw.repoRanges && typeof raw.repoRanges === "object"
|
||||
? {
|
||||
repoRanges: Object.fromEntries(
|
||||
Object.entries(raw.repoRanges).filter((e): e is [string, string] => typeof e[1] === "string"),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
regex: raw.regex === true,
|
||||
matchCase: raw.matchCase === true,
|
||||
};
|
||||
@@ -625,7 +637,7 @@ function restoreLogSession(root: string | null) {
|
||||
typeof tab === "object" &&
|
||||
typeof tab.id === "string" &&
|
||||
typeof tab.target === "string" &&
|
||||
["history", "branch", "log", "external"].includes(tab.kind) &&
|
||||
["history", "branch", "log", "external", "update"].includes(tab.kind) &&
|
||||
(tab.repo == null || typeof tab.repo === "string"),
|
||||
)
|
||||
: [];
|
||||
@@ -907,6 +919,7 @@ function loadPage(replace: boolean, id: string, before = false): Promise<void> {
|
||||
!f.path &&
|
||||
!f.paths?.length &&
|
||||
!f.range &&
|
||||
!f.repoRanges &&
|
||||
!f.date &&
|
||||
!o.noMerges &&
|
||||
!o.firstParent
|
||||
@@ -932,7 +945,7 @@ function loadPage(replace: boolean, id: string, before = false): Promise<void> {
|
||||
textRegex: f.regex,
|
||||
textMatchCase: f.matchCase,
|
||||
range: null,
|
||||
ranges: f.range?.split(/\s+/).filter(Boolean) ?? [],
|
||||
ranges: ((repo && f.repoRanges?.[repo]) || f.range)?.split(/\s+/).filter(Boolean) ?? [],
|
||||
request,
|
||||
summaryOnly: true,
|
||||
stopAt,
|
||||
|
||||
@@ -9,7 +9,12 @@ import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { attachDocument, editorsFor } from "@/editor/api";
|
||||
import { maybeEditorService, notifications, type NotificationService } from "@/workbench/contributions";
|
||||
import {
|
||||
maybeEditorService,
|
||||
notifications,
|
||||
toolWindowService,
|
||||
type NotificationService,
|
||||
} from "@/workbench/contributions";
|
||||
import { cancelTask, upsertTaskSoon, useTasks } from "@/workbench/tasks";
|
||||
import { progressFraction } from "./model";
|
||||
import { saveDiffWindows } from "./diffWindowSave";
|
||||
@@ -329,6 +334,24 @@ const commitsText = (n: number) => (n === 1 ? tx`${n} commit` : tx`${n} commits`
|
||||
const pushedTitle = (n: number, to: string) =>
|
||||
n === 1 ? tx`Pushed ${n} commit to ${to}` : tx`Pushed ${n} commits to ${to}`;
|
||||
|
||||
/**
|
||||
* View Commits: an Update Info tab in the Git tool window, the Log of each updated repository
|
||||
* limited to the commits the update brought in. Each update opens a tab of its own.
|
||||
*/
|
||||
async function openUpdateInfo(updated: readonly UpdatedRange[]) {
|
||||
const { roots, root } = useVcs.getState();
|
||||
const repoRanges = Object.fromEntries(
|
||||
updated.flatMap(({ repo, from, to }) => {
|
||||
const r = repo ?? roots[0] ?? root;
|
||||
return r ? [[r, `${from}..${to}`]] : [];
|
||||
}),
|
||||
);
|
||||
const time = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
const { openLogTab } = await import("./logStore");
|
||||
openLogTab("update", time, "toolWindow", Object.keys(repoRanges), { repoRanges });
|
||||
toolWindowService().show("git", true);
|
||||
}
|
||||
|
||||
/** IDEA's Update Project result: "N files updated in M commits" with View Commits. */
|
||||
async function notifyUpdated(updated: readonly UpdatedRange[]) {
|
||||
if (!updated.length) {
|
||||
@@ -364,10 +387,7 @@ async function notifyUpdated(updated: readonly UpdatedRange[]) {
|
||||
actions: [
|
||||
{
|
||||
label: "View Commits",
|
||||
run: () => {
|
||||
const { repo, from, to } = updated.find((u) => u.repo === currentRepo()) ?? updated[0]!;
|
||||
void import("./CompareBranches").then((m) => m.showCommitRange("Update Info", from, to, repo));
|
||||
},
|
||||
run: () => void openUpdateInfo(updated),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import { tx } from "@/platform/i18n";
|
||||
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
|
||||
import { setFileDecorations, type DecorationSegment, type FileDecoration } from "@/workbench/contributions";
|
||||
import { rootOf } from "./model";
|
||||
import { useVcs } from "./store";
|
||||
import { useVcs, type RepoHead } from "./store";
|
||||
|
||||
const PROVIDER = "vcs-root-sync";
|
||||
const GIT_CHANGE_DELAY_MS = 250;
|
||||
@@ -95,6 +95,18 @@ async function branchInfoOf(root: string): Promise<[string, BranchInfo] | null>
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a repository's branch or HEAD commit differs between two refreshes. */
|
||||
export function headsMoved(a: Readonly<Record<string, RepoHead>>, b: Readonly<Record<string, RepoHead>>): boolean {
|
||||
if (a === b) return false;
|
||||
const roots = new Set([...Object.keys(a), ...Object.keys(b)]);
|
||||
for (const root of roots) {
|
||||
const x = a[root];
|
||||
const y = b[root];
|
||||
if (x?.head !== y?.head || x?.headCommit !== y?.headCommit) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function sameDecorations(a: ReadonlyMap<string, FileDecoration>, b: ReadonlyMap<string, FileDecoration>): boolean {
|
||||
if (a.size !== b.size) return false;
|
||||
for (const [root, d] of a) if (JSON.stringify(d) !== JSON.stringify(b.get(root))) return false;
|
||||
@@ -167,7 +179,14 @@ export function installRootSync(): () => void {
|
||||
};
|
||||
|
||||
const unsubVcs = useVcs.subscribe((s, prev) => {
|
||||
if (s.available !== prev.available || s.roots.join("\n") !== prev.roots.join("\n")) schedule();
|
||||
if (
|
||||
s.available !== prev.available ||
|
||||
s.roots.join("\n") !== prev.roots.join("\n") ||
|
||||
// A commit, checkout or update moved a HEAD; a fetch or push finished.
|
||||
headsMoved(s.heads, prev.heads) ||
|
||||
(prev.remoteBusy && !s.remoteBusy)
|
||||
)
|
||||
schedule();
|
||||
// The changed-file counts follow the working tree as the status refreshes, without asking git.
|
||||
else if (s.status !== prev.status) render();
|
||||
});
|
||||
|
||||
@@ -90,10 +90,9 @@ export function activate(): () => void {
|
||||
registerExternalFileOpenHandler({
|
||||
id: "viewers.associatedApps",
|
||||
order: 1,
|
||||
open: (path) => {
|
||||
const patterns = useProject.getState().settings?.files?.associatedApplications ?? [];
|
||||
return associatedApplication(path, patterns) ? openWithSystemApp(path) : false;
|
||||
},
|
||||
matches: (path) =>
|
||||
associatedApplication(path, useProject.getState().settings?.files?.associatedApplications ?? []),
|
||||
open: openWithSystemApp,
|
||||
}),
|
||||
registerEditorKind({ kind: IMAGE_KIND, component: ImageViewer, title: titleOf, icon: iconOf }),
|
||||
registerEditorKind({ kind: BINARY_KIND, component: HexViewer, title: titleOf, icon: iconOf }),
|
||||
|
||||
@@ -240,6 +240,16 @@ export const DEPENDENCY_INSPECTION = "builtin:dependency-versions";
|
||||
export const CONFLICT_MARKERS_PRODUCER = "merge-conflict-markers";
|
||||
export const CONFLICT_MARKERS_INSPECTION = "builtin:merge-conflict-markers";
|
||||
|
||||
/** Python inheritance checks the IDE computes from its own inheritance graph (no server offers one). */
|
||||
export const PYTHON_CIRCULAR_BASES_PRODUCER = "python-circular-bases";
|
||||
export const PYTHON_CIRCULAR_BASES_INSPECTION = "builtin:python-circular-bases";
|
||||
export const PYTHON_OVERRIDE_PRODUCER = "python-override";
|
||||
export const PYTHON_OVERRIDE_INSPECTION = "builtin:python-override";
|
||||
export const PYTHON_ABSTRACT_METHOD_PRODUCER = "python-abstract-method";
|
||||
export const PYTHON_ABSTRACT_METHOD_INSPECTION = "builtin:python-abstract-method";
|
||||
export const PYTHON_REDUNDANT_OVERRIDE_PRODUCER = "python-redundant-override";
|
||||
export const PYTHON_REDUNDANT_OVERRIDE_INSPECTION = "builtin:python-redundant-override";
|
||||
|
||||
/** IDEA's Typo options: which parts of source files are checked (plain text always is). */
|
||||
export const SPELLING_OPTIONS = {
|
||||
code: "processCode",
|
||||
@@ -310,6 +320,42 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [
|
||||
defaultLevel: "warning",
|
||||
byCode: true,
|
||||
},
|
||||
{
|
||||
id: PYTHON_CIRCULAR_BASES_INSPECTION,
|
||||
producer: PYTHON_CIRCULAR_BASES_PRODUCER,
|
||||
name: "Circular inheritance",
|
||||
group: "Python",
|
||||
description:
|
||||
"Reports a Python class that ends up among its own ancestors: Python raises 'Cannot create a consistent MRO' when the module is imported.",
|
||||
defaultLevel: "error",
|
||||
},
|
||||
{
|
||||
id: PYTHON_OVERRIDE_INSPECTION,
|
||||
producer: PYTHON_OVERRIDE_PRODUCER,
|
||||
name: "Inconsistent '@override'",
|
||||
group: "Python",
|
||||
description:
|
||||
"Reports a method marked typing.override that no base class declares. Only hierarchies the IDE's index knows completely are checked: a base outside the project may declare the method, so those are left alone.",
|
||||
defaultLevel: "warning",
|
||||
},
|
||||
{
|
||||
id: PYTHON_ABSTRACT_METHOD_INSPECTION,
|
||||
producer: PYTHON_ABSTRACT_METHOD_PRODUCER,
|
||||
name: "Abstract method not implemented",
|
||||
group: "Python",
|
||||
description:
|
||||
"Reports a class that leaves a base class's @abstractmethod unimplemented, in a hierarchy the IDE's index knows completely. A class that declares an abstract method of its own is abstract, so it is not reported.",
|
||||
defaultLevel: "warning",
|
||||
},
|
||||
{
|
||||
id: PYTHON_REDUNDANT_OVERRIDE_INSPECTION,
|
||||
producer: PYTHON_REDUNDANT_OVERRIDE_PRODUCER,
|
||||
name: "Redundant override",
|
||||
group: "Python",
|
||||
description:
|
||||
"Reports a method whose body only repeats the inherited one — 'pass' over a method that does nothing, or calling 'super()' with the same arguments — so the override can be removed.",
|
||||
defaultLevel: "weakWarning",
|
||||
},
|
||||
{
|
||||
id: "builtin:sql",
|
||||
producer: "sql-inspections",
|
||||
|
||||
@@ -78,7 +78,7 @@ describe("IDEA keymap parity", () => {
|
||||
["editor.nextSplitter", ["Alt+Tab"], ["Alt+Tab"]],
|
||||
["toolwindow.resizeLeft", ["Ctrl+Alt+Left"], ["Ctrl+Alt+Shift+Left"]],
|
||||
["toolwindow.closeContent", ["Meta+W", "Ctrl+Shift+F4"], ["Ctrl+F4", "Ctrl+Shift+F4"]],
|
||||
["layout.restoreDefault", ["Shift+F12"], ["Shift+F12"]],
|
||||
["layout.restoreCurrent", ["Shift+F12"], ["Shift+F12"]],
|
||||
["workbench.stopBackgroundProcesses", ["Meta+Shift+F2"], ["Ctrl+Shift+F2"]],
|
||||
["navigate.back", ["Meta+[", "Meta+Alt+Left", "Button4", "SwipeRight"], ["Ctrl+Alt+Left", "Button4"]],
|
||||
["navigate.forward", ["Meta+]", "Meta+Alt+Right", "Button5", "SwipeLeft"], ["Ctrl+Alt+Right", "Button5"]],
|
||||
|
||||
@@ -237,7 +237,8 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"toolwindow.resizeRight": ["Ctrl+Alt+Right"],
|
||||
"toolwindow.resizeUp": ["Ctrl+Alt+Up"],
|
||||
"toolwindow.resizeDown": ["Ctrl+Alt+Down"],
|
||||
"layout.restoreDefault": ["Shift+F12"],
|
||||
"layout.restoreCurrent": ["Shift+F12"],
|
||||
"layout.restoreDefault": [],
|
||||
"toolwindow.jumpToLast": ["F12"],
|
||||
"toolwindow.hideActive": ["Shift+Escape"],
|
||||
"toolwindow.focusEditor": ["Escape"],
|
||||
|
||||
@@ -234,7 +234,8 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"toolwindow.terminal": ["Alt+F12"],
|
||||
"toolwindow.hideAll": ["Ctrl+Shift+F12"],
|
||||
"toolwindow.maximize": ["Ctrl+Shift+'"],
|
||||
"layout.restoreDefault": ["Shift+F12"],
|
||||
"layout.restoreCurrent": ["Shift+F12"],
|
||||
"layout.restoreDefault": [],
|
||||
"toolwindow.jumpToLast": ["F12"],
|
||||
"toolwindow.hideActive": ["Shift+Escape"],
|
||||
"toolwindow.focusEditor": ["Escape"],
|
||||
|
||||
@@ -65,6 +65,7 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"toolwindow.resizeRight": [],
|
||||
"toolwindow.resizeUp": [],
|
||||
"toolwindow.resizeDown": [],
|
||||
"layout.restoreCurrent": [],
|
||||
"layout.restoreDefault": [],
|
||||
"workbench.stopBackgroundProcesses": [],
|
||||
"navigate.typeHierarchy": [],
|
||||
|
||||
@@ -457,6 +457,8 @@
|
||||
"menu.runAnything.show": "Run Anything…",
|
||||
"menu.localHistory.putLabel": "Put Label…",
|
||||
"menu.toolWindowLayouts": "Tool Window Layouts",
|
||||
"menu.layout.saveCurrent": "Save Changes in Current Layout",
|
||||
"menu.layout.restoreCurrent": "Restore Current Layout",
|
||||
"menu.layout.save": "Save Current Layout as…",
|
||||
"menu.layout.restoreDefault": "Restore Default Layout",
|
||||
"menu.layout.rename": "Rename Layout…",
|
||||
|
||||
@@ -532,8 +532,8 @@
|
||||
"Library": "Library",
|
||||
"Select Classes Directory": "Select Classes Directory",
|
||||
"Select Library JAR": "Select Library JAR",
|
||||
"Add JAR or Directory…": "Add JAR or Directory…",
|
||||
"Add Classes Folder…": "Add Classes Folder…",
|
||||
"JAR or Directory…": "JAR or Directory…",
|
||||
"Classes Folder…": "Classes Folder…",
|
||||
"Remove Library": "Remove Library",
|
||||
"No project libraries added.": "No project libraries added.",
|
||||
"Library Details": "Library Details",
|
||||
@@ -586,7 +586,7 @@
|
||||
"Project Structure sections": "Project Structure sections",
|
||||
"Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "Custom test output paths are not supported yet. Maven and Gradle manage their own test output.",
|
||||
"Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.",
|
||||
"Add Module Overrides": "Add Module Overrides",
|
||||
"Add Module Overrides…": "Add Module Overrides…",
|
||||
"Import Module from Existing Sources": "Import Module from Existing Sources",
|
||||
"Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.",
|
||||
"Directory for production classes, relative to the project root and inside this module.": "Directory for production classes, relative to the project root and inside this module.",
|
||||
@@ -1753,5 +1753,17 @@
|
||||
"YAML File": "YAML File",
|
||||
"TOML File": "TOML File",
|
||||
"EditorConfig File": "EditorConfig File",
|
||||
".gitignore File": ".gitignore File"
|
||||
".gitignore File": ".gitignore File",
|
||||
"Circular inheritance": "Circular inheritance",
|
||||
"Inconsistent '@override'": "Inconsistent '@override'",
|
||||
"Abstract method not implemented": "Abstract method not implemented",
|
||||
"Redundant override": "Redundant override",
|
||||
"Reports a Python class that ends up among its own ancestors: Python raises 'Cannot create a consistent MRO' when the module is imported.": "Reports a Python class that ends up among its own ancestors: Python raises 'Cannot create a consistent MRO' when the module is imported.",
|
||||
"Reports a method marked typing.override that no base class declares. Only hierarchies the IDE's index knows completely are checked: a base outside the project may declare the method, so those are left alone.": "Reports a method marked typing.override that no base class declares. Only hierarchies the IDE's index knows completely are checked: a base outside the project may declare the method, so those are left alone.",
|
||||
"Reports a class that leaves a base class's @abstractmethod unimplemented, in a hierarchy the IDE's index knows completely. A class that declares an abstract method of its own is abstract, so it is not reported.": "Reports a class that leaves a base class's @abstractmethod unimplemented, in a hierarchy the IDE's index knows completely. A class that declares an abstract method of its own is abstract, so it is not reported.",
|
||||
"Reports a method whose body only repeats the inherited one — 'pass' over a method that does nothing, or calling 'super()' with the same arguments — so the override can be removed.": "Reports a method whose body only repeats the inherited one — 'pass' over a method that does nothing, or calling 'super()' with the same arguments — so the override can be removed.",
|
||||
"Circular inheritance: '{name}' inherits from itself": "Circular inheritance: '{name}' inherits from itself",
|
||||
"Method '{name}' is marked @override but no base class declares it": "Method '{name}' is marked @override but no base class declares it",
|
||||
"Class '{name}' does not implement abstract method '{method}'": "Class '{name}' does not implement abstract method '{method}'",
|
||||
"Redundant override of '{name}'": "Redundant override of '{name}'"
|
||||
}
|
||||
@@ -2604,7 +2604,7 @@
|
||||
"Restored branch {name}": "Rama {name} restaurada",
|
||||
"Commits of {name}": "Confirmaciones de {name}",
|
||||
"All files are up-to-date": "Todos los archivos están actualizados",
|
||||
"Update Info": "Información de actualización",
|
||||
"Update Info: {target}": "Información de actualización: {target}",
|
||||
"Press again to go to the next file": "Presiona de nuevo para ir al siguiente archivo",
|
||||
"Press again to go to the previous file": "Presiona de nuevo para ir al archivo anterior",
|
||||
"Include in commit": "Incluir en la confirmación",
|
||||
@@ -4040,7 +4040,6 @@
|
||||
"Headers ({count})": "Encabezados ({count})",
|
||||
"Headers": "Encabezados",
|
||||
"Delete the macro '{name}'?": "¿Eliminar la macro '{name}'?",
|
||||
"{count} processes": "{count} procesos",
|
||||
"Memory: {usage}": "Memoria: {usage}",
|
||||
" Memory {before} → {after}.": " Memoria {before} → {after}.",
|
||||
"{count} syntax tree dropped, index compacted.{memory}": "{count} árbol sintáctico descartado, índice compactado.{memory}",
|
||||
|
||||
@@ -2505,7 +2505,7 @@
|
||||
"Restored branch {name}": "Branche {name} restaurée",
|
||||
"Commits of {name}": "Commits de {name}",
|
||||
"All files are up-to-date": "Tous les fichiers sont à jour",
|
||||
"Update Info": "Informations de mise à jour",
|
||||
"Update Info: {target}": "Informations de mise à jour: {target}",
|
||||
"Press again to go to the next file": "Appuyez à nouveau pour aller au fichier suivant",
|
||||
"Press again to go to the previous file": "Appuyez à nouveau pour aller au fichier précédent",
|
||||
"Include in commit": "Inclure dans le commit",
|
||||
@@ -3904,7 +3904,6 @@
|
||||
"Headers ({count})": "En-têtes ({count})",
|
||||
"Headers": "En-têtes",
|
||||
"Delete the macro '{name}'?": "Supprimer la macro '{name}' ?",
|
||||
"{count} processes": "{count} processus",
|
||||
"Memory: {usage}": "Mémoire : {usage}",
|
||||
" Memory {before} → {after}.": " Mémoire {before} → {after}.",
|
||||
"{count} syntax tree dropped, index compacted.{memory}": "{count} arbre syntaxique supprimé, index compacté.{memory}",
|
||||
|
||||
@@ -2654,7 +2654,7 @@
|
||||
"Restored branch {name}": "{name} 브랜치를 복원했습니다",
|
||||
"Commits of {name}": "{name}의 커밋",
|
||||
"All files are up-to-date": "모든 파일이 최신 상태입니다",
|
||||
"Update Info": "업데이트 정보",
|
||||
"Update Info: {target}": "업데이트 정보: {target}",
|
||||
"Press again to go to the next file": "다음 파일로 이동하려면 다시 누르세요",
|
||||
"Press again to go to the previous file": "이전 파일로 이동하려면 다시 누르세요",
|
||||
"Include in commit": "커밋에 포함",
|
||||
@@ -4101,7 +4101,6 @@
|
||||
"Headers ({count})": "헤더({count})",
|
||||
"Headers": "헤더",
|
||||
"Delete the macro '{name}'?": "매크로 '{name}'을(를) 삭제하시겠습니까?",
|
||||
"{count} processes": "프로세스 {count}개",
|
||||
"Memory: {usage}": "메모리: {usage}",
|
||||
" Memory {before} → {after}.": " 메모리 {before} → {after}.",
|
||||
"{count} syntax tree dropped, index compacted.{memory}": "구문 트리 {count}개를 삭제하고 색인을 압축했습니다.{memory}",
|
||||
|
||||
@@ -2581,7 +2581,7 @@
|
||||
"Restored branch {name}": "Przywrócono gałąź {name}",
|
||||
"Commits of {name}": "Zatwierdzenia dla {name}",
|
||||
"All files are up-to-date": "Wszystkie pliki są aktualne",
|
||||
"Update Info": "Informacje o aktualizacji",
|
||||
"Update Info: {target}": "Informacje o aktualizacji: {target}",
|
||||
"Press again to go to the next file": "Naciśnij ponownie, aby przejść do następnego pliku",
|
||||
"Press again to go to the previous file": "Naciśnij ponownie, aby przejść do poprzedniego pliku",
|
||||
"Include in commit": "Dołącz do zatwierdzenia",
|
||||
@@ -3999,7 +3999,6 @@
|
||||
"Headers ({count})": "Nagłówki ({count})",
|
||||
"Headers": "Nagłówki",
|
||||
"Delete the macro '{name}'?": "Usunąć makro '{name}'?",
|
||||
"{count} processes": "Liczba procesów: {count}",
|
||||
"Memory: {usage}": "Pamięć: {usage}",
|
||||
" Memory {before} → {after}.": " Pamięć {before} → {after}.",
|
||||
"{count} syntax tree dropped, index compacted.{memory}": "Odrzucono drzewo składniowe ({count}), indeks skompresowany.{memory}",
|
||||
|
||||
@@ -2582,7 +2582,7 @@
|
||||
"Restored branch {name}": "Branch {name} restaurada",
|
||||
"Commits of {name}": "Commits de {name}",
|
||||
"All files are up-to-date": "Todos os arquivos estão atualizados",
|
||||
"Update Info": "Informações de atualização",
|
||||
"Update Info: {target}": "Informações de atualização: {target}",
|
||||
"Press again to go to the next file": "Pressione novamente para ir para o próximo arquivo",
|
||||
"Press again to go to the previous file": "Pressione novamente para ir para o arquivo anterior",
|
||||
"Include in commit": "Incluir no commit",
|
||||
@@ -4005,7 +4005,6 @@
|
||||
"Headers ({count})": "Cabeçalhos ({count})",
|
||||
"Headers": "Cabeçalhos",
|
||||
"Delete the macro '{name}'?": "Excluir a macro '{name}'?",
|
||||
"{count} processes": "{count} processos",
|
||||
"Memory: {usage}": "Memória: {usage}",
|
||||
" Memory {before} → {after}.": " Memória {before} → {after}.",
|
||||
"{count} syntax tree dropped, index compacted.{memory}": "{count} árvore sintática descartada, índice compactado.{memory}",
|
||||
|
||||
@@ -2098,8 +2098,8 @@
|
||||
"Library": "库",
|
||||
"Select Classes Directory": "选择类目录",
|
||||
"Select Library JAR": "选择库 JAR",
|
||||
"Add JAR or Directory…": "添加 JAR 或目录…",
|
||||
"Add Classes Folder…": "添加类文件夹…",
|
||||
"JAR or Directory…": "JAR 或目录…",
|
||||
"Classes Folder…": "类文件夹…",
|
||||
"Remove Library": "移除库",
|
||||
"No project libraries added.": "尚未添加项目库。",
|
||||
"Library Details": "库详情",
|
||||
@@ -2390,6 +2390,9 @@
|
||||
"Restart is only available in the desktop app": "只有桌面应用可以重启",
|
||||
"Restore Default": "恢复默认值",
|
||||
"Restore Default Layout": "恢复默认布局",
|
||||
"Restore Current Layout": "恢复当前布局",
|
||||
"Save Changes in Current Layout": "保存对当前布局的更改",
|
||||
"Restores the active saved layout, or the default layout when none is active.": "恢复当前选中的已保存布局;没有选中的布局时恢复默认布局。",
|
||||
"Restore Defaults": "恢复默认值",
|
||||
"Restore Rows": "恢复行",
|
||||
"Restore Size": "恢复大小",
|
||||
@@ -3229,7 +3232,7 @@
|
||||
"Restored branch {name}": "已恢复分支 {name}",
|
||||
"Commits of {name}": "{name} 的提交",
|
||||
"All files are up-to-date": "所有文件都是最新的",
|
||||
"Update Info": "更新信息",
|
||||
"Update Info: {target}": "更新信息: {target}",
|
||||
"Press again to go to the next file": "再按一次转到下一个文件",
|
||||
"Press again to go to the previous file": "再按一次转到上一个文件",
|
||||
"Include in commit": "包含在提交中",
|
||||
@@ -4715,7 +4718,6 @@
|
||||
"Headers ({count})": "标头 ({count})",
|
||||
"Headers": "标头",
|
||||
"Delete the macro '{name}'?": "是否删除宏 '{name}'?",
|
||||
"{count} processes": "{count} 个进程",
|
||||
"Memory: {usage}": "内存:{usage}",
|
||||
" Memory {before} → {after}.": " 内存 {before} → {after}。",
|
||||
"{count} syntax tree dropped, index compacted.{memory}": "已丢弃 {count} 个语法树,已压缩索引。{memory}",
|
||||
@@ -7006,7 +7008,7 @@
|
||||
"The check could not run: {reason}": "检查无法运行:{reason}",
|
||||
"Custom test output paths are not supported yet. Maven and Gradle manage their own test output.": "暂不支持自定义测试输出路径。测试输出由 Maven 和 Gradle 管理。",
|
||||
"Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.": "暂不支持自定义制品打包。请构建和部署 Maven 或 Gradle 定义的制品。",
|
||||
"Add Module Overrides": "添加模块覆盖设置",
|
||||
"Add Module Overrides…": "添加模块覆盖设置…",
|
||||
"Module overrides only apply to a directory inside the opened project. To import an existing module from outside it, use Import Module from Existing Sources.": "模块覆盖设置只适用于当前打开项目内的目录。要从外部导入已有模块,请使用「导入已有模块」。",
|
||||
"Directory for production classes, relative to the project root and inside this module.": "生产类文件目录,相对于项目根目录,且必须位于当前模块内。",
|
||||
"Scope controls Run/Debug only. JARs are also available to Java code assistance.": "作用域仅控制运行和调试。JAR 库也可用于 Java 代码辅助。",
|
||||
@@ -8141,5 +8143,25 @@
|
||||
"YAML File": "YAML 文件",
|
||||
"TOML File": "TOML 文件",
|
||||
"EditorConfig File": "EditorConfig 文件",
|
||||
".gitignore File": ".gitignore 文件"
|
||||
".gitignore File": ".gitignore 文件",
|
||||
"Circular inheritance": "循环继承",
|
||||
"Inconsistent '@override'": "不一致的 '@override'",
|
||||
"Abstract method not implemented": "未实现抽象方法",
|
||||
"Redundant override": "冗余的重写",
|
||||
"Reports a Python class that ends up among its own ancestors: Python raises 'Cannot create a consistent MRO' when the module is imported.": "报告最终成为自身祖先的 Python 类:导入该模块时 Python 会抛出 'Cannot create a consistent MRO'。",
|
||||
"Reports a method marked typing.override that no base class declares. Only hierarchies the IDE's index knows completely are checked: a base outside the project may declare the method, so those are left alone.": "报告标记了 typing.override 但没有任何基类声明该方法的方法。只检查 IDE 索引完整已知的继承层次:项目之外的基类可能声明了该方法,因此这些情况不做报告。",
|
||||
"Reports a class that leaves a base class's @abstractmethod unimplemented, in a hierarchy the IDE's index knows completely. A class that declares an abstract method of its own is abstract, so it is not reported.": "报告在 IDE 索引完整已知的继承层次中未实现基类 @abstractmethod 的类。自身声明了抽象方法的类本身就是抽象类,因此不做报告。",
|
||||
"Reports a method whose body only repeats the inherited one — 'pass' over a method that does nothing, or calling 'super()' with the same arguments — so the override can be removed.": "报告方法体只是重复继承来的方法(对什么都不做的方法使用 'pass',或以相同参数调用 'super()')的重写,这类重写可以删除。",
|
||||
"Circular inheritance: '{name}' inherits from itself": "循环继承:'{name}' 继承了自身",
|
||||
"Method '{name}' is marked @override but no base class declares it": "方法 '{name}' 标记了 @override,但没有任何基类声明该方法",
|
||||
"Class '{name}' does not implement abstract method '{method}'": "类 '{name}' 未实现抽象方法 '{method}'",
|
||||
"Redundant override of '{name}'": "冗余的重写:'{name}'",
|
||||
"Import Module from Existing Sources…": "导入已有模块…",
|
||||
"{name} (copy)": "{name}(副本)",
|
||||
"{name} (copy {n})": "{name}(副本 {n})",
|
||||
"New Project Library": "新建项目库",
|
||||
"Copy Library": "复制库",
|
||||
"PID {pid}": "PID {pid}",
|
||||
"PID {pid} · {count} processes": "PID {pid} · {count} 个进程",
|
||||
"End Process {label}": "结束进程 {label}"
|
||||
}
|
||||
@@ -457,6 +457,8 @@
|
||||
"menu.runAnything.show": "运行任何内容…",
|
||||
"menu.localHistory.putLabel": "添加标签…",
|
||||
"menu.toolWindowLayouts": "工具窗口布局",
|
||||
"menu.layout.saveCurrent": "保存对当前布局的更改",
|
||||
"menu.layout.restoreCurrent": "恢复当前布局",
|
||||
"menu.layout.save": "将当前布局另存为…",
|
||||
"menu.layout.restoreDefault": "恢复默认布局",
|
||||
"menu.layout.rename": "重命名布局…",
|
||||
|
||||
@@ -162,6 +162,18 @@ describe("Tree keyboard navigation", () => {
|
||||
expect(lead()).toBe("src");
|
||||
});
|
||||
|
||||
it("collapsing a node collapses everything expanded below it", () => {
|
||||
const onExpandedChange = vi.fn();
|
||||
const { tree, key } = setup({ defaultExpanded: ["src", "main"], onExpandedChange });
|
||||
expect(labels(tree)).toEqual(["src", "main", "App.tsx", "index.ts", "util.ts", "README.md"]);
|
||||
key("Home");
|
||||
key("ArrowLeft");
|
||||
expect(labels(tree)).toEqual(["src", "README.md"]);
|
||||
expect([...onExpandedChange.mock.calls[0]![0]]).toEqual([]);
|
||||
key("ArrowRight");
|
||||
expect(labels(tree)).toEqual(["src", "main", "util.ts", "README.md"]);
|
||||
});
|
||||
|
||||
it("Enter toggles folders and activates leaves", () => {
|
||||
const { tree, lead, key, onActivate } = setup();
|
||||
key("ArrowDown");
|
||||
|
||||
+10
-1
@@ -395,7 +395,16 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
if (!row.expandable || row.expanded === open) return;
|
||||
const next = new Set(expanded);
|
||||
if (open) next.add(row.key);
|
||||
else next.delete(row.key);
|
||||
else {
|
||||
// Collapsing a node also collapses everything expanded below it, so expanding it again
|
||||
// shows only its direct children.
|
||||
next.delete(row.key);
|
||||
const stack = [...(getChildren(row.node) ?? [])];
|
||||
while (next.size && stack.length) {
|
||||
const n = stack.pop()!;
|
||||
if (next.delete(getKey(n)) || isExpandable(n)) stack.push(...(getChildren(n) ?? []));
|
||||
}
|
||||
}
|
||||
if (!expandedControlled) setExpandedInner(next);
|
||||
props.onExpandedChange?.(next, row.node, open);
|
||||
if (open && getChildren(row.node) === undefined) void loadChildren?.(row.node);
|
||||
|
||||
@@ -3,6 +3,11 @@
|
||||
display: block;
|
||||
}
|
||||
|
||||
.image {
|
||||
object-fit: cover;
|
||||
border-radius: var(--radius-small);
|
||||
}
|
||||
|
||||
.mono {
|
||||
color: var(--icon-color, currentColor);
|
||||
}
|
||||
|
||||
@@ -284,3 +284,30 @@ describe("fileIconName", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("image icons", () => {
|
||||
const png =
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";
|
||||
|
||||
it("renders a raster data URI as an image of the icon's size", () => {
|
||||
const { container } = render(<Icon name={png} size={14} />);
|
||||
const img = container.querySelector("img")!;
|
||||
expect(img.getAttribute("src")).toBe(png);
|
||||
expect([img.width, img.height]).toEqual([14, 14]);
|
||||
expect(container.querySelector("svg")).toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to the file icon for other URIs and oversized images", () => {
|
||||
for (const name of [
|
||||
"https://example.com/avatar.png",
|
||||
"data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=",
|
||||
`data:image/png;base64,${"A".repeat(70 * 1024)}`,
|
||||
"data:image/png;base64,not base64!",
|
||||
]) {
|
||||
const { container, unmount } = render(<Icon name={name} />);
|
||||
expect(container.querySelector("img")).toBeNull();
|
||||
expect(container.querySelector("svg")).toBeTruthy();
|
||||
unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
+32
-2
@@ -816,8 +816,19 @@ const withIds = (p: Prepared, prefix: string) => (p.hasIds ? p.html.replace(/__I
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Largest `data:` image accepted as an icon (an avatar or a status badge a plugin fetched). */
|
||||
const MAX_IMAGE_ICON = 64 * 1024;
|
||||
|
||||
/** A small raster image given as a `data:` URI (PNG, JPEG, GIF, WebP), shown in place of an icon. */
|
||||
function isImageIcon(name: string): boolean {
|
||||
return name.length <= MAX_IMAGE_ICON && /^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+=*$/.test(name);
|
||||
}
|
||||
|
||||
export interface IconProps {
|
||||
/** Icon name; unknown names render the generic file icon. `symbol-<kind>` renders a symbol node icon. */
|
||||
/**
|
||||
* Icon name; unknown names render the generic file icon. `symbol-<kind>` renders a symbol node icon,
|
||||
* and a raster `data:` image URI (see `isImageIcon`) renders that image.
|
||||
*/
|
||||
name: IconName | (string & {});
|
||||
size?: number;
|
||||
className?: string;
|
||||
@@ -826,7 +837,26 @@ export interface IconProps {
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function Icon({ name, size = 16, className, style, label }: IconProps) {
|
||||
export function Icon(props: IconProps) {
|
||||
return isImageIcon(props.name) ? <ImageIcon {...props} /> : <SvgIcon {...props} />;
|
||||
}
|
||||
|
||||
function ImageIcon({ name, size = 16, className, style, label }: IconProps) {
|
||||
return (
|
||||
<img
|
||||
className={clsx(styles.icon, styles.image, className)}
|
||||
style={style}
|
||||
src={name}
|
||||
width={size}
|
||||
height={size}
|
||||
alt={label ?? ""}
|
||||
aria-hidden={label ? undefined : true}
|
||||
draggable={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SvgIcon({ name, size = 16, className, style, label }: IconProps) {
|
||||
useFileIconRevision();
|
||||
const uid = useId();
|
||||
const path = iconPath(name);
|
||||
|
||||
@@ -4,7 +4,12 @@ import clsx from "clsx";
|
||||
import { BarButton, IconButton, Popup, ProgressBar, showContextMenu, T, tooltipAttrs } from "@/ui";
|
||||
import { useContributions, useStatusInfo, type StatusItemContribution } from "./contributions";
|
||||
import { ErrorBoundary } from "./ErrorBoundary";
|
||||
import { isStatusItemVisible, statusBarMenu, useStatusWidgetOverrides } from "./statusBarWidgets";
|
||||
import {
|
||||
isStatusItemVisible,
|
||||
statusBarMenu,
|
||||
useStatusWidgetOverrides,
|
||||
useUnavailableStatusWidgets,
|
||||
} from "./statusBarWidgets";
|
||||
import { cancelTask, canCancel, useTasks, type BackgroundTask } from "./tasks";
|
||||
import styles from "./StatusBar.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -32,7 +37,8 @@ export function StatusBar({ lightEdit = false }: { lightEdit?: boolean }) {
|
||||
() => orderStatusItems([...map.values()].filter((i) => !lightEdit || i.lightEdit)),
|
||||
[map, lightEdit],
|
||||
);
|
||||
const visible = (i: StatusItemContribution) => isStatusItemVisible(i, overrides);
|
||||
const unavailable = useUnavailableStatusWidgets();
|
||||
const visible = (i: StatusItemContribution) => !unavailable.has(i.id) && isStatusItemVisible(i, overrides);
|
||||
const render = (item: StatusItemContribution) => {
|
||||
const C = item.component;
|
||||
const shrink = item.align === "left" || item.id === "workbench.tasks";
|
||||
|
||||
@@ -531,6 +531,8 @@ export interface ExternalFileOpenHandler {
|
||||
id: string;
|
||||
/** Lower asks first. Default 100. */
|
||||
order?: number;
|
||||
/** Whether `path` goes to another application. */
|
||||
matches(path: string): boolean;
|
||||
/** Opens `path` outside the IDE; true when it was handed over. */
|
||||
open(path: string): boolean | Promise<boolean>;
|
||||
}
|
||||
@@ -544,6 +546,11 @@ export function registerExternalFileOpenHandler(handler: ExternalFileOpenHandler
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether opening `path` would hand it to another application. */
|
||||
export function opensExternally(path: string): boolean {
|
||||
return [...externalFileOpenHandlers.values()].some((h) => h.matches(path));
|
||||
}
|
||||
|
||||
/** Opens `path` with another application; false when no handler took it. Handler failures fall through. */
|
||||
export async function openFileExternally(path: string): Promise<boolean> {
|
||||
const handlers = [...externalFileOpenHandlers.values()].sort(
|
||||
@@ -551,7 +558,7 @@ export async function openFileExternally(path: string): Promise<boolean> {
|
||||
);
|
||||
for (const handler of handlers) {
|
||||
try {
|
||||
if (await handler.open(path)) return true;
|
||||
if (handler.matches(path) && (await handler.open(path))) return true;
|
||||
} catch (e) {
|
||||
console.warn(`external file opener ${handler.id} failed`, e);
|
||||
}
|
||||
@@ -619,6 +626,8 @@ export interface OpenOptions {
|
||||
focus?: boolean;
|
||||
/** Open in the text editor even when a file editor provider claims the file (SVG as text). */
|
||||
asText?: boolean;
|
||||
/** False: leave files that go to another application unopened (autoscroll must not launch apps). */
|
||||
external?: boolean;
|
||||
}
|
||||
|
||||
export interface OpenEditorTab {
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { openFileExternally, registerExternalFileOpenHandler, type ExternalFileOpenHandler } from "./contributions";
|
||||
import {
|
||||
openFileExternally,
|
||||
opensExternally,
|
||||
registerExternalFileOpenHandler,
|
||||
type ExternalFileOpenHandler,
|
||||
} from "./contributions";
|
||||
|
||||
const disposers: Array<() => void> = [];
|
||||
|
||||
function register(handler: ExternalFileOpenHandler) {
|
||||
const dispose = registerExternalFileOpenHandler(handler);
|
||||
function register(handler: Omit<ExternalFileOpenHandler, "matches"> & Partial<ExternalFileOpenHandler>) {
|
||||
const dispose = registerExternalFileOpenHandler({ matches: () => true, ...handler });
|
||||
disposers.push(dispose);
|
||||
return dispose;
|
||||
}
|
||||
@@ -57,6 +62,15 @@ describe("external file openers", () => {
|
||||
expect(await openFileExternally("/p/a.ts")).toBe(false);
|
||||
});
|
||||
|
||||
it("skips handlers that do not match and reports whether one would", async () => {
|
||||
const open = vi.fn(() => true);
|
||||
register({ id: "pdf", matches: (p) => p.endsWith(".pdf"), open });
|
||||
expect(opensExternally("/p/a.pdf")).toBe(true);
|
||||
expect(opensExternally("/p/a.ts")).toBe(false);
|
||||
expect(await openFileExternally("/p/a.ts")).toBe(false);
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("disposal removes a handler", async () => {
|
||||
const dispose = register({ id: "only", open: () => true });
|
||||
expect(await openFileExternally("/p/a.xlsx")).toBe(true);
|
||||
|
||||
@@ -16,7 +16,7 @@ import { useProject } from "@/platform/project";
|
||||
import { ContextMenuHost } from "@/ui";
|
||||
import { registerStatusItem, type StatusItemContribution } from "./contributions";
|
||||
import { StatusBar } from "./StatusBar";
|
||||
import { isStatusItemVisible, statusBarMenu } from "./statusBarWidgets";
|
||||
import { isStatusItemVisible, setStatusWidgetAvailable, statusBarMenu } from "./statusBarWidgets";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { registerShellActions } from "./shellActions";
|
||||
|
||||
@@ -106,6 +106,28 @@ describe("status bar widgets", () => {
|
||||
expect(await screen.findByText("w.memory")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("leaves widgets that don't apply to the project out of the bar and the menu", async () => {
|
||||
disposers.push(
|
||||
registerStatusItem(item("w.caret", { title: "Line:Column Number", priority: 1 })),
|
||||
registerStatusItem(item("w.php", { title: "PHP Language Level", priority: 2 })),
|
||||
() => setStatusWidgetAvailable("w.php", true),
|
||||
);
|
||||
render(
|
||||
<>
|
||||
<StatusBar />
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
expect(screen.getByText("w.php")).toBeTruthy();
|
||||
act(() => setStatusWidgetAvailable("w.php", false));
|
||||
expect(screen.queryByText("w.php")).toBeNull();
|
||||
fireEvent.contextMenu(screen.getByLabelText("Status bar"), { clientX: 10, clientY: 10 });
|
||||
expect(await screen.findByRole("menuitemcheckbox", { name: /Line:Column Number/ })).toBeTruthy();
|
||||
expect(screen.queryByRole("menuitemcheckbox", { name: /PHP Language Level/ })).toBeNull();
|
||||
act(() => setStatusWidgetAvailable("w.php", true));
|
||||
expect(screen.getByText("w.php")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("toggles one widget by id from View › Appearance › Status Bar Widgets", async () => {
|
||||
disposers.push(
|
||||
registerShellActions(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** Which status bar widgets are shown: per-widget defaults, overridden in `appearance.statusBarWidgets`. */
|
||||
import { create } from "zustand";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -14,6 +15,28 @@ export function isStatusItemVisible(
|
||||
return overrides?.[item.id] ?? item.defaultVisible !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Widgets that don't apply to the open project (a language's widget in a project without
|
||||
* that language): neither shown nor listed in the menus until they apply again.
|
||||
*/
|
||||
const useUnavailable = create<{ ids: ReadonlySet<string> }>(() => ({ ids: new Set() }));
|
||||
|
||||
export function setStatusWidgetAvailable(id: string, available: boolean): void {
|
||||
useUnavailable.setState((s) => {
|
||||
if (s.ids.has(id) !== available) return s;
|
||||
const ids = new Set(s.ids);
|
||||
if (available) ids.delete(id);
|
||||
else ids.add(id);
|
||||
return { ids };
|
||||
});
|
||||
}
|
||||
|
||||
export const isStatusWidgetAvailable = (id: string) => !useUnavailable.getState().ids.has(id);
|
||||
|
||||
export function useUnavailableStatusWidgets(): ReadonlySet<string> {
|
||||
return useUnavailable((s) => s.ids);
|
||||
}
|
||||
|
||||
export interface StatusWidgetRow {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -22,13 +45,13 @@ export interface StatusWidgetRow {
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
/** Every titled widget of `items` (in bar order) with its visibility: the rows users can switch. */
|
||||
/** Every titled widget of `items` that applies (in bar order) with its visibility: the rows users can switch. */
|
||||
export function statusWidgetRows(
|
||||
items: StatusItemContribution[],
|
||||
overrides: WidgetOverrides | undefined,
|
||||
): StatusWidgetRow[] {
|
||||
return items
|
||||
.filter((i) => i.title)
|
||||
.filter((i) => i.title && isStatusWidgetAvailable(i.id))
|
||||
.map((i) => ({
|
||||
id: i.id,
|
||||
title: i.title!,
|
||||
|
||||
@@ -10,8 +10,10 @@ import {
|
||||
deleteLayout,
|
||||
layoutNames,
|
||||
renameLayout,
|
||||
restoreCurrentLayout,
|
||||
restoreDefaultLayout,
|
||||
restoreLayout,
|
||||
saveCurrentLayout,
|
||||
saveLayout,
|
||||
useToolWindowLayouts,
|
||||
} from "./layouts";
|
||||
@@ -93,6 +95,28 @@ function layoutActions(): Action[] {
|
||||
if (name) restoreLayout(name);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "layout.restoreCurrent",
|
||||
title: "Restore Current Layout",
|
||||
description: "Restores the active saved layout, or the default layout when none is active.",
|
||||
category: "Window",
|
||||
keywords: ["tool window layout", "reset"],
|
||||
when: "projectOpen",
|
||||
run: () => {
|
||||
exitDistractionFree();
|
||||
restoreCurrentLayout();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "layout.saveCurrent",
|
||||
title: "Save Changes in Current Layout",
|
||||
category: "Window",
|
||||
keywords: ["tool window layout", "store layout"],
|
||||
when: "projectOpen && toolWindowLayoutActive",
|
||||
run: () => {
|
||||
saveCurrentLayout();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "layout.restoreDefault",
|
||||
title: "Restore Default Layout",
|
||||
@@ -175,7 +199,11 @@ export function installToolWindowActions(): () => void {
|
||||
const unsubscribe = useContributions.subscribe((s, prev) => {
|
||||
if (s.toolWindows !== prev.toolWindows) sync();
|
||||
});
|
||||
const publishLayouts = () => setContext("toolWindowLayoutsSaved", useToolWindowLayouts.getState().layouts.length > 0);
|
||||
const publishLayouts = () => {
|
||||
const { layouts, active } = useToolWindowLayouts.getState();
|
||||
setContext("toolWindowLayoutsSaved", layouts.length > 0);
|
||||
setContext("toolWindowLayoutActive", !!active);
|
||||
};
|
||||
publishLayouts();
|
||||
const unsubscribeLayouts = useToolWindowLayouts.subscribe(publishLayouts);
|
||||
/** The window an Options menu names, else the active one. */
|
||||
|
||||
@@ -43,6 +43,32 @@ beforeEach(() => {
|
||||
afterEach(() => disposers.forEach((d) => d()));
|
||||
|
||||
describe("tool window layouts", () => {
|
||||
it("restores the current layout, and saves changes into it", async () => {
|
||||
setContext("projectOpen", true);
|
||||
setToolWindowSize("bottom", 400);
|
||||
saveLayout("Custom 1");
|
||||
setToolWindowSize("bottom", 200);
|
||||
await executeAction("layout.restoreCurrent");
|
||||
expect(useToolWindowLayout.getState().sizes.bottom).toBe(400);
|
||||
|
||||
expect(getContext().toolWindowLayoutActive).toBe(true);
|
||||
setToolWindowSize("bottom", 300);
|
||||
await executeAction("layout.saveCurrent");
|
||||
setToolWindowSize("bottom", 200);
|
||||
await executeAction("layout.restoreCurrent");
|
||||
expect(useToolWindowLayout.getState().sizes.bottom).toBe(300);
|
||||
expect(layoutNames()).toEqual(["Custom 1"]);
|
||||
|
||||
// With no active layout it is the default one.
|
||||
restoreDefaultLayout();
|
||||
expect(getContext().toolWindowLayoutActive).toBe(false);
|
||||
const defaultBottom = useToolWindowLayout.getState().sizes.bottom;
|
||||
setToolWindowSize("bottom", 350);
|
||||
await executeAction("layout.restoreCurrent");
|
||||
expect(useToolWindowLayout.getState().sizes.bottom).toBe(defaultBottom);
|
||||
setContext("projectOpen", false);
|
||||
});
|
||||
|
||||
it("saves and restores visible windows and sizes by name", () => {
|
||||
showToolWindow("structure");
|
||||
showToolWindow("terminal");
|
||||
|
||||
@@ -72,6 +72,20 @@ export function restoreLayout(name: string): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Restore Current Layout: the active saved layout again, or the default one when none is active. */
|
||||
export function restoreCurrentLayout() {
|
||||
const { active } = useToolWindowLayouts.getState();
|
||||
if (!active || !restoreLayout(active)) restoreDefaultLayout();
|
||||
}
|
||||
|
||||
/** Save Changes in Current Layout: the active saved layout takes the windows as they are now. */
|
||||
export function saveCurrentLayout(): boolean {
|
||||
const { active } = useToolWindowLayouts.getState();
|
||||
if (!active) return false;
|
||||
saveLayout(active);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function restoreDefaultLayout() {
|
||||
applyToolWindowLayout(defaultLayoutSnapshot());
|
||||
write({ ...useToolWindowLayouts.getState(), active: null });
|
||||
|
||||
Reference in new issue
Заблокувати користувача