Compare commits

...
Author SHA1 Message Date
l0ng-ai e9a5a4c907 feat(sdk): add a JDK from disk in Project Structure › SDKs
The SDKs list showed only detected JDKs, with Download JDK… as the only way
to add one. The toolbar's + now offers Download JDK… and Add JDK from Disk…:
the picked folder (a macOS .jdk bundle too) is checked to be a JDK home and
kept in the global languages.java.addedJdks, which detection lists from then on
(source "added"), so it is also offered in every JDK picker. − removes a JDK
added this way; detected ones stay.
2026-11-16 12:00:10 +08:00
15 changed files with 277 additions and 10 deletions

No files matched your search

+3
View File
@@ -1347,6 +1347,9 @@ pub struct JavaSettings {
pub jdtls_vm_args: String,
/// Share one JDT LS across builds in an ordinary project window; other windows remain separate.
pub jdtls_shared: bool,
/// JDK homes added by hand (Platform Settings › SDKs › Add JDK from Disk…), listed with the
/// detected ones.
pub added_jdks: Vec<String>,
/// Build Tools › Maven.
pub maven: MavenSettings,
/// Build Tools › Gradle.
+9
View File
@@ -190,6 +190,7 @@ impl Host {
open_locks: Default::default(),
};
host.apply_proxy();
host.apply_added_jdks();
ops::agent::move_user_mcp_values(&host);
host
}
@@ -564,3 +565,11 @@ mod tests {
host.close_project("main");
}
}
impl Host {
/// Lists the JDKs added by hand (global Settings › SDKs) with the detected ones.
pub fn apply_added_jdks(&self) {
let homes = self.global_settings.effective().languages.java.added_jdks;
ide_sdk::java::set_added_jdks(homes.into_iter().map(PathBuf::from));
}
}
+3
View File
@@ -232,6 +232,9 @@ pub fn set_settings(
if key == "ssh" || key.starts_with("ssh.") {
host.ssh.set_configs(host.global_settings.effective().ssh.configs);
}
if key == "languages" || key == "languages.java" || key.starts_with("languages.java.addedJdks") {
host.apply_added_jdks();
}
if is_proxy {
host.apply_proxy();
}
+14
View File
@@ -37,6 +37,9 @@ pub struct ProjectInterpreter {
pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<Vec<Sdk>> {
host.require_trust(window)?;
let project = host.project(window).ok();
if kind == SdkKind::Jdk {
host.apply_added_jdks();
}
let root = project.as_ref().map(|p| p.root.clone());
// The interpreter the project uses is a choice even where detection doesn't look (a
// virtualenv in a subfolder, one picked by path), so it shows by name and version.
@@ -372,9 +375,20 @@ pub async fn sdk_python_pip(
result?
}
/// The JDK whose home is `path` (a macOS bundle too), as the SDK list shows it; `None` when
/// `path` is no JDK home (Add JDK from Disk…).
pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
tokio::task::spawn_blocking(move || {
ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))
})
.await
.map_err(join_err)
}
/// Commands of this module the remote server answers.
pub(crate) fn register(d: &mut Dispatcher) {
d.add("sdk_detect", |c| async move { sdk_detect(&c.host, &c.window, c.arg("kind")?).await });
d.add("sdk_jdk_at", |c| async move { sdk_jdk_at(c.arg("path")?).await });
d.add(
"sdk_python_project_interpreters",
|c| async move { sdk_python_project_interpreters(&c.host, &c.window).await },
+2
View File
@@ -885,6 +885,8 @@ pub fn jdk_sdk(j: &crate::java::Jdk) -> Sdk {
"JAVA_HOME"
} else if crate::java::is_downloaded(&j.home) {
"downloaded"
} else if crate::java::is_added(&j.home) {
"added"
} else {
version_managers::manager_of(&j.home).unwrap_or("system")
};
+41
View File
@@ -138,6 +138,26 @@ pub fn add_jdk_root(dir: &Path) {
}
}
/// JDK homes added by hand (Settings › SDKs › Add JDK from Disk…).
static ADDED: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Sets the JDK homes added by hand; the next scan lists them (a change drops the cached scan).
pub fn set_added_jdks(homes: impl IntoIterator<Item = PathBuf>) {
let homes: Vec<PathBuf> = homes.into_iter().filter(|h| !h.as_os_str().is_empty()).collect();
let mut added = ADDED.lock().unwrap_or_else(|e| e.into_inner());
if *added != homes {
*added = homes;
drop(added);
*JDKS.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
}
/// Whether `home` is a JDK added by hand.
pub fn is_added(home: &Path) -> bool {
let added = ADDED.lock().unwrap_or_else(|e| e.into_inner());
added.iter().any(|h| jdk_at(h).is_some_and(|j| j.home == home))
}
/// Whether `home` lies in a folder registered with [`add_jdk_root`].
pub fn is_downloaded(home: &Path) -> bool {
let roots = EXTRA_ROOTS.lock().unwrap_or_else(|e| e.into_inner());
@@ -190,6 +210,7 @@ fn scan() -> Vec<Jdk> {
for (dir, _) in ide_core::version_managers::installs(ide_core::version_managers::Tool::Java) {
homes.extend([dir.join("Contents/Home"), dir]);
}
homes.extend(ADDED.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned());
let mut out: Vec<Jdk> = Vec::new();
for h in homes {
if let Some(jdk) = jdk_at(&h)
@@ -1364,6 +1385,26 @@ mod tests {
assert!(is_downloaded(&home) && !is_downloaded(Path::new("/elsewhere")));
}
#[test]
fn jdks_added_by_hand_are_listed_until_removed() {
let tmp = tempfile::tempdir().unwrap();
// A macOS bundle picked as its folder: listed by its `Contents/Home`.
let bundle = tmp.path().join("odd place/my-jdk.jdk");
let home = bundle.join("Contents/Home");
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("release"), "JAVA_VERSION=\"17.0.9\"\nIMPLEMENTOR=\"Acme\"\n").unwrap();
std::fs::write(home.join("bin").join(crate::exe("java")), "").unwrap();
let home = dunce::canonicalize(&home).unwrap();
set_added_jdks([bundle.clone()]);
assert!(installed_jdks().iter().any(|j| j.home == home && j.major == 17));
assert!(is_added(&home));
let sdk = crate::jdk_sdk(&jdk_at(&bundle).unwrap());
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Acme 17.0.9", "added"));
set_added_jdks(Vec::new());
assert!(!installed_jdks().iter().any(|j| j.home == home));
assert!(!is_added(&home));
}
#[test]
fn jdtls_runs_on_the_chosen_server_jdk() {
let fixtures = tempfile::tempdir().unwrap();
+1
View File
@@ -489,6 +489,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
sdk::sdk_python_interpreter,
sdk::sdk_python_effective,
sdk::sdk_php_effective,
sdk::sdk_jdk_at,
sdk::sdk_container_python,
sdk::sdk_container_python_refresh,
sdk::sdk_php_xdebug,
+7
View File
@@ -17,6 +17,13 @@ pub async fn sdk_detect(window: Window, state: State<'_, AppState>, kind: SdkKin
ide_host::ops::sdk::sdk_detect(&state.host, window.label(), kind).await
}
/// The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home.
#[tauri::command]
#[specta::specta]
pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
ide_host::ops::sdk::sdk_jdk_at(path).await
}
/// The Python interpreters of the recently opened projects, each with its project.
#[tauri::command]
#[specta::specta]
+1
View File
@@ -513,6 +513,7 @@ scaffold_requirements always project_host bin
sdk_container_python trusted project_host bindings sync
sdk_container_python_refresh trusted project_host bindings async
sdk_detect trusted project_host bindings async
sdk_jdk_at trusted project_host bindings async
sdk_locate_tools trusted project_host bindings async
sdk_php_composer_install trusted project_host bindings async
sdk_php_effective trusted project_host bindings sync
+25
View File
@@ -1096,6 +1096,26 @@ export const commands = {
sdkPythonEffective: (near: string | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective", { near })),
/** The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`. */
sdkPhpEffective: () => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_php_effective")),
/** The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home. */
sdkJdkAt: (path: string) => typedError<{
/**
* Executable (`python`, `node`, `pnpm`) or directory (Rust toolchain bin
* dir, GOROOT, TypeScript `lib` dir) that the setting stores.
*/
path: IpcPath,
/** Display name, e.g. `Python 3.12 (.venv)` or `stable-aarch64-apple-darwin`. */
name: string,
version: string | null,
/**
* Where it was found: `venv` | `system` | `pyenv` | `conda` | `uv` | `nvm` |
* `rustup` | `bundled` | `workspace` | `path` …
*/
source: string,
/** Environment / toolchain root (virtualenv dir, rustup toolchain dir, GOROOT). */
home: IpcPath | null,
/** Rust standard library sources, Go default GOPATH. */
extra: IpcPath | null,
} | null, IdeError>(__TAURI_INVOKE("sdk_jdk_at", { path })),
/** The project interpreter when it is a Docker or Compose run target's, with its snapshot. */
sdkContainerPython: () => typedError<{
/** The run target's id. */
@@ -6720,6 +6740,11 @@ export type JavaSettings = {
jdtlsVmArgs?: string,
/** Share one JDT LS across builds in an ordinary project window; other windows remain separate. */
jdtlsShared?: boolean,
/**
* JDK homes added by hand (Platform Settings › SDKs › Add JDK from Disk…), listed with the
* detected ones.
*/
addedJdks?: string[],
/** Build Tools › Maven. */
maven?: MavenSettings,
/** Build Tools › Gradle. */
@@ -0,0 +1,94 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import type { Sdk, Settings } from "@/platform/ipc";
const open = vi.fn();
const JDK: Sdk = {
path: "/opt/jdks/acme-17/Contents/Home",
name: "Acme 17.0.9",
version: "17.0.9",
source: "system",
home: "/opt/jdks/acme-17/Contents/Home",
extra: null,
};
vi.mock("@/platform/dialog", () => ({ open: (...args: unknown[]) => open(...args) }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: {
...real.commands,
sdkDetect: vi.fn(async () => ({ status: "ok", data: [] })),
sdkJdkAt: vi.fn(async (path: string) => ({
status: "ok",
data: path.startsWith("/opt/jdks/acme-17") ? JDK : null,
})),
settingsSet: vi.fn(async () => ({ status: "ok", data: {} })),
settingsGet: vi.fn(async () => ({})),
settingsGetGlobal: vi.fn(async () => ({})),
},
};
});
import { useProject } from "@/platform/project";
import { useContextMenuStore } from "@/ui/Menu";
import { DEFAULT_SETTINGS } from "../model/schema";
import { openProjectStructure, stagedValue, useSettingsDialog } from "../model/staging";
import { ProjectStructureDialog } from "../languages/ProjectStructurePage";
import { useSdks } from "../languages/api";
function addMenuItem(label: string) {
fireEvent.click(screen.getByRole("button", { name: "Add SDK" }));
const item = useContextMenuStore.getState().menu?.items.find((i) => "label" in i && i.label === label) as
| { run?: () => void }
| undefined;
expect(item?.run).toBeDefined();
item!.run!();
}
const added = () => stagedValue(useSettingsDialog.getState(), "global", "languages.java.addedJdks");
beforeEach(() => {
open.mockReset();
useSdks.setState({ byKind: {}, loading: {}, errors: {} });
useProject.setState({
settings: structuredClone(DEFAULT_SETTINGS) as Settings,
project: { name: "demo", root: "/project" } as never,
});
render(<ProjectStructureDialog />);
act(() => openProjectStructure("sdks"));
});
afterEach(() => {
act(() => useSettingsDialog.setState({ projectStructureOpen: false }));
useProject.setState({ project: null, settings: null });
});
describe("SDKs › Add JDK from Disk…", () => {
it("adds the picked JDK home to the list and the global settings, and removes it again", async () => {
open.mockResolvedValue("/opt/jdks/acme-17");
await act(async () => addMenuItem("Add JDK from Disk…"));
expect(open).toHaveBeenCalledWith(expect.objectContaining({ directory: true }));
expect(screen.getAllByText("Acme 17.0.9").length).toBeGreaterThan(0);
expect(added()).toEqual([JDK.path]);
fireEvent.click(screen.getByRole("button", { name: "Remove SDK" }));
expect(screen.queryByText("Acme 17.0.9")).not.toBeInTheDocument();
expect(added()).toEqual([]);
});
it("refuses a folder that is no JDK home", async () => {
open.mockResolvedValue("/tmp/not-a-jdk");
await act(async () => addMenuItem("Add JDK from Disk…"));
expect(screen.getByRole("alert")).toHaveTextContent("The selected directory is not a valid home for JDK");
expect(added() ?? []).toEqual([]);
});
it("keeps detected SDKs from being removed", async () => {
await act(async () => useSdks.setState({ byKind: { jdk: [JDK] } }));
fireEvent.click(screen.getByRole("option", { name: /Acme 17\.0\.9/ }));
expect(screen.getByRole("button", { name: "Remove SDK" })).toBeDisabled();
});
});
@@ -28,7 +28,7 @@ import { call, commands, isTauri, nextRequestId, type FileEntry } from "@/platfo
import { mergeLibraryGroups } from "@/platform/libraries";
import type { BuildModel, LibraryGroup, WebArtifact } from "@/bindings";
import { relativePath, useProject } from "@/platform/project";
import { PageContext, useSettingsFormFor } from "../components/context";
import { PageContext, useSetting, useSettingsFormFor } from "../components/context";
import {
applySettings,
closeProjectStructure,
@@ -61,7 +61,7 @@ import {
} from "@/platform/languageSettings";
import { initProjectRoots, useDetectedRoots } from "@/platform/projectRoots";
import { Row, Section } from "../components/Form";
import { detectSdks, useSdks, type SdkKind } from "./api";
import { detectSdks, forgetSdk, rememberSdk, useSdks, type SdkKind } from "./api";
import { choosePath } from "@/platform/choosePath";
import { DownloadJdkDialog } from "./DownloadJdkDialog";
import { SdkField, tildify, useDetected, useJdtlsJdk, useProjectSetting } from "./components";
@@ -1790,8 +1790,31 @@ function SdksSection() {
const [downloading, setDownloading] = useState(false);
const [selectedKey, setSelectedKey] = useState<string>("");
const [projectJdk, setProjectJdk] = useProjectSetting<string>("languages.java.jdk");
const [addedJdks, setAddedJdks] = useSetting<string[] | undefined>("languages.java.addedJdks", "global");
const [addError, setAddError] = useState<string | null>(null);
useDetected("jdk");
const addJdkFromDisk = async () => {
setAddError(null);
const picked = await choosePath({ directory: true, title: tx("Select Home Directory for JDK") });
if (!picked) return;
const sdk = await call(commands.sdkJdkAt(picked)).catch(() => null);
if (!sdk) {
setAddError(tx`The selected directory is not a valid home for JDK: ${tildify(picked)}`);
return;
}
const added = addedJdks ?? [];
if (!added.includes(sdk.path)) setAddedJdks([...added, sdk.path]);
rememberSdk("jdk", { ...sdk, source: "added" });
setSelectedKey(`jdk:${sdk.path}`);
};
const removeAddedJdk = (path: string) => {
setAddedJdks((addedJdks ?? []).filter((p) => p !== path));
forgetSdk("jdk", path);
setSelectedKey("");
};
useEffect(() => {
for (const { kind } of SDK_KINDS) {
void detectSdks(kind);
@@ -1805,8 +1828,15 @@ function SdksSection() {
};
const rows = useMemo(() => {
const out: Array<{ key: string; kind: SdkKind; kindLabel: string; name: string; version: string; path: string }> =
[];
const out: Array<{
key: string;
kind: SdkKind;
kindLabel: string;
name: string;
version: string;
path: string;
added: boolean;
}> = [];
for (const { kind, label } of SDK_KINDS) {
for (const sdk of byKind[kind] ?? []) {
out.push({
@@ -1816,11 +1846,12 @@ function SdksSection() {
name: sdk.name,
version: sdk.version ?? "",
path: sdk.path,
added: kind === "jdk" && (sdk.source === "added" || (addedJdks ?? []).includes(sdk.path)),
});
}
}
return out;
}, [byKind]);
}, [byKind, addedJdks]);
const activeSdk = rows.find((r) => r.key === selectedKey) ?? rows[0];
@@ -1829,12 +1860,33 @@ function SdksSection() {
<div className={styles.splitLayout}>
<div className={styles.sideList}>
<div className={styles.tableToolbar}>
<Button size="small" variant="ghost" icon="plus" onClick={() => setDownloading(true)}>
<T>Download JDK…</T>
</Button>
<IconButton
icon="plus"
size="small"
title="Add SDK"
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
showContextMenu({ x: r.left, y: r.bottom + 2 }, [
{ label: tx("Download JDK…"), icon: "download", run: () => setDownloading(true) },
{ label: tx("Add JDK from Disk…"), icon: "folder-open", run: () => void addJdkFromDisk() },
]);
}}
/>
<IconButton
icon="minus"
size="small"
title="Remove SDK"
disabled={!activeSdk?.added}
onClick={() => activeSdk && removeAddedJdk(activeSdk.path)}
/>
<span className={styles.spacer} />
<IconButton icon="refresh" size="small" title="Detect again" onClick={refreshAll} />
</div>
{addError && (
<div className={styles.error} role="alert">
{addError}
</div>
)}
<div className={styles.sideItems} role="listbox" aria-label={tx("SDKs")}>
{rows.length === 0 && (
<div className={styles.empty}>
+5
View File
@@ -63,6 +63,11 @@ export function detectSdks(kind: SdkKind, force = false): Promise<Sdk[]> {
return p;
}
/** Drops an SDK (e.g. a JDK added by hand, then removed) from the cached list. */
export function forgetSdk(kind: SdkKind, path: string) {
useSdks.setState((s) => ({ byKind: { ...s.byKind, [kind]: (s.byKind[kind] ?? []).filter((x) => x.path !== path) } }));
}
/** Adds an SDK (e.g. a just-created virtualenv) to the cached list. */
export function rememberSdk(kind: SdkKind, sdk: Sdk) {
const remember = () =>
+6 -1
View File
@@ -2002,5 +2002,10 @@
"Target": "Target",
"Foreign Keys": "Foreign Keys",
"Indexes": "Indexes",
"Columns": "Columns"
"Columns": "Columns",
"Add JDK from Disk…": "Add JDK from Disk…",
"Select Home Directory for JDK": "Select Home Directory for JDK",
"The selected directory is not a valid home for JDK: {path}": "The selected directory is not a valid home for JDK: {path}",
"Add SDK": "Add SDK",
"Remove SDK": "Remove SDK"
}
+6 -1
View File
@@ -8390,5 +8390,10 @@
"Only in target": "仅在目标中",
"Different": "不同",
"Foreign Keys": "外键",
"Indexes": "索引"
"Indexes": "索引",
"Add JDK from Disk…": "从磁盘添加 JDK…",
"Select Home Directory for JDK": "选择 JDK 主目录",
"The selected directory is not a valid home for JDK: {path}": "所选目录不是有效的 JDK 主目录:{path}",
"Add SDK": "添加 SDK",
"Remove SDK": "移除 SDK"
}