mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 09:39:27 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e091561937 |
No files matched your search
@@ -102,8 +102,6 @@ pub enum IdeEvent {
|
||||
WorkspaceEditApplied {
|
||||
id: u32,
|
||||
paths: Vec<crate::IpcPath>,
|
||||
/// Files the edit renamed, as the edit named them: editors open on them follow.
|
||||
moves: Vec<crate::FileMove>,
|
||||
/// Made by an agent through the MCP server's tools: undoable like a refactoring, but
|
||||
/// not announced as one.
|
||||
by_agent: bool,
|
||||
|
||||
@@ -110,17 +110,6 @@ pub struct WorkspaceEditPrecondition {
|
||||
}
|
||||
|
||||
impl WorkspaceEdit {
|
||||
/// The files and folders the edit renames, in order.
|
||||
pub fn moves(&self) -> Vec<FileMove> {
|
||||
self.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Rename { from, to } => Some(FileMove { from: from.clone(), to: to.clone() }),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Coalesces aliases of the same file before applying edits against its original text.
|
||||
/// Resource operations separate batches because later edits may use the new contents.
|
||||
pub fn deduplicate(&mut self) {
|
||||
@@ -195,14 +184,6 @@ pub enum FileEdit {
|
||||
},
|
||||
}
|
||||
|
||||
/// One file or folder move.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileMove {
|
||||
pub from: crate::IpcPath,
|
||||
pub to: crate::IpcPath,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Severity {
|
||||
|
||||
@@ -668,8 +668,8 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
if hits.len() > limit {
|
||||
break;
|
||||
}
|
||||
// Find in Files reports a very long line in windows cut around its matches: such lines
|
||||
// are matched again in the file's whole text, so a match keeps its real end.
|
||||
// Find in Files keeps a window of very long lines and drops the matches outside it:
|
||||
// such lines are matched again in the file's whole text.
|
||||
let long = |m: &ide_search::LineMatch| m.text_offset > 0 || m.text.encode_utf16().count() + 1 >= LINE_WINDOW;
|
||||
let whole = if file.matches.iter().any(long) {
|
||||
crate::ops::fs::fs_read_text(&host, call.window(), file.path.0.clone())
|
||||
@@ -679,15 +679,11 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// One window per far-apart match: a line is expanded once.
|
||||
let mut expanded = std::collections::HashSet::new();
|
||||
for m in &file.matches {
|
||||
if let Some((ranges, text)) = &whole
|
||||
&& long(m)
|
||||
{
|
||||
if expanded.insert(m.line) {
|
||||
hits.extend(line_hits(path, text, ranges, m.line));
|
||||
}
|
||||
hits.extend(line_hits(path, text, ranges, m.line));
|
||||
continue;
|
||||
}
|
||||
let line_end = m.text_offset + m.text.encode_utf16().count() as u32;
|
||||
|
||||
@@ -85,7 +85,7 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
|
||||
}
|
||||
|
||||
/// Structure view: LSP document symbols when available (with tree-sitter
|
||||
/// visibility and type-alias kinds), tree-sitter otherwise.
|
||||
/// visibility), tree-sitter otherwise.
|
||||
/// Tree-sitter answers come from the per-document tree cache (incremental
|
||||
/// re-parse); large documents get no syntax structure.
|
||||
#[command(trust = always)]
|
||||
@@ -113,13 +113,10 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
|
||||
};
|
||||
let syntax = || project.syntax.outline(doc, &snap.language, snap.version, &snap.text);
|
||||
Ok(match lsp {
|
||||
// Server symbols carry no visibility, nor a kind for type aliases; borrow them from
|
||||
// the syntax tree.
|
||||
// Server symbols carry no visibility; borrow it from the syntax tree.
|
||||
Some(mut items) => {
|
||||
if !snap.large {
|
||||
let syntax = syntax();
|
||||
ide_language::merge_visibility(&mut items, &syntax);
|
||||
ide_language::merge_kinds(&mut items, &syntax);
|
||||
ide_language::merge_visibility(&mut items, &syntax());
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
@@ -22,17 +22,6 @@ pub fn literal_range(l: ide_language::Literal) -> ide_search::LiteralRange {
|
||||
ide_search::LiteralRange { start: l.start, end: l.end, kind }
|
||||
}
|
||||
|
||||
/// Comments and string literals of `text`, for the search context of Find and Replace in Files.
|
||||
pub(crate) fn literals_of(
|
||||
project: &crate::project::Project,
|
||||
syntax: &ide_language::Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
) -> Option<Vec<ide_search::LiteralRange>> {
|
||||
let language = project.languages.detect(path, text.lines().next());
|
||||
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
|
||||
}
|
||||
|
||||
/// Find in Files. Results stream through `on_event`; ends with `Done`.
|
||||
/// Cancel with `cancel_request(request)`.
|
||||
#[command(trust = always)]
|
||||
@@ -109,7 +98,10 @@ pub(crate) fn search_project(
|
||||
Some(ProjectFileSet::Test) => roots.is_test(rel),
|
||||
_ => true,
|
||||
};
|
||||
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
let literals = |path: &Path, text: &str| {
|
||||
let language = project.languages.detect(path, text.lines().next());
|
||||
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
|
||||
};
|
||||
let defaults = project.documents.file_defaults();
|
||||
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
|
||||
let mut total = SearchSummary::default();
|
||||
|
||||
@@ -75,19 +75,9 @@ pub async fn replace_in_files(
|
||||
let summary = tokio::task::spawn_blocking(move || {
|
||||
let targets = if all_in_scope { scope_targets(&project, &syntax, &query, targets, &cancel)? } else { targets };
|
||||
let host = DocumentsHost(&project.documents);
|
||||
let literals = |path: &Path, text: &str| super::literals_of(&project, &syntax, path, text);
|
||||
ide_search::replace_files_in_context(
|
||||
&host,
|
||||
&query,
|
||||
&replacement,
|
||||
preserve_case,
|
||||
&targets,
|
||||
Some(&literals),
|
||||
&cancel,
|
||||
&|e| {
|
||||
let _ = events.send(e);
|
||||
},
|
||||
)
|
||||
ide_search::replace_files(&host, &query, &replacement, preserve_case, &targets, &cancel, &|e| {
|
||||
let _ = events.send(e);
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ide_core::IdeError::internal(e.to_string()));
|
||||
|
||||
@@ -187,19 +187,6 @@ async fn reads_unsaved_text_and_searches_the_overlay_with_a_limit() {
|
||||
assert_eq!(std::fs::read_to_string(h.root.join("src/a.txt")).unwrap(), "old text\nneedle needle\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn every_match_of_a_long_line_is_found_once() {
|
||||
let h = Harness::new();
|
||||
std::fs::write(
|
||||
h.root.join("src/min.js"),
|
||||
format!("a=1;{}b='longneedle';{}longneedle\n", "x".repeat(2000), "y".repeat(2000)),
|
||||
)
|
||||
.unwrap();
|
||||
let found = h.json("search_text", json!({"q":"longneedle","limit":20})).await;
|
||||
let columns: Vec<_> = found["items"].as_array().unwrap().iter().map(|i| i["startColumn"].clone()).collect();
|
||||
assert_eq!(columns, [json!(2008), json!(4020)], "{found}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn window_reports_supply_editor_selection_and_problems_then_disappear_on_close() {
|
||||
let h = Harness::new();
|
||||
|
||||
@@ -195,56 +195,3 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
/// Replace All past the limit replaces what the search lists: only the matches its Search
|
||||
/// Context keeps (comments, string literals or code), as below the limit.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn replace_all_past_the_limit_keeps_to_the_search_context() {
|
||||
use ide_search::SearchContext as C;
|
||||
let comments = |word: &str| lines(2001, &format!("// {word}"));
|
||||
let code = |name: &str, string: &str| format!("fn {name}() -> &'static str {{ \"{string}\" }}\n");
|
||||
let original = format!("{}{}", comments("tok"), code("tok", "tok"));
|
||||
let cases = [
|
||||
(C::Any, format!("{}{}", comments("X"), code("X", "X"))),
|
||||
(C::InComments, format!("{}{}", comments("X"), code("tok", "tok"))),
|
||||
(C::InStringLiterals, format!("{}{}", comments("tok"), code("tok", "X"))),
|
||||
(C::ExceptComments, format!("{}{}", comments("tok"), code("X", "X"))),
|
||||
(C::ExceptStringLiterals, format!("{}{}", comments("X"), code("X", "tok"))),
|
||||
(C::ExceptCommentsAndStringLiterals, format!("{}{}", comments("tok"), code("X", "tok"))),
|
||||
];
|
||||
for (context, expected) in cases {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("lib.rs"), &original).unwrap();
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
SearchQuery { context, ..query("tok", false) },
|
||||
"X".into(),
|
||||
false,
|
||||
vec![],
|
||||
true,
|
||||
ops::Channel::new(|_| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(root.join("lib.rs")).unwrap(), expected, "{context:?}");
|
||||
host.close_project("main");
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ pub use syntax::{
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
|
||||
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
|
||||
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
|
||||
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility,
|
||||
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
|
||||
@@ -28,7 +28,7 @@ use ide_core::{LanguageId, OutlineItem, Pos, Range};
|
||||
pub use inheritance::ClassBases;
|
||||
pub use lines::{shift_pos, shift_range};
|
||||
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
|
||||
pub use outline::{merge_kinds, merge_visibility};
|
||||
pub use outline::merge_visibility;
|
||||
pub use php_align::PhpAlignment;
|
||||
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
use std::cell::RefCell;
|
||||
|
||||
@@ -495,36 +495,6 @@ pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the syntax tree's kind where a server reported a declared type as a value or a type
|
||||
/// parameter: LSP has no kind for type aliases, so servers fall back to one of those
|
||||
/// (typescript-language-server: Variable; rust-analyzer, sourcekit-lsp: TypeParameter).
|
||||
/// Matched by name and position like [`merge_visibility`].
|
||||
pub fn merge_kinds(target: &mut [OutlineItem], source: &[OutlineItem]) {
|
||||
fn index(items: &[OutlineItem], out: &mut HashMap<(ide_core::Pos, String), SymbolKind>) {
|
||||
for i in items {
|
||||
if i.kind.is_type_like() {
|
||||
out.insert((i.selection_range.start, i.name.clone()), i.kind);
|
||||
}
|
||||
index(&i.children, out);
|
||||
}
|
||||
}
|
||||
fn apply(items: &mut [OutlineItem], map: &HashMap<(ide_core::Pos, String), SymbolKind>) {
|
||||
for i in items {
|
||||
if matches!(i.kind, SymbolKind::Variable | SymbolKind::TypeParameter)
|
||||
&& let Some(&kind) = map.get(&(i.selection_range.start, i.name.clone()))
|
||||
{
|
||||
i.kind = kind;
|
||||
}
|
||||
apply(&mut i.children, map);
|
||||
}
|
||||
}
|
||||
let mut map = HashMap::new();
|
||||
index(source, &mut map);
|
||||
if !map.is_empty() {
|
||||
apply(target, &map);
|
||||
}
|
||||
}
|
||||
|
||||
/// End of `node` without trailing whitespace (C macros and others include the newline).
|
||||
fn trimmed_end(node: &Node, text: &str) -> usize {
|
||||
let (s, e) = (node.start_byte(), node.end_byte());
|
||||
|
||||
@@ -1476,88 +1476,6 @@ fn merge_visibility_matches_by_name_and_position() {
|
||||
assert_eq!(lsp[1].visibility, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_kinds_names_types_a_server_reported_as_values_or_type_parameters() {
|
||||
fn kinds(items: &[OutlineItem], out: &mut Vec<(String, SymbolKind)>) {
|
||||
for i in items {
|
||||
out.push((i.name.clone(), i.kind));
|
||||
kinds(&i.children, out);
|
||||
}
|
||||
}
|
||||
/// The syntax outline with each kind replaced as a server reports it.
|
||||
fn as_server(ts: &[OutlineItem], server: &[(&str, SymbolKind)]) -> Vec<OutlineItem> {
|
||||
fn set(items: &mut [OutlineItem], server: &[(&str, SymbolKind)], at: &mut usize) {
|
||||
for i in items {
|
||||
i.kind = server[*at].1;
|
||||
assert_eq!(i.name, server[*at].0);
|
||||
*at += 1;
|
||||
set(&mut i.children, server, at);
|
||||
}
|
||||
}
|
||||
let mut lsp = ts.to_vec();
|
||||
set(&mut lsp, server, &mut 0);
|
||||
lsp
|
||||
}
|
||||
fn merged(language: &str, src: &str, server: &[(&str, SymbolKind)]) -> Vec<(String, SymbolKind)> {
|
||||
let ts = syntax().outline(&lang(language), src);
|
||||
let mut lsp = as_server(&ts, server);
|
||||
crate::merge_kinds(&mut lsp, &ts);
|
||||
let mut out = Vec::new();
|
||||
kinds(&lsp, &mut out);
|
||||
out
|
||||
}
|
||||
use SymbolKind as K;
|
||||
let owned = |v: &[(&str, SymbolKind)]| v.iter().map(|(n, k)| (n.to_string(), *k)).collect::<Vec<_>>();
|
||||
|
||||
// typescript-language-server: a type alias is a Variable; `const` is one too.
|
||||
let ts = "type Cents = number;\ninterface Shape {}\nconst rate = 1;\n";
|
||||
assert_eq!(
|
||||
merged("typescript", ts, &[("Cents", K::Variable), ("Shape", K::Interface), ("rate", K::Variable)]),
|
||||
owned(&[("Cents", K::TypeAlias), ("Shape", K::Interface), ("rate", K::Variable)]),
|
||||
);
|
||||
|
||||
// rust-analyzer: type aliases and associated types are TypeParameters, a trait an Interface.
|
||||
let rs = "pub type Meters = u32;\ntrait Measure { type Unit; }\nstruct Rope;\nimpl Measure for Rope { type Unit = Meters; }\n";
|
||||
assert_eq!(
|
||||
merged(
|
||||
"rust",
|
||||
rs,
|
||||
&[
|
||||
("Meters", K::TypeParameter),
|
||||
("Measure", K::Interface),
|
||||
("Unit", K::TypeParameter),
|
||||
("Rope", K::Struct),
|
||||
("impl Measure for Rope", K::Variable),
|
||||
("Unit", K::TypeParameter),
|
||||
],
|
||||
),
|
||||
owned(&[
|
||||
("Meters", K::TypeAlias),
|
||||
("Measure", K::Interface),
|
||||
("Unit", K::TypeAlias),
|
||||
("Rope", K::Struct),
|
||||
("impl Measure for Rope", K::Variable),
|
||||
("Unit", K::TypeAlias),
|
||||
]),
|
||||
);
|
||||
|
||||
// sourcekit-lsp: typealias and associatedtype are TypeParameters.
|
||||
let swift = "typealias Meters = Int\nprotocol Measure { associatedtype Unit }\n";
|
||||
assert_eq!(
|
||||
merged("swift", swift, &[("Meters", K::TypeParameter), ("Measure", K::Interface), ("Unit", K::TypeParameter)]),
|
||||
owned(&[("Meters", K::TypeAlias), ("Measure", K::Interface), ("Unit", K::TypeAlias)]),
|
||||
);
|
||||
|
||||
// A type kind the server chose stays: clangd's Class for a typedef, gopls's Struct.
|
||||
let c = "typedef unsigned int meters;\n";
|
||||
assert_eq!(merged("c", c, &[("meters", K::Class)]), owned(&[("meters", K::Class)]));
|
||||
let go = "package p\n\ntype Point struct{}\n";
|
||||
assert_eq!(
|
||||
merged("go", go, &[("p", K::Package), ("Point", K::Struct)]),
|
||||
owned(&[("p", K::Package), ("Point", K::Struct)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spelling_regions_cover_declared_names_only() {
|
||||
let src = "// note\nfn parse_input(raw_text: &str) -> Value { let mut counter = helper(raw_text); \"hi\" }\n";
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
//! Parallel walk + per-file search.
|
||||
|
||||
use crate::iter::for_each_match;
|
||||
use crate::line::line_matches;
|
||||
use crate::line::line_match;
|
||||
use crate::mask::FileMask;
|
||||
use crate::pattern::ScopePattern;
|
||||
use crate::query::{Compiled, line_terminator};
|
||||
use crate::{
|
||||
FileMatches, LineMatch, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary, TextSource,
|
||||
FileMatches, LineMatch, LiteralKind, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary,
|
||||
TextSource,
|
||||
};
|
||||
use grep_regex::RegexMatcher;
|
||||
use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch};
|
||||
@@ -51,7 +52,6 @@ struct Control<'a> {
|
||||
matches: AtomicU32,
|
||||
files: AtomicU32,
|
||||
max: u32,
|
||||
whole_word: bool,
|
||||
}
|
||||
|
||||
impl Control<'_> {
|
||||
@@ -131,7 +131,6 @@ pub(crate) fn run(req: Request<'_>) -> IdeResult<SearchSummary> {
|
||||
matches: AtomicU32::new(0),
|
||||
files: AtomicU32::new(0),
|
||||
max: if req.max_matches == 0 { DEFAULT_MAX_MATCHES } else { req.max_matches },
|
||||
whole_word: req.compiled.whole_word,
|
||||
},
|
||||
};
|
||||
let mut searcher_builder = SearcherBuilder::new();
|
||||
@@ -463,6 +462,12 @@ impl<'a> FileSink<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
|
||||
fn literal_at(literals: &[LiteralRange], pos: usize) -> Option<LiteralKind> {
|
||||
let i = literals.partition_point(|l| l.start <= pos);
|
||||
literals[..i].last().filter(|l| pos < l.end).map(|l| l.kind)
|
||||
}
|
||||
|
||||
impl Sink for FileSink<'_> {
|
||||
type Error = io::Error;
|
||||
|
||||
@@ -483,12 +488,12 @@ impl Sink for FileSink<'_> {
|
||||
let mut found = std::mem::take(&mut self.found);
|
||||
let mut ranges = std::mem::take(&mut self.ranges);
|
||||
found.clear();
|
||||
for_each_match(self.matcher, self.ctl.whole_word, &buffer[..range.end], range.start, |mm| {
|
||||
for_each_match(self.matcher, &buffer[..range.end], range.start, |mm| {
|
||||
found.push((mm.start() - range.start, mm.end() - range.start));
|
||||
});
|
||||
if let Some((context, literals)) = self.context {
|
||||
let block_start = usize::try_from(m.absolute_byte_offset()).unwrap_or(usize::MAX);
|
||||
found.retain(|&(a, _)| context.keeps(literals, block_start.saturating_add(a)));
|
||||
found.retain(|&(a, _)| context.accepts(literal_at(literals, block_start.saturating_add(a))));
|
||||
}
|
||||
|
||||
let mut next = found.iter().copied().peekable();
|
||||
@@ -516,7 +521,7 @@ impl Sink for FileSink<'_> {
|
||||
if !ranges.is_empty() {
|
||||
self.count = self.count.saturating_add(u32::try_from(ranges.len()).unwrap_or(u32::MAX));
|
||||
let line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
|
||||
line_matches(line_no, &block[line_start..content_end], &ranges, &mut self.lines);
|
||||
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
|
||||
}
|
||||
line_start = line_end_incl;
|
||||
line_no += 1;
|
||||
@@ -701,7 +706,6 @@ mod budget_tests {
|
||||
matches: AtomicU32::new(0),
|
||||
files: AtomicU32::new(0),
|
||||
max,
|
||||
whole_word: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,16 @@
|
||||
//! Match iteration that never splits a UTF-8 sequence after an empty match
|
||||
//! (`grep-matcher`'s iterators advance by a single byte), and that applies
|
||||
//! IDEA's whole-word rule.
|
||||
//! (`grep-matcher`'s iterators advance by a single byte).
|
||||
|
||||
use grep_matcher::{Captures, Match, Matcher};
|
||||
use grep_regex::{RegexCaptures, RegexMatcher};
|
||||
|
||||
/// Calls `f` for each non-overlapping match in `haystack[at..]`; `haystack[..at]`
|
||||
/// is only used as look-behind context. With `whole_word`, only [`is_whole_word`] matches.
|
||||
pub(crate) fn for_each_match(
|
||||
matcher: &RegexMatcher,
|
||||
whole_word: bool,
|
||||
haystack: &[u8],
|
||||
at: usize,
|
||||
mut f: impl FnMut(Match),
|
||||
) {
|
||||
/// is only used as look-behind context.
|
||||
pub(crate) fn for_each_match(matcher: &RegexMatcher, haystack: &[u8], at: usize, mut f: impl FnMut(Match)) {
|
||||
let mut at = at;
|
||||
let mut last_end = None;
|
||||
while at <= haystack.len() {
|
||||
let Ok(Some(m)) = matcher.find_at(haystack, at) else { break };
|
||||
if whole_word && !is_whole_word(haystack, m) {
|
||||
at = next_char(haystack, m.start());
|
||||
continue;
|
||||
}
|
||||
at = advance(haystack, m);
|
||||
if m.is_empty() && last_end == Some(m.end()) {
|
||||
continue;
|
||||
@@ -34,7 +23,6 @@ pub(crate) fn for_each_match(
|
||||
/// Like [`for_each_match`] but with capture groups.
|
||||
pub(crate) fn for_each_captures(
|
||||
matcher: &RegexMatcher,
|
||||
whole_word: bool,
|
||||
haystack: &[u8],
|
||||
caps: &mut RegexCaptures,
|
||||
mut f: impl FnMut(&RegexCaptures),
|
||||
@@ -46,10 +34,6 @@ pub(crate) fn for_each_captures(
|
||||
break;
|
||||
}
|
||||
let Some(m) = caps.get(0) else { break };
|
||||
if whole_word && !is_whole_word(haystack, m) {
|
||||
at = next_char(haystack, m.start());
|
||||
continue;
|
||||
}
|
||||
at = advance(haystack, m);
|
||||
if m.is_empty() && last_end == Some(m.end()) {
|
||||
continue;
|
||||
@@ -61,59 +45,12 @@ pub(crate) fn for_each_captures(
|
||||
|
||||
/// Where to resume after `m`: its end, or past the next char for empty matches.
|
||||
fn advance(haystack: &[u8], m: Match) -> usize {
|
||||
if !m.is_empty() { m.end() } else { next_char(haystack, m.end()) }
|
||||
}
|
||||
|
||||
/// The start of the char after the one at `at`.
|
||||
fn next_char(haystack: &[u8], at: usize) -> usize {
|
||||
let mut next = at + 1;
|
||||
if !m.is_empty() {
|
||||
return m.end();
|
||||
}
|
||||
let mut next = m.end() + 1;
|
||||
while next < haystack.len() && (haystack[next] & 0xC0) == 0x80 {
|
||||
next += 1;
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
/// IDEA's whole word (`FindManagerBase.isWholeWord`): an edge where the match has an
|
||||
/// identifier character must not touch another one, unless it follows an escape such as
|
||||
/// `\n`; an edge with another character only must not repeat that character (`==` is not
|
||||
/// in `===`).
|
||||
fn is_whole_word(haystack: &[u8], m: Match) -> bool {
|
||||
let (start, end) = (m.start(), m.end());
|
||||
let word_start = match (char_before(haystack, start), char_at(haystack, start)) {
|
||||
(Some(prev), Some(first)) if is_identifier(first) => {
|
||||
let escaped = char_before(haystack, start - prev.len_utf8()) == Some('\\');
|
||||
!is_identifier(prev) || escaped
|
||||
}
|
||||
(Some(prev), Some(first)) => prev != first,
|
||||
_ => true,
|
||||
};
|
||||
let word_end = match (char_at(haystack, end), char_before(haystack, end)) {
|
||||
(Some(next), Some(last)) if is_identifier(last) => !is_identifier(next),
|
||||
(Some(next), Some(last)) => next != last,
|
||||
(Some(_), None) | (None, _) => true,
|
||||
};
|
||||
word_start && word_end
|
||||
}
|
||||
|
||||
/// Java's identifier part, near enough: letters, digits, `_` and `$`.
|
||||
fn is_identifier(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_' || c == '$'
|
||||
}
|
||||
|
||||
/// The char starting at byte `at` (`None` at the end or in invalid UTF-8).
|
||||
fn char_at(haystack: &[u8], at: usize) -> Option<char> {
|
||||
let rest = haystack.get(at..)?;
|
||||
let len = rest.len().min(4);
|
||||
let s = match std::str::from_utf8(&rest[..len]) {
|
||||
Ok(s) => s,
|
||||
Err(e) => std::str::from_utf8(&rest[..e.valid_up_to()]).ok()?,
|
||||
};
|
||||
s.chars().next()
|
||||
}
|
||||
|
||||
/// The char ending at byte `at` (`None` at the start or in invalid UTF-8).
|
||||
fn char_before(haystack: &[u8], at: usize) -> Option<char> {
|
||||
let head = haystack.get(..at)?;
|
||||
let from = head.len().saturating_sub(4);
|
||||
(from..head.len()).find_map(|i| std::str::from_utf8(&head[i..]).ok().and_then(|s| s.chars().next_back()))
|
||||
}
|
||||
@@ -22,7 +22,7 @@ pub use mask::FileMask;
|
||||
pub use pattern::ScopePattern;
|
||||
pub use replace::{
|
||||
ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview,
|
||||
replace_files, replace_files_in_context, replacement_edits,
|
||||
replace_files, replacement_edits,
|
||||
};
|
||||
pub use words::{WordFiles, WordQuery, files_with_word};
|
||||
|
||||
@@ -99,15 +99,8 @@ impl SearchContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a match starting at byte `at` is kept, given the file's sorted comments and
|
||||
/// string literals. Find and Replace both filter with it, so they keep the same matches.
|
||||
pub fn keeps(self, literals: &[LiteralRange], at: usize) -> bool {
|
||||
let i = literals.partition_point(|l| l.start <= at);
|
||||
self.accepts(literals[..i].last().filter(|l| at < l.end).map(|l| l.kind))
|
||||
}
|
||||
|
||||
/// Only matches inside comments / string literals: files without any are skipped.
|
||||
pub(crate) fn needs_literals(self) -> bool {
|
||||
fn needs_literals(self) -> bool {
|
||||
matches!(self, Self::InComments | Self::InStringLiterals)
|
||||
}
|
||||
}
|
||||
@@ -167,8 +160,7 @@ pub type PathFilter<'a> = &'a (dyn Fn(&str) -> bool + Sync);
|
||||
pub struct LineMatch {
|
||||
/// 0-based line.
|
||||
pub line: u32,
|
||||
/// Line text, truncated around the matches for very long lines: such a line comes as one
|
||||
/// `LineMatch` per window, so the same `line` can repeat.
|
||||
/// Line text, truncated around the match for very long lines.
|
||||
pub text: String,
|
||||
/// UTF-16 column ranges within `text`.
|
||||
pub ranges: Vec<(u32, u32)>,
|
||||
@@ -293,9 +285,7 @@ pub fn match_ranges(text: &str, query: &SearchQuery) -> IdeResult<Vec<(usize, us
|
||||
}
|
||||
let compiled = query::compile(query)?;
|
||||
let mut out = Vec::new();
|
||||
iter::for_each_match(&compiled.matcher, compiled.whole_word, text.as_bytes(), 0, |m| {
|
||||
out.push((m.start(), m.end()))
|
||||
});
|
||||
iter::for_each_match(&compiled.matcher, text.as_bytes(), 0, |m| out.push((m.start(), m.end())));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -318,7 +308,7 @@ pub fn replace_in_text(text: &str, query: &SearchQuery, replacement: &str) -> Id
|
||||
let mut out = Vec::with_capacity(text.len());
|
||||
let mut count = 0u32;
|
||||
let mut last = 0;
|
||||
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
|
||||
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
|
||||
let Some(m) = caps.get(0) else { return };
|
||||
out.extend_from_slice(&haystack[last..m.start()]);
|
||||
last = m.end();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Turns a matched line plus byte ranges into [`LineMatch`]es with UTF-16
|
||||
//! columns. A very long line is cut into windows: one around its first match
|
||||
//! and the matches that fit with it, then one around each match left out.
|
||||
//! Turns a matched line plus byte ranges into a [`LineMatch`] with UTF-16
|
||||
//! columns, truncating very long lines to a window around the first match.
|
||||
|
||||
use crate::LineMatch;
|
||||
|
||||
@@ -9,57 +8,33 @@ pub(crate) const MAX_LINE_LEN: usize = 500;
|
||||
/// How much text before the first match a truncated line keeps.
|
||||
const CONTEXT_BEFORE: usize = 100;
|
||||
|
||||
/// Appends the matches of one line to `out`: a single [`LineMatch`], or one per window of a
|
||||
/// very long line. `line` excludes the line terminator; `ranges` are sorted, non-overlapping
|
||||
/// `line` excludes the line terminator; `ranges` are sorted, non-overlapping
|
||||
/// byte ranges within `line`.
|
||||
pub(crate) fn line_matches(line_no: u32, line: &[u8], ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
|
||||
pub(crate) fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
|
||||
match std::str::from_utf8(line) {
|
||||
Ok(s) => from_str(line_no, s, ranges, out),
|
||||
Ok(s) => from_str(line_no, s, ranges),
|
||||
Err(_) => {
|
||||
let (s, mapped) = lossy(line, ranges);
|
||||
from_str(line_no, &s, &mapped, out)
|
||||
from_str(line_no, &s, &mapped)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
|
||||
let mut out = Vec::new();
|
||||
line_matches(line_no, line, ranges, &mut out);
|
||||
out.swap_remove(0)
|
||||
}
|
||||
|
||||
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
|
||||
if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
|
||||
out.push(in_window(line_no, s, ranges, (0, s.len())).0);
|
||||
return;
|
||||
}
|
||||
let mut rest = ranges;
|
||||
loop {
|
||||
let bounds = window(s, floor_boundary(s, rest.first().map_or(0, |r| r.0.min(s.len()))));
|
||||
let (m, used) = in_window(line_no, s, rest, bounds);
|
||||
out.push(m);
|
||||
rest = &rest[used.max(1)..];
|
||||
if rest.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`LineMatch`] of the text in `bounds` with the leading `ranges` that end inside it (at
|
||||
/// least the first one, cut to the window), and how many ranges it took.
|
||||
fn in_window(line_no: u32, s: &str, ranges: &[(usize, usize)], (start, end): (usize, usize)) -> (LineMatch, usize) {
|
||||
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)]) -> LineMatch {
|
||||
let (start, end) = if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
|
||||
(0, s.len())
|
||||
} else {
|
||||
window(s, floor_boundary(s, ranges.first().map_or(0, |r| r.0.min(s.len()))))
|
||||
};
|
||||
let text = &s[start..end];
|
||||
let text_offset = if start == 0 { 0 } else { utf16_len(&s.as_bytes()[..start]) };
|
||||
|
||||
let mut out = Vec::with_capacity(ranges.len());
|
||||
let (mut pos, mut col) = (start, 0usize);
|
||||
let mut used = 0;
|
||||
for &(a, b) in ranges {
|
||||
if a > end || (a == end && b > a) || (used > 0 && b > end) {
|
||||
if a > end || (a == end && b > a) {
|
||||
break;
|
||||
}
|
||||
used += 1;
|
||||
let (a, b) = (floor_boundary(s, a.max(start)), ceil_boundary(s, b.min(end)));
|
||||
if a < pos {
|
||||
continue;
|
||||
@@ -70,7 +45,7 @@ fn in_window(line_no: u32, s: &str, ranges: &[(usize, usize)], (start, end): (us
|
||||
pos = b;
|
||||
out.push((col_a as u32, col as u32));
|
||||
}
|
||||
(LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }, used)
|
||||
LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }
|
||||
}
|
||||
|
||||
/// Byte window `[start, end)` of at most `MAX_LINE_LEN` UTF-16 units that
|
||||
@@ -211,30 +186,4 @@ mod tests {
|
||||
assert_eq!(m.ranges, vec![(100, 106)]);
|
||||
assert!(utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_outside_the_first_window_get_their_own() {
|
||||
// Two matches 100 apart share a window; the one 1000 further gets another.
|
||||
let s = format!("{}ab{}cd{}ef{}", "x".repeat(1000), "x".repeat(100), "x".repeat(1000), "x".repeat(10));
|
||||
let at = |needle: &str| s.find(needle).unwrap();
|
||||
let ranges = [(at("ab"), at("ab") + 2), (at("cd"), at("cd") + 2), (at("ef"), at("ef") + 2)];
|
||||
let mut out = Vec::new();
|
||||
line_matches(7, s.as_bytes(), &ranges, &mut out);
|
||||
let found: Vec<Vec<u32>> =
|
||||
out.iter().map(|m| m.ranges.iter().map(|&(a, _)| m.text_offset + a).collect()).collect();
|
||||
let col = |needle: &str| at(needle) as u32;
|
||||
assert_eq!(found, vec![vec![col("ab"), col("cd")], vec![col("ef")]]);
|
||||
assert!(out.iter().all(|m| m.line == 7 && utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN));
|
||||
assert_eq!(&out[1].text[out[1].ranges[0].0 as usize..out[1].ranges[0].1 as usize], "ef");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_longer_than_the_window_is_cut_to_it() {
|
||||
let s = format!("{}{}tail", "x".repeat(100), "y".repeat(1000));
|
||||
let mut out = Vec::new();
|
||||
line_matches(0, s.as_bytes(), &[(100, 1100), (1100, 1104)], &mut out);
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_eq!(out[0].ranges, vec![(100, 500)]);
|
||||
assert_eq!(out[1].text_offset + out[1].ranges[0].0, 1100);
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,6 @@ use ide_core::{IdeError, IdeResult};
|
||||
pub(crate) struct Compiled {
|
||||
pub matcher: RegexMatcher,
|
||||
pub multi_line: bool,
|
||||
/// Keep only whole-word matches ([`crate::iter`] checks IDEA's rule on each match).
|
||||
pub whole_word: bool,
|
||||
}
|
||||
|
||||
/// The line terminator shared by the matcher and the searcher. CRLF mode lets
|
||||
@@ -21,13 +19,12 @@ pub(crate) fn line_terminator() -> LineTerminator {
|
||||
|
||||
pub(crate) fn compile(query: &SearchQuery) -> IdeResult<Compiled> {
|
||||
let multi_line = needs_multi_line(query);
|
||||
let whole_word = query.whole_word;
|
||||
match build(query, multi_line) {
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line, whole_word }),
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line }),
|
||||
// Patterns such as `[\n]` or `\x0A` can only match across lines;
|
||||
// retry in multi-line mode before reporting an error.
|
||||
Err(err) if !multi_line => match build(query, true) {
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line: true, whole_word }),
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line: true }),
|
||||
Err(_) => Err(invalid_pattern(query, &err)),
|
||||
},
|
||||
Err(err) => Err(invalid_pattern(query, &err)),
|
||||
@@ -38,8 +35,7 @@ fn build(query: &SearchQuery, multi_line: bool) -> Result<RegexMatcher, grep_reg
|
||||
let mut b = RegexMatcherBuilder::new();
|
||||
b.case_smart(false)
|
||||
.case_insensitive(!query.case_sensitive)
|
||||
// Not `.word()`: ripgrep's rule wants a non-word character on both sides even of
|
||||
// `foo(`, IDEA's (in `iter`) only beside the match's identifier characters.
|
||||
.word(query.whole_word)
|
||||
.fixed_strings(!query.is_regex)
|
||||
.unicode(true)
|
||||
// `^`/`$` always mean start/end of line, as in IDEA and ripgrep.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! (the document layer in the app, so open editors update and each file is one
|
||||
//! undoable step).
|
||||
|
||||
use crate::{LiteralRange, Literals, SearchContext, SearchQuery, iter, query};
|
||||
use crate::{SearchQuery, iter, query};
|
||||
use grep_matcher::{Captures, Matcher};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, Range, TextEdit};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -128,11 +128,10 @@ pub fn replacement_edits(
|
||||
preserve: bool,
|
||||
only: Option<&[Pos]>,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
edits_except(text, query, replacement, preserve, only, None, None)
|
||||
edits_except(text, query, replacement, preserve, only, None)
|
||||
}
|
||||
|
||||
/// [`replacement_edits`] leaving out the matches that start at `skip` and, given the text's
|
||||
/// comments and string literals, those outside the query's [`crate::SearchContext`].
|
||||
/// [`replacement_edits`] leaving out the matches that start at `skip`.
|
||||
fn edits_except(
|
||||
text: &str,
|
||||
query: &SearchQuery,
|
||||
@@ -140,7 +139,6 @@ fn edits_except(
|
||||
preserve: bool,
|
||||
only: Option<&[Pos]>,
|
||||
skip: Option<&[Pos]>,
|
||||
literals: Option<&[LiteralRange]>,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
if query.pattern.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -155,13 +153,10 @@ fn edits_except(
|
||||
let mut caps = matcher.new_captures().map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let mut edits = Vec::new();
|
||||
let mut buf = Vec::new();
|
||||
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
|
||||
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
|
||||
let Some(m) = caps.get(0) else { return };
|
||||
let start = lines.pos(m.start());
|
||||
if only.as_ref().is_some_and(|o| !o.contains(&start))
|
||||
|| skip.contains(&start)
|
||||
|| literals.is_some_and(|l| !query.context.keeps(l, m.start()))
|
||||
{
|
||||
if only.as_ref().is_some_and(|o| !o.contains(&start)) || skip.contains(&start) {
|
||||
return;
|
||||
}
|
||||
let mut new_text = if query.is_regex {
|
||||
@@ -232,23 +227,6 @@ pub fn replace_files(
|
||||
cancel: &CancellationToken,
|
||||
on_event: &dyn Fn(ReplaceEvent),
|
||||
) -> IdeResult<ReplaceSummary> {
|
||||
replace_files_in_context(host, query, replacement, preserve, targets, None, cancel, on_event)
|
||||
}
|
||||
|
||||
/// [`replace_files`] honouring [`SearchQuery::context`] with the comments and string literals
|
||||
/// `literals` finds, as [`crate::search_in_context`] does; without it every match is plain code.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn replace_files_in_context(
|
||||
host: &dyn ReplaceHost,
|
||||
query: &SearchQuery,
|
||||
replacement: &str,
|
||||
preserve: bool,
|
||||
targets: &[ReplaceTarget],
|
||||
literals: Option<Literals<'_>>,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &dyn Fn(ReplaceEvent),
|
||||
) -> IdeResult<ReplaceSummary> {
|
||||
let literals = literals.filter(|_| query.context != SearchContext::Any);
|
||||
// Fail fast on an invalid pattern instead of once per file.
|
||||
if !query.pattern.is_empty() {
|
||||
query::compile(query)?;
|
||||
@@ -266,14 +244,8 @@ pub fn replace_files_in_context(
|
||||
if only.is_some_and(|o| o.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
let result = host.edit_file(&target.path, &mut |text| {
|
||||
let found = match literals.map(|l| l(&target.path, text)) {
|
||||
// No syntax tree: nothing is in a comment or string, as in the search.
|
||||
Some(None) if query.context.needs_literals() => return Ok(Vec::new()),
|
||||
found => found.map(Option::unwrap_or_default),
|
||||
};
|
||||
edits_except(text, query, replacement, preserve, only, skip, found.as_deref())
|
||||
});
|
||||
let result =
|
||||
host.edit_file(&target.path, &mut |text| edits_except(text, query, replacement, preserve, only, skip));
|
||||
match result {
|
||||
Ok(n) => {
|
||||
if n > 0 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, TextEdit};
|
||||
use ide_search::{
|
||||
LiteralKind, LiteralRange, ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case,
|
||||
preview, replace_files, replace_files_in_context, replacement_edits,
|
||||
ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case, preview, replace_files,
|
||||
replacement_edits,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -169,46 +169,3 @@ fn replace_files_respects_selected_matches_and_invalid_patterns() {
|
||||
let err = replace_files(&docs, ®ex("("), "x", false, &t, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
/// `// …` comments and `"…"` strings of `.rs` files; other files have no syntax tree.
|
||||
fn toy_literals(path: &Path, text: &str) -> Option<Vec<LiteralRange>> {
|
||||
if path.extension().is_none_or(|e| e != "rs") {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (i, _) in text.match_indices("//") {
|
||||
let end = text[i..].find('\n').map_or(text.len(), |n| i + n);
|
||||
out.push(LiteralRange { start: i, end, kind: LiteralKind::Comment });
|
||||
}
|
||||
let quotes: Vec<usize> = text.match_indices('"').map(|(i, _)| i).collect();
|
||||
for pair in quotes.chunks(2) {
|
||||
if let [a, b] = pair {
|
||||
out.push(LiteralRange { start: *a, end: b + 1, kind: LiteralKind::String });
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|l| l.start);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_files_in_context_keeps_to_the_search_context() {
|
||||
use ide_search::SearchContext as C;
|
||||
let text = "foo(\"foo\"); // foo\nfoo\n";
|
||||
let plain = "foo // foo\n";
|
||||
let cases = [
|
||||
(C::Any, "x(\"x\"); // x\nx\n", "x // x\n"),
|
||||
(C::InComments, "foo(\"foo\"); // x\nfoo\n", plain),
|
||||
(C::InStringLiterals, "foo(\"x\"); // foo\nfoo\n", plain),
|
||||
(C::ExceptComments, "x(\"x\"); // foo\nx\n", "x // x\n"),
|
||||
(C::ExceptStringLiterals, "x(\"foo\"); // x\nx\n", "x // x\n"),
|
||||
(C::ExceptCommentsAndStringLiterals, "x(\"foo\"); // foo\nx\n", "x // x\n"),
|
||||
];
|
||||
for (context, in_rs, in_txt) in cases {
|
||||
let docs = FakeDocs::with(&[("a.rs", text), ("b.txt", plain)]);
|
||||
let q = SearchQuery { context, ..query("foo") };
|
||||
let t = targets(&["a.rs", "b.txt"]);
|
||||
replace_files_in_context(&docs, &q, "x", false, &t, Some(&toy_literals), &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
assert_eq!((docs.text("a.rs").as_str(), docs.text("b.txt").as_str()), (in_rs, in_txt), "{context:?}");
|
||||
}
|
||||
}
|
||||
@@ -132,36 +132,6 @@ fn whole_word() {
|
||||
assert_eq!(views[0].matches[0].ranges, vec![(0, 3), (27, 30), (32, 35)]);
|
||||
}
|
||||
|
||||
/// IDEA's whole word: a word boundary is needed only at an edge where the match has an
|
||||
/// identifier character; a punctuation edge only needs a different character beside it.
|
||||
#[test]
|
||||
fn whole_word_needs_a_boundary_only_at_identifier_edges() {
|
||||
let starts = |text: &str, q: SearchQuery| -> Vec<usize> {
|
||||
let q = SearchQuery { whole_word: true, ..q };
|
||||
ide_search::match_ranges(text, &q).unwrap().into_iter().map(|r| r.0).collect()
|
||||
};
|
||||
let text = "doWork(arg); redoWork(x); list: string[] = [];";
|
||||
assert_eq!(starts(text, query("doWork(")), [0]);
|
||||
assert_eq!(starts(text, query("(arg)")), [6]);
|
||||
assert_eq!(starts(text, query("[]")), [38, 43]);
|
||||
assert_eq!(starts(text, query("list")), [26]);
|
||||
assert_eq!(starts("a == b; c === d", query("==")), [2]);
|
||||
// `$` is part of an identifier (Java, Kotlin, JavaScript).
|
||||
assert_eq!(starts("foo$bar foo", query("foo")), [8]);
|
||||
// After an escape such as `\n`, a word starts.
|
||||
assert_eq!(starts(r#"s = "\nfoo";"#, query("foo")), [7]);
|
||||
assert_eq!(starts("é1 1 éé", query("1")), [4]);
|
||||
// Regex matches follow the same rule.
|
||||
assert_eq!(starts(text, regex(r"\w+\(")), [0, 13]);
|
||||
assert_eq!(starts(text, regex(r"\[\]")), [38, 43]);
|
||||
|
||||
let p = project(&[("a.ts", text.as_bytes())]);
|
||||
let (views, summary) = run(p.path(), &SearchQuery { whole_word: true, ..query("[]") });
|
||||
assert_eq!((summary.matches, views[0].matches[0].ranges.clone()), (2, vec![(38, 40), (43, 45)]));
|
||||
let (out, n) = replace_in_text(text, &SearchQuery { whole_word: true, ..query("doWork(") }, "run(").unwrap();
|
||||
assert_eq!((out.as_str(), n), ("run(arg); redoWork(x); list: string[] = [];", 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_regex_is_reported() {
|
||||
let p = project(&[("a.txt", b"x\n")]);
|
||||
@@ -461,41 +431,6 @@ fn long_lines_are_truncated() {
|
||||
assert_eq!(second.text, "short needle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_match_of_a_long_line_is_reported_in_its_own_window() {
|
||||
let long = format!("a='needle';{}b='needle';{}needle!\n", "x".repeat(2000), "y".repeat(2000));
|
||||
let p = project(&[("min.js", long.as_bytes())]);
|
||||
let (views, summary) = run(p.path(), &query("needle"));
|
||||
assert_eq!(summary.matches, 3);
|
||||
let lines = &views[0].matches;
|
||||
assert_eq!(lines.len(), 3, "one window per far-apart match");
|
||||
let line_utf16: Vec<u16> = long.trim_end().encode_utf16().collect();
|
||||
let mut starts = Vec::new();
|
||||
for m in lines {
|
||||
assert_eq!(m.line, 0);
|
||||
assert!(m.text.encode_utf16().count() <= 500);
|
||||
let [(a, b)] = m.ranges[..] else { panic!("{:?}", m.ranges) };
|
||||
let text: Vec<u16> = m.text.encode_utf16().collect();
|
||||
assert_eq!(String::from_utf16(&text[a as usize..b as usize]).unwrap(), "needle");
|
||||
let col = (m.text_offset + a) as usize;
|
||||
assert_eq!(String::from_utf16(&line_utf16[col..col + 6]).unwrap(), "needle");
|
||||
starts.push(ide_core::Pos::new(0, m.text_offset + a));
|
||||
}
|
||||
// The reported positions are the ones Replace takes: all of them are replaced.
|
||||
let edits = ide_search::replacement_edits(&long, &query("needle"), "pin", false, Some(&starts)).unwrap();
|
||||
assert_eq!(edits.len(), 3);
|
||||
assert!(!ide_search::apply_edits(&long, &edits).contains("needle"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_limit_counts_every_match_of_a_long_line() {
|
||||
let long = format!("needle{}needle{}needle\n", "x".repeat(1000), "y".repeat(1000));
|
||||
let p = project(&[("min.js", long.as_bytes())]);
|
||||
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 2, ..query("needle") });
|
||||
assert!(summary.limit_hit);
|
||||
assert_eq!((summary.matches, total(&views)), (2, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_line_matches() {
|
||||
let p = project(&[("a.rs", b"fn foo() {\n bar();\n}\nfoo\nbar\n")]);
|
||||
|
||||
@@ -235,12 +235,6 @@ fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
Ok((map, conflicts))
|
||||
}
|
||||
|
||||
/// Keeps `git status` from rewriting the index with refreshed stat data. Such a write is not
|
||||
/// one of ours to the watcher, so it would schedule another refresh, which runs git again (#4792).
|
||||
fn read_only() -> [(&'static str, &'static std::ffi::OsStr); 1] {
|
||||
[("GIT_OPTIONAL_LOCKS", std::ffi::OsStr::new("0"))]
|
||||
}
|
||||
|
||||
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
|
||||
/// In Restricted Mode git compares content without the repository's clean/process
|
||||
/// filters and doesn't ask submodules for their own status (which runs their config).
|
||||
@@ -251,7 +245,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
if !crate::execution_allowed() {
|
||||
args.push("--ignore-submodules=dirty");
|
||||
}
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
let out = crate::cli::run(r.root(), &args, None)?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
@@ -266,7 +260,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe
|
||||
}
|
||||
args.push("--");
|
||||
args.extend(paths.iter().map(String::as_str));
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
let out = crate::cli::run(r.root(), &args, None)?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
@@ -403,29 +397,6 @@ mod tests {
|
||||
assert!(staged.stdout.is_empty(), "{}", String::from_utf8_lossy(&staged.stdout));
|
||||
}
|
||||
|
||||
/// #4792: the dirty-scope `git status` must not rewrite the index after refreshing stale
|
||||
/// stat data, or the watcher sees a foreign index write and refreshes again.
|
||||
#[test]
|
||||
fn git_status_of_paths_leaves_the_index_alone() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
git(dir, &["config", "user.name", "Test User"]);
|
||||
git(dir, &["config", "user.email", "[email protected]"]);
|
||||
git(dir, &["config", "commit.gpgsign", "false"]);
|
||||
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
|
||||
commit_all(dir, "base");
|
||||
// Same content, new stat data: plain `git status` would refresh and write the index.
|
||||
std::thread::sleep(std::time::Duration::from_millis(1100));
|
||||
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
|
||||
let index = dir.join(".git/index");
|
||||
let before = std::fs::read(&index).unwrap();
|
||||
|
||||
let repo = Repo::discover(dir).unwrap().expect("repository found");
|
||||
assert!(status_paths(&repo, &["a.txt".to_owned()]).unwrap().is_empty());
|
||||
assert_eq!(std::fs::read(&index).unwrap(), before, "git status rewrote the index");
|
||||
}
|
||||
|
||||
/// git's porcelain answer (used when gitoxide can't read the tree) matches gitoxide's.
|
||||
#[test]
|
||||
fn git_and_gitoxide_report_the_same_status() {
|
||||
|
||||
@@ -422,8 +422,6 @@ impl Documents {
|
||||
}
|
||||
// Validate project rules before path resolution can erase linked components.
|
||||
crate::file_ops::validate_workspace_edit_paths(edit)?;
|
||||
// Editors know the paths as the edit named them, before link resolution.
|
||||
let moves = edit.moves();
|
||||
let mut edit = normalize_edit(edit)?;
|
||||
let captured = !edit.preconditions.is_empty();
|
||||
crate::file_ops::expand_workspace_edit(&mut edit)?;
|
||||
@@ -503,7 +501,7 @@ impl Documents {
|
||||
});
|
||||
}
|
||||
history.prune(SystemTime::now(), MAX_HISTORY_BYTES, MAX_HISTORY_AGE);
|
||||
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, moves, by_agent });
|
||||
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, by_agent });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -4,13 +4,20 @@
|
||||
|
||||
use crate::documents::Documents;
|
||||
use crate::history::LocalHistory;
|
||||
pub use ide_core::FileMove;
|
||||
use ide_core::{FileEdit, IdeError, IdeResult, WorkspaceEdit};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// One file or folder move.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileMove {
|
||||
pub from: ide_core::IpcPath,
|
||||
pub to: ide_core::IpcPath,
|
||||
}
|
||||
|
||||
/// What [`FileMoves::undo`] did.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use ide_core::{ChangeSet, FileEdit, FileMove, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
|
||||
use ide_core::{ChangeSet, FileEdit, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
|
||||
use ide_core::{IdeEvent, error::ErrorKind};
|
||||
use ide_workspace::Documents;
|
||||
use parking_lot::Mutex;
|
||||
@@ -162,45 +162,6 @@ fn undo_id(events: &Mutex<Vec<IdeEvent>>) -> u32 {
|
||||
.expect("successful transaction has one undo record")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applied_event_lists_the_files_the_edit_renamed() {
|
||||
for by_agent in [false, true] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let from = tmp.path().join("ListPrice.java");
|
||||
let to = tmp.path().join("BasePrice.java");
|
||||
let user = tmp.path().join("BulkDiscount.java");
|
||||
std::fs::write(&from, "old").unwrap();
|
||||
std::fs::write(&user, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let edit = WorkspaceEdit {
|
||||
files: vec![edit(&user, "new"), FileEdit::Rename { from: from.clone().into(), to: to.clone().into() }],
|
||||
..Default::default()
|
||||
};
|
||||
if by_agent { docs.apply_agent_workspace_edit(&edit) } else { docs.apply_workspace_edit(&edit) }.unwrap();
|
||||
let moves = events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|event| match event {
|
||||
IdeEvent::WorkspaceEditApplied { moves, .. } => Some(moves.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(moves, vec![FileMove { from: from.into(), to: to.into() }], "by_agent: {by_agent}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applied_event_lists_no_moves_for_text_edits() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
assert!(
|
||||
events.lock().iter().any(|e| matches!(e, IdeEvent::WorkspaceEditApplied { moves, .. } if moves.is_empty()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_the_encoding_chosen_for_a_file_opened_after_the_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,18 +1,7 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { BuildModel, BuildTool, MavenDependency } from "../src/platform/ipc";
|
||||
import type { BuildModel, BuildTool } from "../src/platform/ipc";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const jsonCore: MavenDependency = {
|
||||
groupId: "com.example.json",
|
||||
artifactId: "json-core",
|
||||
version: "2.1.0",
|
||||
type: "jar",
|
||||
classifier: null,
|
||||
scope: "compile",
|
||||
optional: false,
|
||||
children: [],
|
||||
};
|
||||
|
||||
const model: BuildModel = {
|
||||
maven: {
|
||||
projects: [
|
||||
@@ -28,14 +17,7 @@ const model: BuildModel = {
|
||||
modules: [],
|
||||
aggregated: false,
|
||||
plugins: [],
|
||||
dependencies: [
|
||||
jsonCore,
|
||||
{
|
||||
...jsonCore,
|
||||
artifactId: "json-mapper",
|
||||
children: [{ ...jsonCore, version: "2.0.0", omitted: "conflict", conflictWith: "2.1.0" }],
|
||||
},
|
||||
],
|
||||
dependencies: [],
|
||||
profiles: [],
|
||||
javaVersion: 21,
|
||||
command: "mvn",
|
||||
@@ -115,45 +97,3 @@ for (const tool of ["maven", "gradle"] as const) {
|
||||
await expect(menu).toBeHidden();
|
||||
});
|
||||
}
|
||||
|
||||
test("Dependency Analyzer pairs its pane controls and stacks usages in a narrow editor", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1360, height: 780 });
|
||||
await showTool(page, "maven");
|
||||
const toolActions = page.getByRole("toolbar", { name: "Maven actions" });
|
||||
await toolActions.getByRole("button", { name: "More Actions", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Analyze Dependencies…", exact: true }).click();
|
||||
|
||||
const filters = page.getByRole("toolbar", { name: "Dependency Analyzer", exact: true });
|
||||
const resolved = page.getByRole("heading", { name: "Resolved Dependencies", exact: true });
|
||||
const usages = page.getByRole("heading", { name: "Usages of com.example.json:json-core:2.1.0", exact: true });
|
||||
const dependencies = page.getByRole("tree", { name: "Dependencies", exact: true });
|
||||
const core = dependencies.getByRole("treeitem", { name: /^com\.example\.json:json-core\b/ });
|
||||
const treeMode = page.getByRole("button", { name: "Show as Tree", exact: true });
|
||||
const conflicts = filters.getByRole("button", { name: "Show conflicts only", exact: true });
|
||||
await expect(resolved).toBeVisible();
|
||||
await expect(filters.getByRole("button", { name: "Show as Tree" })).toHaveCount(0);
|
||||
await treeMode.click();
|
||||
await expect(treeMode).toHaveAttribute("aria-pressed", "true");
|
||||
await page.getByRole("button", { name: "Show as List", exact: true }).click();
|
||||
await conflicts.press("Space");
|
||||
await expect(conflicts).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(dependencies.getByRole("treeitem")).toHaveCount(1);
|
||||
await core.click();
|
||||
await expect(usages).toBeVisible();
|
||||
await expect(page.getByText("omitted for conflict with 2.1.0")).toBeVisible();
|
||||
const wideLeft = (await resolved.boundingBox())!;
|
||||
const wideRight = (await usages.boundingBox())!;
|
||||
expect(Math.abs(wideLeft.y - wideRight.y)).toBeLessThan(1);
|
||||
expect(wideRight.x).toBeGreaterThan(wideLeft.x + wideLeft.width);
|
||||
|
||||
await page.setViewportSize({ width: 790, height: 780 });
|
||||
await expect
|
||||
.poll(async () => (await usages.boundingBox())!.y - (await resolved.boundingBox())!.y)
|
||||
.toBeGreaterThan(100);
|
||||
expect(Math.abs((await usages.boundingBox())!.x - (await resolved.boundingBox())!.x)).toBeLessThan(1);
|
||||
expect(await filters.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await expect(core).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByRole("button", { name: "Copy Coordinates" })).toBeInViewport({ ratio: 1 });
|
||||
});
|
||||
@@ -65,26 +65,6 @@ for (const locale of ["en", "zh"]) {
|
||||
});
|
||||
}
|
||||
|
||||
test("keeps Open project in options within narrow System Settings", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
await selectPage(page, "general");
|
||||
const group = dialog.getByRole("radiogroup", { name: "Open project in", exact: true });
|
||||
const longest = group.getByRole("radio", { name: "New tab in current window", exact: true });
|
||||
await expect(longest).toBeVisible();
|
||||
await page.setViewportSize({ width: 520, height: 760 });
|
||||
const overflow = await longest.evaluate(async (radio) => {
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
||||
const label = radio.closest("label")!;
|
||||
const group = radio.closest('[role="radiogroup"]')!;
|
||||
const text = document.createRange();
|
||||
text.selectNodeContents(label);
|
||||
return text.getBoundingClientRect().right - group.getBoundingClientRect().right;
|
||||
});
|
||||
expect(overflow).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("settings sidebar resizes with mouse and keyboard and remembers its width", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
|
||||
+2
-7
@@ -538,7 +538,7 @@ export const commands = {
|
||||
docOpenVirtual: (uri: string) => typedError<DocumentInfo, IdeError>(__TAURI_INVOKE("doc_open_virtual", { uri })),
|
||||
/**
|
||||
* Structure view: LSP document symbols when available (with tree-sitter
|
||||
* visibility and type-alias kinds), tree-sitter otherwise.
|
||||
* visibility), tree-sitter otherwise.
|
||||
* Tree-sitter answers come from the per-document tree cache (incremental
|
||||
* re-parse); large documents get no syntax structure.
|
||||
*/
|
||||
@@ -7126,8 +7126,6 @@ version: number } |
|
||||
{ type: "docDiskConflict"; doc: DocId; path: string } |
|
||||
/** A complete workspace edit can be undone as one operation. */
|
||||
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
|
||||
/** Files the edit renamed, as the edit named them: editors open on them follow. */
|
||||
moves: FileMove[];
|
||||
/**
|
||||
* Made by an agent through the MCP server's tools: undoable like a refactoring, but
|
||||
* not announced as one.
|
||||
@@ -8163,10 +8161,7 @@ export type LineMarkerInfo = {
|
||||
export type LineMatch = {
|
||||
/** 0-based line. */
|
||||
line: number,
|
||||
/**
|
||||
* Line text, truncated around the matches for very long lines: such a line comes as one
|
||||
* `LineMatch` per window, so the same `line` can repeat.
|
||||
*/
|
||||
/** Line text, truncated around the match for very long lines. */
|
||||
text: string,
|
||||
/** UTF-16 column ranges within `text`. */
|
||||
ranges: ([number, number])[],
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { redo, redoDepth, undo, undoDepth, history } from "@codemirror/commands";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { _provideOpenEditorPaths, workspaceEditHistory } from "@/editor/api";
|
||||
import { workspaceEditHistory } from "@/editor/api";
|
||||
import { installWorkspaceEditUndo } from "@/features/code-insight/workspaceUndo";
|
||||
import {
|
||||
provideEditorService,
|
||||
provideNotificationService,
|
||||
type EditorService,
|
||||
type NotificationService,
|
||||
} from "@/workbench/contributions";
|
||||
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { createMemoryBackend, type MemoryBackend } from "../backend";
|
||||
import { _resetLanguages } from "../cm/languages";
|
||||
@@ -66,7 +61,6 @@ async function rename() {
|
||||
type: "workspaceEditApplied",
|
||||
id: 9,
|
||||
paths: ["/p/A.java", "/p/B.java", "/p/closed.java"],
|
||||
moves: [],
|
||||
byAgent: false,
|
||||
});
|
||||
}
|
||||
@@ -194,13 +188,7 @@ it("rebuilds multiple redo markers in order when a closed file opens", async ()
|
||||
const a = await open("/p/A.java");
|
||||
await rename();
|
||||
await replace("alt");
|
||||
emitLocalIdeEvent({
|
||||
type: "workspaceEditApplied",
|
||||
id: 10,
|
||||
paths: ["/p/A.java", "/p/B.java"],
|
||||
moves: [],
|
||||
byAgent: true,
|
||||
});
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 10, paths: ["/p/A.java", "/p/B.java"], byAgent: true });
|
||||
commands.undoWorkspaceEdit.mockImplementation(async (id: number) => {
|
||||
await replace(id === 10 ? "new" : "old");
|
||||
return { status: "ok", data: null };
|
||||
@@ -269,56 +257,3 @@ it("keeps refactoring markers current while a secondary view is unmounted", asyn
|
||||
expect(commands.undoWorkspaceEdit).toHaveBeenCalledOnce();
|
||||
att.release();
|
||||
});
|
||||
|
||||
it("editors on a file the edit renamed reopen at its new path, through Undo and Redo", async () => {
|
||||
const live = () => slots.filter((s) => !closed.has(s));
|
||||
const closed = new Set<EditorSlot>();
|
||||
const openFile = vi.fn(async (path: string) => {
|
||||
if (!live().some((s) => s.model.path === path)) await open(path);
|
||||
});
|
||||
const closePath = vi.fn(async (path: string) => {
|
||||
for (const s of live())
|
||||
if (s.model.path === path) {
|
||||
closed.add(s);
|
||||
s.dispose();
|
||||
}
|
||||
return true;
|
||||
});
|
||||
provideEditorService({
|
||||
openFile,
|
||||
closePath,
|
||||
activePath: () => live().at(-1)?.model.path ?? null,
|
||||
saveAll: vi.fn(),
|
||||
} as unknown as EditorService);
|
||||
_provideOpenEditorPaths(() => live().map((s) => s.model.path));
|
||||
backend.files.set("/p/Renamed.java", "old");
|
||||
const moved = async (from: string, to: string, run: () => Promise<unknown>) => {
|
||||
openFile.mockClear();
|
||||
await run();
|
||||
await vi.waitFor(() => expect(openFile).toHaveBeenCalledExactlyOnceWith(to, { focus: false }));
|
||||
expect(closePath).toHaveBeenCalledWith(from);
|
||||
expect(live().map((s) => s.model.path)).toEqual(["/p/B.java", to]);
|
||||
};
|
||||
try {
|
||||
await open("/p/B.java");
|
||||
await open("/p/A.java");
|
||||
await moved("/p/A.java", "/p/Renamed.java", async () => {
|
||||
await replace("new");
|
||||
emitLocalIdeEvent({
|
||||
type: "workspaceEditApplied",
|
||||
id: 11,
|
||||
paths: ["/p/A.java", "/p/Renamed.java", "/p/B.java"],
|
||||
moves: [{ from: "/p/A.java", to: "/p/Renamed.java" }],
|
||||
byAgent: false,
|
||||
});
|
||||
});
|
||||
// Reopened editors take part in the refactoring's history like the ones they replace.
|
||||
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
|
||||
await moved("/p/A.java", "/p/Renamed.java", () => workspaceEditHistory(11, true));
|
||||
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
provideEditorService(undefined as unknown as EditorService);
|
||||
_provideOpenEditorPaths(() => []);
|
||||
}
|
||||
});
|
||||
@@ -3,8 +3,7 @@ import { invertedEffects, isolateHistory, redo, undo } from "@codemirror/command
|
||||
import { EditorState, Prec, StateEffect, type Transaction, type Extension } from "@codemirror/state";
|
||||
import { EditorView, keymap } from "@codemirror/view";
|
||||
import { _emitWorkspaceEditHistory, _provideWorkspaceHistory, isExternalChange } from "@/editor/api";
|
||||
import { editorsFollowAppliedMoves, reversedMoves, withEditorsFollowing } from "@/editor/fileMoves";
|
||||
import { call, commands, onIdeEvent, type FileMove } from "@/platform/ipc";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
interface Marker {
|
||||
@@ -21,7 +20,7 @@ export interface WorkspaceHistoryTarget {
|
||||
|
||||
export class WorkspaceHistory {
|
||||
private targets = new Set<WorkspaceHistoryTarget>();
|
||||
private records = new Map<number, { paths: string[]; moves: FileMove[]; undone: boolean }>();
|
||||
private records = new Map<number, { paths: string[]; undone: boolean }>();
|
||||
private project = useProject.getState().project;
|
||||
private busy = false;
|
||||
private moving = false;
|
||||
@@ -32,7 +31,7 @@ export class WorkspaceHistory {
|
||||
) {}
|
||||
|
||||
start(): () => void {
|
||||
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths, moves }) => {
|
||||
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths }) => {
|
||||
if (this.project !== useProject.getState().project) {
|
||||
this.records.clear();
|
||||
this.project = useProject.getState().project;
|
||||
@@ -44,11 +43,9 @@ export class WorkspaceHistory {
|
||||
record.paths.some((path) => this.affects(paths, path) || paths.some((root) => root.startsWith(`${path}/`)))
|
||||
)
|
||||
this.records.delete(key);
|
||||
this.records.set(id, { paths, moves, undone: false });
|
||||
this.records.set(id, { paths, undone: false });
|
||||
while (this.records.size > 20) this.records.delete(this.records.keys().next().value!);
|
||||
for (const target of this.targets) if (this.affects(paths, target.path)) this.mark(target, id);
|
||||
// Now, before the file watcher reports the old paths gone and their tabs close.
|
||||
void editorsFollowAppliedMoves(moves);
|
||||
});
|
||||
const unprovide = _provideWorkspaceHistory((id, redo) => this.run(id, redo));
|
||||
return () => {
|
||||
@@ -157,21 +154,14 @@ export class WorkspaceHistory {
|
||||
for (const target of targets)
|
||||
if (!this.step(target, id, forward))
|
||||
throw new Error("Undo newer editor changes before undoing this refactoring");
|
||||
await withEditorsFollowing(
|
||||
async () => {
|
||||
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
|
||||
await this.synced();
|
||||
for (const target of targets) {
|
||||
if (!this.targets.has(target)) continue;
|
||||
const tr = this.step(target, id, forward);
|
||||
if (tr) target.dispatch(tr);
|
||||
}
|
||||
// Editors reopened at moved paths build their history from the record: settle it first.
|
||||
record.undone = !forward;
|
||||
},
|
||||
() => (forward ? record.moves : reversedMoves(record.moves)),
|
||||
{ save: false },
|
||||
);
|
||||
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
|
||||
await this.synced();
|
||||
for (const target of targets) {
|
||||
if (!this.targets.has(target)) continue;
|
||||
const tr = this.step(target, id, forward);
|
||||
if (tr) target.dispatch(tr);
|
||||
}
|
||||
record.undone = !forward;
|
||||
_emitWorkspaceEditHistory({ id, undone: record.undone });
|
||||
} catch (error) {
|
||||
// A refused backend restore must leave the initiating editor's history intact.
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { provideEditorService, type EditorService } from "@/workbench/contributions";
|
||||
import { createMemoryBackend } from "./core/backend";
|
||||
import { EditorController, useTabs } from "./core/controller";
|
||||
import { initialTabsState } from "./core/model/tabs";
|
||||
import { editorsFollowAppliedMoves } from "./fileMoves";
|
||||
|
||||
let ctrl: EditorController | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
ctrl?.stop();
|
||||
ctrl = null;
|
||||
useTabs.setState(initialTabsState(), true);
|
||||
});
|
||||
|
||||
function setup(files: Record<string, string>) {
|
||||
const backend = createMemoryBackend(files);
|
||||
backend.onFsChanged = (h) => onIdeEvent("fsChanged", h);
|
||||
const controller = new EditorController(backend);
|
||||
controller.start();
|
||||
ctrl = controller;
|
||||
provideEditorService({
|
||||
openFile: (path, o) => controller.openFile(path, o),
|
||||
activePath: () => controller.activePath(),
|
||||
closePath: (path) => controller.closePath(path),
|
||||
saveAll: async () => {},
|
||||
} as Partial<EditorService> as EditorService);
|
||||
return { controller, backend };
|
||||
}
|
||||
|
||||
const tabPaths = () =>
|
||||
Object.values(useTabs.getState().panes).flatMap((pane) => pane.tabs.map((tab) => tab.input.path));
|
||||
|
||||
it("a renamed active file stays the active editor", async () => {
|
||||
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
|
||||
await controller.openFile("/p/B.java", { focus: false });
|
||||
await controller.openFile("/p/A.java", { focus: false });
|
||||
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
|
||||
backend.files.delete("/p/A.java");
|
||||
|
||||
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
|
||||
|
||||
expect(tabPaths()).toEqual(["/p/B.java", "/p/Renamed.java"]);
|
||||
expect(controller.activePath()).toBe("/p/Renamed.java");
|
||||
});
|
||||
|
||||
it("a renamed background file leaves the active editor in place", async () => {
|
||||
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
|
||||
await controller.openFile("/p/A.java", { focus: false });
|
||||
await controller.openFile("/p/B.java", { focus: false });
|
||||
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
|
||||
backend.files.delete("/p/A.java");
|
||||
|
||||
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
|
||||
|
||||
expect(tabPaths().sort()).toEqual(["/p/B.java", "/p/Renamed.java"]);
|
||||
expect(controller.activePath()).toBe("/p/B.java");
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
/** IDEA keeps editors on files that a refactoring moves or renames: they reopen at the new paths. */
|
||||
import type { FileMove } from "@/bindings";
|
||||
import { openEditorPaths } from "@/editor/api";
|
||||
import { notifyFilesMoved, trackFileMove } from "@/platform/fileOps";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { maybeEditorService } from "@/workbench/contributions";
|
||||
|
||||
export async function saveAllQuietly(editor: { saveAll(): Promise<void> }) {
|
||||
try {
|
||||
await editor.saveAll();
|
||||
} catch {
|
||||
/* unsaved files are reported by the editor */
|
||||
}
|
||||
}
|
||||
|
||||
/** `path` after `moves`. */
|
||||
export function movedPath(path: string, moves: readonly FileMove[]): string {
|
||||
let p = path;
|
||||
for (const m of moves) if (isSameOrInside(p, m.from)) p = m.to + p.slice(m.from.length);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Moves in the opposite direction, last first: what Undo of `moves` does. */
|
||||
export function reversedMoves(moves: readonly FileMove[]): FileMove[] {
|
||||
return [...moves].reverse().map((m) => ({ from: m.to, to: m.from }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `run`, which moves the files `done` names, with the editors following: unsaved changes
|
||||
* are saved first (unless `save` is false), tabs reopen at the new paths.
|
||||
*/
|
||||
export async function withEditorsFollowing<T>(
|
||||
run: () => Promise<T>,
|
||||
done: (r: T) => readonly FileMove[],
|
||||
{ save = true }: { save?: boolean } = {},
|
||||
): Promise<T> {
|
||||
const projectRoot = () => useProject.getState().project?.root ?? null;
|
||||
const root = projectRoot();
|
||||
const editor = maybeEditorService();
|
||||
const openBefore = editor ? openEditorPaths() : [];
|
||||
if (editor && save) await saveAllQuietly(editor);
|
||||
const active = editor?.activePath() ?? null;
|
||||
const { result, applied } = await trackFileMove(root, async () => {
|
||||
const result = await run();
|
||||
const applied = done(result);
|
||||
if (root === projectRoot()) await notifyFilesMoved(applied);
|
||||
return { result, applied };
|
||||
});
|
||||
if (root !== projectRoot()) return result;
|
||||
const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));
|
||||
if (applied.length)
|
||||
emitLocalIdeEvent({
|
||||
type: "fsChanged",
|
||||
created: applied.map((m) => m.to),
|
||||
modified: [],
|
||||
removed: applied.map((m) => m.from),
|
||||
});
|
||||
if (!editor || !open.length) return result;
|
||||
// The editor closes tabs of removed files in a queue; an open that starts before an
|
||||
// active tab's close counts as superseded and stays in the background.
|
||||
for (const p of open) await editor.closePath?.(p).catch(() => false);
|
||||
const ordered = active && open.includes(active) ? [...open.filter((p) => p !== active), active] : open;
|
||||
for (const p of ordered) await editor.openFile(movedPath(p, applied), { focus: false }).catch(() => {});
|
||||
if (active && !open.includes(active)) await editor.openFile(active, { focus: false }).catch(() => {});
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Editors follow `moves` that a workspace edit already made (a server's rename, Move, a quick
|
||||
* fix): called when the backend reports the edit, before the file watcher closes their tabs.
|
||||
*/
|
||||
export function editorsFollowAppliedMoves(moves: readonly FileMove[]): Promise<void> {
|
||||
if (!moves.length) return Promise.resolve();
|
||||
return withEditorsFollowing(
|
||||
() => Promise.resolve(),
|
||||
() => moves,
|
||||
{ save: false },
|
||||
);
|
||||
}
|
||||
@@ -205,96 +205,6 @@ describe("locationItems", () => {
|
||||
expect((await locationItems([target("/p/src/a.py", "refresh", 3)]))[0]!.label).toBe("refresh");
|
||||
});
|
||||
|
||||
describe("takes the container only from a type whose body holds the target", () => {
|
||||
const cart = [
|
||||
'import { type Cents } from "./money.ts";',
|
||||
"",
|
||||
"export interface Product {",
|
||||
" id: string;",
|
||||
" price: Cents;",
|
||||
"}",
|
||||
"",
|
||||
"export interface CartLine {",
|
||||
" product: Product;",
|
||||
" quantity: number;",
|
||||
"}",
|
||||
"",
|
||||
'export type Discount = { kind: "percent"; percent: number } | { kind: "fixed"; amount: Cents };',
|
||||
"",
|
||||
"export class Cart {",
|
||||
" private discount: Discount | null = null;",
|
||||
"",
|
||||
" total(): Cents {",
|
||||
" return 0;",
|
||||
" }",
|
||||
"}",
|
||||
];
|
||||
const at = (line: number, col: number) => ({
|
||||
path: "/p/src/cart.ts",
|
||||
uri: null,
|
||||
range: { start: { line, col }, end: { line, col: col + 1 } },
|
||||
});
|
||||
beforeEach(() => {
|
||||
readManyFileLines.mockResolvedValue(new Map([["/p/src/cart.ts", cart]]));
|
||||
project("/p");
|
||||
});
|
||||
|
||||
it("anonymous targets after a closed interface", async () => {
|
||||
const union = cart[12]!;
|
||||
const items = await locationItems([at(12, union.indexOf("{")), at(12, union.lastIndexOf("{ kind"))]);
|
||||
expect(items.map((i) => [i.label, i.detail])).toEqual([
|
||||
["cart.ts", "src/cart.ts:13"],
|
||||
["cart.ts", "src/cart.ts:13"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("a named target after a closed interface", async () => {
|
||||
const item = (await locationItems([at(7, cart[7]!.indexOf("CartLine"))]))[0]!;
|
||||
expect([item.label, item.detail]).toEqual(["CartLine", "src/cart.ts:8"]);
|
||||
});
|
||||
|
||||
it("a member after a closed type, inside its own class", async () => {
|
||||
const item = (await locationItems([at(17, cart[17]!.indexOf("total"))]))[0]!;
|
||||
expect([item.label, item.detail]).toEqual(["total", "Cart · src/cart.ts:18"]);
|
||||
});
|
||||
|
||||
it("indentation-delimited bodies: a function after a class, a method after a dict literal", async () => {
|
||||
const lines = [
|
||||
"class Config:",
|
||||
" defaults = {}",
|
||||
"",
|
||||
" def load(self) -> None:",
|
||||
" pass",
|
||||
"",
|
||||
"def main() -> None:",
|
||||
" pass",
|
||||
];
|
||||
readManyFileLines.mockResolvedValue(new Map([["/p/src/mod.py", lines]]));
|
||||
const items = await locationItems([target("/p/src/mod.py", "load", 3), target("/p/src/mod.py", "main", 6)]);
|
||||
expect(items.map((i) => i.detail)).toEqual(["Config · src/mod.py:4", "src/mod.py:7"]);
|
||||
const main = {
|
||||
...target("/p/src/mod.py", "main", 6),
|
||||
range: { start: { line: 6, col: 0 }, end: { line: 6, col: 3 } },
|
||||
};
|
||||
expect((await locationItems([main]))[0]!.detail).toBe("src/mod.py:7");
|
||||
});
|
||||
|
||||
it("Go: a method's container is its receiver, declared outside the struct's body", async () => {
|
||||
const lines = [
|
||||
"type Square struct {",
|
||||
"\tside float64",
|
||||
"}",
|
||||
"",
|
||||
"func (s *Square) Area() float64 {",
|
||||
"\treturn 0",
|
||||
"}",
|
||||
];
|
||||
readManyFileLines.mockResolvedValue(new Map([["/p/shapes.go", lines]]));
|
||||
const at = { path: "/p/shapes.go", uri: null, range: { start: { line: 4, col: 17 }, end: { line: 4, col: 21 } } };
|
||||
expect((await locationItems([at]))[0]!.detail).toBe("Square · shapes.go:5");
|
||||
});
|
||||
});
|
||||
|
||||
it("does not query the index for index symbols, which carry their container", async () => {
|
||||
readManyFileLines.mockResolvedValue(new Map());
|
||||
project("/p");
|
||||
|
||||
@@ -172,89 +172,41 @@ const GO_RECEIVER = /^\s*func\s*\(\s*(?:[\p{L}_][\p{L}\p{N}_]*\s+)?\*?\s*([\p{L}
|
||||
|
||||
const FENCES = [`"""`, `'''`];
|
||||
|
||||
/** Code of a line without comments, strings and docstring text; null for a line with no code. */
|
||||
type CodeLine = string | null;
|
||||
|
||||
/**
|
||||
* Name of the type a target sits in (the nearest type declaration above it whose body is still
|
||||
* open at the target); null without one.
|
||||
* Name of the type a target sits in (the nearest type declaration above it); null without one.
|
||||
* Text heuristic: docstrings (`"""` / `'''` fences) and line comments (`#`, `//`, `*`…) cannot
|
||||
* declare a type, so "the base class does all that is needed" in a comment is not one.
|
||||
*/
|
||||
export function enclosingType(lines: readonly string[] | null | undefined, target: Location): string | null {
|
||||
if (!lines) return null;
|
||||
const targetLine = lines[target.range.start.line] ?? "";
|
||||
const receiver = GO_RECEIVER.exec(targetLine)?.[1];
|
||||
if (receiver) return receiver;
|
||||
const from = Math.max(0, target.range.start.line - 2000);
|
||||
const code: CodeLine[] = [];
|
||||
const declarations: { line: number; end: number; name: string }[] = [];
|
||||
let container: string | null = null;
|
||||
let fence: string | null = null;
|
||||
for (let l = from; l < target.range.start.line; l++) {
|
||||
for (let l = Math.max(0, target.range.start.line - 2000); l < target.range.start.line; l++) {
|
||||
const line = lines[l] ?? "";
|
||||
code.push(null);
|
||||
if (fence) {
|
||||
if ((line.split(fence).length - 1) % 2 === 1) fence = null;
|
||||
continue;
|
||||
}
|
||||
// Comments first: a `#`/`//` line cannot open a docstring fence either.
|
||||
const text = line.replace(/(^|\s)(#|\/\/).*$/, "$1");
|
||||
if (!text.trim()) continue;
|
||||
const opened = FENCES.find((f) => (text.split(f).length - 1) % 2 === 1);
|
||||
const code = line.replace(/(^|\s)(#|\/\/).*$/, "$1");
|
||||
if (!code.trim()) continue;
|
||||
const opened = FENCES.find((f) => (code.split(f).length - 1) % 2 === 1);
|
||||
if (opened) {
|
||||
fence = opened;
|
||||
continue;
|
||||
}
|
||||
// A single-line docstring (fences open and close on the line) is text too.
|
||||
if (FENCES.some((f) => text.includes(f)) || /^\s*(\*|\/\*)/.test(line)) continue;
|
||||
code[l - from] = text;
|
||||
const m = TYPE_DECLARATION.exec(text);
|
||||
if (m) declarations.push({ line: l - from, end: m.index + m[0].length, name: (m[1] ?? m[2])! });
|
||||
if (FENCES.some((f) => code.includes(f))) continue;
|
||||
const m = TYPE_DECLARATION.exec(code);
|
||||
if (m && !/^\s*(\*|\/\*)/.test(line)) container = (m[1] ?? m[2])!;
|
||||
}
|
||||
code.push(targetLine);
|
||||
const col = target.range.start.col;
|
||||
for (const d of declarations.reverse()) if (bodyHolds(code, d.line, d.end, col)) return d.name;
|
||||
return null;
|
||||
return container;
|
||||
}
|
||||
|
||||
const STRING_LITERAL = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
|
||||
|
||||
/**
|
||||
* Whether the body of the declaration on `code[line]` (ending at `end`) is still open at `col`
|
||||
* of the last entry of `code` (the target's line): braces when the body opens with one on the
|
||||
* declaration's line or the next (Allman style), else indentation (Python, Ruby, a declaration
|
||||
* without a body).
|
||||
*/
|
||||
function bodyHolds(code: readonly CodeLine[], line: number, end: number, col: number): boolean {
|
||||
const last = code.length - 1;
|
||||
const next = code.findIndex((c, i) => i > line && i < last && c !== null);
|
||||
const braced = code[line]!.slice(end).includes("{") || (next > 0 && /^\s*\{/.test(code[next]!));
|
||||
if (braced) {
|
||||
let depth = 0;
|
||||
let opened = false;
|
||||
for (let i = line; i <= last; i++) {
|
||||
const text = (i === line ? code[i]!.slice(end) : i === last ? code[i]!.slice(0, col) : code[i]) ?? "";
|
||||
for (const c of text.replace(STRING_LITERAL, "")) {
|
||||
if (c === "{") {
|
||||
depth++;
|
||||
opened = true;
|
||||
} else if (c === "}" && --depth === 0 && opened) return false;
|
||||
}
|
||||
}
|
||||
return depth > 0;
|
||||
}
|
||||
const indent = (s: string) => s.length - s.trimStart().length;
|
||||
const own = indent(code[line]!);
|
||||
for (let i = line + 1; i < code.length; i++) {
|
||||
const text = code[i];
|
||||
// A wrapped header (`) : Base {`) continues the declaration.
|
||||
if (text?.trim() && indent(text) <= own && !/^\s*[)\]]/.test(text)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Name of the type a target sits in: the type declaration around it, else the file name. */
|
||||
/** Name of the type a target sits in: the nearest type declaration above it, else the file name. */
|
||||
export function enclosingTypeName(lines: readonly string[] | null | undefined, target: Location): string {
|
||||
const receiver = GO_RECEIVER.exec(lines?.[target.range.start.line] ?? "")?.[1];
|
||||
if (receiver) return receiver;
|
||||
const found = enclosingType(lines, target);
|
||||
if (found) return found;
|
||||
const file = target.path.split(/[\\/]/).pop() ?? target.path;
|
||||
|
||||
@@ -357,56 +357,3 @@ describe("SessionAssets component", () => {
|
||||
expect(await screen.findByRole("button", { name: "1 Artifact" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("SessionAssets binary file artifacts", () => {
|
||||
const entries: AgentEntry[] = [
|
||||
{
|
||||
type: "tool",
|
||||
id: "t-doc",
|
||||
title: "Write spec",
|
||||
kind: "edit",
|
||||
status: "completed",
|
||||
locations: ["/repo/spec.docx"],
|
||||
output: null,
|
||||
diffs: [{ path: "/repo/spec.docx", added: 1, removed: 0 }],
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resetSessionAssetsCacheForTests();
|
||||
clearDismissedAssets("task-1");
|
||||
useAgents.setState({ composers: new Map([["task-1", emptyDraft()]]) });
|
||||
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
|
||||
vi.spyOn(ipc, "call").mockImplementation(async (promise) => promise);
|
||||
vi.spyOn(ipc.commands, "vcsRemotes").mockResolvedValue([] as never);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function openArtifact() {
|
||||
render(<SessionAssets task={makeTask()} entries={entries} head="feat/session" />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "1 Artifact" }));
|
||||
const dialog = await screen.findByRole("dialog", { name: "Artifacts" });
|
||||
fireEvent.click(within(dialog).getByText("spec.docx"));
|
||||
}
|
||||
|
||||
it("opens a binary file with its application through the backend's checked command", async () => {
|
||||
const open = vi.spyOn(ipc.commands, "fsOpenWithSystem").mockResolvedValue(null as never);
|
||||
await openArtifact();
|
||||
await waitFor(() => expect(open).toHaveBeenCalledWith("/repo/spec.docx"));
|
||||
expect(openFileMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to the editor when the backend refuses the launch", async () => {
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const open = vi
|
||||
.spyOn(ipc.commands, "fsOpenWithSystem")
|
||||
.mockRejectedValue({ kind: "unavailable", message: "Project is in Restricted Mode." } as never);
|
||||
await openArtifact();
|
||||
await waitFor(() => expect(openFileMock).toHaveBeenCalledWith("/repo/spec.docx", { focus: true }));
|
||||
expect(open).toHaveBeenCalledWith("/repo/spec.docx");
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,6 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { AgentEntry, AgentTask, PullRequestSummary } from "@/bindings";
|
||||
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { openWithSystemApp } from "@/platform/fileManager";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -149,7 +148,15 @@ function issueIcon(state: IssueAssetState | undefined): IconName {
|
||||
}
|
||||
|
||||
async function openFileArtifact(artifact: Extract<SessionArtifact, { kind: "file" }>) {
|
||||
if (artifact.externalBinary && (await openWithSystemApp(artifact.path))) return;
|
||||
if (artifact.externalBinary && isTauri()) {
|
||||
try {
|
||||
const { openPath } = await import("@tauri-apps/plugin-opener");
|
||||
await openPath(artifact.path);
|
||||
return;
|
||||
} catch {
|
||||
/* fall back to editor */
|
||||
}
|
||||
}
|
||||
await editorService().openFile(artifact.path, { focus: true });
|
||||
}
|
||||
|
||||
|
||||
@@ -16,28 +16,22 @@
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.module {
|
||||
min-width: min(136px, 100%);
|
||||
max-width: min(260px, 100%);
|
||||
min-width: 160px;
|
||||
max-width: 260px;
|
||||
}
|
||||
.search {
|
||||
flex: 1 1 140px;
|
||||
min-width: min(140px, 100%);
|
||||
min-width: 140px;
|
||||
max-width: 360px;
|
||||
}
|
||||
.scope {
|
||||
min-width: min(96px, 100%);
|
||||
max-width: min(240px, 100%);
|
||||
min-width: 110px;
|
||||
}
|
||||
.toolbarActions,
|
||||
.viewActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
flex: none;
|
||||
}
|
||||
.toolbarActions {
|
||||
padding-inline-start: var(--space-1);
|
||||
border-inline-start: 1px solid var(--border);
|
||||
.sep {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
margin: 0 2px;
|
||||
background: var(--border);
|
||||
}
|
||||
.banner {
|
||||
flex: none;
|
||||
@@ -66,7 +60,13 @@
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.tree {
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.panel > * {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -94,6 +94,7 @@
|
||||
}
|
||||
.version {
|
||||
flex: none;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
@@ -119,24 +120,22 @@
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
}
|
||||
.paneHeader {
|
||||
.usagesHeader {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-height: calc(var(--h-field) + var(--space-1));
|
||||
min-height: 32px;
|
||||
padding: 0 10px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.paneTitle {
|
||||
.usagesTitle {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--fs-ui);
|
||||
font-weight: 500;
|
||||
font-family: var(--font-mono);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.conflictNote {
|
||||
@@ -168,6 +167,7 @@
|
||||
}
|
||||
.usageVersion {
|
||||
flex: none;
|
||||
font-family: var(--font-mono);
|
||||
color: var(--fg);
|
||||
}
|
||||
.usageStatus {
|
||||
|
||||
@@ -114,8 +114,7 @@ describe("dependency analyzer", () => {
|
||||
it("marks conflicts, shows their usages and excludes through the direct dependency", async () => {
|
||||
ipc.exclude.mockResolvedValue({ path: "/p/pom.xml", range: {} });
|
||||
render(<DependencyAnalyzer input={{ kind: ANALYZER_KIND, key: ANALYZER_KIND }} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show conflicts only", pressed: false }));
|
||||
expect(screen.getByRole("button", { name: "Show conflicts only", pressed: true })).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Show conflicts only" }));
|
||||
expect(screen.queryByText("com.google.inject:guice")).toBeNull();
|
||||
fireEvent.mouseDown(screen.getByText("com.google.guava:guava").closest("[role=treeitem]")!, { button: 0 });
|
||||
expect(screen.getByText("omitted for conflict with 32.1.3-jre")).toBeTruthy();
|
||||
@@ -214,7 +213,7 @@ describe("dependency analyzer for Gradle", () => {
|
||||
render(<DependencyAnalyzer input={{ kind: ANALYZER_KIND, key: ANALYZER_KIND }} />);
|
||||
expect(ipc.gradle).toHaveBeenCalledWith(":app", "runtimeClasspath", false, expect.any(Number), "");
|
||||
await screen.findByText("com.fasterxml.jackson.core:jackson-databind");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show conflicts only", pressed: false }));
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Show conflicts only" }));
|
||||
expect(screen.queryByText("org.springframework.boot:spring-boot-starter-json")).toBeNull();
|
||||
fireEvent.mouseDown(screen.getByText("com.fasterxml.jackson.core:jackson-databind").closest("[role=treeitem]")!, {
|
||||
button: 0,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* selected artifact every path that brings it in, with Exclude / Jump to Source (Maven)
|
||||
* and Copy Coordinates. Gradle trees are read per configuration, on demand.
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
call,
|
||||
@@ -15,10 +15,11 @@ import {
|
||||
type MavenDependency,
|
||||
type MavenProject,
|
||||
} from "@/platform/ipc";
|
||||
import { useTx, useTxTemplate } from "@/platform/i18n";
|
||||
import { useTx, useTxTemplate, tx } from "@/platform/i18n";
|
||||
import { editorService, notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
@@ -312,37 +313,28 @@ function UsagesPane({
|
||||
moduleIcon: string;
|
||||
pom: string | null;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const symbol = artifact ? coordinates(artifact) : null;
|
||||
if (!artifact) return <EmptyState title="Select a dependency to see its usages" />;
|
||||
const usages = sortedUsages(artifact.usages);
|
||||
const coords = coordinates({ ...artifact, version: artifact.version });
|
||||
return (
|
||||
<div className={styles.usages}>
|
||||
<div className={styles.paneHeader}>
|
||||
<h2 className={styles.paneTitle} title={symbol ?? undefined}>
|
||||
{symbol ? tx`Usages of ${symbol}` : tx("Usages")}
|
||||
</h2>
|
||||
{symbol && (
|
||||
<IconButton icon="copy" size="small" title="Copy Coordinates" onClick={() => void copyText(symbol)} />
|
||||
)}
|
||||
<div className={styles.usagesHeader}>
|
||||
<span className={clsx(styles.usagesTitle, artifact.conflict && styles.conflict)}>{coords}</span>
|
||||
<IconButton icon="copy" size="small" title="Copy Coordinates" onClick={() => void copyText(coords)} />
|
||||
</div>
|
||||
{artifact ? (
|
||||
<>
|
||||
{artifact.conflict && (
|
||||
<div className={styles.conflictNote} role="note">
|
||||
<Icon name="warning" size={16} />
|
||||
<span>
|
||||
<T>Versions requested</T>: {artifact.requested.join(", ")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.usageList} aria-label={tx("Usages")}>
|
||||
{sortedUsages(artifact.usages).map((u, i) => (
|
||||
<UsageBlock key={i} usage={u} moduleName={moduleName} moduleIcon={moduleIcon} pom={pom} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<EmptyState title="Select a dependency to see its usages" />
|
||||
{artifact.conflict && (
|
||||
<div className={styles.conflictNote} role="note">
|
||||
<Icon name="warning" size={16} />
|
||||
<span>
|
||||
<T>Versions requested</T>: {artifact.requested.join(", ")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.usageList} aria-label={tx("Usages")}>
|
||||
{usages.map((u, i) => (
|
||||
<UsageBlock key={i} usage={u} moduleName={moduleName} moduleIcon={moduleIcon} pom={pom} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -355,18 +347,6 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
|
||||
const gradleSync = useBuild((s) => s.syncing.gradle);
|
||||
const root = useBuild((s) => s.root);
|
||||
const chosen = useAnalyzer((s) => s.module);
|
||||
const hasProject = !!maven || !!gradle?.length;
|
||||
const view = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
useLayoutEffect(() => {
|
||||
const frame = view.current;
|
||||
if (!frame) return;
|
||||
const measure = () => setStacked(frame.clientWidth < 580);
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(frame);
|
||||
return () => observer.disconnect();
|
||||
}, [hasProject]);
|
||||
const [query, setQuery] = useState("");
|
||||
const [conflictsOnly, setConflictsOnly] = useState(false);
|
||||
const [scope, setScope] = useState<string>(ALL_SCOPES);
|
||||
@@ -480,41 +460,17 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
|
||||
showContextMenu({ x: e.clientX, y: e.clientY }, items);
|
||||
};
|
||||
|
||||
if (!hasProject) return <EmptyState title="No Maven or Gradle projects" />;
|
||||
if (!maven && !gradle?.length) return <EmptyState title="No Maven or Gradle projects" />;
|
||||
|
||||
const treeView = (
|
||||
<div className={styles.body}>
|
||||
<SplitGroup
|
||||
orientation={stacked ? "vertical" : "horizontal"}
|
||||
orientation="horizontal"
|
||||
id="maven-dependency-analyzer-split"
|
||||
storageKey={stacked ? "openidea.dependencyAnalyzer.split.vertical" : "openidea.dependencyAnalyzer.split"}
|
||||
storageKey="openidea.dependencyAnalyzer.split"
|
||||
>
|
||||
<SplitPanel id="dependencies" minSize={stacked ? "30%" : 200}>
|
||||
<div className={styles.paneHeader}>
|
||||
<h2 className={styles.paneTitle}>
|
||||
<T>Resolved Dependencies</T>
|
||||
</h2>
|
||||
<div className={styles.viewActions}>
|
||||
<IconButton
|
||||
icon="list"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Show as List"
|
||||
pressed={mode === "list"}
|
||||
onClick={() => setMode("list")}
|
||||
/>
|
||||
<IconButton
|
||||
icon="hierarchy"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Show as Tree"
|
||||
pressed={mode === "tree"}
|
||||
onClick={() => setMode("tree")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<SplitPanel id="dependencies" minSize={200} className={styles.panel}>
|
||||
<Tree<Node>
|
||||
className={styles.tree}
|
||||
aria-label="Dependencies"
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
@@ -545,7 +501,7 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
|
||||
/>
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="usages" minSize={stacked ? "30%" : 240}>
|
||||
<SplitPanel id="usages" minSize={240} className={styles.panel}>
|
||||
<UsagesPane
|
||||
artifact={selected}
|
||||
moduleName={module?.displayName ?? gradleProject?.name ?? ""}
|
||||
@@ -558,7 +514,7 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
|
||||
);
|
||||
|
||||
return (
|
||||
<div ref={view} className={styles.view}>
|
||||
<div className={styles.view}>
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx("Dependency Analyzer")}>
|
||||
<Select
|
||||
aria-label="Module"
|
||||
@@ -578,6 +534,7 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
|
||||
aria-label="Search dependencies"
|
||||
clearable
|
||||
/>
|
||||
<Checkbox checked={conflictsOnly} onChange={setConflictsOnly} label="Show conflicts only" />
|
||||
{gradlePath != null ? (
|
||||
<Select
|
||||
aria-label="Configuration"
|
||||
@@ -599,29 +556,37 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
|
||||
onChange={setScope}
|
||||
/>
|
||||
)}
|
||||
<div className={styles.toolbarActions}>
|
||||
<IconButton
|
||||
icon="warning"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Show conflicts only"
|
||||
pressed={conflictsOnly}
|
||||
onClick={() => setConflictsOnly((current) => !current)}
|
||||
/>
|
||||
{gradlePath != null ? (
|
||||
configuration === null && gradleSync ? (
|
||||
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={() => cancelSync("gradle")} />
|
||||
) : report.loading ? (
|
||||
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={report.cancel} />
|
||||
) : (
|
||||
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshGradle} />
|
||||
)
|
||||
) : syncing ? (
|
||||
<IconButton icon="stop" size="small" iconSize={16} action="maven.cancelReload" />
|
||||
<span className={styles.sep} />
|
||||
<IconButton
|
||||
icon="list"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Show as List"
|
||||
pressed={mode === "list"}
|
||||
onClick={() => setMode("list")}
|
||||
/>
|
||||
<IconButton
|
||||
icon="hierarchy"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Show as Tree"
|
||||
pressed={mode === "tree"}
|
||||
onClick={() => setMode("tree")}
|
||||
/>
|
||||
<span className={styles.sep} />
|
||||
{gradlePath != null ? (
|
||||
configuration === null && gradleSync ? (
|
||||
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={() => cancelSync("gradle")} />
|
||||
) : report.loading ? (
|
||||
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={report.cancel} />
|
||||
) : (
|
||||
<IconButton icon="refresh" size="small" iconSize={16} action="maven.reload" />
|
||||
)}
|
||||
</div>
|
||||
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshGradle} />
|
||||
)
|
||||
) : syncing ? (
|
||||
<IconButton icon="stop" size="small" iconSize={16} action="maven.cancelReload" />
|
||||
) : (
|
||||
<IconButton icon="refresh" size="small" iconSize={16} action="maven.reload" />
|
||||
)}
|
||||
</div>
|
||||
{gradlePath != null ? (
|
||||
<>
|
||||
|
||||
@@ -35,7 +35,7 @@ it("waits for pending typing before undoing the entire backend transaction", asy
|
||||
release = resolve;
|
||||
}),
|
||||
);
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [], moves: [], byAgent: false });
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [], byAgent: false });
|
||||
const action = notices[0]!.actions![0]!;
|
||||
expect(action.label).toBe("Undo");
|
||||
const pending = action.run();
|
||||
@@ -47,13 +47,13 @@ it("waits for pending typing before undoing the entire backend transaction", asy
|
||||
|
||||
it("reports a refused undo instead of discarding newer work", async () => {
|
||||
mocks.undo.mockRejectedValue(new Error("a.txt changed"));
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [], moves: [], byAgent: false });
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [], byAgent: false });
|
||||
await notices[0]!.actions![0]!.run();
|
||||
expect(notices[1]).toMatchObject({ level: "error", title: "Cannot undo refactoring", body: "a.txt changed" });
|
||||
});
|
||||
|
||||
it("does not apply an old notification's id to a different project", async () => {
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [], moves: [], byAgent: false });
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [], byAgent: false });
|
||||
const previous = useProject.getState().project;
|
||||
useProject.setState({ project: { ...previous, root: "/different-project" } as NonNullable<typeof previous> });
|
||||
try {
|
||||
@@ -66,6 +66,6 @@ it("does not apply an old notification's id to a different project", async () =>
|
||||
});
|
||||
|
||||
it("does not announce an agent's edit as a refactoring", () => {
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 20, paths: [], moves: [], byAgent: true });
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 20, paths: [], byAgent: true });
|
||||
expect(notices).toEqual([]);
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import type { FileMove, WorkspaceEdit } from "@/bindings";
|
||||
import { movedPath } from "@/editor/fileMoves";
|
||||
import { onFilesMoved } from "@/platform/fileOps";
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
import {
|
||||
lastFileRefactoring,
|
||||
mergeEdits,
|
||||
movedPath,
|
||||
runFileRefactoring,
|
||||
setRefactorBackendForTests,
|
||||
touchesOtherFiles,
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
* files change, then the move itself — one step that Undo reverts.
|
||||
*/
|
||||
import type { FileMove, UndoOutcome, WorkspaceEdit } from "@/bindings";
|
||||
import { saveAllQuietly, withEditorsFollowing } from "@/editor/fileMoves";
|
||||
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
|
||||
import { openEditorPaths } from "@/editor/api";
|
||||
import { notifyFilesMoved, trackFileMove } from "@/platform/fileOps";
|
||||
import { call, commands, emitLocalIdeEvent, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import { projectFs } from "./fs";
|
||||
import { isSameOrInside, nameOf, parentOf } from "./paths";
|
||||
@@ -164,6 +166,54 @@ export function touchesOtherFiles(edit: WorkspaceEdit, moves: readonly FileMove[
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Editors follow the move
|
||||
|
||||
async function saveAllQuietly(editor: { saveAll(): Promise<void> }) {
|
||||
try {
|
||||
await editor.saveAll();
|
||||
} catch {
|
||||
/* unsaved files are reported by the editor */
|
||||
}
|
||||
}
|
||||
|
||||
/** `path` after `moves`. */
|
||||
export function movedPath(path: string, moves: readonly FileMove[]): string {
|
||||
let p = path;
|
||||
for (const m of moves) if (isSameOrInside(p, m.from)) p = m.to + p.slice(m.from.length);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** IDEA retargets editors of moved files: unsaved changes are saved first, tabs reopen at the new paths. */
|
||||
async function withEditorsFollowing<T>(run: () => Promise<T>, done: (r: T) => FileMove[]): Promise<T> {
|
||||
const projectRoot = () => useProject.getState().project?.root ?? null;
|
||||
const root = projectRoot();
|
||||
const editor = maybeEditorService();
|
||||
const openBefore = editor ? openEditorPaths() : [];
|
||||
if (editor) await saveAllQuietly(editor);
|
||||
const active = editor?.activePath() ?? null;
|
||||
const { result, applied } = await trackFileMove(root, async () => {
|
||||
const result = await run();
|
||||
const applied = done(result);
|
||||
if (root === projectRoot()) await notifyFilesMoved(applied);
|
||||
return { result, applied };
|
||||
});
|
||||
if (root !== projectRoot()) return result;
|
||||
const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));
|
||||
if (applied.length)
|
||||
emitLocalIdeEvent({
|
||||
type: "fsChanged",
|
||||
created: applied.map((m) => m.to),
|
||||
modified: [],
|
||||
removed: applied.map((m) => m.from),
|
||||
});
|
||||
if (!editor || !open.length) return result;
|
||||
const ordered = active && open.includes(active) ? [...open.filter((p) => p !== active), active] : open;
|
||||
for (const p of ordered) await editor.openFile(movedPath(p, applied), { focus: false }).catch(() => {});
|
||||
if (active && !open.includes(active)) await editor.openFile(active, { focus: false }).catch(() => {});
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Run / undo
|
||||
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import {
|
||||
provideNotificationService,
|
||||
provideToolWindowService,
|
||||
type ToolWindowService,
|
||||
} from "@/workbench/contributions";
|
||||
import { resetRuns, rerunFailed, runSelectedTests, runtime, startRun, useRun } from "./store";
|
||||
|
||||
const classModules = vi.hoisted(() =>
|
||||
vi.fn(async (cls: string) => ({ "com.a.AlphaTest": ["alpha"], "com.b.BetaTest": ["beta"] })[cls] ?? []),
|
||||
);
|
||||
vi.mock("@/platform/javaLaunch", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/javaLaunch")>()),
|
||||
classModules,
|
||||
}));
|
||||
vi.mock("./dialogs", () => ({
|
||||
confirmRerun: vi.fn(async () => true),
|
||||
confirmTerminate: vi.fn(async () => true),
|
||||
promptValue: vi.fn(),
|
||||
RunDialogsOverlay: () => null,
|
||||
}));
|
||||
|
||||
const rootTests: RunConfig = {
|
||||
id: "gradle:test",
|
||||
name: "gradle test",
|
||||
kind: "gradle",
|
||||
command: "./gradlew",
|
||||
args: ["test"],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: true,
|
||||
isTest: true,
|
||||
debugAdapter: null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
resetRuns();
|
||||
provideToolWindowService({ show: vi.fn(), isVisible: () => true } as unknown as ToolWindowService);
|
||||
provideNotificationService({ notify: () => undefined });
|
||||
});
|
||||
|
||||
const failedRootRun = async () => {
|
||||
const session = (await startRun(rootTests))!;
|
||||
runtime(session.id)!.tests!.apply([
|
||||
{ type: "result", path: ["com.a.AlphaTest", "one"], status: "failed" },
|
||||
{ type: "result", path: ["com.b.BetaTest", "two"], status: "failed" },
|
||||
]);
|
||||
useRun.setState({
|
||||
sessions: useRun.getState().sessions.map((s) => (s.id === session.id ? { ...s, status: "finished" } : s)),
|
||||
});
|
||||
return session;
|
||||
};
|
||||
|
||||
const lastArgs = () => useRun.getState().sessions.at(-1)!.config.args;
|
||||
|
||||
describe("Gradle reruns after a run of the root test task", () => {
|
||||
it("Rerun Failed Tests runs each test in its own subproject's test task", async () => {
|
||||
const session = await failedRootRun();
|
||||
expect(await rerunFailed(session.id)).toBe(true);
|
||||
await vi.waitFor(() =>
|
||||
expect(lastArgs()).toEqual([
|
||||
":alpha:test",
|
||||
"--tests",
|
||||
"com.a.AlphaTest.one",
|
||||
":beta:test",
|
||||
"--tests",
|
||||
"com.b.BetaTest.two",
|
||||
"--continue",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("running a selection from the tree does the same", async () => {
|
||||
const session = await failedRootRun();
|
||||
const beta = runtime(session.id)!.tests!.node(["com.b.BetaTest", "two"]);
|
||||
expect(await runSelectedTests(session.id, [beta.id], false)).toBe(true);
|
||||
expect(lastArgs()).toEqual([":beta:test", "--tests", "com.b.BetaTest.two"]);
|
||||
});
|
||||
|
||||
it("keeps today's command line when a class is not found", async () => {
|
||||
classModules.mockResolvedValueOnce([]);
|
||||
const session = await failedRootRun();
|
||||
expect(await rerunFailed(session.id)).toBe(true);
|
||||
await vi.waitFor(() =>
|
||||
expect(lastArgs()).toEqual(["test", "--tests", "com.a.AlphaTest.one", "--tests", "com.b.BetaTest.two"]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -55,7 +55,6 @@ import { TeamcityOutput } from "./testing/teamcity";
|
||||
import type { TestStdout } from "./testing/types";
|
||||
import { recordTestStates } from "./testing/states";
|
||||
import { failedTestPaths, leafTestPaths, rerunFailedConfigs, testsConfigs } from "./testing/rerun";
|
||||
import { testsBySubproject } from "./testing/gradleSubprojects";
|
||||
import { buildCMake, isCMakeBuild } from "./cmake";
|
||||
import { compoundChildren } from "./configs";
|
||||
import { remoteLabel, startWithRemedies } from "./remote";
|
||||
@@ -1540,11 +1539,8 @@ export async function rerunFailed(sessionId: string): Promise<boolean> {
|
||||
const session = getSession(sessionId);
|
||||
if (!session || isLive(session)) return false;
|
||||
const base = baseConfigOf(session);
|
||||
const paths = failedTests(sessionId);
|
||||
const selection = rerunFailedConfigs(base, paths);
|
||||
const derived = await Promise.all(
|
||||
(selection instanceof Promise ? await selection : selection).map((c) => testsBySubproject(c, paths)),
|
||||
);
|
||||
const selection = rerunFailedConfigs(base, failedTests(sessionId));
|
||||
const derived = selection instanceof Promise ? await selection : selection;
|
||||
if (getSession(sessionId) !== session || isLive(session)) return false;
|
||||
if (!derived.length) return false;
|
||||
derived.forEach((config, index) => void startRun(config, index === 0 ? sessionId : undefined, base));
|
||||
@@ -1568,9 +1564,7 @@ export async function runSelectedTests(
|
||||
const base = baseConfigOf(session);
|
||||
const name = nodes.length === 1 ? nodes[0]!.name : `${paths.length} tests`;
|
||||
const selection = testsConfigs(base, paths, name);
|
||||
const derived = await Promise.all(
|
||||
(selection instanceof Promise ? await selection : selection).map((c) => testsBySubproject(c, paths)),
|
||||
);
|
||||
const derived = selection instanceof Promise ? await selection : selection;
|
||||
if (getSession(sessionId) !== session) return false;
|
||||
if (!derived.length) return false;
|
||||
for (const [index, next] of derived.entries()) {
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { testsBySubproject } from "./gradleSubprojects";
|
||||
|
||||
const cfg = (args: string[], over: Partial<RunConfig> = {}): RunConfig => ({
|
||||
id: "gradle:test",
|
||||
name: "Failed: gradle test",
|
||||
kind: "gradle",
|
||||
command: "./gradlew",
|
||||
args,
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: true,
|
||||
isTest: true,
|
||||
debugAdapter: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
const modules: Record<string, string[]> = {
|
||||
"com.a.AlphaTest": ["alpha"],
|
||||
"com.b.BetaTest": ["services/beta"],
|
||||
"com.r.RootTest": [""],
|
||||
"com.x.Twice": ["alpha", "services/beta"],
|
||||
};
|
||||
const find = async (cls: string) => modules[cls] ?? [];
|
||||
|
||||
describe("Gradle tests by subproject", () => {
|
||||
it("runs each failed test with its own subproject's test task", async () => {
|
||||
const derived = cfg(["test", "--tests", "com.a.AlphaTest.one", "--tests", "com.b.BetaTest$Inner.two"]);
|
||||
const paths = [
|
||||
["com.a.AlphaTest", "one()"],
|
||||
["com.b.BetaTest$Inner", "two"],
|
||||
];
|
||||
expect((await testsBySubproject(derived, paths, find)).args).toEqual([
|
||||
":alpha:test",
|
||||
"--tests",
|
||||
"com.a.AlphaTest.one",
|
||||
":services:beta:test",
|
||||
"--tests",
|
||||
"com.b.BetaTest$Inner.two",
|
||||
"--continue",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the other options and needs no --continue for one subproject", async () => {
|
||||
const derived = cfg(["--offline", "test", "--tests", "com.b.BetaTest"]);
|
||||
expect((await testsBySubproject(derived, [["com.b.BetaTest"]], find)).args).toEqual([
|
||||
"--offline",
|
||||
":services:beta:test",
|
||||
"--tests",
|
||||
"com.b.BetaTest",
|
||||
]);
|
||||
});
|
||||
|
||||
it("addresses the root project's own tests as :test next to a subproject's", async () => {
|
||||
const derived = cfg(["test", "--tests", "com.r.RootTest.a", "--tests", "com.a.AlphaTest.one"]);
|
||||
const paths = [
|
||||
["com.r.RootTest", "a"],
|
||||
["com.a.AlphaTest", "one"],
|
||||
];
|
||||
expect((await testsBySubproject(derived, paths, find)).args).toEqual([
|
||||
":test",
|
||||
"--tests",
|
||||
"com.r.RootTest.a",
|
||||
":alpha:test",
|
||||
"--tests",
|
||||
"com.a.AlphaTest.one",
|
||||
"--continue",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the configuration when a class is not found in exactly one module", async () => {
|
||||
const derived = cfg(["test", "--tests", "com.a.AlphaTest.one", "--tests", "com.z.Gone.x"]);
|
||||
const paths = [
|
||||
["com.a.AlphaTest", "one"],
|
||||
["com.z.Gone", "x"],
|
||||
];
|
||||
expect(await testsBySubproject(derived, paths, find)).toBe(derived);
|
||||
const twice = cfg(["test", "--tests", "com.x.Twice"]);
|
||||
expect(await testsBySubproject(twice, [["com.x.Twice"]], find)).toBe(twice);
|
||||
});
|
||||
|
||||
it("leaves runs alone that already name a task, run only root tests, or are not Gradle", async () => {
|
||||
const scoped = cfg([":alpha:test", "--tests", "com.a.AlphaTest.one"]);
|
||||
expect(await testsBySubproject(scoped, [["com.a.AlphaTest", "one"]], find)).toBe(scoped);
|
||||
const root = cfg(["test", "--tests", "com.r.RootTest.a"]);
|
||||
expect(await testsBySubproject(root, [["com.r.RootTest", "a"]], find)).toBe(root);
|
||||
const maven = cfg(["test", "-Dtest=com.a.AlphaTest#one"], { kind: "maven", command: "./mvnw" });
|
||||
expect(await testsBySubproject(maven, [["com.a.AlphaTest", "one"]], find)).toBe(maven);
|
||||
});
|
||||
});
|
||||
@@ -1,51 +0,0 @@
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { classModules } from "@/platform/javaLaunch";
|
||||
import { inGradleModule } from "../gradleModuleTests";
|
||||
|
||||
const isGradle = (config: Pick<RunConfig, "kind" | "command">) =>
|
||||
config.kind === "gradle" || /(^|[/\\])gradlew?(\.bat)?$/.test(config.command);
|
||||
|
||||
/** `--tests` filter of a test tree path, as `rerun.ts` writes it. */
|
||||
const filterOf = (path: string[]) =>
|
||||
path.length >= 2 ? `${path[0]}.${path[path.length - 1]!.replace(/\(\)$/, "")}` : path[0]!;
|
||||
|
||||
/**
|
||||
* `derived`, a run of the build's plain `test` task narrowed to the tests at `paths`, with each
|
||||
* test's filter on its own subproject's test task (`:alpha:test --tests A :beta:test --tests B`;
|
||||
* a task's `--tests` applies to that task only). The plain task filters every subproject's tests,
|
||||
* and one without a match fails the build before the others run. IDEA reruns the original tasks
|
||||
* and fails the same way. `derived` unchanged when a test class is not found in exactly one
|
||||
* module, or every test is the root project's.
|
||||
*/
|
||||
export async function testsBySubproject(
|
||||
derived: RunConfig,
|
||||
paths: readonly string[][],
|
||||
findModules: (className: string) => Promise<string[]> = classModules,
|
||||
): Promise<RunConfig> {
|
||||
if (!isGradle(derived) || !derived.args.includes("test") || !paths.length) return derived;
|
||||
const groups = new Map<string, string[]>();
|
||||
for (const path of paths) {
|
||||
const modules = await findModules(path[0]!.split("$")[0]!);
|
||||
if (modules.length !== 1) return derived;
|
||||
const filters = groups.get(modules[0]!) ?? [];
|
||||
filters.push(filterOf(path));
|
||||
groups.set(modules[0]!, filters);
|
||||
}
|
||||
if (groups.size === 1 && groups.has("")) return derived;
|
||||
let cwd = derived.cwd;
|
||||
const tasks = [...groups].flatMap(([module, filters]) => {
|
||||
const scoped = inGradleModule({ ...derived, args: ["test"] }, module);
|
||||
cwd = scoped.cwd;
|
||||
const task = scoped.args[0] === "test" ? ":test" : scoped.args[0]!;
|
||||
return [task, ...[...new Set(filters)].flatMap((f) => ["--tests", f])];
|
||||
});
|
||||
const args: string[] = [];
|
||||
for (let i = 0; i < derived.args.length; i++) {
|
||||
const a = derived.args[i]!;
|
||||
if (a === "--tests") i++;
|
||||
else if (a === "test") args.push(...tasks);
|
||||
else if (!a.startsWith("--tests=")) args.push(a);
|
||||
}
|
||||
if (groups.size > 1 && !args.includes("--continue")) args.push("--continue");
|
||||
return { ...derived, cwd, args };
|
||||
}
|
||||
@@ -165,15 +165,6 @@ describe("items and rows", () => {
|
||||
expect([t!.col, t!.endCol]).toEqual([8, 13]);
|
||||
});
|
||||
|
||||
it("textItems keeps each window of a long line as its own item", () => {
|
||||
const items = textItems("/p/min.js", "min.js", [
|
||||
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 0 },
|
||||
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 2000 },
|
||||
]);
|
||||
expect(new Set(items.map((i) => i.key)).size).toBe(2);
|
||||
expect(items.map((i) => i.col)).toEqual([2, 2002]);
|
||||
});
|
||||
|
||||
it("buildRows orders sections, adds headers and more rows", () => {
|
||||
const sections = new Map<SectionId, SectionState>([
|
||||
[
|
||||
|
||||
@@ -219,24 +219,6 @@ describe("result helpers", () => {
|
||||
expect(rows[0]).toMatchObject({ text: "let foo = 1", ranges: [[4, 7]], col: 18, endCol: 21, matched: ["foo"] });
|
||||
});
|
||||
|
||||
it("matchRows keeps each window of a long line as its own row", () => {
|
||||
const rows = matchRows([
|
||||
{
|
||||
path: "/p/min.js",
|
||||
relPath: "min.js",
|
||||
matches: [
|
||||
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 0 },
|
||||
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 2000 },
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(new Set(rows.map((r) => r.key)).size).toBe(2);
|
||||
expect(rows.flatMap((r) => r.starts)).toEqual([
|
||||
{ line: 0, col: 2 },
|
||||
{ line: 0, col: 2002 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("previewReplacement supports Rust-style regex groups", () => {
|
||||
const re = { pattern: "(\\w+)=(\\d+)", isRegex: true, caseSensitive: true };
|
||||
expect(previewReplacement("a=1", re, "${2}:$1")).toBe("1:a");
|
||||
|
||||
@@ -87,14 +87,6 @@ describe("buildFindTree", () => {
|
||||
expect(roots.map((n) => n.key)).toEqual(["f:/p/a.ts", "f:/p/src/a.ts", "f:/p/src/b.ts"]);
|
||||
});
|
||||
|
||||
it("keeps each window of a long line as its own node", () => {
|
||||
const long = file("min.js");
|
||||
long.matches.push({ ...long.matches[0]!, textOffset: 2000 });
|
||||
const [f] = buildFindTree([long]);
|
||||
const children = f?.kind === "file" ? f.children : [];
|
||||
expect(new Set(children.map((n) => n.key)).size).toBe(2);
|
||||
});
|
||||
|
||||
it("groups files by directory on request", () => {
|
||||
const roots = buildFindTree(files, true);
|
||||
expect(roots.map((n) => (n.kind === "dir" ? [n.label, n.count] : n.kind))).toEqual([
|
||||
|
||||
@@ -442,7 +442,7 @@ export function textItems(path: string, rel: string, matches: readonly LineMatch
|
||||
const first = m.ranges[0] ?? [0, 0];
|
||||
out.push({
|
||||
kind: "text",
|
||||
key: `t:${path}:${m.line}:${first[0] + m.textOffset}`,
|
||||
key: `t:${path}:${m.line}:${first[0]}`,
|
||||
path,
|
||||
rel,
|
||||
line: m.line,
|
||||
|
||||
@@ -95,7 +95,7 @@ export function buildFindTree(files: readonly FileMatches[], groupByDirectory =
|
||||
const first = m.ranges[0] ?? [0, 0];
|
||||
return {
|
||||
kind: "match",
|
||||
key: `m:${f.path}:${m.line}:${first[0] + m.textOffset}`,
|
||||
key: `m:${f.path}:${m.line}`,
|
||||
path: f.path,
|
||||
line: m.line,
|
||||
col: first[0] + m.textOffset,
|
||||
|
||||
@@ -197,8 +197,7 @@ export function matchRows(files: readonly FileMatches[]): MatchRow[] {
|
||||
.filter(([s, e]) => e > s);
|
||||
const first = m.ranges[0] ?? [0, 0];
|
||||
rows.push({
|
||||
// A long line comes in several windows: the column tells them apart.
|
||||
key: `${f.path}:${m.line}:${first[0] + m.textOffset}`,
|
||||
key: `${f.path}:${m.line}`,
|
||||
path: f.path,
|
||||
relPath: f.relPath,
|
||||
line: m.line,
|
||||
|
||||
@@ -123,12 +123,11 @@
|
||||
.radio {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
max-inline-size: 100%;
|
||||
white-space: nowrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.radio input {
|
||||
flex: none;
|
||||
margin: 0;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
@@ -156,31 +156,6 @@
|
||||
width: calc(min(var(--image-width), 100%) * var(--markdown-zoom-scale, 1));
|
||||
height: auto;
|
||||
}
|
||||
/* the wrapper takes the image's size, so the image fills it */
|
||||
.preview :global(.image-zoom) {
|
||||
display: inline-block;
|
||||
max-width: calc(100% * var(--markdown-zoom-scale, 1));
|
||||
}
|
||||
.preview :global(.image-zoom[data-natural-width]) {
|
||||
width: calc(min(var(--image-width), 100%) * var(--markdown-zoom-scale, 1));
|
||||
}
|
||||
.preview :global(.image-zoom > .pan-zoom-content > img) {
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
height: auto;
|
||||
}
|
||||
.preview :global(.image-zoom[data-zoomed="true"]) {
|
||||
overflow: hidden;
|
||||
cursor: grab;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
}
|
||||
.preview :global(.image-zoom[data-zoomed="true"] img) {
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
.preview :global(.image-zoom[data-dragging="true"]) {
|
||||
cursor: grabbing;
|
||||
}
|
||||
.preview :global(ul.contains-task-list) {
|
||||
list-style: none;
|
||||
padding-left: 1.2em;
|
||||
|
||||
@@ -56,7 +56,6 @@ import { applyImageZoomWidth, svgDataUrlSize } from "@/ui/svgSize";
|
||||
import styles from "./Markdown.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
import { attachPanZoom } from "../panZoom";
|
||||
|
||||
/** Loaded local images by absolute path (data URLs), shared by all previews. */
|
||||
const imageCache = new Map<string, Promise<string>>();
|
||||
@@ -78,18 +77,6 @@ function openExternal(url: string) {
|
||||
else window.open(url, "_blank", "noopener");
|
||||
}
|
||||
|
||||
/** Wrapper that gives each preview image its own ⌘/Ctrl+wheel pan/zoom, like a Mermaid diagram. */
|
||||
const IMAGE_ZOOM = "image-zoom";
|
||||
|
||||
function attachImagePanZoom(img: HTMLImageElement): void {
|
||||
if (img.closest(`.${IMAGE_ZOOM}`)) return;
|
||||
const box = document.createElement("span");
|
||||
box.className = IMAGE_ZOOM;
|
||||
img.replaceWith(box);
|
||||
box.append(img);
|
||||
attachPanZoom(box);
|
||||
}
|
||||
|
||||
const SPLIT_STORAGE_KEY = "openidea.markdown.split";
|
||||
|
||||
export function MarkdownEditor({
|
||||
@@ -228,17 +215,15 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
let live = true;
|
||||
const size = (img: HTMLImageElement, intrinsic?: { w: number; h: number } | null) =>
|
||||
applyImageZoomWidth(img, intrinsic, img.closest<HTMLElement>(`.${IMAGE_ZOOM}`) ?? img);
|
||||
const bindImageUrl = (img: HTMLImageElement, url: string, asyncLoad: boolean) => {
|
||||
const svgSize = svgDataUrlSize(url);
|
||||
if (svgSize && size(img, svgSize) && asyncLoad) {
|
||||
if (svgSize && applyImageZoomWidth(img, svgSize) && asyncLoad) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
img.onload = () => {
|
||||
if (!live) return;
|
||||
if (!img.hasAttribute("data-natural-width") && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||
if (size(img, { w: img.naturalWidth, h: img.naturalHeight })) {
|
||||
if (applyImageZoomWidth(img, { w: img.naturalWidth, h: img.naturalHeight })) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
} else if (asyncLoad) {
|
||||
@@ -247,13 +232,12 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
};
|
||||
img.src = url;
|
||||
if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||
size(img, { w: img.naturalWidth, h: img.naturalHeight });
|
||||
applyImageZoomWidth(img, { w: img.naturalWidth, h: img.naturalHeight });
|
||||
}
|
||||
};
|
||||
const imgs = [...root.querySelectorAll<HTMLImageElement>("img[data-src]")];
|
||||
imgs.forEach((img) => {
|
||||
attachImagePanZoom(img);
|
||||
size(img);
|
||||
applyImageZoomWidth(img);
|
||||
const src = img.dataset.src ?? "";
|
||||
if (/^data:image\//i.test(src)) {
|
||||
bindImageUrl(img, src, false);
|
||||
@@ -464,8 +448,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
if (!editorPrefs().general.wheelZoom) return;
|
||||
const zoom = wheelZoomStep(e);
|
||||
if (zoom === null) return;
|
||||
// a zoomed-in diagram or image keeps the wheel for its own zoom
|
||||
if ((e.target as Element | null)?.closest?.('[data-zoomed="true"]')) return;
|
||||
if ((e.target as Element | null)?.closest?.('.mermaid-output[data-zoomed="true"]')) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (zoom) stepMarkdownPreviewFontZoom(path, root, zoom);
|
||||
|
||||
@@ -171,7 +171,6 @@ describe("editor font size actions", () => {
|
||||
});
|
||||
|
||||
it("sizes embedded excalidraw.svg, graph SVGs and raster images so they scale with font zoom", async () => {
|
||||
const box = (img: HTMLImageElement) => img.closest<HTMLElement>(".image-zoom")!;
|
||||
const excalidrawSvg =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 940" width="1280" height="940"><!-- svg-source:excalidraw --></svg>';
|
||||
const excalidrawUrl = `data:image/svg+xml;base64,${btoa(excalidrawSvg)}`;
|
||||
@@ -223,19 +222,19 @@ describe("editor font size actions", () => {
|
||||
|
||||
const arch = preview.querySelector<HTMLImageElement>('img[alt="Architecture"]')!;
|
||||
expect(arch.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(box(arch).style.getPropertyValue("--image-width")).toBe("1280px");
|
||||
expect(arch.style.getPropertyValue("--image-width")).toBe("1280px");
|
||||
|
||||
const graph = preview.querySelector<HTMLImageElement>('img[alt="Graph"]')!;
|
||||
expect(graph.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(box(graph).style.getPropertyValue("--image-width")).toBe("400px");
|
||||
expect(graph.style.getPropertyValue("--image-width")).toBe("400px");
|
||||
|
||||
const wordmark = preview.querySelector<HTMLImageElement>('img[alt="Wordmark"]')!;
|
||||
expect(wordmark.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(box(wordmark).style.getPropertyValue("--image-width")).toBe("280px");
|
||||
expect(wordmark.style.getPropertyValue("--image-width")).toBe("280px");
|
||||
|
||||
const icon = preview.querySelector<HTMLImageElement>('img[alt="Icon"]')!;
|
||||
expect(icon.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(box(icon).style.getPropertyValue("--image-width")).toBe("80px");
|
||||
expect(icon.style.getPropertyValue("--image-width")).toBe("80px");
|
||||
|
||||
const shot = preview.querySelector<HTMLImageElement>('img[alt="Shot"]')!;
|
||||
Object.defineProperty(shot, "naturalWidth", { value: 960, configurable: true });
|
||||
@@ -244,60 +243,7 @@ describe("editor font size actions", () => {
|
||||
shot.dispatchEvent(new Event("load"));
|
||||
});
|
||||
expect(shot.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(box(shot).style.getPropertyValue("--image-width")).toBe("960px");
|
||||
} finally {
|
||||
fsReadImage.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("zooms a preview image with ⌘/Ctrl+wheel without wheelZoom, and resets it with a double-click", async () => {
|
||||
const ipc = await import("@/platform/ipc");
|
||||
const fsReadImage = vi
|
||||
.spyOn(ipc.commands, "fsReadImage")
|
||||
.mockResolvedValue({ status: "ok", data: "data:image/png;base64,iVBORw0KGgo=" });
|
||||
try {
|
||||
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc: "", extensions: [fontZoom, live.extensions(mdCtx)] }),
|
||||
});
|
||||
const handle = { view, ctx: mdCtx };
|
||||
_addEditor(handle);
|
||||
disposers.push(() => _removeEditor(handle));
|
||||
views.push(view);
|
||||
activate(view);
|
||||
act(() => useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, t: "preview" } })));
|
||||
render(
|
||||
<MarkdownEditor path={mdCtx.path} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
const shot = await vi.waitFor(() => preview.querySelector<HTMLImageElement>('img[alt="Shot"]')!);
|
||||
const box = shot.closest<HTMLElement>(".image-zoom")!;
|
||||
const pan = box.querySelector<HTMLElement>(".pan-zoom-content")!;
|
||||
expect(pan.contains(shot)).toBe(true);
|
||||
|
||||
const zoomIn = new WheelEvent("wheel", { bubbles: true, cancelable: true, metaKey: true, deltaY: -100 });
|
||||
act(() => {
|
||||
shot.dispatchEvent(zoomIn);
|
||||
});
|
||||
expect(zoomIn.defaultPrevented).toBe(true);
|
||||
expect(pan.style.transform).toMatch(/scale\(1\.1/);
|
||||
expect(box.dataset.zoomed).toBe("true");
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
|
||||
|
||||
// Once zoomed in, the image keeps the wheel even when wheelZoom scales the preview.
|
||||
act(() => useProject.setState({ settings: { editor: { general: { wheelZoom: true } } } } as never));
|
||||
act(() => {
|
||||
shot.dispatchEvent(new WheelEvent("wheel", { bubbles: true, cancelable: true, ctrlKey: true, deltaY: -100 }));
|
||||
});
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
|
||||
|
||||
act(() => {
|
||||
box.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
|
||||
});
|
||||
expect(pan.style.transform).toBe("");
|
||||
expect(box.dataset.zoomed).toBe("");
|
||||
expect(shot.style.getPropertyValue("--image-width")).toBe("960px");
|
||||
} finally {
|
||||
fsReadImage.mockRestore();
|
||||
}
|
||||
|
||||
@@ -192,13 +192,7 @@ export async function findJavaModule(config: RunConfig): Promise<string | null>
|
||||
if (config.module != null) return config.module;
|
||||
const main = parseJavaArgs(config.args).mainClass;
|
||||
if (!main) return null;
|
||||
const modules = await classModules(main);
|
||||
return modules.length === 1 ? modules[0]! : null;
|
||||
}
|
||||
|
||||
/** Module directories (as {@link jvmModuleDir}) of the project's sources declaring the class `binaryName`. */
|
||||
export async function classModules(binaryName: string): Promise<string[]> {
|
||||
const outer = binaryName.split("$")[0]!;
|
||||
const outer = main.split("$")[0]!;
|
||||
const simple = outer.slice(outer.lastIndexOf(".") + 1);
|
||||
const pkg = outer.slice(0, Math.max(0, outer.lastIndexOf(".")));
|
||||
const names = [`${simple}.java`, `${simple}.kt`, ...(simple.endsWith("Kt") ? [`${simple.slice(0, -2)}.kt`] : [])];
|
||||
@@ -212,7 +206,7 @@ export async function classModules(binaryName: string): Promise<string[]> {
|
||||
const sourcePackage = /^\s*package\s+([\w.]+)\s*[;\r\n]/m.exec(text)?.[1] ?? "";
|
||||
if (sourcePackage === pkg) modules.add(jvmModuleDir(file.relPath, configs));
|
||||
}
|
||||
return [...modules];
|
||||
return modules.size === 1 ? [...modules][0]! : null;
|
||||
}
|
||||
|
||||
export async function resolveJavaModule(config: RunConfig): Promise<string> {
|
||||
|
||||
@@ -1108,8 +1108,6 @@
|
||||
"Connect to local socket {path} — equivalent to running arbitrary code on the project machine": "Connect to local socket {path} — equivalent to running arbitrary code on the project machine",
|
||||
"Send requests to the {server} language server, which reads and changes the project's files": "Send requests to the {server} language server, which reads and changes the project's files",
|
||||
"Read the project's resolved Maven and Gradle dependencies": "Read the project's resolved Maven and Gradle dependencies",
|
||||
"Resolved Dependencies": "Resolved Dependencies",
|
||||
"Usages of {symbol}": "Usages of {symbol}",
|
||||
"Read the clipboard's text and images when you run one of its commands": "Read the clipboard's text and images when you run one of its commands",
|
||||
"Output: {channel}": "Output: {channel}",
|
||||
"You can close this tab.": "You can close this tab.",
|
||||
|
||||
@@ -4797,7 +4797,6 @@
|
||||
"Dependency Analyzer": "依赖分析器",
|
||||
"Search dependencies": "搜索依赖",
|
||||
"Show conflicts only": "仅显示冲突",
|
||||
"Resolved Dependencies": "已解析的依赖项",
|
||||
"All scopes": "所有范围",
|
||||
"Show as List": "以列表显示",
|
||||
"Show as Tree": "以树形显示",
|
||||
|
||||
+7
-12
@@ -123,30 +123,25 @@ const formatPx = (n: number) => `${Number(n.toFixed(2))}px`;
|
||||
/**
|
||||
* Sets an `<img>`'s 1× base width so CSS scales it by `--markdown-zoom-scale`,
|
||||
* respecting explicit HTML `width` / `height` attributes when present.
|
||||
* The width goes on `box` when the image sits in a wrapper that takes its size.
|
||||
*/
|
||||
export function applyImageZoomWidth(
|
||||
img: HTMLImageElement,
|
||||
intrinsic?: { w: number; h: number } | null,
|
||||
box: HTMLElement = img,
|
||||
): boolean {
|
||||
export function applyImageZoomWidth(img: HTMLImageElement, intrinsic?: { w: number; h: number } | null): boolean {
|
||||
const rawWidth = img.getAttribute("width");
|
||||
const pct = parsePercent(rawWidth);
|
||||
if (pct !== null) {
|
||||
box.style.width = `calc(${pct}% * var(--markdown-zoom-scale, 1))`;
|
||||
box.style.height = "auto";
|
||||
img.style.width = `calc(${pct}% * var(--markdown-zoom-scale, 1))`;
|
||||
img.style.height = "auto";
|
||||
return true;
|
||||
}
|
||||
const attrW = parseLengthPx(rawWidth);
|
||||
if (attrW !== null) {
|
||||
box.style.setProperty("--image-width", formatPx(attrW));
|
||||
img.dataset.naturalWidth = box.dataset.naturalWidth = "";
|
||||
img.style.setProperty("--image-width", formatPx(attrW));
|
||||
img.dataset.naturalWidth = "";
|
||||
return true;
|
||||
}
|
||||
if (!intrinsic || intrinsic.w <= 0 || intrinsic.h <= 0) return false;
|
||||
const attrH = parseLengthPx(img.getAttribute("height"));
|
||||
const baseW = attrH !== null ? (attrH * intrinsic.w) / intrinsic.h : intrinsic.w;
|
||||
box.style.setProperty("--image-width", formatPx(baseW));
|
||||
img.dataset.naturalWidth = box.dataset.naturalWidth = "";
|
||||
img.style.setProperty("--image-width", formatPx(baseW));
|
||||
img.dataset.naturalWidth = "";
|
||||
return true;
|
||||
}
|
||||
Reference in new issue
Block a user