From 62e26fa7e3aeca2a26716eea3899f009f84602d7 Mon Sep 17 00:00:00 2001 From: Jesse <30562260+fengling375@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:49:18 +0800 Subject: [PATCH] feat(unreal): support Unreal Engine projects (#5444) A folder whose top level holds a .uproject is now an Unreal project. The Project tool window switches to an Unreal view: Source is a source root, Config a resources root, and Binaries, Intermediate, Saved and DerivedDataCache are excluded from the tree, index, search and file watching even before Unreal creates them. The root label names the engine the project's EngineAssociation resolves to (HKCU Builds / HKLM InstalledDirectory on Windows; a registered directory that no longer exists is dropped), and three run configurations start UnrealEditor with the project as the editor, as a game (-game) or as a dedicated server (-server), debugged through lldb-dap. Nested projects are detected like Godot and Flutter ones, and the .NET detector skips the same generated directories case-insensitively. Also sets the new field in the remote_dev test ProjectInfo and keeps "Unreal Engine" and the .uproject placeholder in English in the catalogs. Co-authored-by: fengling375 <30562260+fengling375@users.noreply.github.com> --- Cargo.lock | 2 + crates/ide-host/src/ops/project.rs | 3 + crates/ide-run/Cargo.toml | 1 + crates/ide-run/src/detect.rs | 70 +++++++++++++++- crates/ide-run/src/detect/dotnet.rs | 8 +- crates/ide-run/tests/detect.rs | 37 +++++++++ crates/ide-workspace/Cargo.toml | 3 + crates/ide-workspace/src/lib.rs | 1 + crates/ide-workspace/src/unreal.rs | 88 ++++++++++++++++++++ crates/ide-workspace/src/unreal/engine.rs | 92 +++++++++++++++++++++ languages/json.toml | 2 +- src-tauri/src/remote_dev.rs | 1 + src/bindings.ts | 19 +++++ src/features/app/__tests__/windows.test.ts | 8 ++ src/features/app/windows.ts | 9 +- src/features/project-tree/HeaderActions.tsx | 5 +- src/features/project-tree/index.ts | 12 ++- src/features/project-tree/model.ts | 16 ++++ src/features/project-tree/store.ts | 43 ++++++++-- src/features/run/types.ts | 42 ++++++++++ src/platform/i18n.test.ts | 3 + src/platform/locales/text/zh.json | 6 ++ src/ui/projectType.ts | 2 + 23 files changed, 457 insertions(+), 16 deletions(-) create mode 100644 crates/ide-workspace/src/unreal.rs create mode 100644 crates/ide-workspace/src/unreal/engine.rs diff --git a/Cargo.lock b/Cargo.lock index 44fdffc106..d542c12766 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4816,6 +4816,7 @@ dependencies = [ "ide-build", "ide-core", "ide-language", + "ide-workspace", "libc", "parking_lot", "portable-pty", @@ -5096,6 +5097,7 @@ dependencies = [ "toml_edit 0.25.17+spec-1.1.0", "tracing", "uuid", + "winreg 0.56.0", "zip", ] diff --git a/crates/ide-host/src/ops/project.rs b/crates/ide-host/src/ops/project.rs index 395938bac1..29f13b3a2e 100644 --- a/crates/ide-host/src/ops/project.rs +++ b/crates/ide-host/src/ops/project.rs @@ -22,6 +22,8 @@ pub struct ProjectInfo { pub workspace: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub unity: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub unreal: Option, } pub fn info(project: &Project) -> ProjectInfo { @@ -45,6 +47,7 @@ pub fn info(project: &Project) -> ProjectInfo { root: project.root.clone().into(), workspace, unity: ide_workspace::unity::detect(&project.root), + unreal: ide_workspace::unreal::detect(&project.root), } } diff --git a/crates/ide-run/Cargo.toml b/crates/ide-run/Cargo.toml index e2328b041c..9b442c6ab9 100644 --- a/crates/ide-run/Cargo.toml +++ b/crates/ide-run/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true [dependencies] ide-core.workspace = true ide-language.workspace = true +ide-workspace.workspace = true dunce.workspace = true encoding_rs.workspace = true serde.workspace = true diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index 04a91180e1..050f52c3a2 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -84,11 +84,16 @@ pub(crate) fn detect_with_profiles( } } detect_projects(root, &["build.zig"], zig::detect, &mut out); - dotnet::detect(root, &mut out); + // A UE project's `.sln` lists the engine's own tool projects; expanding it would bury the + // run menu under dozens of `.NET Project` entries that cannot run from here. + if !ide_workspace::unreal::is_project(root) { + dotnet::detect(root, &mut out); + } detect_projects(root, &["Makefile", "makefile", "GNUmakefile"], detect_make, &mut out); detect_projects(root, &["justfile", "Justfile", ".justfile"], detect_just, &mut out); detect_godot(root, &mut out); detect_projects(root, &["pubspec.yaml"], detect_flutter, &mut out); + detect_unreal(root, &mut out); crate::external::detect(root, &mut out); let mut seen = HashSet::new(); @@ -1608,6 +1613,49 @@ pub(crate) fn just_recipes(src: &str) -> Vec { // ---------------------------------------------------------------- godot +// ---------------------------------------------------------------- unreal + +/// Unreal Engine projects (`.uproject`) run through the engine's editor executable, which reads +/// its start-up mode from the command line: no flag is the editor, `-game` the game and `-server` +/// a dedicated server. All three exist for every project, blueprint-only ones included, because +/// the mode is decided at start-up rather than built. +fn detect_unreal(root: &Path, out: &mut Vec) { + detect_projects_matching(root, |dir| ide_workspace::unreal::project_file(dir).is_some(), detect_one_unreal, out); +} + +/// One Unreal project: the editor, the game and a dedicated server, all run by the same +/// `UnrealEditor.exe` and differing only in the flag. +fn detect_one_unreal(root: &Path, out: &mut Vec) { + let Some(info) = ide_workspace::unreal::detect(root) else { return }; + // Detection already resolved the engine; a project without one offers nothing to run. + let Some(found) = info.engine.as_ref() else { + tracing::debug!("no Unreal Engine installation for {}", root.display()); + return; + }; + let engine = + ide_workspace::unreal::engine::EngineInstall { id: found.id.clone(), root: PathBuf::from(&found.root) }; + let Some(project) = ide_workspace::unreal::project_file(root) else { return }; + let editor = engine.editor().to_string_lossy().into_owned(); + out.extend(unreal_configs(&project, &editor)); +} + +/// The editor, the game and a dedicated server: the three start-up modes the engine documents, +/// all run by `UnrealEditor.exe` and differing only in the flag. +fn unreal_configs(project: &Path, editor: &str) -> Vec { + let project = project.to_string_lossy().into_owned(); + [ + ("unreal:editor", "Unreal Editor", None), + ("unreal:game", "Unreal Game", Some("-game")), + ("unreal:server", "Unreal Server", Some("-server")), + ] + .into_iter() + .map(|(id, name, flag)| { + let args: Vec<&str> = std::iter::once(project.as_str()).chain(flag).collect(); + config(id.to_owned(), name, "unreal", editor, &args).debug("lldb-dap") + }) + .collect() +} + // ---------------------------------------------------------------- rebar3 / mix /// rebar3 (Erlang): the shell with the applications started, the EUnit tests and, with @@ -1690,3 +1738,23 @@ fn detect_just(root: &Path, out: &mut Vec) { out.push(c); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_unreal_project_offers_the_editor_the_game_and_a_dedicated_server() { + let configs = unreal_configs(Path::new("/p/Game.uproject"), "UE/UnrealEditor.exe"); + let listed: Vec<(&str, &str)> = configs.iter().map(|c| (c.id.as_str(), c.name.as_str())).collect(); + assert_eq!( + listed, + [("unreal:editor", "Unreal Editor"), ("unreal:game", "Unreal Game"), ("unreal:server", "Unreal Server"),] + ); + assert_eq!(configs[0].args, ["/p/Game.uproject"]); + assert_eq!(configs[1].args, ["/p/Game.uproject", "-game"]); + assert_eq!(configs[2].args, ["/p/Game.uproject", "-server"]); + assert!(configs.iter().all(|c| c.command == "UE/UnrealEditor.exe" && c.cwd.is_none())); + assert!(configs.iter().all(|c| c.debug_adapter.as_deref() == Some("lldb-dap") && c.kind == "unreal")); + } +} diff --git a/crates/ide-run/src/detect/dotnet.rs b/crates/ide-run/src/detect/dotnet.rs index ce1f433e04..fb8025370c 100644 --- a/crates/ide-run/src/detect/dotnet.rs +++ b/crates/ide-run/src/detect/dotnet.rs @@ -19,11 +19,15 @@ pub(crate) fn detect(root: &Path, out: &mut Vec) { let path = entry.path(); let name = entry.file_name().to_string_lossy().into_owned(); if entry.file_type().is_ok_and(|t| t.is_dir()) { - if !name.starts_with('.') + // Case-insensitive: Unreal's generated trees (`Binaries`, `Intermediate`, …) hold + // tens of thousands of files and copies of the engine's own tool projects. + let lower = name.to_ascii_lowercase(); + if !lower.starts_with('.') && !matches!( - name.as_str(), + lower.as_str(), "bin" | "obj" | "node_modules" | "target" | "build" | "dist" | "vendor" | "packages" ) + && !ide_workspace::unreal::GENERATED_DIRS.iter().any(|dir| dir.eq_ignore_ascii_case(&lower)) { dirs.push(path); } diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs index bfb77b27f6..84b1a433c8 100644 --- a/crates/ide-run/tests/detect.rs +++ b/crates/ide-run/tests/detect.rs @@ -1417,3 +1417,40 @@ fn sbt_projects() { assert_eq!(cmdline(&detect(dir.path())[1]), "./sbt test"); } } + +/// UE writes a `.sln` listing the engine's own tool projects; expanding it buries the run menu. +#[test] +fn a_solution_in_a_unreal_project_is_not_expanded_into_dotnet_configurations() { + let dir = project(&[ + ("Game.uproject", r#"{"FileVersion":3,"EngineAssociation":"5.8"}"#), + ( + "Game.sln", + r#"Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Game", "Source\Game\Game.csproj", "{00000000-0000-0000-0000-000000000000}" +EndProject +"#, + ), + ( + "Source/Game/Game.csproj", + r#"Exe"#, + ), + ]); + let c = detect(dir.path()); + assert!(c.iter().all(|c| !c.kind.starts_with("dotnet")), "{:?}", ids(&c)); +} + +/// The engine keeps copies of its tool projects under the generated trees, which hold no code +/// anyone runs from here — and on a real project they are deep enough to slow detection down. +#[test] +fn csproj_under_unreal_generated_directories_is_not_detected() { + let exe = + r#"Exe"#; + let dir = project(&[ + ("Intermediate/ProjectFiles/UnrealBuildTool/UnrealBuildTool.csproj", exe), + ("Binaries/Win64/ShaderCopy/ShaderCopy.csproj", exe), + ("Saved/Tools/Helper/Helper.csproj", exe), + ("DerivedDataCache/Worker/Worker.csproj", exe), + ]); + let c = detect(dir.path()); + assert!(c.is_empty(), "{:?}", ids(&c)); +} diff --git a/crates/ide-workspace/Cargo.toml b/crates/ide-workspace/Cargo.toml index 1a1b5d0298..f3e8d275e5 100644 --- a/crates/ide-workspace/Cargo.toml +++ b/crates/ide-workspace/Cargo.toml @@ -25,5 +25,8 @@ uuid.workspace = true zip.workspace = true encoding_rs.workspace = true +[target.'cfg(windows)'.dependencies] +winreg = "0.56" + [dev-dependencies] tempfile.workspace = true diff --git a/crates/ide-workspace/src/lib.rs b/crates/ide-workspace/src/lib.rs index 9791bb4780..b39a3a9221 100644 --- a/crates/ide-workspace/src/lib.rs +++ b/crates/ide-workspace/src/lib.rs @@ -18,6 +18,7 @@ pub mod roots; pub mod settings; pub mod text_refs; pub mod unity; +pub mod unreal; pub mod window_groups; pub mod workspace; diff --git a/crates/ide-workspace/src/unreal.rs b/crates/ide-workspace/src/unreal.rs new file mode 100644 index 0000000000..5032e4806e --- /dev/null +++ b/crates/ide-workspace/src/unreal.rs @@ -0,0 +1,88 @@ +//! Unreal Engine project identity, read from the `.uproject` at the root. +//! +//! Only the root and the engine tree are looked at: everything else in a UE project is +//! content, generated output, or engine code, and must never be walked. + +pub mod engine; + +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::path::{Path, PathBuf}; + +/// Generated directory beside the project root; excluded from the index, the search and the tree. +pub const GENERATED_DIRS: &[&str] = &["Binaries", "Intermediate", "Saved", "DerivedDataCache"]; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UnrealProjectInfo { + /// The engine the project builds against. `None` means none could be located, which is the + /// only reason such a project offers no run configuration at all. + pub engine: Option, +} + +/// A located engine, shown so a project without run configurations says why. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UnrealEngine { + /// `5.8` for a launcher install, or the registry key a source build registered under. + pub id: String, + /// Absolute engine root. + pub root: String, +} + +/// The `.uproject` directly inside `root`, picked by name order when a folder has several. +pub fn project_file(root: &Path) -> Option { + let mut found: Vec = std::fs::read_dir(root) + .ok()? + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("uproject"))) + .collect(); + found.sort(); + found.into_iter().next() +} + +pub fn is_project(root: &Path) -> bool { + project_file(root).is_some() +} + +pub fn detect(root: &Path) -> Option { + let file = project_file(root)?; + let association = std::fs::read_to_string(&file) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .and_then(|json| json.get("EngineAssociation")?.as_str().map(|v| v.trim().to_owned())) + .filter(|v| !v.is_empty()); + let engine = engine::locate(association.as_deref()) + .map(|found| UnrealEngine { id: found.id, root: found.root.to_string_lossy().into_owned() }); + Some(UnrealProjectInfo { engine }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + #[test] + fn a_directory_holding_a_uproject_is_a_project() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + write(&root.join("Arts.uproject"), r#"{"FileVersion":3,"EngineAssociation":"5.8","Plugins":[]}"#); + std::fs::create_dir_all(root.join("Content")).unwrap(); + assert!(is_project(root)); + assert!(detect(root).is_some()); + } + + #[test] + fn a_directory_without_a_uproject_is_not_a_project() { + let temp = tempfile::tempdir().unwrap(); + write(&temp.path().join("Source/Game.Target.cs"), ""); + assert!(!is_project(temp.path())); + assert!(detect(temp.path()).is_none()); + } +} diff --git a/crates/ide-workspace/src/unreal/engine.rs b/crates/ide-workspace/src/unreal/engine.rs new file mode 100644 index 0000000000..6355c80f82 --- /dev/null +++ b/crates/ide-workspace/src/unreal/engine.rs @@ -0,0 +1,92 @@ +//! Locating an installed Unreal Engine. +//! +//! A launcher install registers its directory per version under `HKLM` and a source build under +//! `HKCU`, keyed by whatever the `.uproject`'s `EngineAssociation` names. + +use std::path::PathBuf; + +/// A registered engine, keyed by whatever the machine calls it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EngineInstall { + /// `5.8` for a launcher install, a GUID-like key for a source build. + pub id: String, + pub root: PathBuf, +} + +impl EngineInstall { + /// The editor executable, which runs every start-up mode. + pub fn editor(&self) -> PathBuf { + self.root.join("Engine").join("Binaries").join("Win64").join("UnrealEditor.exe") + } +} + +/// The engine `association` names, following Unreal's own lookup: the association is the key a +/// registered directory is stored under, so an unknown or empty one locates nothing. +pub fn locate(association: Option<&str>) -> Option { + pick(installed(), association) +} + +fn pick(installs: Vec, association: Option<&str>) -> Option { + let id = association?; + // A registered directory that is gone is a leftover from an uninstalled engine. + installs.into_iter().find(|i| i.id.eq_ignore_ascii_case(id) && i.root.is_dir()) +} + +#[cfg(windows)] +fn installed() -> Vec { + use winreg::RegKey; + use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE}; + + let mut out = Vec::new(); + if let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(r"SOFTWARE\EpicGames\Unreal Engine") { + for id in key.enum_keys().flatten() { + let Ok(sub) = key.open_subkey(&id) else { continue }; + let Ok(dir) = sub.get_value::("InstalledDirectory") else { continue }; + if !dir.trim().is_empty() { + out.push(EngineInstall { id, root: PathBuf::from(dir) }); + } + } + } + if let Ok(key) = RegKey::predef(HKEY_CURRENT_USER).open_subkey(r"SOFTWARE\Epic Games\Unreal Engine\Builds") { + for (id, _) in key.enum_values().flatten() { + let Ok(dir) = key.get_value::(&id) else { continue }; + if !dir.trim().is_empty() { + out.push(EngineInstall { id, root: PathBuf::from(dir) }); + } + } + } + out +} + +#[cfg(not(windows))] +fn installed() -> Vec { + Vec::new() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A fake install whose directory exists, so `pick` treats it as usable. + fn install(dir: &std::path::Path, id: &str) -> EngineInstall { + let root = dir.join(format!("UE_{id}")); + std::fs::create_dir_all(root.join("Engine/Binaries/Win64")).unwrap(); + EngineInstall { id: id.to_owned(), root } + } + + #[test] + fn the_association_picks_that_install_and_nothing_else() { + let temp = tempfile::tempdir().unwrap(); + let installs = vec![install(temp.path(), "5.8"), install(temp.path(), "5.3")]; + assert_eq!(pick(installs.clone(), Some("5.3")).unwrap().id, "5.3"); + assert_eq!(pick(installs, Some("4.27")), None); + assert_eq!(pick(Vec::new(), None), None); + } + + #[test] + fn a_registered_engine_that_was_deleted_is_not_picked() { + let temp = tempfile::tempdir().unwrap(); + let ghost = EngineInstall { id: "5.8".to_owned(), root: temp.path().join("gone") }; + assert_eq!(pick(vec![ghost], Some("5.8")), None); + } +} diff --git a/languages/json.toml b/languages/json.toml index 94f29d3502..d34e64a2d7 100644 --- a/languages/json.toml +++ b/languages/json.toml @@ -1,7 +1,7 @@ id = "json" name = "JSON" formatter = { tool = "prettier", parser = "json", range = true } -extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map"] +extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map", "uproject", "uplugin"] filenames = [".prettierrc", ".watchmanconfig", "composer.lock", ".arcconfig"] indent = { tab-size = 2, insert-spaces = true } ui-mode = "JSON" diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 8208877257..5a54f0464b 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -1529,6 +1529,7 @@ mod tests { settings: Default::default(), workspace: None, unity: None, + unreal: None, }) .unwrap()) } diff --git a/src/bindings.ts b/src/bindings.ts index fbbfe7cb75..d201e65dae 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1463,6 +1463,7 @@ export const commands = { settings: Settings_Serialize, workspace?: Workspace_Serialize | null, unity?: UnityProjectInfo | null, + unreal?: UnrealProjectInfo | null, } | null>("project_current"), /** * File › Rename Project…: the project's display name (title bar, recent @@ -11626,6 +11627,7 @@ export type ProjectInfo_Deserialize = { settings: Settings_Deserialize, workspace?: Workspace_Deserialize | null, unity?: UnityProjectInfo | null, + unreal?: UnrealProjectInfo | null, }; export type ProjectInfo_Serialize = { @@ -11637,6 +11639,7 @@ export type ProjectInfo_Serialize = { settings: Settings_Serialize, workspace?: Workspace_Serialize | null, unity?: UnityProjectInfo | null, + unreal?: UnrealProjectInfo | null, }; /** An interpreter another project uses: the project root and the SDK itself. */ @@ -14360,6 +14363,22 @@ export type UnityProjectInfo = { projects: string[], }; +/** A located engine, shown so a project without run configurations says why. */ +export type UnrealEngine = { + /** `5.8` for a launcher install, or the registry key a source build registered under. */ + id: string, + /** Absolute engine root. */ + root: string, +}; + +export type UnrealProjectInfo = { + /** + * The engine the project builds against. `None` means none could be located, which is the + * only reason such a project offers no run configuration at all. + */ + engine: UnrealEngine | null, +}; + /** A requirement the project's interpreter does not satisfy. */ export type UnsatisfiedRequirement = { dependency: ManifestDependency, diff --git a/src/features/app/__tests__/windows.test.ts b/src/features/app/__tests__/windows.test.ts index 2908bdd053..34f0e9598a 100644 --- a/src/features/app/__tests__/windows.test.ts +++ b/src/features/app/__tests__/windows.test.ts @@ -344,6 +344,14 @@ describe("loose files (LightEdit)", () => { expect(fsReadDir).toHaveBeenCalledWith("/x/a.txt"); expect(lightEditOpen).toHaveBeenCalledWith("/x/a.txt"); }); + + it("opens the folder of a dropped .uproject instead of the file", async () => { + windowOpenProject.mockResolvedValue(ok({ kind: "current" })); + await openPaths(["/work/Game/Game.uproject"], async () => false); + expect(windowOpenFiles).not.toHaveBeenCalled(); + expect(lightEditOpen).not.toHaveBeenCalled(); + expect(openProject).toHaveBeenCalledWith("/work/Game"); + }); }); describe("Open Containing Folder as Project", () => { diff --git a/src/features/app/windows.ts b/src/features/app/windows.ts index 6bbe0b4e46..babc5fa482 100644 --- a/src/features/app/windows.ts +++ b/src/features/app/windows.ts @@ -128,14 +128,19 @@ export async function openFiles(files: readonly string[]): Promise { const pathIsDir = (path: string) => call(commands.fsReadDir(path)).then(() => true); +/** A file that names the project around it: dropping it opens that folder, as a double-click would. */ +const projectMarker = /\.uproject$/i; + /** Opens dropped paths: files as loose files ({@link openFiles}), the first folder as a project. */ export async function openPaths( paths: readonly string[], isDir: (path: string) => Promise = pathIsDir, ): Promise { const kinds = await Promise.all(paths.map((p) => isDir(p).catch(() => false))); - const files = paths.filter((_, i) => !kinds[i]); - const dir = paths.find((_, i) => kinds[i]); + // An Unreal project is dragged in as its `.uproject`, which names the folder to open. + const marker = paths.find((p, i) => !kinds[i] && projectMarker.test(p)); + const files = paths.filter((p, i) => !kinds[i] && p !== marker); + const dir = paths.find((_, i) => kinds[i]) ?? (marker ? dirname(marker) : undefined); await openFiles(files); if (dir) await openProjectWithPolicy(dir); } diff --git a/src/features/project-tree/HeaderActions.tsx b/src/features/project-tree/HeaderActions.tsx index 0d54ed692b..a72a26e3eb 100644 --- a/src/features/project-tree/HeaderActions.tsx +++ b/src/features/project-tree/HeaderActions.tsx @@ -21,9 +21,12 @@ export function useProjectTitleMenu(): { label: string; items: MenuItem[] } { const mode = useProjectTree((s) => s.mode); const scope = useProjectTree((s) => s.scope); const unity = useProjectTree((s) => s.unity); + const unreal = useProjectTree((s) => s.unreal); + // The engine panes only exist in a project of that engine. + const available = (id: string) => (id !== "unity" || Boolean(unity)) && (id !== "unreal" || Boolean(unreal)); // User scopes (Settings › Scopes) follow the built-in panes, as in IDEA. const scopes = userScopes(useProject((s) => (s.settings as { scopes?: unknown } | null)?.scopes)); - const items: MenuItem[] = VIEW_MODES.filter(([id]) => id !== "unity" || unity).map(([id, label]) => ({ + const items: MenuItem[] = VIEW_MODES.filter(([id]) => available(id)).map(([id, label]) => ({ id, label, checked: id === mode, diff --git a/src/features/project-tree/index.ts b/src/features/project-tree/index.ts index fee0e57707..610f779212 100644 --- a/src/features/project-tree/index.ts +++ b/src/features/project-tree/index.ts @@ -62,11 +62,19 @@ export function activate(): () => void { const p = useProject.getState().project; const s = useProjectTree.getState(); if ((p?.root ?? null) !== s.root || p?.workspace?.projects !== (s.members ?? undefined)) - initProjectTree(p?.root ?? null, p?.name ?? "", p?.workspace?.projects ?? null, p?.unity ?? null); + initProjectTree( + p?.root ?? null, + p?.name ?? "", + p?.workspace?.projects ?? null, + p?.unity ?? null, + p?.unreal ?? null, + ); else if (p) { - useProjectTree.setState({ name: p.name, unity: p.unity ?? null }); + useProjectTree.setState({ name: p.name, unity: p.unity ?? null, unreal: p.unreal ?? null }); if (p.unity && !s.unity && s.mode === "project") setViewMode("unity"); if (!p.unity && s.mode === "unity") setViewMode("project"); + if (p.unreal && !s.unreal && s.mode === "project") setViewMode("unreal"); + if (!p.unreal && s.mode === "unreal") setViewMode("project"); } }; sync(); diff --git a/src/features/project-tree/model.ts b/src/features/project-tree/model.ts index 76bf89ee65..b2adb1ab03 100644 --- a/src/features/project-tree/model.ts +++ b/src/features/project-tree/model.ts @@ -10,7 +10,10 @@ import { ancestorsWithin, insideAnyOf, isInside, isSameOrInside, nameOf, parentO export interface TreeOptions { /** Applied only by the Unity pane, never persisted as a user preference. */ unityRoot?: string; + /** Applied only by the Unreal pane, never persisted as a user preference. */ + unrealRoot?: string; showUnityMeta: boolean; + /** Generated build output, shared by the engine panes (Unity's Library, Unreal's Binaries/Intermediate). */ showUnityGenerated: boolean; /** Show ignored names (`files.ignoredNames`: `.git`, `.DS_Store`, …). Dotfiles are always shown. */ showHidden: boolean; @@ -90,8 +93,21 @@ export function unityPathVisible(path: string, opts: TreeOptions): boolean { return true; } +/** The Unreal pane hides what UBT writes: build output, and the project files it generates. */ +export function unrealPathVisible(path: string, opts: TreeOptions): boolean { + if (opts.unrealRoot && path.startsWith(opts.unrealRoot + "/")) { + const relative = path.slice(opts.unrealRoot.length + 1); + if (!opts.showUnityGenerated) { + if (/^(Binaries|Intermediate|Saved|DerivedDataCache|\.vs)(\/|$)/.test(relative)) return false; + if (!relative.includes("/") && /\.(sln|slnx|suo|user|vcxproj|pidb)$/i.test(relative)) return false; + } + } + return true; +} + export function isVisible(entry: FileEntry, opts: TreeOptions): boolean { if (!unityPathVisible(entry.path, opts)) return false; + if (!unrealPathVisible(entry.path, opts)) return false; // Ignored names are also excluded on the backend; only "Show Hidden" brings them back. if (isIgnoredName(entry.name)) return opts.showHidden; if (!opts.showExcluded && entry.ignored) return false; diff --git a/src/features/project-tree/store.ts b/src/features/project-tree/store.ts index 105e71583e..8848cc3113 100644 --- a/src/features/project-tree/store.ts +++ b/src/features/project-tree/store.ts @@ -4,7 +4,7 @@ * Kept outside React so actions (keyboard, Find Action, context menu) share it. */ import { create } from "zustand"; -import type { UnityProjectInfo } from "@/bindings"; +import type { UnrealProjectInfo, UnityProjectInfo } from "@/bindings"; import { call } from "@/platform/ipc"; import { commands, type FileEntry, type OutlineItem } from "@/bindings"; import { withDocument } from "@/editor/lsp/files"; @@ -37,6 +37,7 @@ import { visibleEntries, visibleInfo, unityPathVisible, + unrealPathVisible, type Placeholder, type ProjectNode, type TreeModel, @@ -89,10 +90,19 @@ function storedOptions(): ViewOptions { } /** IDEA's Project view panes ("Project ▾" in the tool window header). */ -export type ViewMode = "unity" | "project" | "projectFiles" | "openFiles" | "changedFiles" | "scratches" | "scope"; +export type ViewMode = + | "unity" + | "unreal" + | "project" + | "projectFiles" + | "openFiles" + | "changedFiles" + | "scratches" + | "scope"; export const VIEW_MODES: ReadonlyArray<[ViewMode, string]> = [ ["unity", "Unity"], + ["unreal", "Unreal"], ["project", "Project"], ["projectFiles", "Project Files"], ["openFiles", "Open Files"], @@ -118,6 +128,7 @@ export interface Clipboard { interface ProjectTreeState { unity: UnityProjectInfo | null; + unreal: UnrealProjectInfo | null; root: string | null; name: string; members: readonly string[] | null; @@ -172,6 +183,7 @@ function writeJson(key: string, value: unknown) { export const useProjectTree = create(() => ({ unity: null, + unreal: null, root: null, name: "", members: null, @@ -207,6 +219,7 @@ const set = (patch: Partial) => useProjectTree.setState(patch) let memo: { unity: UnityProjectInfo | null; + unreal: UnrealProjectInfo | null; root: string | null; name: string; members: readonly string[] | null; @@ -232,7 +245,9 @@ const filesOf = (s: ProjectTreeState) => : null; function treeOptions(s: ProjectTreeState): TreeOptions { - return s.mode === "unity" && s.unity && s.root ? { ...s.options, compact: false, unityRoot: s.root } : s.options; + if (s.mode === "unity" && s.unity && s.root) return { ...s.options, compact: false, unityRoot: s.root }; + if (s.mode === "unreal" && s.unreal && s.root) return { ...s.options, compact: false, unrealRoot: s.root }; + return s.options; } export function selectModel(s: ProjectTreeState): TreeModel { @@ -240,6 +255,7 @@ export function selectModel(s: ProjectTreeState): TreeModel { if ( memo && memo.unity === s.unity && + memo.unreal === s.unreal && memo.root === s.root && memo.name === s.name && memo.members === s.members && @@ -300,6 +316,8 @@ export function selectModel(s: ProjectTreeState): TreeModel { else model = withExtraRoots(project(), contributed, s.listings, options, placeholder); if (s.unity && s.mode === "unity" && model.roots[0]) model.roots[0].detail = s.unity.editorVersion ? `Unity ${s.unity.editorVersion}` : "Unity"; + if (s.unreal && s.mode === "unreal" && model.roots[0]) + model.roots[0].detail = s.unreal.engine ? `Unreal ${s.unreal.engine.id}` : "Unreal · engine not found"; const libraries = extraFolders(contributed).flatMap((r) => r.readOnly && r.path !== undefined && isSameOrInside(r.path, s.root!) ? [r.path] : [], ); @@ -307,6 +325,7 @@ export function selectModel(s: ProjectTreeState): TreeModel { } memo = { unity: s.unity, + unreal: s.unreal, root: s.root, name: s.name, members: s.members, @@ -350,6 +369,7 @@ export function initProjectTree( name = "", members: readonly string[] | null = null, unity: UnityProjectInfo | null = null, + unreal: UnrealProjectInfo | null = null, ) { cancelExpansion(); generation++; @@ -363,8 +383,13 @@ export function initProjectTree( autoExpanded.clear(); const previous = get(); const previousMode = previous.mode; + const engineMode: ViewMode | null = unreal ? "unreal" : unity ? "unity" : null; const mode = - unity && previousMode === "project" ? "unity" : !unity && previousMode === "unity" ? "project" : previousMode; + engineMode && previousMode === "project" + ? engineMode + : !engineMode && (previousMode === "unity" || previousMode === "unreal") + ? "project" + : previousMode; // Keep the remaining members' types visible while the workspace is rescanned. const projectTypes = new Map(); if (root === previous.root && members) { @@ -375,6 +400,7 @@ export function initProjectTree( } set({ unity, + unreal, mode, root, name, @@ -411,7 +437,7 @@ function initialExpanded(root: string | null, mode: ViewMode, members = get().me // Keys of nodes that no longer exist are inert. Only a first open expands the roots. const scope = projectLocation(root) ?? root; const persisted = - mode === "project" || mode === "unity" + mode === "project" || mode === "unity" || mode === "unreal" ? (readJson(expandedKey(scope)) ?? (scope !== root ? readJson(expandedKey(root)) : null)) : null; if (persisted) return new Set(persisted); @@ -419,11 +445,11 @@ function initialExpanded(root: string | null, mode: ViewMode, members = get().me } function persistExpanded() { - if (get().mode !== "project" && get().mode !== "unity") return; + if (get().mode !== "project" && get().mode !== "unity" && get().mode !== "unreal") return; clearTimeout(persistTimer); persistTimer = setTimeout(() => { const { root, expanded, mode } = get(); - if (root && (mode === "project" || mode === "unity")) + if (root && (mode === "project" || mode === "unity" || mode === "unreal")) writeJson(expandedKey(projectLocation(root) ?? root), [...expanded].slice(0, MAX_PERSISTED)); }, 300); } @@ -432,6 +458,7 @@ function persistExpanded() { export function setViewMode(mode: ViewMode) { const s = get(); if (mode === "unity" && !s.unity) return; + if (mode === "unreal" && !s.unreal) return; if (s.mode === mode) return; cancelExpansion(); modeExpanded.set(s.mode, s.expanded); @@ -901,6 +928,8 @@ export function modeShows(path: string, mode = get().mode): boolean { switch (mode) { case "unity": return !!state.unity && unityPathVisible(path, treeOptions({ ...state, mode })); + case "unreal": + return !!state.unreal && unrealPathVisible(path, treeOptions({ ...state, mode })); case "project": return true; case "projectFiles": diff --git a/src/features/run/types.ts b/src/features/run/types.ts index 2c3aa3473e..761f225b26 100644 --- a/src/features/run/types.ts +++ b/src/features/run/types.ts @@ -205,6 +205,47 @@ const godot: RunConfigTypeContribution = { }, }; +const isUProject = (a: string) => !a.startsWith("-") && /\.uproject$/i.test(a); + +/** + * Unreal Engine: ` .uproject [-game|-server]`. The editor comes from the + * detected configuration (the engine is registered per version); the mode stays in the + * arguments, so the editor, a game and a server are the same type. + */ +const unreal: RunConfigTypeContribution = { + id: "unreal", + label: "Unreal Engine", + icon: "file-cpp", + group: "Unreal", + description: "Open an Unreal Engine project in the editor, or in game mode", + debugAdapter: "lldb-dap", + fields: [ + { + key: "project", + label: "Project", + mono: true, + browse: "file", + required: true, + placeholder: "…/Game.uproject", + }, + { key: "arguments", label: "Arguments", mono: true, placeholder: "e.g. -game" }, + ], + commandLine: (p) => ({ + command: p.executable || "UnrealEditor.exe", + args: [p.project ?? "", ...parseArgs(p.arguments ?? "")], + cwd: null, + }), + paramsFrom(c) { + const project = c.args.find(isUProject); + if (!project) return null; + return { + project, + arguments: formatArgs(c.args.filter((a) => a !== project)), + ...(c.command !== "UnrealEditor.exe" ? { executable: c.command } : {}), + }; + }, +}; + const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"]; const NPM_COMMANDS = ["run", "test", "start", "install", "ci", "publish", "pack"]; @@ -576,6 +617,7 @@ export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [ maven, godot, flutterType, + unreal, pythonType, pytest, rubyScriptType, diff --git a/src/platform/i18n.test.ts b/src/platform/i18n.test.ts index 79fc105bf5..b2cd1e23fe 100644 --- a/src/platform/i18n.test.ts +++ b/src/platform/i18n.test.ts @@ -356,6 +356,9 @@ describe("catalogs", () => { "DuckDB", "JDBC URL", "path/to/database.duckdb", + // Unreal Engine projects: the product name and the .uproject path placeholder. + "Unreal Engine", + "…/Game.uproject", ]); const translated = SUPPORTED_LOCALES.filter((locale) => locale !== "en").sort(); diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index b66bbf0682..836ef92ad5 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -5304,6 +5304,12 @@ "Scene": "场景", "Main scene": "主场景", "Godot command line options, e.g. --debug-collisions": "Godot 命令行选项,例如 --debug-collisions", + "Unreal Engine": "Unreal Engine", + "Unreal": "Unreal 项目", + "Unreal · engine not found": "Unreal · 未找到引擎", + "Open an Unreal Engine project in the editor, or in game mode": "用编辑器打开 Unreal Engine 项目,或以游戏模式运行", + "…/Game.uproject": "…/Game.uproject", + "e.g. -game": "例如 -game", "Bookmark description": "书签描述", "Cannot open {path}": "无法打开 {path}", "Search context": "搜索上下文", diff --git a/src/ui/projectType.ts b/src/ui/projectType.ts index 081decf8df..37b03d8b71 100644 --- a/src/ui/projectType.ts +++ b/src/ui/projectType.ts @@ -36,6 +36,8 @@ export const PROJECT_TYPES = { godot: { name: "Godot", icon: "file-godot", markers: ["project.godot"] }, cmake: { name: "CMake", icon: "file-cmake", markers: ["CMakeLists.txt"] }, make: { name: "Make", icon: "file-makefile", markers: ["Makefile", "makefile", "GNUmakefile"] }, + // Before .NET: the `.sln` a UE project generates belongs to the project, not to C#. + unreal: { name: "Unreal Engine", icon: "file-cpp", markers: [/^[^/]+\.uproject$/i] }, dotnet: { name: ".NET", icon: "file-csharp", markers: [/^[^/]+\.(?:[cf]sproj|slnx?)$/i] }, } as const satisfies Record;