дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 04:56:08 +02:00
Порівняти коміти
8
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
6ed12adb6d | ||
|
|
fd8f8d6dd0 | ||
|
|
c1bec5182c | ||
|
|
dcb4835a87 | ||
|
|
f74bc7abac | ||
|
|
c871c164c1 | ||
|
|
db65b12afe | ||
|
|
0cc873565a |
No files matched your search
@@ -1143,7 +1143,11 @@ impl AgentManager {
|
||||
.peer
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({ "sessionId": live.session, "cwd": cwd_s, "mcpServers": mcp_servers }),
|
||||
{
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, &mcp_overrides);
|
||||
params["sessionId"] = json!(live.session);
|
||||
params
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
@@ -2316,7 +2320,8 @@ impl Task {
|
||||
let mut session = None;
|
||||
if let (Some(id), true) = (saved, can_load) {
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let params = json!({ "sessionId": &id, "cwd": &cwd_s, "mcpServers": &mcp_servers });
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, &mcp_overrides);
|
||||
params["sessionId"] = json!(&id);
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
self.replaying.store(false, Ordering::Release);
|
||||
@@ -2329,7 +2334,7 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = json!({ "cwd": &cwd_s, "mcpServers": &mcp_servers });
|
||||
let params = session_params(&cwd_s, &mcp_servers, &mcp_overrides);
|
||||
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|
||||
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
|
||||
@@ -3265,6 +3270,22 @@ fn turn_starts(entries: &[AgentEntry]) -> Vec<usize> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
|
||||
/// servers, and the ones switched off for this session, so an agent that also loads its own
|
||||
/// configuration (Claude Code) can keep a same-named server of it off too.
|
||||
fn session_params(cwd: &str, servers: &[Value], overrides: &BTreeMap<String, bool>) -> Value {
|
||||
let off: Vec<&str> = overrides
|
||||
.iter()
|
||||
.filter(|(name, on)| !**on && name.as_str() != mcp::BUILTIN_MCP_NAME)
|
||||
.map(|(name, _)| name.as_str())
|
||||
.collect();
|
||||
let mut params = json!({ "cwd": cwd, "mcpServers": servers });
|
||||
if !off.is_empty() {
|
||||
params["_meta"] = json!({ "openidea": { "mcpServersOff": off } });
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
@@ -170,6 +170,8 @@ struct Session {
|
||||
id: String,
|
||||
cwd: PathBuf,
|
||||
mcp_config: Option<tempfile::TempPath>,
|
||||
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
|
||||
mcp_off: Vec<String>,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -344,9 +346,10 @@ impl Shim {
|
||||
cwd: PathBuf,
|
||||
start: Start,
|
||||
pending: bool,
|
||||
mcp_config: Option<String>,
|
||||
params: &Value,
|
||||
) -> Arc<Session> {
|
||||
let mcp_config = mcp_config.and_then(|json| match write_mcp_config(&json) {
|
||||
let mcp_off = mcp_off(params);
|
||||
let mcp_config = mcp_config(params).and_then(|json| match write_mcp_config(&json) {
|
||||
Ok(path) => Some(path),
|
||||
Err(e) => {
|
||||
tracing::warn!("Claude Code session {id}: cannot write its MCP configuration: {e}");
|
||||
@@ -356,6 +359,7 @@ impl Shim {
|
||||
let session = Arc::new(Session {
|
||||
id: id.to_owned(),
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -411,13 +415,8 @@ impl Shim {
|
||||
}
|
||||
"session/new" => {
|
||||
let id = new_uuid(false);
|
||||
let session = self.add_session(
|
||||
&id,
|
||||
self.cwd_of(¶ms),
|
||||
Start::New { id: id.clone() },
|
||||
false,
|
||||
mcp_config(¶ms),
|
||||
);
|
||||
let session =
|
||||
self.add_session(&id, self.cwd_of(¶ms), Start::New { id: id.clone() }, false, ¶ms);
|
||||
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
|
||||
session.announce_commands();
|
||||
Ok(json!({ "sessionId": id, "configOptions": session.st.lock().settings.options() }))
|
||||
@@ -433,7 +432,7 @@ impl Shim {
|
||||
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
|
||||
};
|
||||
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
|
||||
let session = self.add_session(id, cwd, start, pending, mcp_config(¶ms));
|
||||
let session = self.add_session(id, cwd, start, pending, ¶ms);
|
||||
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
|
||||
if method == "session/load" {
|
||||
session.replay(&chain);
|
||||
@@ -459,7 +458,7 @@ impl Shim {
|
||||
(start, st.settings.clone())
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, mcp_config(¶ms));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms);
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
@@ -666,6 +665,9 @@ impl Session {
|
||||
if let Some(config) = &self.mcp_config {
|
||||
args.extend(["--mcp-config".to_owned(), config.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if !self.mcp_off.is_empty() {
|
||||
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
@@ -1497,6 +1499,24 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
Ok(file.into_temp_path())
|
||||
}
|
||||
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
fn mcp_off(params: &Value) -> Vec<String> {
|
||||
params
|
||||
.pointer("/_meta/openidea/mcpServersOff")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|name| {
|
||||
let name: String =
|
||||
name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect();
|
||||
format!("mcp__{name}")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// ACP `mcpServers` as Claude Code's `--mcp-config` JSON (`None` when there are none).
|
||||
fn mcp_config(params: &Value) -> Option<String> {
|
||||
let servers = params.get("mcpServers")?.as_array()?;
|
||||
|
||||
@@ -1243,6 +1243,13 @@ async fn skipped_questions_have_no_answers() {
|
||||
assert_eq!(cancelled, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn servers_switched_off_become_disallowed_tools() {
|
||||
assert!(mcp_off(&json!({})).is_empty());
|
||||
let off = mcp_off(&json!({ "_meta": { "openidea": { "mcpServersOff": ["github", "my server.v2"] } } }));
|
||||
assert_eq!(off, ["mcp__github", "mcp__my_server_v2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_servers_become_an_mcp_config() {
|
||||
assert_eq!(mcp_config(&json!({ "mcpServers": [] })), None);
|
||||
|
||||
@@ -4238,3 +4238,17 @@ done
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_params_name_the_servers_switched_off() {
|
||||
let overrides = BTreeMap::from([
|
||||
("github".to_owned(), false),
|
||||
("docs".to_owned(), true),
|
||||
(mcp::BUILTIN_MCP_NAME.to_owned(), false),
|
||||
]);
|
||||
let params = session_params("/p", &[json!({ "name": "docs" })], &overrides);
|
||||
assert_eq!(params["cwd"], "/p");
|
||||
assert_eq!(params["mcpServers"][0]["name"], "docs");
|
||||
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
|
||||
assert!(session_params("/p", &[], &BTreeMap::new()).get("_meta").is_none());
|
||||
}
|
||||
@@ -295,9 +295,10 @@ export const lspTheme = EditorView.theme({
|
||||
padding: "6px 10px",
|
||||
borderRadius: "var(--radius-popup)",
|
||||
boxShadow: "var(--shadow-popup)",
|
||||
maxWidth: "480px",
|
||||
whiteSpace: "pre-wrap",
|
||||
},
|
||||
// The hint is the tooltip element itself: beat the editor theme's `.cm-tooltip` width.
|
||||
".cm-tooltip.cm-lsp-hint": { maxWidth: "min(480px, 100%)" },
|
||||
".cm-lsp-hint-error": {
|
||||
backgroundColor: "var(--bg-feedback-error, color-mix(in srgb, var(--danger) 8%, var(--bg-popup)))",
|
||||
borderColor: "color-mix(in srgb, var(--danger) 35%, var(--border-popup))",
|
||||
|
||||
@@ -316,7 +316,7 @@ export async function fillMarkers(
|
||||
const c = up[i]!;
|
||||
const self = classOf(c);
|
||||
if (!self) continue;
|
||||
const found = resolver ? await superMethodsFrom(resolver, self.name, c.symbol, deps) : [];
|
||||
const found = resolver ? await superMethodsFrom(resolver, self, c.symbol, deps) : [];
|
||||
if (!found.length) continue;
|
||||
const known = supers[i]!;
|
||||
// Same merge rule as ↓: add the graph's super methods to what the server answered.
|
||||
@@ -369,41 +369,37 @@ function mergeLocations(first: readonly Location[], more: readonly Location[]):
|
||||
return [...first, ...more.filter((l) => !first.some((f) => sameDeclarationLine(f, l)))];
|
||||
}
|
||||
|
||||
/** Identifies one class declaration in the inheritance graph. */
|
||||
/**
|
||||
* Super methods of `method` declared by a class in `byName`, walking the inheritance
|
||||
* graph's bases up to a few levels. Empty when no base declares the method.
|
||||
* Super methods of `method` declared by a base of the class declaration `start`, walking the
|
||||
* inheritance graph's concrete declarations up to a few levels: a base resolves from the file
|
||||
* that names it, so an unrelated class of the same name never joins the walk. Empty when no
|
||||
* base declares the method.
|
||||
*/
|
||||
async function superMethodsFrom(
|
||||
resolver: InheritanceIndex,
|
||||
start: string,
|
||||
start: ClassInheritance,
|
||||
method: string,
|
||||
deps: MarkerDeps,
|
||||
depth = 3,
|
||||
): Promise<{ location: Location; owner: string }[]> {
|
||||
const bare = method.replace(/\s*[(<].*$/, "");
|
||||
const seen = new Set<string>([start]);
|
||||
const key = (c: ClassInheritance) => `${c.path}:${c.line}:${c.col}`;
|
||||
const seen = new Set<string>([key(start)]);
|
||||
let level = [start];
|
||||
for (let d = 0; d < depth && level.length; d++) {
|
||||
const next: string[] = [];
|
||||
const next: ClassInheritance[] = [];
|
||||
const found: { location: Location; owner: string }[] = [];
|
||||
for (const name of level) {
|
||||
for (const cls of resolver.byName.get(name) ?? []) {
|
||||
for (const base of cls.bases) {
|
||||
if (!seen.add(base)) continue;
|
||||
// Same rule as the graph: a base the imports name, else a unique one.
|
||||
const declarations = await resolver.resolve(base, cls.path);
|
||||
let answered = false;
|
||||
for (const baseCls of declarations) {
|
||||
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
|
||||
const m = methodInOutline(outline, baseCls, bare);
|
||||
if (m) {
|
||||
found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
|
||||
answered = true;
|
||||
}
|
||||
}
|
||||
// Not found in a base that declares nothing: keep walking its own bases.
|
||||
if (!answered) next.push(base);
|
||||
for (const cls of level) {
|
||||
for (const base of cls.bases) {
|
||||
// Same rule as the graph: a base the imports name, else a unique one.
|
||||
for (const baseCls of await resolver.resolve(base, cls.path)) {
|
||||
if (seen.has(key(baseCls))) continue;
|
||||
seen.add(key(baseCls));
|
||||
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
|
||||
const m = methodInOutline(outline, baseCls, bare);
|
||||
if (m) found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
|
||||
// Not declared there: keep walking that class's own bases.
|
||||
else next.push(baseCls);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -803,6 +803,26 @@ describe("python inheritance fallback", () => {
|
||||
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind])).toEqual([[0, "overridden"]]);
|
||||
});
|
||||
|
||||
it("walks up from the class itself, not every class of its name", async () => {
|
||||
// a.py: `class BaseA` with `foo`, `class Child(BaseA)` with `foo`; b.py the same with BaseB.
|
||||
const outline = (base: string) => [
|
||||
item(base, "class", 0, 2, [item("foo", "method", 1, 1)], 6),
|
||||
item("Child", "class", 3, 5, [item("foo", "method", 4, 4)], 6),
|
||||
];
|
||||
const graph: ClassInheritance[] = [
|
||||
{ path: "/p/a.py", line: 0, col: 6, name: "BaseA", bases: [] },
|
||||
{ path: "/p/a.py", line: 3, col: 6, name: "Child", bases: ["BaseA"] },
|
||||
{ path: "/p/b.py", line: 0, col: 6, name: "BaseB", bases: [] },
|
||||
{ path: "/p/b.py", line: 3, col: 6, name: "Child", bases: ["BaseB"] },
|
||||
];
|
||||
const { deps } = pythonServer(graph, { "/p/a.py": outline("BaseA"), "/p/b.py": outline("BaseB") });
|
||||
const candidates = markerCandidates(outline("BaseA"), () => "");
|
||||
const cache = emptyCache();
|
||||
await fillMarkers("/p/a.py", candidates, ALL, deps(), cache);
|
||||
const up = cachedMarkers(candidates, ALL, cache).find((m) => m.line === 4 && m.kind === "overriding");
|
||||
expect(up?.targets.map((t) => [t.path, t.range.start.line])).toEqual([["/p/a.py", 1]]);
|
||||
});
|
||||
|
||||
it("resolves an ambiguous base name through the subclass file's imports", async () => {
|
||||
// Two modules declare `Config`; `from pkg.b import Config` picks one of them, so
|
||||
// only b.py's Config is marked as subclassed.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { MethodSignature } from "@/bindings";
|
||||
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
@@ -46,7 +46,11 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
const ready = !busy && !problem && signatureChanged(info, signature);
|
||||
const current = Math.min(selected, rows.length - 1);
|
||||
|
||||
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
|
||||
const running = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => running.current?.abort(), []);
|
||||
const close = () => {
|
||||
running.current?.abort();
|
||||
useSignatureDialog.setState({ request: null });
|
||||
request.view.focus();
|
||||
};
|
||||
@@ -72,9 +76,10 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
};
|
||||
const submit = async (preview: boolean) => {
|
||||
if (!ready) return;
|
||||
const run = (running.current = new AbortController());
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const outcome = await changeSignature(request, signature, delegate, preview);
|
||||
const outcome = await changeSignature(request, signature, delegate, preview, run.signal);
|
||||
if (useSignatureDialog.getState().request !== request) return;
|
||||
setBusy(false);
|
||||
if (outcome.status === "done") close();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** IDEA's Extract Interface dialog for Java classes (`extractInterface.ts`). */
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import {
|
||||
@@ -39,7 +39,11 @@ function ExtractInterfaceDialogInner({ request }: { request: InterfaceRequest })
|
||||
const ready = !busy && !problem && !!target;
|
||||
const allChecked = checked.size === info.members.length;
|
||||
|
||||
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
|
||||
const running = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => running.current?.abort(), []);
|
||||
const close = () => {
|
||||
running.current?.abort();
|
||||
useExtractInterfaceDialog.setState({ request: null });
|
||||
request.view.focus();
|
||||
};
|
||||
@@ -52,10 +56,11 @@ function ExtractInterfaceDialogInner({ request }: { request: InterfaceRequest })
|
||||
});
|
||||
const submit = async (preview: boolean) => {
|
||||
if (!ready) return;
|
||||
const run = (running.current = new AbortController());
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const members = info.members.map((m) => m.handleIdentifier).filter((id) => checked.has(id));
|
||||
const outcome = await extractInterface(request, trimmed, target, members, preview);
|
||||
const outcome = await extractInterface(request, trimmed, target, members, preview, run.signal);
|
||||
if (useExtractInterfaceDialog.getState().request !== request) return;
|
||||
setBusy(false);
|
||||
if (outcome.status === "done") close();
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const cancelRequest = vi.fn(async (_id: number) => ({ status: "ok", data: null }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const ipc = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...ipc, commands: { ...ipc.commands, cancelRequest } };
|
||||
});
|
||||
|
||||
const { cancellable } = await import("./signature");
|
||||
const { isCancelled } = await import("@/platform/ipc");
|
||||
|
||||
describe("cancellable refactoring requests", () => {
|
||||
it("cancels the request in flight when the dialog closes", async () => {
|
||||
const run = new AbortController();
|
||||
let sent = -1;
|
||||
let answer!: (v: string) => void;
|
||||
const reply = cancellable(run.signal, (id) => {
|
||||
sent = id;
|
||||
return new Promise<string>((r) => (answer = r));
|
||||
});
|
||||
run.abort();
|
||||
expect(cancelRequest).toHaveBeenCalledWith(sent);
|
||||
answer("late");
|
||||
await expect(reply).resolves.toBe("late");
|
||||
});
|
||||
|
||||
it("leaves a request alone once it answered", async () => {
|
||||
cancelRequest.mockClear();
|
||||
const run = new AbortController();
|
||||
await cancellable(run.signal, async () => "done");
|
||||
run.abort();
|
||||
expect(cancelRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never sends a request the dialog closed before", async () => {
|
||||
const run = new AbortController();
|
||||
run.abort();
|
||||
const send = vi.fn(async () => "sent");
|
||||
const err = await cancellable(run.signal, send).catch((e: unknown) => e);
|
||||
expect(isCancelled(err)).toBe(true);
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -25,5 +25,9 @@ describe("extract interface", () => {
|
||||
expect(interfaceProblem("Shape", "Shape", 1)).toBe("Interface name should differ from the class name");
|
||||
expect(interfaceProblem("HasArea", "Shape", 0)).toBe("Select the members to form the interface");
|
||||
expect(interfaceProblem("HasArea", "Shape", 2)).toBeNull();
|
||||
// Java identifiers take letters of any script.
|
||||
expect(interfaceProblem("处理器", "Shape", 1)).toBeNull();
|
||||
expect(interfaceProblem("Größe", "Shape", 1)).toBeNull();
|
||||
expect(interfaceProblem("a-b", "Shape", 1)).toBe("Interface name is not a valid identifier");
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,7 @@ import { tx } from "@/platform/i18n";
|
||||
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { cannotPerform } from "./catalog";
|
||||
import { applyEdit, confirmProblems } from "./signature";
|
||||
import { JAVA_NAME, applyEdit, cancellable, confirmProblems } from "./signature";
|
||||
|
||||
/** Languages whose server extracts interfaces through the dialog. */
|
||||
export const EXTRACT_INTERFACE_LANGUAGES = new Set(["java"]);
|
||||
@@ -51,8 +51,6 @@ export function memberLabel(m: InterfaceMember): string {
|
||||
return `${m.name}${params}: ${m.typeName}`;
|
||||
}
|
||||
|
||||
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
|
||||
|
||||
/** Why the interface can't be extracted yet, or null. */
|
||||
export function interfaceProblem(name: string, className: string, members: number): string | null {
|
||||
if (!name) return "No interface name specified";
|
||||
@@ -127,6 +125,8 @@ export async function extractInterface(
|
||||
pkg: PackageChoice,
|
||||
members: readonly string[],
|
||||
preview: boolean,
|
||||
/** The dialog closed: nothing is confirmed, previewed or applied any more. */
|
||||
signal?: AbortSignal,
|
||||
): Promise<InterfaceOutcome> {
|
||||
const { view } = request;
|
||||
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
|
||||
@@ -136,27 +136,31 @@ export async function extractInterface(
|
||||
for (;;) {
|
||||
await whenSynced(view);
|
||||
const token: string | null = confirmation;
|
||||
extracted = await lspRequest(() =>
|
||||
commands.lspExtractInterface(nextRequestId(), request.doc, request.pos, [...members], name, pkg.json, token),
|
||||
extracted = await cancellable(signal, (id) =>
|
||||
lspRequest(() =>
|
||||
commands.lspExtractInterface(id, request.doc, request.pos, [...members], name, pkg.json, token),
|
||||
),
|
||||
);
|
||||
if (signal?.aborted) return { status: "stay" };
|
||||
const fatal = extracted.problems.find((p) => p.severity === "fatal");
|
||||
if (fatal || (!extracted.edit && !extracted.confirmation))
|
||||
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
|
||||
if (!extracted.confirmation) break;
|
||||
if (!(await confirmProblems(extracted.problems.map((p) => p.message)))) return { status: "stay" };
|
||||
if (!(await confirmProblems(extracted.problems.map((p) => p.message))) || signal?.aborted)
|
||||
return { status: "stay" };
|
||||
confirmation = extracted.confirmation;
|
||||
}
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return { status: "stay" };
|
||||
if (isCancelled(e) || signal?.aborted) return { status: "stay" };
|
||||
return { status: "stay", error: errorText(e) };
|
||||
}
|
||||
const edit = extracted.edit!;
|
||||
const summary = summarizeWorkspaceEdit(edit);
|
||||
if (!summary.files) return { status: "stay", error: "Nothing to change" };
|
||||
const created = edit.files.find((f) => f.kind === "create")?.path;
|
||||
const apply = async () => {
|
||||
await applyEdit(view, edit);
|
||||
if (created) await editorService().openFile(created, { focus: true });
|
||||
const apply = async (cancel?: AbortSignal) => {
|
||||
await applyEdit(view, edit, cancel);
|
||||
if (created && !cancel?.aborted) await editorService().openFile(created, { focus: true });
|
||||
};
|
||||
if (preview) {
|
||||
openPopup({
|
||||
@@ -167,7 +171,7 @@ export async function extractInterface(
|
||||
onConfirm: () => void apply(),
|
||||
});
|
||||
} else {
|
||||
await apply();
|
||||
await apply(signal);
|
||||
}
|
||||
return { status: "done" };
|
||||
}
|
||||
@@ -23,6 +23,10 @@ describe("change signature", () => {
|
||||
it("tells what keeps the signature from being submitted", () => {
|
||||
expect(signatureProblem(info)).toBeNull();
|
||||
expect(signatureProblem({ ...info, methodName: "2x" })).toBe("Method name is not a valid identifier");
|
||||
expect(signatureProblem({ ...info, methodName: "处理" })).toBeNull();
|
||||
expect(
|
||||
signatureProblem({ ...info, parameters: info.parameters.map((p, i) => ({ ...p, name: `数量${i}` })) }),
|
||||
).toBeNull();
|
||||
expect(signatureProblem({ ...info, returnType: " " })).toBe("Return type is not specified");
|
||||
const dup = { ...info, parameters: [info.parameters[0]!, { ...info.parameters[1]!, name: "a" }] };
|
||||
expect(signatureProblem(dup)).toBe("Duplicate parameter name");
|
||||
|
||||
@@ -15,7 +15,7 @@ import { showHint } from "@/editor/lsp/hint";
|
||||
import { openPopup } from "@/editor/lsp/popupStore";
|
||||
import { summarizeWorkspaceEdit } from "@/editor/lsp/workspaceEdit";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
|
||||
import { IpcError, commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { cannotPerform } from "./catalog";
|
||||
|
||||
@@ -50,7 +50,8 @@ export function signatureText(sig: {
|
||||
return head + throws;
|
||||
}
|
||||
|
||||
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
|
||||
/** A Java identifier: letters of any script, `$` and `_`, then digits and combining marks too. */
|
||||
export const JAVA_NAME = /^[\p{L}\p{Nl}\p{Sc}\p{Pc}][\p{L}\p{Nl}\p{Sc}\p{Pc}\p{Nd}\p{Mn}\p{Mc}]*$/u;
|
||||
|
||||
/** Why the edited signature can't be submitted yet, or null. */
|
||||
export function signatureProblem(sig: MethodSignature): string | null {
|
||||
@@ -128,15 +129,31 @@ export async function startChangeSignature(view: EditorView): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
|
||||
export async function applyEdit(view: EditorView, edit: WorkspaceEdit, signal?: AbortSignal) {
|
||||
try {
|
||||
await whenAllSynced();
|
||||
// The dialog closed while the editors were syncing: nothing is applied.
|
||||
if (signal?.aborted) return;
|
||||
await lspRequest(() => commands.applyWorkspaceEdit(edit));
|
||||
} catch (e) {
|
||||
reportLspError(view, e, true);
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends `send(id)` with a fresh request id that `signal` cancels. */
|
||||
export async function cancellable<T>(signal: AbortSignal | undefined, send: (id: number) => Promise<T>): Promise<T> {
|
||||
// Closed before the request went out: it never does (a cancel can't reach an unsent request).
|
||||
if (signal?.aborted) throw new IpcError({ kind: "cancelled", message: "Cancelled" });
|
||||
const id = nextRequestId();
|
||||
const abort = () => void commands.cancelRequest(id);
|
||||
signal?.addEventListener("abort", abort);
|
||||
try {
|
||||
return await send(id);
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmProblems(messages: readonly string[]): Promise<boolean> {
|
||||
const { button } = await ask({
|
||||
title: "Problems Detected",
|
||||
@@ -158,6 +175,8 @@ export async function changeSignature(
|
||||
signature: MethodSignature,
|
||||
delegate: boolean,
|
||||
preview: boolean,
|
||||
/** The dialog closed: nothing is confirmed, previewed or applied any more. */
|
||||
signal?: AbortSignal,
|
||||
): Promise<SignatureOutcome> {
|
||||
const { view } = request;
|
||||
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
|
||||
@@ -167,18 +186,20 @@ export async function changeSignature(
|
||||
for (;;) {
|
||||
await whenSynced(view);
|
||||
const token: string | null = confirmation;
|
||||
changed = await lspRequest(() =>
|
||||
commands.lspChangeSignature(nextRequestId(), request.doc, request.pos, signature, delegate, token),
|
||||
changed = await cancellable(signal, (id) =>
|
||||
lspRequest(() => commands.lspChangeSignature(id, request.doc, request.pos, signature, delegate, token)),
|
||||
);
|
||||
if (signal?.aborted) return { status: "stay" };
|
||||
const fatal = changed.problems.find((p) => p.severity === "fatal");
|
||||
if (fatal || (!changed.edit && !changed.confirmation))
|
||||
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
|
||||
if (!changed.confirmation) break;
|
||||
if (!(await confirmProblems(changed.problems.map((p) => p.message)))) return { status: "stay" };
|
||||
if (!(await confirmProblems(changed.problems.map((p) => p.message))) || signal?.aborted)
|
||||
return { status: "stay" };
|
||||
confirmation = changed.confirmation;
|
||||
}
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return { status: "stay" };
|
||||
if (isCancelled(e) || signal?.aborted) return { status: "stay" };
|
||||
return { status: "stay", error: errorText(e) };
|
||||
}
|
||||
const edit = changed.edit!;
|
||||
@@ -193,7 +214,7 @@ export async function changeSignature(
|
||||
onConfirm: () => void applyEdit(view, edit),
|
||||
});
|
||||
} else {
|
||||
await applyEdit(view, edit);
|
||||
await applyEdit(view, edit, signal);
|
||||
}
|
||||
return { status: "done" };
|
||||
}
|
||||
@@ -281,3 +281,32 @@ it("confirmLeave asks about running processes before closing", async () => {
|
||||
expect(asked[0]?.title).toContain("app");
|
||||
expect(asked[0]?.body).toContain("app");
|
||||
});
|
||||
|
||||
it("counts untitled buffers only when leaving for Welcome, and stays when one isn't saved", async () => {
|
||||
const service = await import("@/workbench/contributions");
|
||||
const { confirmLeave } = await import("../closeGuard");
|
||||
let untitled = [7];
|
||||
const spy = vi.spyOn(service, "maybeEditorService").mockReturnValue({
|
||||
dirtyDocumentIds: () => [7],
|
||||
untitledDirtyDocumentIds: () => untitled,
|
||||
saveAll: vi.fn(async () => {}),
|
||||
} as never);
|
||||
try {
|
||||
// Another project in place keeps the buffer: nothing to ask.
|
||||
const kept = deps([]);
|
||||
await expect(confirmLeave(kept.d, "openidea", true)).resolves.toBe(true);
|
||||
expect(kept.asked).toHaveLength(0);
|
||||
// Close Project asks; Save with the Save As cancelled keeps the project open, quietly.
|
||||
const left = deps([{ button: "save", checked: false }]);
|
||||
await expect(confirmLeave(left.d, "openidea", false)).resolves.toBe(false);
|
||||
expect(left.asked[0]?.body).toContain("1");
|
||||
expect(left.d.saveAll).toHaveBeenCalled();
|
||||
// Saved: the project closes.
|
||||
untitled = [];
|
||||
const saved = deps([{ button: "save", checked: false }]);
|
||||
left.d.saveAll = vi.fn(async () => {});
|
||||
await expect(confirmLeave(saved.d, "openidea", false)).resolves.toBe(true);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
@@ -12,7 +12,7 @@
|
||||
* `general.closeWithoutWelcome` is on, in which case it closes. When
|
||||
* `general.closeTabsWithWindow` is on, that close drops the saved editor tabs.
|
||||
*/
|
||||
import { commands, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
|
||||
import { IpcError, commands, isCancelled, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { closeProject, provideLeaveProjectGuard, useProject } from "@/platform/project";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
@@ -171,6 +171,7 @@ const defaultDeps: CloseDeps = {
|
||||
while ((await liveProcesses()).length > 0) await new Promise((r) => setTimeout(r, 100));
|
||||
},
|
||||
onSaveFailed: (e) =>
|
||||
!isCancelled(e) &&
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.unsaved.saveFailed"),
|
||||
@@ -224,7 +225,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
const s = useProject.getState();
|
||||
// The last project or LightEdit window can return to Welcome. Otherwise it closes.
|
||||
if (returnsToWelcome(ctx.quitting, ctx.windows, !!(s.project || s.lightEdit), s.settings)) {
|
||||
if (await confirmLeave(deps)) {
|
||||
if (await confirmLeave(deps, undefined, false)) {
|
||||
forgot = forgetTabs();
|
||||
try {
|
||||
await closeProject();
|
||||
@@ -276,16 +277,27 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
export async function confirmLeave(
|
||||
deps: CloseDeps = defaultDeps,
|
||||
project = (useProject.getState().project?.displayName || useProject.getState().project?.name) ?? null,
|
||||
keepUntitled = true,
|
||||
): Promise<boolean> {
|
||||
if (!(await closeDocumentWindows())) return false;
|
||||
const confirmTerminate = workflowSettings().run.confirmTerminate;
|
||||
// Untitled buffers follow the window across projects: they are neither
|
||||
// counted nor saved by this guard (the window keeps them open).
|
||||
const untitled = new Set(maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []);
|
||||
// Untitled buffers follow the window into another project: they are neither counted nor
|
||||
// saved then (the window keeps them open). Closing to Welcome drops them, so they count.
|
||||
const untitled = new Set(keepUntitled ? (maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []) : []);
|
||||
const saveDeps: CloseDeps =
|
||||
untitled.size > 0
|
||||
? { ...deps, saveAll: () => Promise.resolve(maybeEditorService()?.saveAll({ skipUntitled: true })) }
|
||||
: deps;
|
||||
: keepUntitled
|
||||
? deps
|
||||
: {
|
||||
...deps,
|
||||
// Save asks for each untitled buffer's path; one left unsaved (Save As cancelled) keeps the project open.
|
||||
saveAll: async () => {
|
||||
await deps.saveAll();
|
||||
if (maybeEditorService()?.untitledDirtyDocumentIds?.().length)
|
||||
throw new IpcError({ kind: "cancelled", message: "Untitled files were not saved" });
|
||||
},
|
||||
};
|
||||
return decideClose(
|
||||
{
|
||||
quitting: false,
|
||||
@@ -331,7 +343,7 @@ export function installCloseGuard(deps: CloseDeps = defaultDeps): () => void {
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root || s.lightEdit !== prev.lightEdit) dirtyDocs.clear();
|
||||
}),
|
||||
provideLeaveProjectGuard(() => confirmLeave(deps)),
|
||||
provideLeaveProjectGuard((keepUntitled) => confirmLeave(deps, undefined, keepUntitled)),
|
||||
];
|
||||
let unlisten: (() => void) | undefined;
|
||||
let disposed = false;
|
||||
|
||||
@@ -79,7 +79,7 @@ export function activate(): () => void {
|
||||
keywords: ["ssh", "remote", "close"],
|
||||
when: "projectOpen",
|
||||
run: async () => {
|
||||
if (!(await confirmLeaveProject())) return;
|
||||
if (!(await confirmLeaveProject(false))) return;
|
||||
try {
|
||||
await disconnectRemote();
|
||||
} catch (e) {
|
||||
|
||||
@@ -71,6 +71,9 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.body[hidden] {
|
||||
display: none;
|
||||
}
|
||||
/* Space a block takes before its diff loads, so the scrollbar is roughly right. */
|
||||
.placeholder {
|
||||
height: 160px;
|
||||
|
||||
@@ -98,14 +98,15 @@ function Block({
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{!collapsed &&
|
||||
(near ? (
|
||||
<div className={styles.body}>
|
||||
<DiffEditor input={input} fit />
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.placeholder} />
|
||||
))}
|
||||
{/* A collapsed block keeps its loaded diff, hidden: unmounting it would release the
|
||||
working-tree document and, with autosave off, drop its unsaved edits. */}
|
||||
{near ? (
|
||||
<div className={styles.body} hidden={collapsed}>
|
||||
<DiffEditor input={input} fit />
|
||||
</div>
|
||||
) : (
|
||||
!collapsed && <div className={styles.placeholder} />
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -83,20 +83,24 @@ describe("the all-in-one diff tab", () => {
|
||||
expect(screen.getAllByText("src")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("collapses a file and all files", () => {
|
||||
it("collapses a file and all files, keeping their diffs (and unsaved edits) loaded", () => {
|
||||
render(<CombinedDiffTab input={input} />);
|
||||
const shown = () => screen.queryAllByTestId("block-diff").filter((b) => !b.closest("[hidden]"));
|
||||
const first = screen.getAllByTestId("block-diff")[0]!;
|
||||
act(() => {
|
||||
fireEvent.click(screen.getAllByRole("button", { name: "Collapse File" })[0]!);
|
||||
});
|
||||
expect(screen.getAllByTestId("block-diff")).toHaveLength(2);
|
||||
expect(shown()).toHaveLength(2);
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Collapse All Files" }));
|
||||
});
|
||||
expect(screen.queryAllByTestId("block-diff")).toHaveLength(0);
|
||||
expect(shown()).toHaveLength(0);
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Expand All Files" }));
|
||||
});
|
||||
expect(screen.getAllByTestId("block-diff")).toHaveLength(3);
|
||||
expect(shown()).toHaveLength(3);
|
||||
// The same diff all along: collapsing never released its document.
|
||||
expect(screen.getAllByTestId("block-diff")[0]).toBe(first);
|
||||
});
|
||||
|
||||
it("switches every block between side-by-side and unified", () => {
|
||||
|
||||
@@ -59,6 +59,26 @@ describe("staging area inclusion", () => {
|
||||
expect(plan.stage).toEqual(["/p/src/Unstaged.kt", "/p/src/Gone.kt"]);
|
||||
});
|
||||
|
||||
it("lists and commits a staged addition deleted from disk; the change lists leave it out", () => {
|
||||
const gone = file("src/New.txt", "added", "deleted");
|
||||
const status = [gone, unstagedOnly];
|
||||
expect(isCommitAll(status)).toBe(false);
|
||||
const plan = planCommit(status, stagingChecks(status));
|
||||
expect(plan.included.map((f) => f.relPath)).toEqual(["src/New.txt"]);
|
||||
expect(plan.exclude).toEqual([]);
|
||||
// Staged shows the addition, Unstaged the deletion.
|
||||
const tree = buildChangeTree(status, "/p", false, undefined, [], true);
|
||||
const kinds = (group: string) =>
|
||||
tree.find((n) => n.group === group)?.children?.flatMap((n) => (n.label === "New.txt" ? [n.kind] : []));
|
||||
expect(kinds("staged")).toEqual(["added"]);
|
||||
expect(kinds("unstaged")).toEqual(["deleted"]);
|
||||
// Without the staging area it is no change against HEAD: listed nowhere, never committed.
|
||||
expect(buildChangeTree(status, "/p", false).flatMap((n) => n.files.map((f) => f.relPath))).toEqual([
|
||||
"src/Unstaged.kt",
|
||||
]);
|
||||
expect(planCommit(status, new Map([[unstagedOnly.path, "all" as const]])).exclude).toEqual(["/p/src/New.txt"]);
|
||||
});
|
||||
|
||||
it("is not Commit All when only unversioned files changed", () => {
|
||||
expect(isCommitAll([untracked])).toBe(false);
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { FileStatus, Stash } from "@/bindings";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { groupOf, remainingOverrides, renamedFromPath } from "./changes";
|
||||
import { addedThenDeleted, groupOf, remainingOverrides, renamedFromPath } from "./changes";
|
||||
import { runCommitChecks } from "./commitChecks";
|
||||
import { contributedCheckProblems, currentPlan, selectionOf } from "./commitSelection";
|
||||
import { forgetAmendDraft, keepMessageAfterCommit, rememberMessage, useCommit } from "./commitStore";
|
||||
@@ -54,7 +54,10 @@ export async function commitChanges(): Promise<string | undefined> {
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
const candidates = plan.included.map((f) => ({ path: stripSlash(f.path), exists: effectiveKind(f) !== "deleted" }));
|
||||
const candidates = plan.included.map((f) => ({
|
||||
path: stripSlash(f.path),
|
||||
exists: effectiveKind(f) !== "deleted" && !addedThenDeleted(f),
|
||||
}));
|
||||
// IDEA: failed checks show in the commit panel; the next Commit ("Commit Anyway") skips them.
|
||||
const checked = !useCommit.getState().checkProblems.length;
|
||||
if (checked) {
|
||||
|
||||
@@ -57,6 +57,14 @@ export function groupOf(fs: FileStatus): GroupId | null {
|
||||
return "changes";
|
||||
}
|
||||
|
||||
/**
|
||||
* Added to the index, then deleted from disk: no change against HEAD, so the change list leaves
|
||||
* it out, but the staging area shows the staged addition (and the deletion, unstaged).
|
||||
*/
|
||||
export function addedThenDeleted(fs: Pick<FileStatus, "staged" | "unstaged">): boolean {
|
||||
return fs.staged === "added" && fs.unstaged === "deleted";
|
||||
}
|
||||
|
||||
export function isPartiallyStaged(fs: FileStatus): boolean {
|
||||
return (
|
||||
!!fs.staged &&
|
||||
@@ -99,7 +107,9 @@ const KIND_ORDER: GroupId[] = ["conflicts", "changes", "unversioned"];
|
||||
function fileNode(fs: FileStatus, root: string, group: GroupId, flat: boolean, scope: string = group): ChangeNode {
|
||||
const path = stripSlash(fs.path);
|
||||
const rel = relTo(root, path);
|
||||
const kind = effectiveKind(fs) ?? "modified";
|
||||
// Under Staged / Unstaged, a file without an overall kind (added, then deleted) shows its side's.
|
||||
const side = group === "staged" ? fs.staged : group === "unstaged" ? fs.unstaged : null;
|
||||
const kind = effectiveKind(fs) ?? (side === "added" || side === "deleted" ? side : "modified");
|
||||
const dir = dirName(rel);
|
||||
return {
|
||||
key: `${scope}:${path}`,
|
||||
@@ -259,7 +269,7 @@ export function buildChangeTree(
|
||||
const repoRoots = byRepo ? repos : [];
|
||||
const byGroup = new Map<GroupId, FileStatus[]>();
|
||||
for (const fs of status) {
|
||||
const g = groupOf(fs);
|
||||
const g = groupOf(fs) ?? (byStaging && addedThenDeleted(fs) ? "changes" : null);
|
||||
if (!g) continue;
|
||||
let list = byGroup.get(g);
|
||||
if (!list) byGroup.set(g, (list = []));
|
||||
@@ -400,8 +410,12 @@ export function planCommit(status: readonly FileStatus[], checks: ReadonlyMap<st
|
||||
const plan: CommitPlan = { stage: [], exclude: [], included: [], partial: [] };
|
||||
for (const fs of status) {
|
||||
if (!groupOf(fs)) {
|
||||
// Listed nowhere, yet staged: added to the index, then deleted from disk. It is no
|
||||
// change against HEAD, so the commit must not pick up the staged addition.
|
||||
// Added to the index, then deleted from disk: no change against HEAD, so the commit
|
||||
// leaves the staged addition out, unless the staging area commits it (checked "staged").
|
||||
if (addedThenDeleted(fs) && (checks.get(fs.path) ?? checks.get(stripSlash(fs.path))) === "staged") {
|
||||
plan.included.push(fs);
|
||||
continue;
|
||||
}
|
||||
if (fs.staged && fs.staged !== "conflicted" && fs.unstaged !== "ignored") plan.exclude.push(stripSlash(fs.path));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import type { ChangelistState, FileStatus } from "@/bindings";
|
||||
import { useWorkflowSettings, workflowSettings } from "@/platform/workflowSettings";
|
||||
import { groupOf, type CheckState } from "./changes";
|
||||
import { addedThenDeleted, groupOf, type CheckState } from "./changes";
|
||||
import { withListDefaults } from "./changelists";
|
||||
|
||||
const enabled = (vcs: { git: { stagingArea: boolean }; commit: { nonModal: boolean } }) =>
|
||||
@@ -31,6 +31,8 @@ export function stagingChecks(status: readonly FileStatus[]): Map<string, CheckS
|
||||
const all = isCommitAll(status);
|
||||
const out = new Map<string, CheckState>();
|
||||
for (const f of status) {
|
||||
// A staged addition deleted from disk is committed as staged (nothing against HEAD for Commit All).
|
||||
if (addedThenDeleted(f) && !all) out.set(f.path, "staged");
|
||||
if (groupOf(f) !== "changes") continue;
|
||||
out.set(f.path, all ? "all" : staged(f) ? "staged" : "none");
|
||||
}
|
||||
|
||||
@@ -2157,5 +2157,6 @@
|
||||
"Extract Interface from '{name}'": "Extract Interface from '{name}'",
|
||||
"The interface could not be extracted": "The interface could not be extracted",
|
||||
"Extract Interface is not supported for {name}": "Extract Interface is not supported for {name}",
|
||||
"Package for new interface": "Package for new interface"
|
||||
"Package for new interface": "Package for new interface",
|
||||
"Untitled files were not saved": "Untitled files were not saved"
|
||||
}
|
||||
@@ -8540,5 +8540,6 @@
|
||||
"Extract Interface from '{name}'": "从 '{name}' 提取接口",
|
||||
"The interface could not be extracted": "无法提取接口",
|
||||
"Extract Interface is not supported for {name}": "{name} 不支持提取接口",
|
||||
"Package for new interface": "新接口的软件包"
|
||||
"Package for new interface": "新接口的软件包",
|
||||
"Untitled files were not saved": "未命名文件未保存"
|
||||
}
|
||||
@@ -25,20 +25,26 @@ export const useProject = create<ProjectState>(() => ({
|
||||
|
||||
useProject.subscribe((s) => setContext("projectOpening", s.openingPath !== null));
|
||||
|
||||
let leaveGuard: (() => Promise<boolean>) | null = null;
|
||||
/** `keepUntitled`: the window opens another project in place and keeps its untitled buffers. */
|
||||
type LeaveGuard = (keepUntitled: boolean) => Promise<boolean>;
|
||||
let leaveGuard: LeaveGuard | null = null;
|
||||
|
||||
/** Installs the check run before this window leaves its project (unsaved changes). */
|
||||
export function provideLeaveProjectGuard(guard: () => Promise<boolean>): () => void {
|
||||
export function provideLeaveProjectGuard(guard: LeaveGuard): () => void {
|
||||
leaveGuard = guard;
|
||||
return () => {
|
||||
if (leaveGuard === guard) leaveGuard = null;
|
||||
};
|
||||
}
|
||||
|
||||
/** False when the user chose to stay (another project in place, Close Project). */
|
||||
export function confirmLeaveProject(): Promise<boolean> {
|
||||
/**
|
||||
* False when the user chose to stay (another project in place, Close Project). Untitled buffers
|
||||
* follow the window only into another local project (`keepUntitled`); leaving for Welcome or a
|
||||
* remote host asks about them too.
|
||||
*/
|
||||
export function confirmLeaveProject(keepUntitled = true): Promise<boolean> {
|
||||
const s = useProject.getState();
|
||||
return (s.project || s.lightEdit) && leaveGuard ? leaveGuard() : Promise.resolve(true);
|
||||
return (s.project || s.lightEdit) && leaveGuard ? leaveGuard(keepUntitled) : Promise.resolve(true);
|
||||
}
|
||||
|
||||
let startupLaunch: Promise<void> | null = null;
|
||||
|
||||
@@ -105,6 +105,7 @@
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
width: 340px;
|
||||
max-width: 100%;
|
||||
/* Never grow past the window: the close button must stay reachable. */
|
||||
max-height: calc(100vh - 48px);
|
||||
padding: 14px 34px 14px 14px;
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
position: fixed;
|
||||
/* Inside the editor island's bottom-right corner, clear of the right stripe. */
|
||||
right: 78px;
|
||||
/* A narrow window narrows the balloons instead of pushing them off its left edge. */
|
||||
left: 16px;
|
||||
bottom: calc(var(--h-statusbar) + 16px);
|
||||
/* Balloons belong to the main window: modal dialogs cover them, like IDEA. */
|
||||
z-index: calc(var(--z-dialog) - 1);
|
||||
@@ -12,6 +14,7 @@
|
||||
pointer-events: none;
|
||||
}
|
||||
.balloon {
|
||||
max-width: 100%;
|
||||
pointer-events: auto;
|
||||
animation: slideIn var(--dur) var(--ease);
|
||||
}
|
||||
|
||||
@@ -65,7 +65,8 @@ export async function openRemoteProject(
|
||||
await call(commands.windowOpenRemote(target, path, true));
|
||||
return true;
|
||||
}
|
||||
if (!(await confirmLeaveProject())) return false;
|
||||
// The remote host's project doesn't take this window's untitled buffers.
|
||||
if (!(await confirmLeaveProject(false))) return false;
|
||||
try {
|
||||
await here();
|
||||
return true;
|
||||
|
||||
@@ -69,7 +69,7 @@ export function registerShellActions(): () => void {
|
||||
category: "File",
|
||||
when: "projectOpen",
|
||||
run: async () => {
|
||||
if (!useProject.getState().project || !(await confirmLeaveProject())) return;
|
||||
if (!useProject.getState().project || !(await confirmLeaveProject(false))) return;
|
||||
try {
|
||||
await closeProject();
|
||||
} catch (e) {
|
||||
|
||||
Reference in new issue
Заблокувати користувача