Compare commits

...
1 Commits
Author SHA1 Message Date
l0ng-ai f53f7c0208 feat(refactor): Java Move for classes, static members, nested types and instance methods
Move… (F6, Refactor This) in Java now asks for the destination and moves:
a top-level class to another package (package declaration, imports and
references follow), a static member or nested type to another class (or a
nested type to a new file), an instance method to the class of one of its
fields or parameters. jdtls offers these only as client-side commands
(java.action.applyRefactoringCommand), now enabled with
moveRefactoringSupport; the IDE picks the destination from
java/getMoveDestinations or java/searchSymbols, then java/move checks the move
and computes the edit, confirmed in Problems Detected when it warns.

Code actions can register client-side command handlers
(registerClientCommand); jdtls' changeSignature command opens the Change
Signature dialog. New IPC: lsp_java_move_destinations, lsp_java_source_types,
lsp_java_move. SignatureChanged is now ServerRefactored.
2026-11-16 15:34:57 +08:00
20 changed files with 635 additions and 42 deletions

No files matched your search

+87 -1
View File
@@ -1199,7 +1199,7 @@ pub async fn lsp_change_signature(
signature: MethodSignature,
delegate: bool,
confirmation: Option<String>,
) -> IdeResult<SignatureChanged> {
) -> IdeResult<ServerRefactored> {
let project = host.project(window)?;
let documents = project.documents.clone();
let version = blocking(move || documents.version(doc)).await?;
@@ -1222,6 +1222,73 @@ pub async fn lsp_change_signature(
.await
}
fn json_argument(args: &str) -> IdeResult<serde_json::Value> {
serde_json::from_str(args).map_err(|e| IdeError::invalid(format!("invalid move arguments: {e}")))
}
fn json_strings(values: Vec<serde_json::Value>) -> Vec<String> {
values.iter().map(serde_json::Value::to_string).collect()
}
/// Where a Java Move code action of `kind` can go; `args` (JSON) carries the code action's own
/// arguments back unchanged, and each destination comes back as JSON.
pub async fn lsp_java_move_destinations(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
kind: String,
args: String,
) -> IdeResult<Vec<String>> {
let args = json_argument(&args)?;
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.java_move_destinations(doc, kind, args, cancel).await;
host.end_request(request);
result.map(json_strings)
}
/// The project's Java source types, for moving a member or type into a class.
pub async fn lsp_java_source_types(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
project_name: Option<String>,
) -> IdeResult<Vec<String>> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.java_source_types(doc, project_name, cancel).await;
host.end_request(request);
result.map(json_strings)
}
/// Checks a Java move and computes its edit without applying it.
#[allow(clippy::too_many_arguments)]
pub async fn lsp_java_move(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
kind: String,
args: String,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
let args = json_argument(&args)?;
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.java_move(doc, kind, args, confirmation, cancel).await;
host.end_request(request);
let mut moved = result?;
blocking(move || {
if let Some(edit) = &mut moved.edit {
project.documents.prepare_workspace_edit(edit)?;
}
Ok(moved)
})
.await
}
pub async fn lsp_rename(
host: &Host,
window: &str,
@@ -1961,6 +2028,25 @@ pub(crate) fn register(d: &mut Dispatcher) {
)
.await
});
d.add("lsp_java_move_destinations", |c| async move {
lsp_java_move_destinations(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("kind")?, c.arg("args")?)
.await
});
d.add("lsp_java_source_types", |c| async move {
lsp_java_source_types(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("projectName")?).await
});
d.add("lsp_java_move", |c| async move {
lsp_java_move(
&c.host,
&c.window,
c.arg("request")?,
c.arg("doc")?,
c.arg("kind")?,
c.arg("args")?,
c.arg("confirmation")?,
)
.await
});
d.add("lsp_format", |c| async move {
lsp_format(&c.host, &c.window, c.arg("doc")?, c.arg("range")?, c.arg("options")?).await
});
+1
View File
@@ -22,6 +22,7 @@ pub(crate) mod configuration;
mod formatter;
mod hierarchy;
pub(crate) mod jvm_inspect;
mod move_refactoring;
pub(crate) mod reserved_names;
mod signature;
pub use formatter::configure_formatter;
@@ -0,0 +1,116 @@
//! Move (F6) through jdtls' own requests. jdtls offers Move as code actions whose command the
//! client runs (`java.action.applyRefactoringCommand` with `moveFile`, `moveType`,
//! `moveStaticMember` or `moveInstanceMethod`); the UI picks the destination from
//! `java/getMoveDestinations` or `java/searchSymbols` and `java/move` checks the move and
//! computes the edit, which the UI applies itself. Requests carry the code action's own
//! arguments back unchanged.
use super::COMMAND_TIMEOUT;
use super::signature::{RefactorEdit, changed};
use crate::types::ServerRefactored;
use crate::{LspManager, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult};
use serde_json::{Value, json};
const FEATURE: &str = "Move";
/// What `java/getMoveDestinations` and `java/move` accept as `moveKind`.
const KINDS: [&str; 6] =
["moveResource", "moveInstanceMethod", "moveStaticMember", "moveTypeToNewFile", "moveTypeToClass", "moveType"];
fn move_params(kind: &str, request: &Value) -> IdeResult<Value> {
if !KINDS.contains(&kind) {
return Err(IdeError::invalid(format!("unknown move kind `{kind}`")));
}
let mut params = json!({
"moveKind": kind,
"sourceUris": request.get("sourceUris").cloned().unwrap_or(json!([])),
"params": request.get("params").cloned().unwrap_or(Value::Null),
});
if let Some(destination) = request.get("destination").filter(|d| !d.is_null()) {
params["destination"] = destination.clone();
}
Ok(params)
}
impl LspManager {
/// Where the move of `kind` can go (packages, or the fields and parameters an instance
/// method can move to); an invalid-input error carries jdtls' reason when there is none.
pub async fn java_move_destinations(
&self,
doc: DocId,
kind: String,
request: Value,
cancel: CancellationToken,
) -> IdeResult<Vec<Value>> {
let (_, t) = self.jdtls_target(doc, FEATURE).await?;
let params = move_params(&kind, &request)?;
let answer: Value = self.call(&t, "java/getMoveDestinations", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if let Some(message) = answer.get("errorMessage").and_then(Value::as_str).filter(|m| !m.is_empty()) {
return Err(IdeError::invalid(message.to_owned()));
}
Ok(answer.get("destinations").and_then(Value::as_array).cloned().unwrap_or_default())
}
/// The project's source types (`java/searchSymbols`), for moving a member or type into a class.
pub async fn java_source_types(
&self,
doc: DocId,
project: Option<String>,
cancel: CancellationToken,
) -> IdeResult<Vec<Value>> {
let (_, t) = self.jdtls_target(doc, FEATURE).await?;
let params = json!({ "query": "*", "projectName": project, "sourceOnly": true });
let answer: Option<Vec<Value>> =
self.call(&t, "java/searchSymbols", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Ok(answer.unwrap_or_default())
}
/// Checks the move and computes the edit without applying it; `confirmation` accepts the
/// warnings an earlier check returned with it.
pub async fn java_move(
&self,
doc: DocId,
kind: String,
request: Value,
confirmation: Option<String>,
cancel: CancellationToken,
) -> IdeResult<ServerRefactored> {
let (_, t) = self.jdtls_target(doc, FEATURE).await?;
let mut params = move_params(&kind, &request)?;
params["updateReferences"] = json!(true);
if let Some(token) = confirmation {
params["confirmationToken"] = json!(token);
}
let answer: Option<RefactorEdit> = self.call(&t, "java/move", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let conv = self.conv(t.enc());
Ok(changed(answer.unwrap_or_default(), |e| convert::workspace_edit(&conv, e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn passes_the_code_action_arguments_back_for_known_kinds_only() {
let request = json!({
"sourceUris": ["file:///p/A.java"],
"params": { "textDocument": { "uri": "file:///p/A.java" } },
"destination": { "displayName": "com.example" },
});
let params = move_params("moveResource", &request).unwrap();
assert_eq!(params["moveKind"], "moveResource");
assert_eq!(params["sourceUris"][0], "file:///p/A.java");
assert_eq!(params["destination"]["displayName"], "com.example");
assert!(move_params("moveResource", &json!({})).unwrap().get("destination").is_none());
assert!(move_params("deleteEverything", &request).is_err());
}
}
+16 -16
View File
@@ -2,7 +2,7 @@
//! a position, `java/getRefactorEdit` (`changeSignature`) checks the new signature and computes the
//! edit. The UI edits the signature and applies the edit itself.
use super::{COMMAND_TIMEOUT, SERVER};
use crate::types::{MethodSignature, ProblemSeverity, RefactoringProblem, SignatureChanged};
use crate::types::{MethodSignature, ProblemSeverity, RefactoringProblem, ServerRefactored};
use crate::{DocSnap, LspManager, Target, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
use serde::Deserialize;
@@ -18,20 +18,20 @@ struct Info {
error_message: Option<String>,
}
#[derive(Deserialize)]
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RefactorEdit {
pub(super) struct RefactorEdit {
edit: Option<lsp_types::WorkspaceEdit>,
error_message: Option<String>,
confirmation_token: Option<String>,
}
/// `java/getRefactorEdit`'s answer as Change Signature's result: an error message alone is fatal;
/// A `java/getRefactorEdit` or `java/move` answer as the result: an error message alone is fatal;
/// with a confirmation token it lists warnings to accept before the edit is computed.
fn changed(
pub(super) fn changed(
answer: RefactorEdit,
convert_edit: impl FnOnce(lsp_types::WorkspaceEdit) -> ide_core::WorkspaceEdit,
) -> SignatureChanged {
) -> ServerRefactored {
let problem = |severity| {
answer
.error_message
@@ -40,7 +40,7 @@ fn changed(
.map(|message| RefactoringProblem { severity, message: message.trim().to_owned() })
};
if let Some(token) = answer.confirmation_token {
return SignatureChanged {
return ServerRefactored {
problems: problem(ProblemSeverity::Warning).into_iter().collect(),
edit: None,
confirmation: Some(token),
@@ -48,9 +48,9 @@ fn changed(
}
match answer.edit {
Some(edit) if answer.error_message.is_none() => {
SignatureChanged { problems: Vec::new(), edit: Some(convert_edit(edit)), confirmation: None }
ServerRefactored { problems: Vec::new(), edit: Some(convert_edit(edit)), confirmation: None }
}
_ => SignatureChanged {
_ => ServerRefactored {
problems: problem(ProblemSeverity::Fatal).into_iter().collect(),
edit: None,
confirmation: None,
@@ -59,12 +59,12 @@ fn changed(
}
impl LspManager {
async fn signature_target(&self, doc: DocId) -> IdeResult<(DocSnap, Target)> {
let (snap, targets) = self.doc_targets(doc, FEATURE, |_| true).await?;
pub(super) async fn jdtls_target(&self, doc: DocId, feature: &str) -> IdeResult<(DocSnap, Target)> {
let (snap, targets) = self.doc_targets(doc, feature, |_| true).await?;
let t = targets
.into_iter()
.find(|t| t.server.name == SERVER)
.ok_or_else(|| IdeError::unavailable(format!("{FEATURE} needs the Java language server (jdtls)")))?;
.ok_or_else(|| IdeError::unavailable(format!("{feature} needs the Java language server (jdtls)")))?;
Ok((snap, t))
}
@@ -84,7 +84,7 @@ impl LspManager {
pos: Pos,
cancel: CancellationToken,
) -> IdeResult<MethodSignature> {
let (snap, t) = self.signature_target(doc).await?;
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let params = Self::signature_context(&snap, &t, pos);
let info: Option<Info> =
self.call(&t, "java/getChangeSignatureInfo", params, Some(&cancel), COMMAND_TIMEOUT).await?;
@@ -108,8 +108,8 @@ impl LspManager {
delegate: bool,
confirmation: Option<String>,
cancel: CancellationToken,
) -> IdeResult<SignatureChanged> {
let (snap, t) = self.signature_target(doc).await?;
) -> IdeResult<ServerRefactored> {
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let MethodSignature { method_identifier, modifier, return_type, method_name, parameters, exceptions } =
signature;
let mut params = json!({
@@ -128,7 +128,7 @@ impl LspManager {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let answer = answer.unwrap_or(RefactorEdit { edit: None, error_message: None, confirmation_token: None });
let answer = answer.unwrap_or_default();
let conv = self.conv(t.enc());
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
}
+3 -3
View File
@@ -539,11 +539,11 @@ pub struct MethodSignature {
pub exceptions: Vec<SignatureException>,
}
/// Change Signature's check: problems to show, the edit when none is fatal, and the token that
/// confirms going on despite warnings.
/// A refactoring checked by the server (Change Signature, Move): problems to show, the edit when
/// none is fatal, and the token that confirms going on despite warnings.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SignatureChanged {
pub struct ServerRefactored {
pub problems: Vec<RefactoringProblem>,
pub edit: Option<WorkspaceEdit>,
pub confirmation: Option<String>,
+1 -1
View File
@@ -63,7 +63,7 @@ When the language server cannot help, Introduce Variable and Introduce Constant
In the Project view, **Rename…** (`⇧F6` / `Shift+F6`), **Move…** (`F6`, drag and drop, or cut and paste) and **Copy…** (`F5`, copy and paste, or `⌥`-drag / `Alt`-drag) open a dialog. With **Search for references** on, references to the file are updated through the language servers that support it (for example imports in TypeScript); **Search in comments and strings** also looks there. The changes are shown in a preview first.
In the editor, **Move…** on a symbol runs the server's move refactoring, where the language has one.
In the editor, **Move…** on a symbol runs the server's move refactoring, where the language has one. In Java it asks where to: a top-level class goes to another package (its package declaration, imports and every reference follow), a static member or nested class to another class, an instance method to the class of one of its fields or parameters; warnings are confirmed in **Problems Detected** first.
## Safe Delete
+1 -1
View File
@@ -58,7 +58,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
在项目视图中,**重命名…**(`⇧F6` / `Shift+F6`)、**移动…**(`F6`、拖放或剪切后粘贴)和 **复制…**(`F5`、复制后粘贴,或按住 `⌥` / `Alt` 拖动)会打开对话框。勾选 **搜索引用** 后,支持此功能的语言服务器会更新对该文件的引用(例如 TypeScript 的 import);**在注释和字符串中搜索** 会把注释和字符串也算进去。改动会先显示预览。
在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。
在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。在 Java 中会先询问目标:顶层类移动到其他包(包声明、import 和所有引用随之更新),静态成员或嵌套类移动到其他类,实例方法移动到其某个字段或形参的类;有警告时先在 **检测到问题** 中确认。
## 安全删除
+3
View File
@@ -36,6 +36,9 @@ bundles = []
# Library classes open as `jdt://` virtual documents (`java/classFileContents`).
classFileContentsSupport = true
resolveAdditionalTextEditsSupport = true
# Move (F6) code actions run the client-side refactoring command; the IDE asks for the
# destination and requests the edit (`java/getMoveDestinations`, `java/move`).
moveRefactoringSupport = true
[language-servers.initialization-options.settings.java]
autobuild = { enabled = true }
+41 -1
View File
@@ -341,7 +341,7 @@ pub async fn lsp_change_signature(
signature: MethodSignature,
delegate: bool,
confirmation: Option<String>,
) -> IdeResult<SignatureChanged> {
) -> IdeResult<ServerRefactored> {
ide_host::ops::lsp::lsp_change_signature(
&state.host,
window.label(),
@@ -355,6 +355,46 @@ pub async fn lsp_change_signature(
.await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_java_move_destinations(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
kind: String,
args: String,
) -> IdeResult<Vec<String>> {
ide_host::ops::lsp::lsp_java_move_destinations(&state.host, window.label(), request, doc, kind, args).await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_java_source_types(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
project_name: Option<String>,
) -> IdeResult<Vec<String>> {
ide_host::ops::lsp::lsp_java_source_types(&state.host, window.label(), request, doc, project_name).await
}
#[tauri::command]
#[specta::specta]
#[allow(clippy::too_many_arguments)]
pub async fn lsp_java_move(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
kind: String,
args: String,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
ide_host::ops::lsp::lsp_java_move(&state.host, window.label(), request, doc, kind, args, confirmation).await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_format(
+3
View File
@@ -304,6 +304,9 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::lsp_hierarchy_refactor,
lsp::lsp_signature_info,
lsp::lsp_change_signature,
lsp::lsp_java_move_destinations,
lsp::lsp_java_source_types,
lsp::lsp_java_move,
lsp::lsp_format,
lsp::lsp_inlay_hints,
lsp::lsp_semantic_tokens,
+3
View File
@@ -315,6 +315,9 @@ lsp_hover trusted project_host bin
lsp_implementations trusted project_host bindings async
lsp_inlay_hints trusted project_host bindings async
lsp_inline_completion trusted project_host bindings async
lsp_java_move trusted project_host bindings async
lsp_java_move_destinations trusted project_host bindings async
lsp_java_source_types trusted project_host bindings async
lsp_library_sources trusted project_host bindings async
lsp_prepare_rename trusted project_host bindings async
lsp_prepare_type_hierarchy trusted project_host bindings async
+14 -11
View File
@@ -643,7 +643,10 @@ export const commands = {
/** Checks Pull Members Up / Push Members Down and computes the edit without applying it. */
lspHierarchyRefactor: (request: RequestId, doc: DocId, pos: Pos, kind: HierarchyRefactoring, target: string | null, choices: HierarchyChoice[]) => typedError<HierarchyRefactored, IdeError>(__TAURI_INVOKE("lsp_hierarchy_refactor", { request, doc, pos, kind, target, choices })),
lspSignatureInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError<MethodSignature, IdeError>(__TAURI_INVOKE("lsp_signature_info", { request, doc, pos })),
lspChangeSignature: (request: RequestId, doc: DocId, pos: Pos, signature: MethodSignature, delegate: boolean, confirmation: string | null) => typedError<SignatureChanged, IdeError>(__TAURI_INVOKE("lsp_change_signature", { request, doc, pos, signature, delegate, confirmation })),
lspChangeSignature: (request: RequestId, doc: DocId, pos: Pos, signature: MethodSignature, delegate: boolean, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_change_signature", { request, doc, pos, signature, delegate, confirmation })),
lspJavaMoveDestinations: (request: RequestId, doc: DocId, kind: string, args: string) => typedError<string[], IdeError>(__TAURI_INVOKE("lsp_java_move_destinations", { request, doc, kind, args })),
lspJavaSourceTypes: (request: RequestId, doc: DocId, projectName: string | null) => typedError<string[], IdeError>(__TAURI_INVOKE("lsp_java_source_types", { request, doc, projectName })),
lspJavaMove: (request: RequestId, doc: DocId, kind: string, args: string, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_java_move", { request, doc, kind, args, confirmation })),
lspFormat: (doc: DocId, range: {
start: Pos,
end: Pos,
@@ -10051,6 +10054,16 @@ export type ServerInfo = {
label?: string | null,
};
/**
* A refactoring checked by the server (Change Signature, Move): problems to show, the edit when
* none is fatal, and the token that confirms going on despite warnings.
*/
export type ServerRefactored = {
problems: RefactoringProblem[],
edit: WorkspaceEdit | null,
confirmation: string | null,
};
export type ServerStatus = "starting" | "ready" | "busy" | "crashed" | "stopped" | "missing" |
/**
* Not started: its configuration can't launch it (e.g. no JDK new enough);
@@ -10300,16 +10313,6 @@ export type Signature = {
parameters: ([number, number])[],
};
/**
* Change Signature's check: problems to show, the edit when none is fatal, and the token that
* confirms going on despite warnings.
*/
export type SignatureChanged = {
problems: RefactoringProblem[],
edit: WorkspaceEdit | null,
confirmation: string | null,
};
/** A declared exception (`throws`), with the server's handle of its type. */
export type SignatureException = {
type: string,
+8 -2
View File
@@ -22,7 +22,7 @@ import { diagnosticsExtension, installDiagnosticsEvents } from "./diagnostics";
import { hoverExtension } from "./hover";
import { parameterTabKeys, signatureExtension } from "./signature";
import { navigationExtension } from "./navigation";
import { intentionsExtension } from "./intentions";
import { intentionsExtension, registerClientCommand } from "./intentions";
import { inlayExtension } from "./inlay";
import { inlineCompletionExtension, registerInlineCompletionActions } from "./inlineCompletion";
import { semanticExtension } from "./semantic";
@@ -42,7 +42,12 @@ import { DOCUMENTATION_WINDOW } from "./docs";
import { prefetchMarkdown } from "./markdown";
import { outsideProjectBanner } from "./outsideProject";
import { implementationGutter, registerNavigationActions } from "@/editor/navigation";
import { ChangeSignatureDialog, HierarchyDialog } from "@/editor/refactor";
import {
ChangeSignatureDialog,
HierarchyDialog,
JAVA_REFACTORING_COMMAND,
runJavaRefactoringCommand,
} from "@/editor/refactor";
export function lspExtensions(ctx: EditorDocContext): Extension[] {
return [
@@ -117,6 +122,7 @@ export function activate(): () => void {
registerOverlay({ id: "editor-lsp.popups", component: LspPopups }),
registerOverlay({ id: "editor-lsp.hierarchyDialog", component: HierarchyDialog }),
registerOverlay({ id: "editor-lsp.changeSignatureDialog", component: ChangeSignatureDialog }),
registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand),
registerEditorBanner(outsideProjectBanner),
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
// IDEA's Documentation tool window: right side, listed once F1 moved documentation there.
+24
View File
@@ -202,6 +202,28 @@ export async function applyQuickFix(view: EditorView) {
showHint(view, "No quick fixes available");
}
/**
* Commands a server leaves to the client (jdtls' `java.action.applyRefactoringCommand`, which
* opens a dialog or asks for a destination). A handler returns false for arguments it doesn't take.
*/
type ClientCommand = (view: EditorView, args: readonly unknown[]) => Promise<boolean>;
const clientCommands = new Map<string, ClientCommand>();
export function registerClientCommand(name: string, run: ClientCommand): () => void {
clientCommands.set(name, run);
return () => {
if (clientCommands.get(name) === run) clientCommands.delete(name);
};
}
function parseArgument(arg: string): unknown {
try {
return JSON.parse(arg);
} catch {
return arg;
}
}
export async function applyCodeAction(view: EditorView, action: EditorQuickFix) {
if ("run" in action) return action.run();
const doc = docOf(view);
@@ -210,6 +232,8 @@ export async function applyCodeAction(view: EditorView, action: EditorQuickFix)
showHint(view, action.disabledReason);
return;
}
const client = !action.edit && action.command ? clientCommands.get(action.command.command) : undefined;
if (client && (await client(view, action.command!.arguments.map(parseArgument)))) return;
const before = view.state.doc;
try {
if (!(await runInteractiveCodeAction(doc.doc, action))) return;
+1
View File
@@ -2,4 +2,5 @@ export { refactorThis, runRefactoring, showNothingHere } from "./refactorThis";
export { askUsagesDetected, fileUsages, safeDelete, viewUsages } from "./safeDelete";
export { startHierarchyRefactoring } from "./hierarchy";
export { ChangeSignatureDialog } from "./ChangeSignatureDialog";
export { JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand } from "./javaMove";
export { HierarchyDialog } from "./HierarchyDialog";
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { packageRow, runJavaRefactoringCommand, targetTypes } from "./javaMove";
describe("java move", () => {
it("shows packages by name and marks the current one", () => {
expect(packageRow({ displayName: "com.example", path: "/app/src/main/java/com/example" })).toEqual({
label: "com.example",
detail: "/app/src/main/java/com/example",
current: false,
});
expect(packageRow({ displayName: "", isParentOfSelectedFile: true }).label).toBe("(default package)");
expect(packageRow({ isParentOfSelectedFile: true }).current).toBe(true);
});
it("offers every source type but the member's own, sorted by name", () => {
const types = [
{ name: "Order", containerName: "com.example.orders" },
{ name: "App", containerName: "com.example.orders" },
{ name: "Strings", containerName: "com.example.util" },
{ name: "" },
];
expect(targetTypes(types, new Set(["com.example.orders.App"])).map((t) => t.name)).toEqual(["Order", "Strings"]);
});
it("leaves commands it doesn't know to the server", async () => {
expect(await runJavaRefactoringCommand({} as never, ["extractInterface"])).toBe(false);
});
});
+256
View File
@@ -0,0 +1,256 @@
/**
* Java Move (F6) and Change Signature from jdtls' client-side refactoring command
* (`java.action.applyRefactoringCommand`): Move asks for the destination (a package, a class,
* or the field or parameter an instance method moves to), then jdtls checks the move and
* computes the edit, which is applied as one change after its problems are confirmed.
*/
import type { EditorView } from "@codemirror/view";
import type { ServerRefactored } from "@/bindings";
import { whenSynced } from "@/editor/api";
import { docOf, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
import { showHint } from "@/editor/lsp/hint";
import { caretAnchor, openPopup, type ListPopupItem } from "@/editor/lsp/popupStore";
import { tx } from "@/platform/i18n";
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { cannotPerform } from "./catalog";
import { applyEdit, confirmProblems, startChangeSignature } from "./signature";
export const JAVA_REFACTORING_COMMAND = "java.action.applyRefactoringCommand";
type Json = Record<string, unknown>;
const record = (v: unknown): Json => (v && typeof v === "object" ? (v as Json) : {});
const text = (v: unknown): string => (typeof v === "string" ? v : "");
/** The file of the code action's parameters. */
const sourceOf = (params: unknown): string[] => {
const uri = text(record(record(params).textDocument).uri);
return uri ? [uri] : [];
};
/** What a Move request sends: the code action's parameters, its file and the destination. */
export interface MoveRequest {
sourceUris: string[];
params: unknown;
destination?: unknown;
}
/** A package from `java/getMoveDestinations` (moveResource) as a chooser row. */
export function packageRow(p: Json): { label: string; detail: string; current: boolean } {
return {
label: text(p.displayName) || "(default package)",
detail: text(p.path),
current: !!p.isParentOfSelectedFile,
};
}
/** The classes a member or type can move into: every source type but its own and itself, by name. */
export function targetTypes(types: readonly unknown[], exclude: ReadonlySet<string>): Json[] {
return types
.map(record)
.filter((t) => {
const name = text(t.name);
const container = text(t.containerName);
return name && !exclude.has(container ? `${container}.${name}` : name);
})
.sort((a, b) => text(a.name).localeCompare(text(b.name)));
}
function errorText(e: unknown): string {
if (isUnavailable(e)) return unavailableText(e, "No language server available");
return e instanceof Error ? e.message : String(e);
}
function choose(view: EditorView, title: string, items: ListPopupItem[]) {
openPopup({ kind: "list", anchor: caretAnchor(view, view.state.selection.main.head), title, items });
}
/** Asks jdtls to move, confirming its warnings, and applies the edit. */
async function move(view: EditorView, kind: string, request: MoveRequest) {
const ctx = docOf(view);
if (!ctx) return;
let confirmation: string | null = null;
let moved: ServerRefactored;
try {
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
moved = await lspRequest(() =>
commands.lspJavaMove(nextRequestId(), ctx.doc, kind, JSON.stringify(request), token),
);
const fatal = moved.problems.find((p) => p.severity === "fatal");
if (fatal || (!moved.edit && !moved.confirmation)) {
showHint(view, cannotPerform(fatal?.message ?? "Nothing to change"));
return;
}
if (!moved.confirmation) break;
if (!(await confirmProblems(moved.problems.map((p) => p.message)))) return;
confirmation = moved.confirmation;
}
} catch (e) {
if (!isCancelled(e)) showHint(view, cannotPerform(errorText(e)));
return;
}
await applyEdit(view, moved.edit!);
}
async function destinations(view: EditorView, kind: string, request: MoveRequest): Promise<Json[] | null> {
const ctx = docOf(view);
if (!ctx) return null;
try {
const found = await lspRequest(() =>
commands.lspJavaMoveDestinations(nextRequestId(), ctx.doc, kind, JSON.stringify(request)),
);
return found.map((d) => record(JSON.parse(d)));
} catch (e) {
if (!isCancelled(e)) showHint(view, cannotPerform(errorText(e)));
return null;
}
}
async function chooseClass(view: EditorView, title: string, info: Json, exclude: Set<string>, run: (t: Json) => void) {
const ctx = docOf(view);
if (!ctx) return;
let types: unknown[];
try {
const project = text(info.projectName) || null;
const found = await lspRequest(() => commands.lspJavaSourceTypes(nextRequestId(), ctx.doc, project));
types = found.map((t) => JSON.parse(t) as unknown);
} catch (e) {
if (!isCancelled(e)) showHint(view, cannotPerform(errorText(e)));
return;
}
const targets = targetTypes(types, exclude);
if (!targets.length) {
showHint(view, cannotPerform("No classes to move to"));
return;
}
choose(
view,
title,
targets.map((t, i) => ({
id: `${i}`,
label: text(t.name),
detail: text(t.containerName),
symbol: "class",
run: () => run(t),
})),
);
}
async function moveFile(view: EditorView, info: Json) {
const uri = text(info.uri);
if (!uri) return;
const request: MoveRequest = { sourceUris: [uri], params: null };
const packages = await destinations(view, "moveResource", request);
if (!packages) return;
if (!packages.length) {
showHint(view, cannotPerform("No packages to move the file to"));
return;
}
const name = decodeURIComponent(uri.slice(uri.lastIndexOf("/") + 1));
choose(
view,
tx`Move ${name} to Package`,
packages.map((p, i) => {
const row = packageRow(p);
return {
id: `${i}`,
label: row.label,
detail: row.detail,
icon: "package",
disabled: row.current ? tx("Current package") : null,
run: () => void move(view, "moveResource", { ...request, destination: p }),
};
}),
);
}
async function moveInstanceMethod(view: EditorView, params: unknown, info: Json) {
const request: MoveRequest = { sourceUris: sourceOf(params), params };
const targets = await destinations(view, "moveInstanceMethod", request);
if (!targets) return;
if (!targets.length) {
showHint(view, cannotPerform("No fields or parameters to move the method to"));
return;
}
choose(
view,
tx`Move Instance Method ${text(info.displayName)}`,
targets.map((d, i) => ({
id: `${i}`,
label: `${text(d.type)} ${text(d.name)}`,
detail: d.isField ? tx("Field") : tx("Parameter"),
run: () => void move(view, "moveInstanceMethod", { ...request, destination: d }),
})),
);
}
function excluded(info: Json, nestedType: boolean): Set<string> {
const exclude = new Set<string>();
const enclosing = text(info.enclosingTypeName);
if (enclosing) {
exclude.add(enclosing);
if (nestedType) exclude.add(`${enclosing}.${text(info.displayName)}`);
}
return exclude;
}
async function moveStaticMember(view: EditorView, params: unknown, info: Json) {
// 55, 71, 81: a class, enum or annotation type (JDT element kinds).
const nested = [55, 71, 81].includes(Number(info.memberType));
await chooseClass(
view,
tx`Move ${text(info.displayName)} to Class`,
info,
excluded(info, nested),
(t) => void move(view, "moveStaticMember", { sourceUris: sourceOf(params), params, destination: t }),
);
}
async function moveType(view: EditorView, params: unknown, info: Json) {
const name = text(info.displayName);
const kinds = Array.isArray(info.supportedDestinationKinds) ? info.supportedDestinationKinds.map(text) : [];
const request: MoveRequest = { sourceUris: sourceOf(params), params };
const toClass = () =>
chooseClass(
view,
tx`Move ${name} to Class`,
info,
excluded(info, true),
(t) => void move(view, "moveTypeToClass", { ...request, destination: t }),
);
const items: ListPopupItem[] = [];
if (kinds.includes("newFile"))
items.push({
id: "file",
label: tx`Move ${name} to a new file`,
run: () => void move(view, "moveTypeToNewFile", request),
});
if (kinds.includes("class"))
items.push({ id: "class", label: tx`Move ${name} to another class`, run: () => void toClass() });
if (items.length === 1) return void items[0]!.run();
if (items.length) choose(view, tx("Move"), items);
}
/** `java.action.applyRefactoringCommand`: the refactorings jdtls leaves to the client. */
export async function runJavaRefactoringCommand(view: EditorView, args: readonly unknown[]): Promise<boolean> {
const [command, params, info] = [text(args[0]), args[1], record(args[2])];
switch (command) {
case "changeSignature":
await startChangeSignature(view);
return true;
case "moveFile":
await moveFile(view, info);
return true;
case "moveInstanceMethod":
await moveInstanceMethod(view, params, info);
return true;
case "moveStaticMember":
await moveStaticMember(view, params, info);
return true;
case "moveType":
await moveType(view, params, info);
return true;
default:
return false;
}
}
+4 -4
View File
@@ -7,7 +7,7 @@
import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { create } from "zustand";
import type { MethodSignature, Pos, SignatureChanged, SignatureParameter, WorkspaceEdit } from "@/bindings";
import type { MethodSignature, Pos, ServerRefactored, SignatureParameter, WorkspaceEdit } from "@/bindings";
import { whenAllSynced, whenSynced } from "@/editor/api";
import { docOf, isUnavailable, lspRequest, reportLspError } from "@/editor/lsp/lsp";
import { offsetToPos } from "@/editor/lsp/positions";
@@ -128,7 +128,7 @@ export async function startChangeSignature(view: EditorView): Promise<void> {
}
}
async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
export async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
try {
await whenAllSynced();
await lspRequest(() => commands.applyWorkspaceEdit(edit));
@@ -137,7 +137,7 @@ async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
}
}
async function confirmProblems(messages: readonly string[]): Promise<boolean> {
export async function confirmProblems(messages: readonly string[]): Promise<boolean> {
const { button } = await ask({
title: "Problems Detected",
icon: "warning",
@@ -162,7 +162,7 @@ export async function changeSignature(
const { view } = request;
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
let confirmation: string | null = null;
let changed: SignatureChanged;
let changed: ServerRefactored;
try {
for (;;) {
await whenSynced(view);
+13 -1
View File
@@ -2127,5 +2127,17 @@
"Duplicate parameter name": "Duplicate parameter name",
"Default value is not specified for a new parameter": "Default value is not specified for a new parameter",
"Visibility": "Visibility",
"Change Signature of '{name}'": "Change Signature of '{name}'"
"Change Signature of '{name}'": "Change Signature of '{name}'",
"Move {name} to Package": "Move {name} to Package",
"Current package": "Current package",
"No packages to move the file to": "No packages to move the file to",
"No fields or parameters to move the method to": "No fields or parameters to move the method to",
"Move Instance Method {name}": "Move Instance Method {name}",
"Move {name} to Class": "Move {name} to Class",
"No classes to move to": "No classes to move to",
"Move {name} to a new file": "Move {name} to a new file",
"Move {name} to another class": "Move {name} to another class",
"(default package)": "(default package)",
"Field": "Field",
"Move": "Move"
}
+12 -1
View File
@@ -8511,5 +8511,16 @@
"Duplicate parameter name": "形参名重复",
"Default value is not specified for a new parameter": "未给新形参指定默认值",
"Visibility": "可见性",
"Change Signature of '{name}'": "更改 '{name}' 的签名"
"Change Signature of '{name}'": "更改 '{name}' 的签名",
"Move {name} to Package": "将 {name} 移动到包",
"Current package": "当前包",
"No packages to move the file to": "没有可移动到的包",
"No fields or parameters to move the method to": "没有可移动到的字段或形参",
"Move Instance Method {name}": "移动实例方法 {name}",
"Move {name} to Class": "将 {name} 移动到类",
"No classes to move to": "没有可移动到的类",
"Move {name} to a new file": "将 {name} 移动到新文件",
"Move {name} to another class": "将 {name} 移动到其他类",
"(default package)": "(默认包)",
"Field": "字段"
}